summaryrefslogtreecommitdiff
path: root/SPECS/network/fetch-polyfill.js
blob: 16375c6445c72a9d5314812671d42edc8dbe1976 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/**
 * Fetch API Detection and Utilities
 *
 * Provides comprehensive Fetch API support detection and utilities:
 * - Native fetch detection
 * - Feature capability testing
 * - Cross-platform compatibility checks
 * - Edge runtime detection
 */

/**
 * Test if ErrorEvent constructor is available
 * @returns {boolean} True if ErrorEvent is supported
 */
function supportsErrorEvent() {
  try {
    new ErrorEvent("");
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * Test if DOMError constructor is available
 * @returns {boolean} True if DOMError is supported
 */
function supportsDOMError() {
  try {
    new DOMError("");
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * Test if DOMException constructor is available
 * @returns {boolean} True if DOMException is supported
 */
function supportsDOMException() {
  try {
    new DOMException("");
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * Test if fetch API is available
 * @returns {boolean} True if fetch is supported
 */
function supportsFetch() {
  const globalObj = getGlobalObject();

  if (!("fetch" in globalObj)) {
    return false;
  }

  try {
    new Request("http://www.example.com");
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * Test if function is native fetch implementation
 * @param {Function} fetchFn - Function to test
 * @returns {boolean} True if it's native fetch
 */
function isNativeFetch(fetchFn) {
  return (
    fetchFn &&
    /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(fetchFn.toString())
  );
}

/**
 * Detect if environment supports native fetch (not polyfilled)
 * @returns {boolean} True if native fetch is available
 */
function supportsNativeFetch() {
  const globalObj = getGlobalObject();

  // Edge Runtime always has native fetch
  if (typeof EdgeRuntime === "string") {
    return true;
  }

  if (!supportsFetch()) {
    return false;
  }

  // Check if window.fetch is native
  if (isNativeFetch(globalObj.fetch)) {
    return true;
  }

  // Test using iframe sandbox for pure fetch detection
  let hasNativeFetch = false;
  const document = globalObj.document;

  if (document && typeof document.createElement === "function") {
    try {
      const iframe = document.createElement("iframe");
      iframe.hidden = true;
      document.head.appendChild(iframe);

      if (iframe.contentWindow && iframe.contentWindow.fetch) {
        hasNativeFetch = isNativeFetch(iframe.contentWindow.fetch);
      }

      document.head.removeChild(iframe);
    } catch (error) {
      // Fallback to window.fetch check if iframe test fails
      console.warn(
        "Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",
        error,
      );
    }
  }

  return hasNativeFetch;
}

/**
 * Test if ReportingObserver is available
 * @returns {boolean} True if ReportingObserver is supported
 */
function supportsReportingObserver() {
  const globalObj = getGlobalObject();
  return "ReportingObserver" in globalObj;
}

/**
 * Test if referrerPolicy is supported in Request constructor
 * @returns {boolean} True if referrerPolicy is supported
 */
function supportsReferrerPolicy() {
  if (!supportsFetch()) {
    return false;
  }

  try {
    new Request("_", { referrerPolicy: "origin" });
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * Parse fetch arguments into method and URL
 * @param {Array} args - Fetch function arguments
 * @returns {Object} Parsed arguments with method and url
 */
function parseFetchArgs(args) {
  if (args.length === 0) {
    return { method: "GET", url: "" };
  }

  if (args.length === 2) {
    const [input, init] = args;
    return {
      url: extractUrl(input),
      method: hasProperty(init, "method")
        ? String(init.method).toUpperCase()
        : "GET",
    };
  }

  const input = args[0];
  return {
    url: extractUrl(input),
    method: hasProperty(input, "method")
      ? String(input.method).toUpperCase()
      : "GET",
  };
}

/**
 * Extract URL from fetch input parameter
 * @param {string|Request|URL} input - Fetch input parameter
 * @returns {string} Extracted URL string
 */
function extractUrl(input) {
  if (typeof input === "string") {
    return input;
  }

  if (!input) {
    return "";
  }

  if (hasProperty(input, "url")) {
    return input.url;
  }

  if (input.toString) {
    return input.toString();
  }

  return "";
}

/**
 * Check if object has a specific property
 * @param {any} obj - Object to check
 * @param {string} prop - Property name
 * @returns {boolean} True if object has property
 */
function hasProperty(obj, prop) {
  return !!(obj && typeof obj === "object" && obj[prop]);
}

/**
 * Get global object (window, global, self, etc.)
 * @returns {Object} Global object
 */
function getGlobalObject() {
  return (
    (typeof globalThis === "object" && globalThis) ||
    (typeof window === "object" && window) ||
    (typeof self === "object" && self) ||
    (typeof global === "object" && global) ||
    (function () {
      return this;
    })() ||
    {}
  );
}

/**
 * Create fetch capability report
 * @returns {Object} Comprehensive capability report
 */
function getFetchCapabilities() {
  const globalObj = getGlobalObject();

  return {
    // Basic availability
    hasFetch: supportsFetch(),
    hasNativeFetch: supportsNativeFetch(),

    // Related API support
    hasErrorEvent: supportsErrorEvent(),
    hasDOMError: supportsDOMError(),
    hasDOMException: supportsDOMException(),
    hasReportingObserver: supportsReportingObserver(),
    hasReferrerPolicy: supportsReferrerPolicy(),

    // Environment detection
    isEdgeRuntime: typeof EdgeRuntime === "string",
    isBrowser: typeof window !== "undefined",
    isNode: typeof global !== "undefined" && !globalObj.window,
    isWorker: typeof self !== "undefined" && typeof window === "undefined",

    // Implementation details
    fetchFunction: globalObj.fetch
      ? globalObj.fetch.toString().slice(0, 100)
      : null,
    nativeFetchDetected: globalObj.fetch
      ? isNativeFetch(globalObj.fetch)
      : false,
  };
}

/**
 * Create a fetch wrapper that adds instrumentation
 * @param {Function} originalFetch - Original fetch function
 * @param {Function} onRequest - Request interceptor
 * @param {Function} onResponse - Response interceptor
 * @param {Function} onError - Error interceptor
 * @returns {Function} Wrapped fetch function
 */
function createInstrumentedFetch(
  originalFetch,
  onRequest,
  onResponse,
  onError,
) {
  return function instrumentedFetch(...args) {
    const { method, url } = parseFetchArgs(args);
    const requestData = {
      args,
      fetchData: { method, url },
      startTimestamp: Date.now(),
    };

    // Call request interceptor
    if (onRequest) {
      onRequest(requestData);
    }

    return originalFetch
      .apply(this, args)
      .then((response) => {
        const responseData = {
          ...requestData,
          endTimestamp: Date.now(),
          response,
        };

        if (onResponse) {
          onResponse(responseData);
        }

        return response;
      })
      .catch((error) => {
        const errorData = {
          ...requestData,
          endTimestamp: Date.now(),
          error,
        };

        if (onError) {
          onError(errorData);
        }

        throw error;
      });
  };
}

module.exports = {
  supportsErrorEvent,
  supportsDOMError,
  supportsDOMException,
  supportsFetch,
  supportsNativeFetch,
  supportsReportingObserver,
  supportsReferrerPolicy,
  isNativeFetch,
  parseFetchArgs,
  extractUrl,
  getFetchCapabilities,
  createInstrumentedFetch,
  getGlobalObject,
};