@cloudflare/pages-shared 0.0.1 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,600 @@
1
+ import {
2
+ FoundResponse,
3
+ InternalServerErrorResponse,
4
+ MethodNotAllowedResponse,
5
+ MovedPermanentlyResponse,
6
+ NotAcceptableResponse,
7
+ NotFoundResponse,
8
+ NotModifiedResponse,
9
+ OkResponse,
10
+ PermanentRedirectResponse,
11
+ SeeOtherResponse,
12
+ TemporaryRedirectResponse,
13
+ } from "./responses";
14
+ import { generateRulesMatcher, replacer } from "./rulesEngine";
15
+ import type {
16
+ Metadata,
17
+ MetadataHeadersEntries,
18
+ MetadataHeadersRulesV2,
19
+ MetadataHeadersV1,
20
+ MetadataHeadersV2,
21
+ } from "./metadata";
22
+
23
+ type BodyEncoding = "manual" | "automatic";
24
+
25
+ // Before serving a 404, we check the cache to see if we've served this asset recently
26
+ // and if so, serve it from the cache instead of responding with a 404.
27
+ // This gives a bit of a grace period between deployments for any clients browsing the old deployment.
28
+ export const ASSET_PRESERVATION_CACHE = "assetPreservationCache";
29
+ const CACHE_CONTROL_PRESERVATION = "public, s-maxage=604800"; // 1 week
30
+
31
+ export const CACHE_CONTROL_BROWSER = "public, max-age=0, must-revalidate"; // have the browser check in with the server to make sure its local cache is valid before using it
32
+ export const REDIRECTS_VERSION = 1;
33
+ export const HEADERS_VERSION = 2;
34
+ export const HEADERS_VERSION_V1 = 1;
35
+ export const ANALYTICS_VERSION = 1;
36
+
37
+ // Takes metadata headers and "normalise" them
38
+ // to the latest version
39
+ export function normaliseHeaders(
40
+ headers: MetadataHeadersV1 | MetadataHeadersV2
41
+ ): MetadataHeadersRulesV2 {
42
+ if (headers.version === HEADERS_VERSION) {
43
+ return headers.rules;
44
+ } else if (headers.version === HEADERS_VERSION_V1) {
45
+ return Object.keys(headers.rules).reduce(
46
+ (acc: MetadataHeadersRulesV2, key) => {
47
+ acc[key] = {
48
+ set: headers.rules[key] as MetadataHeadersEntries,
49
+ };
50
+ return acc;
51
+ },
52
+ {}
53
+ );
54
+ } else {
55
+ return {};
56
+ }
57
+ }
58
+
59
+ type FindAssetEntryForPath<AssetEntry> = (
60
+ path: string
61
+ ) => Promise<null | AssetEntry>;
62
+
63
+ type ServeAsset<AssetEntry> = (
64
+ assetEntry: AssetEntry,
65
+ options?: { preserve: boolean }
66
+ ) => Promise<Response>;
67
+
68
+ type FullHandlerContext<AssetEntry, ContentNegotiation, Asset> = {
69
+ request: Request;
70
+ metadata: Metadata;
71
+ xServerEnvHeader?: string;
72
+ logError: (err: Error) => void;
73
+ findAssetEntryForPath: FindAssetEntryForPath<AssetEntry>;
74
+ getAssetKey(assetEntry: AssetEntry, content: ContentNegotiation): string;
75
+ negotiateContent(
76
+ request: Request,
77
+ assetEntry: AssetEntry
78
+ ): ContentNegotiation;
79
+ fetchAsset: (assetKey: string) => Promise<Asset>;
80
+ generateNotFoundResponse?: (
81
+ request: Request,
82
+ findAssetEntryForPath: FindAssetEntryForPath<AssetEntry>,
83
+ serveAsset: ServeAsset<AssetEntry>
84
+ ) => Promise<Response>;
85
+ attachAdditionalHeaders?: (
86
+ response: Response,
87
+ content: ContentNegotiation,
88
+ assetEntry: AssetEntry,
89
+ asset: Asset
90
+ ) => void;
91
+ caches: CacheStorage;
92
+ waitUntil: (promise: Promise<unknown>) => void;
93
+ };
94
+
95
+ export type HandlerContext<AssetEntry, ContentNegotiation, Asset> =
96
+ | FullHandlerContext<AssetEntry, ContentNegotiation, Asset>
97
+ | (Omit<
98
+ FullHandlerContext<AssetEntry, ContentNegotiation, Asset>,
99
+ "caches" | "waitUntil"
100
+ > & {
101
+ caches?: undefined;
102
+ waitUntil?: undefined;
103
+ });
104
+
105
+ export async function generateHandler<
106
+ AssetEntry,
107
+ ContentNegotiation extends { encoding: string | null } = {
108
+ encoding: string | null;
109
+ },
110
+ Asset extends { body: ReadableStream | null; contentType: string } = {
111
+ body: ReadableStream | null;
112
+ contentType: string;
113
+ }
114
+ >({
115
+ request,
116
+ metadata,
117
+ xServerEnvHeader,
118
+ logError,
119
+ findAssetEntryForPath,
120
+ getAssetKey,
121
+ negotiateContent,
122
+ fetchAsset,
123
+ generateNotFoundResponse = async (
124
+ notFoundRequest,
125
+ notFoundFindAssetEntryForPath,
126
+ notFoundServeAsset
127
+ ) => {
128
+ let assetEntry: AssetEntry | null;
129
+ // No custom 404 page, so try serving as a single-page app
130
+ if ((assetEntry = await notFoundFindAssetEntryForPath("/index.html"))) {
131
+ return notFoundServeAsset(assetEntry, { preserve: false });
132
+ }
133
+
134
+ return new NotFoundResponse();
135
+ },
136
+ attachAdditionalHeaders = () => {},
137
+ caches,
138
+ waitUntil,
139
+ }: HandlerContext<AssetEntry, ContentNegotiation, Asset>) {
140
+ const url = new URL(request.url);
141
+ const { protocol, host, search } = url;
142
+ let { pathname } = url;
143
+
144
+ const earlyHintsCache = metadata.deploymentId
145
+ ? await caches?.open(`eh:${metadata.deploymentId}`)
146
+ : undefined;
147
+
148
+ const headerRules = metadata.headers
149
+ ? normaliseHeaders(metadata.headers)
150
+ : {};
151
+
152
+ const staticRules =
153
+ metadata.redirects?.version === REDIRECTS_VERSION
154
+ ? metadata.redirects.staticRules || {}
155
+ : {};
156
+
157
+ const staticRedirectsMatcher = () => {
158
+ const withHostMatch = staticRules[`https://${host}${pathname}`];
159
+ const withoutHostMatch = staticRules[pathname];
160
+
161
+ if (withHostMatch && withoutHostMatch) {
162
+ if (withHostMatch.lineNumber < withoutHostMatch.lineNumber) {
163
+ return withHostMatch;
164
+ } else {
165
+ return withoutHostMatch;
166
+ }
167
+ }
168
+
169
+ return withHostMatch || withoutHostMatch;
170
+ };
171
+
172
+ const generateRedirectsMatcher = () =>
173
+ generateRulesMatcher(
174
+ metadata.redirects?.version === REDIRECTS_VERSION
175
+ ? metadata.redirects.rules
176
+ : {},
177
+ ({ status, to }, replacements) => ({
178
+ status,
179
+ to: replacer(to, replacements),
180
+ })
181
+ );
182
+
183
+ let assetEntry: AssetEntry | null;
184
+
185
+ async function generateResponse(): Promise<Response> {
186
+ const match =
187
+ staticRedirectsMatcher() || generateRedirectsMatcher()({ request })[0];
188
+
189
+ if (match) {
190
+ const { status, to } = match;
191
+ const destination = new URL(to, request.url);
192
+ const location =
193
+ destination.origin === new URL(request.url).origin
194
+ ? `${destination.pathname}${destination.search || search}${
195
+ destination.hash
196
+ }`
197
+ : `${destination.href}${destination.search ? "" : search}${
198
+ destination.hash
199
+ }`;
200
+ switch (status) {
201
+ case 301:
202
+ return new MovedPermanentlyResponse(location);
203
+ case 303:
204
+ return new SeeOtherResponse(location);
205
+ case 307:
206
+ return new TemporaryRedirectResponse(location);
207
+ case 308:
208
+ return new PermanentRedirectResponse(location);
209
+ case 302:
210
+ default:
211
+ return new FoundResponse(location);
212
+ }
213
+ }
214
+
215
+ if (!request.method.match(/^(get|head)$/i)) {
216
+ return new MethodNotAllowedResponse();
217
+ }
218
+
219
+ try {
220
+ pathname = globalThis.decodeURIComponent(pathname);
221
+ } catch (err) {}
222
+
223
+ if (pathname.endsWith("/")) {
224
+ if ((assetEntry = await findAssetEntryForPath(`${pathname}index.html`))) {
225
+ return serveAsset(assetEntry);
226
+ } else if (pathname.endsWith("/index/")) {
227
+ return new PermanentRedirectResponse(
228
+ `/${pathname.slice(1, -"index/".length)}${search}`
229
+ );
230
+ } else if (
231
+ (assetEntry = await findAssetEntryForPath(
232
+ `${pathname.replace(/\/$/, ".html")}`
233
+ ))
234
+ ) {
235
+ return new PermanentRedirectResponse(
236
+ `/${pathname.slice(1, -1)}${search}`
237
+ );
238
+ } else {
239
+ return notFound();
240
+ }
241
+ }
242
+
243
+ if ((assetEntry = await findAssetEntryForPath(pathname))) {
244
+ if (pathname.endsWith(".html")) {
245
+ const extensionlessPath = pathname.slice(0, -".html".length);
246
+ // Don't redirect to an extensionless URL if another asset exists there
247
+ // or if pathname is /.html
248
+ // FIXME: this doesn't handle files in directories ie: /foobar/.html
249
+ if (extensionlessPath.endsWith("/index")) {
250
+ return new PermanentRedirectResponse(
251
+ `${extensionlessPath.replace(/\/index$/, "/")}${search}`
252
+ );
253
+ } else if (
254
+ (await findAssetEntryForPath(extensionlessPath)) ||
255
+ extensionlessPath === "/"
256
+ ) {
257
+ return serveAsset(assetEntry);
258
+ } else {
259
+ return new PermanentRedirectResponse(`${extensionlessPath}${search}`);
260
+ }
261
+ } else {
262
+ return serveAsset(assetEntry);
263
+ }
264
+ } else if (pathname.endsWith("/index")) {
265
+ return new PermanentRedirectResponse(
266
+ `/${pathname.slice(1, -"index".length)}${search}`
267
+ );
268
+ } else if ((assetEntry = await findAssetEntryForPath(`${pathname}.html`))) {
269
+ return serveAsset(assetEntry);
270
+ } else if (hasFileExtension(pathname)) {
271
+ return notFound();
272
+ }
273
+
274
+ if ((assetEntry = await findAssetEntryForPath(`${pathname}/index.html`))) {
275
+ return new PermanentRedirectResponse(`${pathname}/${search}`);
276
+ } else {
277
+ return notFound();
278
+ }
279
+ }
280
+
281
+ async function attachHeaders(response: Response) {
282
+ const existingHeaders = new Headers(response.headers);
283
+
284
+ const extraHeaders = new Headers({
285
+ "access-control-allow-origin": "*",
286
+ "referrer-policy": "strict-origin-when-cross-origin",
287
+ ...(existingHeaders.has("content-type")
288
+ ? { "x-content-type-options": "nosniff" }
289
+ : {}),
290
+ });
291
+
292
+ const headers = new Headers({
293
+ // But we intentionally override existing headers
294
+ ...Object.fromEntries(existingHeaders.entries()),
295
+ ...Object.fromEntries(extraHeaders.entries()),
296
+ });
297
+
298
+ // Iterate through rules and find rules that match the path
299
+ const headersMatcher = generateRulesMatcher(
300
+ headerRules,
301
+ ({ set = {}, unset = [] }, replacements) => {
302
+ const replacedSet: Record<string, string> = {};
303
+ Object.keys(set).forEach((key) => {
304
+ replacedSet[key] = replacer(set[key], replacements);
305
+ });
306
+ return {
307
+ set: replacedSet,
308
+ unset,
309
+ };
310
+ }
311
+ );
312
+ const matches = headersMatcher({ request });
313
+
314
+ // This keeps track of every header that we've set from _headers
315
+ // because we want to combine user declared headers but overwrite
316
+ // existing and extra ones
317
+ const setMap = new Set();
318
+ // Apply every matched rule in order
319
+ matches.forEach(({ set = {}, unset = [] }) => {
320
+ Object.keys(set).forEach((key) => {
321
+ if (setMap.has(key.toLowerCase())) {
322
+ headers.append(key, set[key]);
323
+ } else {
324
+ headers.set(key, set[key]);
325
+ setMap.add(key.toLowerCase());
326
+ }
327
+ });
328
+ unset.forEach((key) => {
329
+ headers.delete(key);
330
+ });
331
+ });
332
+
333
+ if (earlyHintsCache) {
334
+ const preEarlyHintsHeaders = new Headers(headers);
335
+
336
+ // "Early Hints cache entries are keyed by request URI and ignore query strings."
337
+ // https://developers.cloudflare.com/cache/about/early-hints/
338
+ const earlyHintsCacheKey = `${protocol}//${host}${pathname}`;
339
+ const earlyHintsResponse = await earlyHintsCache.match(
340
+ earlyHintsCacheKey
341
+ );
342
+ if (earlyHintsResponse) {
343
+ const earlyHintsLinkHeader = earlyHintsResponse.headers.get("Link");
344
+ if (earlyHintsLinkHeader) {
345
+ headers.set("Link", earlyHintsLinkHeader);
346
+ }
347
+ }
348
+
349
+ const clonedResponse = response.clone();
350
+
351
+ if (waitUntil) {
352
+ waitUntil(
353
+ (async () => {
354
+ try {
355
+ const links: { href: string; rel: string; as?: string }[] = [];
356
+
357
+ const transformedResponse = new HTMLRewriter()
358
+ .on("link[rel=preconnect],link[rel=preload]", {
359
+ element(element) {
360
+ const href = element.getAttribute("href") || undefined;
361
+ const rel = element.getAttribute("rel") || undefined;
362
+ const as = element.getAttribute("as") || undefined;
363
+ if (href && !href.startsWith("data:") && rel) {
364
+ links.push({ href, rel, as });
365
+ }
366
+ },
367
+ })
368
+ .transform(clonedResponse);
369
+
370
+ // Needed to actually execute the HTMLRewriter handlers
371
+ await transformedResponse.text();
372
+
373
+ links.forEach(({ href, rel, as }) => {
374
+ let link = `<${href}>; rel="${rel}"`;
375
+ if (as) {
376
+ link += `; as=${as}`;
377
+ }
378
+ preEarlyHintsHeaders.append("Link", link);
379
+ });
380
+
381
+ const linkHeader = preEarlyHintsHeaders.get("Link");
382
+ if (linkHeader) {
383
+ await earlyHintsCache.put(
384
+ earlyHintsCacheKey,
385
+ new Response(null, { headers: { Link: linkHeader } })
386
+ );
387
+ }
388
+ } catch (err) {
389
+ // Nbd if we fail here in the deferred 'waitUntil' work. We're probably trying to parse a malformed page or something.
390
+ // Totally fine to skip over any errors.
391
+ // If we need to debug something, you can uncomment the following:
392
+ // logError(err)
393
+ }
394
+ })()
395
+ );
396
+ }
397
+ }
398
+
399
+ // https://fetch.spec.whatwg.org/#null-body-status
400
+ return new Response(
401
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
402
+ {
403
+ headers: headers,
404
+ status: response.status,
405
+ statusText: response.statusText,
406
+ }
407
+ );
408
+ }
409
+
410
+ return await attachHeaders(await generateResponse());
411
+
412
+ async function serveAsset(
413
+ servingAssetEntry: AssetEntry,
414
+ options = { preserve: true }
415
+ ): Promise<Response> {
416
+ let content: ContentNegotiation;
417
+ try {
418
+ content = negotiateContent(request, servingAssetEntry);
419
+ } catch (err) {
420
+ return new NotAcceptableResponse();
421
+ }
422
+
423
+ const assetKey = getAssetKey(servingAssetEntry, content);
424
+
425
+ // https://support.cloudflare.com/hc/en-us/articles/218505467-Using-ETag-Headers-with-Cloudflare
426
+ // We sometimes remove etags unless they are wrapped in quotes
427
+ const etag = `"${assetKey}"`;
428
+ const weakEtag = `W/${etag}`;
429
+
430
+ const ifNoneMatch = request.headers.get("if-none-match");
431
+
432
+ // We sometimes downgrade strong etags to a weak ones, so we need to check for both
433
+ if (ifNoneMatch === weakEtag || ifNoneMatch === etag) {
434
+ return new NotModifiedResponse();
435
+ }
436
+
437
+ try {
438
+ const asset = await fetchAsset(assetKey);
439
+ const headers: Record<string, string> = {
440
+ etag,
441
+ "content-type": asset.contentType,
442
+ };
443
+ let encodeBody: BodyEncoding = "automatic";
444
+
445
+ if (xServerEnvHeader) {
446
+ headers["x-server-env"] = xServerEnvHeader;
447
+ }
448
+
449
+ if (content.encoding) {
450
+ encodeBody = "manual";
451
+ headers["cache-control"] = "no-transform";
452
+ headers["content-encoding"] = content.encoding;
453
+ }
454
+
455
+ const response = new OkResponse(
456
+ request.method === "HEAD" ? null : asset.body,
457
+ {
458
+ headers,
459
+ encodeBody,
460
+ }
461
+ );
462
+
463
+ if (isCacheable(request)) {
464
+ response.headers.append("cache-control", CACHE_CONTROL_BROWSER);
465
+ }
466
+
467
+ attachAdditionalHeaders(response, content, servingAssetEntry, asset);
468
+
469
+ if (isPreview(new URL(request.url))) {
470
+ response.headers.set("x-robots-tag", "noindex");
471
+ }
472
+
473
+ if (options.preserve) {
474
+ // https://fetch.spec.whatwg.org/#null-body-status
475
+ const preservedResponse = new Response(
476
+ [101, 204, 205, 304].includes(response.status)
477
+ ? null
478
+ : response.clone().body,
479
+ response
480
+ );
481
+ preservedResponse.headers.set(
482
+ "cache-control",
483
+ CACHE_CONTROL_PRESERVATION
484
+ );
485
+ preservedResponse.headers.set("x-robots-tag", "noindex");
486
+
487
+ if (waitUntil && caches) {
488
+ waitUntil(
489
+ caches
490
+ .open(ASSET_PRESERVATION_CACHE)
491
+ .then((assetPreservationCache) =>
492
+ assetPreservationCache.put(request.url, preservedResponse)
493
+ )
494
+ .catch((err) => {
495
+ logError(err);
496
+ })
497
+ );
498
+ }
499
+ }
500
+
501
+ if (
502
+ asset.contentType.startsWith("text/html") &&
503
+ metadata.analytics?.version === ANALYTICS_VERSION
504
+ ) {
505
+ return new HTMLRewriter()
506
+ .on("body", {
507
+ element(e) {
508
+ e.append(
509
+ `<!-- Cloudflare Pages Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "${metadata.analytics?.token}"}'></script><!-- Cloudflare Pages Analytics -->`,
510
+ { html: true }
511
+ );
512
+ },
513
+ })
514
+ .transform(response);
515
+ }
516
+
517
+ return response;
518
+ } catch (err) {
519
+ logError(err as Error);
520
+ return new InternalServerErrorResponse(err as Error);
521
+ }
522
+ }
523
+
524
+ async function notFound(): Promise<Response> {
525
+ if (caches) {
526
+ const assetPreservationCache = await caches.open(
527
+ ASSET_PRESERVATION_CACHE
528
+ );
529
+ const preservedResponse = await assetPreservationCache.match(request.url);
530
+ if (preservedResponse) {
531
+ return preservedResponse;
532
+ }
533
+ }
534
+
535
+ // Traverse upwards from the current path looking for a custom 404 page
536
+ let cwd = pathname;
537
+ while (cwd) {
538
+ cwd = cwd.slice(0, cwd.lastIndexOf("/"));
539
+
540
+ if ((assetEntry = await findAssetEntryForPath(`${cwd}/404.html`))) {
541
+ let content: ContentNegotiation;
542
+ try {
543
+ content = negotiateContent(request, assetEntry);
544
+ } catch (err) {
545
+ return new NotAcceptableResponse();
546
+ }
547
+
548
+ const assetKey = getAssetKey(assetEntry, content);
549
+
550
+ try {
551
+ const { body, contentType } = await fetchAsset(assetKey);
552
+ const response = new NotFoundResponse(body);
553
+ response.headers.set("content-type", contentType);
554
+ return response;
555
+ } catch (err) {
556
+ logError(err as Error);
557
+ return new InternalServerErrorResponse(err as Error);
558
+ }
559
+ }
560
+ }
561
+
562
+ return await generateNotFoundResponse(
563
+ request,
564
+ findAssetEntryForPath,
565
+ serveAsset
566
+ );
567
+ }
568
+ }
569
+
570
+ // Parses a list such as "deflate, gzip;q=1.0, *;q=0.5" into
571
+ // {deflate: 1, gzip: 1, *: 0.5}
572
+ export function parseQualityWeightedList(list = "") {
573
+ const items: Record<string, number> = {};
574
+ list
575
+ .replace(/\s/g, "")
576
+ .split(",")
577
+ .forEach((el) => {
578
+ const [item, weight] = el.split(";q=");
579
+ items[item] = weight ? parseFloat(weight) : 1;
580
+ });
581
+
582
+ return items;
583
+ }
584
+
585
+ function isCacheable(request: Request) {
586
+ return !request.headers.has("authorization") && !request.headers.has("range");
587
+ }
588
+
589
+ function hasFileExtension(path: string) {
590
+ return /\/.+\.[a-z0-9]+$/i.test(path);
591
+ }
592
+
593
+ // Parses a request URL hostname to determine if the request
594
+ // is from a project served in "preview" mode.
595
+ function isPreview(url: URL): boolean {
596
+ if (url.hostname.endsWith(".pages.dev")) {
597
+ return url.hostname.split(".").length > 3 ? true : false;
598
+ }
599
+ return false;
600
+ }
@@ -0,0 +1,66 @@
1
+ // TODO: Use types from metadata-generator instead
2
+
3
+ export type MetadataStaticRedirectEntry = {
4
+ status: number;
5
+ to: string;
6
+ lineNumber: number;
7
+ };
8
+
9
+ export type MetadataRedirectEntry = {
10
+ status: number;
11
+ to: string;
12
+ lineNumber?: number;
13
+ };
14
+
15
+ export type MetadataStaticRedirects = {
16
+ [path: string]: MetadataStaticRedirectEntry;
17
+ };
18
+
19
+ export type MetadataRedirects = {
20
+ [path: string]: MetadataRedirectEntry;
21
+ };
22
+
23
+ // v1 Types
24
+ export type MetadataHeadersEntries = Record<string, string>;
25
+
26
+ export type MetadataHeadersRulesV1 = {
27
+ [path: string]: MetadataHeadersEntries;
28
+ };
29
+
30
+ export type MetadataHeadersV1 = {
31
+ version: number; // TODO: This could be 1
32
+ rules: MetadataHeadersRulesV1;
33
+ };
34
+
35
+ // v2 Types
36
+ export type SetHeaders = MetadataHeadersEntries;
37
+
38
+ export type UnsetHeaders = Array<string>;
39
+
40
+ export type MetadataHeadersRulesV2 = {
41
+ [path: string]: MetadataHeaderEntry;
42
+ };
43
+
44
+ export type MetadataHeaderEntry = {
45
+ set?: SetHeaders;
46
+ unset?: UnsetHeaders;
47
+ };
48
+
49
+ export type MetadataHeadersV2 = {
50
+ version: number; // TODO: This could be 2
51
+ rules: MetadataHeadersRulesV2;
52
+ };
53
+
54
+ export type Metadata = {
55
+ redirects?: {
56
+ version: number;
57
+ staticRules?: MetadataStaticRedirects;
58
+ rules: MetadataRedirects;
59
+ };
60
+ headers?: MetadataHeadersV1 | MetadataHeadersV2;
61
+ analytics?: {
62
+ version: number;
63
+ token: string;
64
+ };
65
+ deploymentId?: string;
66
+ };
@@ -0,0 +1,22 @@
1
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2
+ // @ts-nocheck
3
+ globalThis.URL = (function (globalURL) {
4
+ PatchedURL.prototype = globalURL.prototype;
5
+ PatchedURL.createObjectURL = globalURL.createObjectURL;
6
+ PatchedURL.revokeObjectURL = globalURL.revokeObjectURL;
7
+
8
+ return PatchedURL as unknown as typeof globalURL;
9
+
10
+ function PatchedURL(input: string, base?: string | URL) {
11
+ const url = new URL(encodeURI(input), base);
12
+
13
+ return new Proxy(url, {
14
+ get(target, prop) {
15
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
+ return globalThis.decodeURIComponent((target as any)[prop]);
17
+ },
18
+ });
19
+ }
20
+ })(URL);
21
+
22
+ export {};