@bake-native/core 0.0.0 → 0.1.0-rc.1

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.
Files changed (144) hide show
  1. package/LICENSE +21 -0
  2. package/THIRD_PARTY_NOTICES.txt +548 -0
  3. package/bake-prelude.js +189 -0
  4. package/batch-contract.json +21 -0
  5. package/batch-wire.js +674 -0
  6. package/close-watcher.js +137 -0
  7. package/compat.json +64 -0
  8. package/controls.css +108 -0
  9. package/determinism.js +175 -0
  10. package/devtools.d.ts +13 -0
  11. package/devtools.js +73 -0
  12. package/dialogs.js +59 -0
  13. package/direct-style.js +105 -0
  14. package/direct-table.js +261 -0
  15. package/dist/bake.mjs +2211 -0
  16. package/dist/build-BrSFpaK1.mjs +1 -0
  17. package/dist/build-tools-Dxyl6XAf.mjs +80 -0
  18. package/dist/build-vAPG2xQv.mjs +5516 -0
  19. package/dist/client-Cm7o6dQd.mjs +17544 -0
  20. package/dist/compiler.mjs +4 -0
  21. package/dist/config-B1W8gfZY.mjs +12 -0
  22. package/dist/dev-xZblYmDc.mjs +990 -0
  23. package/dist/direct-report-Bdda-k_Y.mjs +153 -0
  24. package/dist/direct-report-Du44nNWl.mjs +1 -0
  25. package/dist/index.d.mts +176 -0
  26. package/dist/index.mjs +1 -0
  27. package/dist/intl-ROnAp2qO.mjs +75 -0
  28. package/dist/jiti-stub-CKcaShwE.mjs +5 -0
  29. package/dist/native-views-BQ8TtbQj.mjs +8046 -0
  30. package/dist/octane/package.json +5 -0
  31. package/dist/package-D2aYD6A4.mjs +2789 -0
  32. package/dist/react/package.json +13 -0
  33. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  34. package/dist/run-BtyJGAQB.mjs +6632 -0
  35. package/dist/scope-8W2aIuQ9.mjs +262 -0
  36. package/dist/screens/BakeNativeScreen.native.ts +9 -0
  37. package/dist/screens/package.json +5 -0
  38. package/dom-exception.js +31 -0
  39. package/element-api.js +158 -0
  40. package/first-screen.js +30 -0
  41. package/fonts/Geist-Italic-Variable.ttf +0 -0
  42. package/fonts/Geist-Variable.ttf +0 -0
  43. package/fonts/GeistMono-Italic-Variable.ttf +0 -0
  44. package/fonts/GeistMono-Variable.ttf +0 -0
  45. package/fonts/OFL.txt +93 -0
  46. package/fonts/README.md +27 -0
  47. package/fonts/geist-italic.css +8 -0
  48. package/fonts/geist-mono-italic.css +8 -0
  49. package/fonts/geist-mono.css +8 -0
  50. package/fonts/geist.css +8 -0
  51. package/header-icons.json +53 -0
  52. package/host-runtime.js +521 -0
  53. package/image-props.js +17 -0
  54. package/index.d.ts +8 -0
  55. package/index.js +7 -0
  56. package/licenses/Apache-2.0.txt +73 -0
  57. package/locale-entry.d.ts +1 -0
  58. package/locale-entry.js +1 -0
  59. package/locale.d.ts +28 -0
  60. package/locale.js +124 -0
  61. package/markup-support.js +87 -0
  62. package/media-element.js +115 -0
  63. package/native-args-entry.js +2 -0
  64. package/native-args.d.ts +7 -0
  65. package/native-args.js +155 -0
  66. package/native-entry.js +1 -0
  67. package/native-globals.d.ts +166 -0
  68. package/native-scenarios.d.ts +17 -0
  69. package/native-scenarios.js +46 -0
  70. package/native-support.json +366 -0
  71. package/native.d.ts +52 -0
  72. package/native.js +237 -0
  73. package/package.json +143 -4
  74. package/page-elements.js +123 -0
  75. package/runtime-provides.json +412 -0
  76. package/safe-area.d.ts +1 -0
  77. package/safe-area.js +44 -0
  78. package/swift-ui/modifiers.js +176 -0
  79. package/tab-icons.js +62 -0
  80. package/templates/create/tabs/AGENTS.md +22 -0
  81. package/templates/create/tabs/README.md +43 -0
  82. package/templates/create/tabs/_gitignore +13 -0
  83. package/templates/create/tabs/android/app/build.gradle.kts +79 -0
  84. package/templates/create/tabs/android/app/src/main/AndroidManifest.xml +39 -0
  85. package/templates/create/tabs/android/app/src/main/kotlin/MainActivity.kt +35 -0
  86. package/templates/create/tabs/android/app/src/main/res/values/themes.xml +8 -0
  87. package/templates/create/tabs/android/build.gradle.kts +5 -0
  88. package/templates/create/tabs/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  89. package/templates/create/tabs/android/gradle/wrapper/gradle-wrapper.properties +9 -0
  90. package/templates/create/tabs/android/gradle.properties +3 -0
  91. package/templates/create/tabs/android/gradlew +248 -0
  92. package/templates/create/tabs/android/settings.gradle.kts +47 -0
  93. package/templates/create/tabs/bake.config.ts +10 -0
  94. package/templates/create/tabs/ios/App/App.swift +30 -0
  95. package/templates/create/tabs/ios/build.sh +23 -0
  96. package/templates/create/tabs/ios/project.yml +57 -0
  97. package/templates/create/tabs/macos/Package.swift +24 -0
  98. package/templates/create/tabs/macos/Sources/__SWIFT_NAME__/App.swift +146 -0
  99. package/templates/create/tabs/macos/build.sh +4 -0
  100. package/templates/create/tabs/package.json +23 -0
  101. package/templates/create/tabs/pnpm-workspace.yaml +6 -0
  102. package/templates/create/tabs/src/App.tsrx +92 -0
  103. package/templates/create/tabs/src/App.tsx +67 -0
  104. package/templates/create/tabs/src/styles.css +32 -0
  105. package/templates/create/tabs/tsconfig.json +5 -0
  106. package/templates/create/tabs/windows/Cargo.toml +29 -0
  107. package/templates/create/tabs/windows/build.rs +9 -0
  108. package/templates/create/tabs/windows/src/main.rs +52 -0
  109. package/templates/create/tabs/windows/src/shell.rs +316 -0
  110. package/templates/module/__NAME__.kt +20 -0
  111. package/templates/module/__NAME__.native.ts +24 -0
  112. package/templates/module/__NAME__.swift +25 -0
  113. package/templates/module/__NAME__.web.ts +13 -0
  114. package/templates/module/__NAME__Test.kt +26 -0
  115. package/templates/module/__NAME__Tests.swift +25 -0
  116. package/templates/module/__SNAKE__.rs +43 -0
  117. package/text.d.ts +20 -0
  118. package/text.js +100 -0
  119. package/transform-entry.js +1 -0
  120. package/transform.d.ts +15 -0
  121. package/transform.js +98 -0
  122. package/tsconfig.native.json +16 -0
  123. package/ui/scope.js +103 -0
  124. package/ui/swift.js +106 -0
  125. package/ui/ui.css +272 -0
  126. package/view-ref-writer.js +268 -0
  127. package/view-ref.d.ts +26 -0
  128. package/view-ref.js +85 -0
  129. package/views/Video.native.ts +68 -0
  130. package/views/generated/VideoViewAndroid.h +68 -0
  131. package/views/generated/VideoViewJSI.h +94 -0
  132. package/views/generated/VideoViewSpec.kt +113 -0
  133. package/views/generated/apple/VideoViewJSI/VideoViewJSIApple.cpp +40 -0
  134. package/views/generated/apple/VideoViewJSI/include/VideoViewJSIApple.h +28 -0
  135. package/views/generated/apple/VideoViewSpec/VideoViewInterop.swift +39 -0
  136. package/views/generated/apple/VideoViewSpec/VideoViewSpec.swift +186 -0
  137. package/views/generated/video_view_spec.rs +189 -0
  138. package/views.d.ts +24 -0
  139. package/views.js +45 -0
  140. package/virtual-window.js +35 -0
  141. package/visibility.js +75 -0
  142. package/web-crypto.js +84 -0
  143. package/web-fetch.js +1071 -0
  144. package/README.md +0 -3
package/web-fetch.js ADDED
@@ -0,0 +1,1071 @@
1
+ // Web networking on the native targets: fetch, Request, Response, Headers,
2
+ // AbortController / AbortSignal, DOMException, Blob, URL / URLSearchParams and (where the engine
3
+ // lacks them) TextEncoder / TextDecoder. One implementation for every native target; only the
4
+ // byte transport differs per platform (native/rust/crates/bake-runtime/src/net.rs).
5
+ //
6
+ // JS -> core: post('net', {op:'fetch', id, method, url, headers:[[k, v]...], body})
7
+ // post('net', {op:'abort', id})
8
+ // core -> JS: __bakeNet(id, {type:'head', status, statusText, headers, url, redirected, body?})
9
+ // __bakeNet(id, {type:'body', body}) | __bakeNet(id, {type:'error', message})
10
+ // bodies: {text} (UTF-8 text) or {latin1} (one char per byte)
11
+ //
12
+ // Web-identical errors: a network error rejects with TypeError, an abort with the signal's
13
+ // reason (DOMException AbortError by default), AbortSignal.timeout with DOMException
14
+ // TimeoutError. Results arrive on the JS thread; main never waits for the network.
15
+ // Fail closed: ReadableStream bodies (`response.body`, stream request bodies), FormData,
16
+ // `redirect: 'manual'` and non-http(s) schemes throw instead of behaving differently.
17
+ //
18
+ // No imports but DOMException (dom-exception.js, shared with web-crypto.js): host-runtime.js
19
+ // installs it before the app module runs, and web-fetch.test.mjs runs it under node against
20
+ // node's own implementations.
21
+ import { installDOMException } from './dom-exception.js';
22
+
23
+ const S = Symbol('bake.internal');
24
+ const UNSUPPORTED = (what) => new TypeError(`${what} is not supported on native targets yet`);
25
+
26
+ // ------------------------------------------------------------------ text
27
+
28
+ function utf8Encode(str) {
29
+ str = String(str);
30
+ const out = [];
31
+ for (let i = 0; i < str.length; i++) {
32
+ let c = str.charCodeAt(i);
33
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
34
+ const d = str.charCodeAt(i + 1);
35
+ if (d >= 0xdc00 && d <= 0xdfff) {
36
+ c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
37
+ i++;
38
+ } else c = 0xfffd;
39
+ } else if (c >= 0xd800 && c <= 0xdfff) c = 0xfffd;
40
+ if (c < 0x80) out.push(c);
41
+ else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
42
+ else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
43
+ else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
44
+ }
45
+ return new Uint8Array(out);
46
+ }
47
+
48
+ // The WHATWG UTF-8 decoder: one U+FFFD per maximal invalid subsequence.
49
+ function utf8Decode(bytes, fatal) {
50
+ let out = '';
51
+ let chunk = [];
52
+ const emit = (c) => {
53
+ if (c >= 0x10000) {
54
+ c -= 0x10000;
55
+ chunk.push(0xd800 + (c >> 10), 0xdc00 + (c & 0x3ff));
56
+ } else chunk.push(c);
57
+ if (chunk.length > 8000) {
58
+ out += String.fromCharCode.apply(null, chunk);
59
+ chunk = [];
60
+ }
61
+ };
62
+ const bad = () => {
63
+ if (fatal) throw new TypeError('The encoded data was not valid for encoding utf-8');
64
+ emit(0xfffd);
65
+ };
66
+ let cp = 0, needed = 0, seen = 0, lower = 0x80, upper = 0xbf;
67
+ for (let i = 0; i < bytes.length; i++) {
68
+ const b = bytes[i];
69
+ if (needed === 0) {
70
+ if (b <= 0x7f) emit(b);
71
+ else if (b >= 0xc2 && b <= 0xdf) { needed = 1; cp = b & 0x1f; }
72
+ else if (b >= 0xe0 && b <= 0xef) {
73
+ if (b === 0xe0) lower = 0xa0;
74
+ if (b === 0xed) upper = 0x9f;
75
+ needed = 2; cp = b & 0xf;
76
+ } else if (b >= 0xf0 && b <= 0xf4) {
77
+ if (b === 0xf0) lower = 0x90;
78
+ if (b === 0xf4) upper = 0x8f;
79
+ needed = 3; cp = b & 7;
80
+ } else bad();
81
+ continue;
82
+ }
83
+ if (b < lower || b > upper) {
84
+ cp = needed = seen = 0;
85
+ lower = 0x80; upper = 0xbf;
86
+ bad();
87
+ i--; // the byte starts over
88
+ continue;
89
+ }
90
+ lower = 0x80; upper = 0xbf;
91
+ cp = (cp << 6) | (b & 0x3f);
92
+ if (++seen === needed) {
93
+ emit(cp);
94
+ cp = needed = seen = 0;
95
+ }
96
+ }
97
+ if (needed) bad();
98
+ return out + String.fromCharCode.apply(null, chunk);
99
+ }
100
+
101
+ function bytesOf(input) {
102
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
103
+ if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
104
+ throw new TypeError('The provided value is not of type (ArrayBuffer or ArrayBufferView)');
105
+ }
106
+
107
+ class TextEncoderPolyfill {
108
+ get encoding() { return 'utf-8'; }
109
+ encode(input = '') { return utf8Encode(input); }
110
+ }
111
+
112
+ class TextDecoderPolyfill {
113
+ constructor(label = 'utf-8', options = {}) {
114
+ const l = String(label).trim().toLowerCase();
115
+ if (l !== 'utf-8' && l !== 'utf8' && l !== 'unicode-1-1-utf-8') throw new RangeError(`The encoding label provided ('${label}') is invalid.`);
116
+ this[S] = { fatal: !!options.fatal, ignoreBOM: !!options.ignoreBOM };
117
+ }
118
+ get encoding() { return 'utf-8'; }
119
+ get fatal() { return this[S].fatal; }
120
+ get ignoreBOM() { return this[S].ignoreBOM; }
121
+ decode(input) {
122
+ if (input === undefined) return '';
123
+ let b = bytesOf(input);
124
+ if (!this[S].ignoreBOM && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf) b = b.subarray(3);
125
+ return utf8Decode(b, this[S].fatal);
126
+ }
127
+ }
128
+
129
+ // One char per byte: the body form the Hermes bridge can carry both ways.
130
+ function latin1ToBytes(s) {
131
+ const b = new Uint8Array(s.length);
132
+ for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i);
133
+ return b;
134
+ }
135
+ function bytesToLatin1(b) {
136
+ let s = '';
137
+ for (let i = 0; i < b.length; i += 8192) s += String.fromCharCode.apply(null, b.subarray(i, i + 8192));
138
+ return s;
139
+ }
140
+
141
+ // ------------------------------------------------------------------ install
142
+
143
+ export function installWebFetch(g, post) {
144
+ const define = (name, value) => {
145
+ if (typeof g[name] === 'undefined') Object.defineProperty(g, name, { value, writable: true, configurable: true, enumerable: false });
146
+ };
147
+ define('TextEncoder', TextEncoderPolyfill);
148
+ define('TextDecoder', TextDecoderPolyfill);
149
+ const DOMException = installDOMException(g);
150
+ const encoder = new g.TextEncoder();
151
+ const decoder = new g.TextDecoder();
152
+ const setTimeout = (fn, ms) => g.setTimeout(fn, ms);
153
+
154
+ // ---------------------------------------------------------------- AbortSignal
155
+
156
+ const KEY = Symbol('AbortSignal');
157
+ class AbortSignal {
158
+ constructor(key) {
159
+ if (key !== KEY) throw new TypeError('Illegal constructor');
160
+ this[S] = { aborted: false, reason: undefined, listeners: [], algorithms: new Set(), onabort: null };
161
+ }
162
+ get aborted() { return this[S].aborted; }
163
+ get reason() { return this[S].reason; }
164
+ get onabort() { return this[S].onabort; }
165
+ set onabort(fn) { this[S].onabort = typeof fn === 'function' ? fn : null; }
166
+ throwIfAborted() { if (this[S].aborted) throw this[S].reason; }
167
+ addEventListener(type, listener, options) {
168
+ if (type !== 'abort' || listener == null) return;
169
+ const once = typeof options === 'object' && options !== null && !!options.once;
170
+ const s = this[S];
171
+ if (!s.listeners.some((l) => l.fn === listener)) s.listeners.push({ fn: listener, once });
172
+ }
173
+ removeEventListener(type, listener) {
174
+ if (type !== 'abort') return;
175
+ const s = this[S];
176
+ s.listeners = s.listeners.filter((l) => l.fn !== listener);
177
+ }
178
+ dispatchEvent(event) {
179
+ const s = this[S];
180
+ const call = (fn) => {
181
+ try {
182
+ if (typeof fn === 'function') fn.call(this, event);
183
+ else if (fn && typeof fn.handleEvent === 'function') fn.handleEvent(event);
184
+ } catch (e) {
185
+ if (g.console) g.console.error(e && e.stack ? e.stack : String(e));
186
+ }
187
+ };
188
+ if (event.type === 'abort' && s.onabort) call(s.onabort);
189
+ for (const l of s.listeners.slice()) {
190
+ if (event.type !== 'abort') continue;
191
+ if (l.once) this.removeEventListener('abort', l.fn);
192
+ call(l.fn);
193
+ }
194
+ return true;
195
+ }
196
+ static abort(reason) {
197
+ const s = new AbortSignal(KEY);
198
+ signalAbort(s, reason);
199
+ return s;
200
+ }
201
+ static timeout(ms) {
202
+ ms = Number(ms);
203
+ if (!(ms >= 0) || ms > Number.MAX_SAFE_INTEGER) throw new TypeError("Failed to execute 'timeout' on 'AbortSignal': Value is outside the 'unsigned long long' value range.");
204
+ const s = new AbortSignal(KEY);
205
+ setTimeout(() => signalAbort(s, new DOMException('signal timed out', 'TimeoutError')), ms);
206
+ return s;
207
+ }
208
+ static any(signals) {
209
+ const s = new AbortSignal(KEY);
210
+ const list = Array.from(signals);
211
+ for (const t of list) {
212
+ if (!(t instanceof AbortSignal)) throw new TypeError("Failed to execute 'any' on 'AbortSignal': Failed to convert value to 'AbortSignal'.");
213
+ if (t.aborted) {
214
+ signalAbort(s, t.reason);
215
+ return s;
216
+ }
217
+ }
218
+ for (const t of list) t[S].algorithms.add(() => signalAbort(s, t.reason));
219
+ return s;
220
+ }
221
+ }
222
+ Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { value: 'AbortSignal' });
223
+
224
+ function signalAbort(signal, reason) {
225
+ const s = signal[S];
226
+ if (s.aborted) return;
227
+ s.aborted = true;
228
+ s.reason = reason === undefined ? new DOMException('signal is aborted without reason', 'AbortError') : reason;
229
+ const algorithms = [...s.algorithms];
230
+ s.algorithms.clear();
231
+ for (const run of algorithms) run();
232
+ signal.dispatchEvent({ type: 'abort', target: signal, currentTarget: signal, bubbles: false, cancelable: false, isTrusted: true, defaultPrevented: false });
233
+ }
234
+
235
+ class AbortController {
236
+ constructor() { this[S] = new AbortSignal(KEY); }
237
+ get signal() { return this[S]; }
238
+ abort(reason) { signalAbort(this[S], reason); }
239
+ }
240
+ Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { value: 'AbortController' });
241
+
242
+ // ---------------------------------------------------------------- URLSearchParams
243
+
244
+ const FORM_SAFE = /[A-Za-z0-9*\-._]/;
245
+ // A URL's searchParams writes the query back (URL sets update).
246
+ const noUpdate = () => {};
247
+ function formEncode(s) {
248
+ let out = '';
249
+ for (const b of encoder.encode(String(s))) {
250
+ const c = String.fromCharCode(b);
251
+ if (b === 0x20) out += '+';
252
+ else if (b < 0x80 && FORM_SAFE.test(c)) out += c;
253
+ else out += '%' + (b < 16 ? '0' : '') + b.toString(16).toUpperCase();
254
+ }
255
+ return out;
256
+ }
257
+ function percentDecode(s) {
258
+ if (s.indexOf('%') < 0) return s;
259
+ const bytes = encoder.encode(s);
260
+ const out = [];
261
+ for (let i = 0; i < bytes.length; i++) {
262
+ const b = bytes[i];
263
+ if (b === 0x25 && i + 2 < bytes.length) {
264
+ const h = String.fromCharCode(bytes[i + 1], bytes[i + 2]);
265
+ if (/^[0-9a-fA-F]{2}$/.test(h)) {
266
+ out.push(parseInt(h, 16));
267
+ i += 2;
268
+ continue;
269
+ }
270
+ }
271
+ out.push(b);
272
+ }
273
+ return utf8Decode(new Uint8Array(out), false);
274
+ }
275
+ function parseForm(s) {
276
+ const list = [];
277
+ for (const part of s.split('&')) {
278
+ if (part === '') continue;
279
+ const eq = part.indexOf('=');
280
+ const name = eq < 0 ? part : part.slice(0, eq);
281
+ const value = eq < 0 ? '' : part.slice(eq + 1);
282
+ list.push([percentDecode(name.replace(/\+/g, ' ')), percentDecode(value.replace(/\+/g, ' '))]);
283
+ }
284
+ return list;
285
+ }
286
+ const usv = (v) => String(v).replace(/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g, (m) => m.replace(/[\ud800-\udfff]/, '\ufffd'));
287
+
288
+ class URLSearchParams {
289
+ constructor(init = '') {
290
+ this[S] = { list: [], update: noUpdate };
291
+ if (init instanceof URLSearchParams) this[S].list = init[S].list.map((p) => p.slice());
292
+ else if (init !== null && typeof init === 'object' && typeof init[Symbol.iterator] === 'function') {
293
+ for (const pair of init) {
294
+ const p = Array.from(pair);
295
+ if (p.length !== 2) throw new TypeError("Failed to construct 'URLSearchParams': Sequence initializer must only contain pair elements");
296
+ this[S].list.push([usv(p[0]), usv(p[1])]);
297
+ }
298
+ } else if (init !== null && typeof init === 'object') {
299
+ for (const k of Object.keys(init)) this[S].list.push([usv(k), usv(init[k])]);
300
+ } else {
301
+ let s = usv(init);
302
+ if (s[0] === '?') s = s.slice(1);
303
+ this[S].list = parseForm(s);
304
+ }
305
+ }
306
+ get size() { return this[S].list.length; }
307
+ append(name, value) { this[S].list.push([usv(name), usv(value)]); this[S].update(); }
308
+ delete(name, value) {
309
+ name = usv(name);
310
+ this[S].list = this[S].list.filter(([n, v]) => n !== name || (value !== undefined && v !== usv(value)));
311
+ this[S].update();
312
+ }
313
+ get(name) { name = usv(name); const p = this[S].list.find(([n]) => n === name); return p ? p[1] : null; }
314
+ getAll(name) { name = usv(name); return this[S].list.filter(([n]) => n === name).map((p) => p[1]); }
315
+ has(name, value) { name = usv(name); return this[S].list.some(([n, v]) => n === name && (value === undefined || v === usv(value))); }
316
+ set(name, value) {
317
+ name = usv(name);
318
+ value = usv(value);
319
+ const list = this[S].list;
320
+ const i = list.findIndex(([n]) => n === name);
321
+ if (i < 0) list.push([name, value]);
322
+ else {
323
+ list[i][1] = value;
324
+ this[S].list = list.filter(([n], j) => j <= i || n !== name);
325
+ }
326
+ this[S].update();
327
+ }
328
+ sort() {
329
+ // Stable, by UTF-16 code units.
330
+ this[S].list = this[S].list.map((p, i) => [p, i]).sort((a, b) => (a[0][0] < b[0][0] ? -1 : a[0][0] > b[0][0] ? 1 : a[1] - b[1])).map((x) => x[0]);
331
+ this[S].update();
332
+ }
333
+ forEach(fn, thisArg) { for (const [n, v] of this[S].list.slice()) fn.call(thisArg, v, n, this); }
334
+ *entries() { for (const p of this[S].list) yield [p[0], p[1]]; }
335
+ *keys() { for (const p of this[S].list) yield p[0]; }
336
+ *values() { for (const p of this[S].list) yield p[1]; }
337
+ [Symbol.iterator]() { return this.entries(); }
338
+ toString() { return this[S].list.map(([n, v]) => formEncode(n) + '=' + formEncode(v)).join('&'); }
339
+ }
340
+ Object.defineProperty(URLSearchParams.prototype, Symbol.toStringTag, { value: 'URLSearchParams' });
341
+
342
+ // ---------------------------------------------------------------- URL
343
+
344
+ const SPECIAL = { 'http:': '80', 'https:': '443', 'ws:': '80', 'wss:': '443', 'ftp:': '21', 'file:': '' };
345
+ const hex = (b) => '%' + (b < 16 ? '0' : '') + b.toString(16).toUpperCase();
346
+ function encodeSet(s, extra) {
347
+ let out = '';
348
+ for (let i = 0; i < s.length; i++) {
349
+ const ch = s[i];
350
+ const c = s.charCodeAt(i);
351
+ if (c >= 0x21 && c <= 0x7e && extra.indexOf(ch) < 0) out += ch;
352
+ else if (c < 0x80) out += hex(c);
353
+ else {
354
+ let cp = ch;
355
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) { cp += s[i + 1]; i++; }
356
+ for (const b of encoder.encode(cp)) out += hex(b);
357
+ }
358
+ }
359
+ return out;
360
+ }
361
+ // Opaque paths (mailto:, data:): only C0 controls and non-ASCII are encoded.
362
+ const encodeC0 = (s) => s.replace(/[\x00-\x1f\x7f-\uffff]+/g, (m) => encodeSet(m, ''));
363
+ // WHATWG percent-encode sets (the code points above 0x20 they add).
364
+ const FRAGMENT_SET = ' "<>`';
365
+ const QUERY_SET = ' "#<>';
366
+ const SPECIAL_QUERY_SET = QUERY_SET + "'";
367
+ const PATH_SET = QUERY_SET + '?^`{}';
368
+ const USERINFO_SET = PATH_SET + '/:;=@[\\]|';
369
+ const encPath = (s) => encodeSet(s, PATH_SET).replace(/%25(?=[0-9A-Fa-f]{2})/g, '%');
370
+ const keepEscapes = (s) => s.replace(/%25(?=[0-9A-Fa-f]{2})/g, '%');
371
+
372
+ function parseHost(input, special) {
373
+ if (input[0] === '[') {
374
+ if (input[input.length - 1] !== ']' || !/^\[[0-9a-fA-F:.]+\]$/.test(input)) throw null;
375
+ return input.toLowerCase();
376
+ }
377
+ if (!special) {
378
+ if (/[\0\t\n\r #/<>?@[\\\]^|]/.test(input)) throw null;
379
+ return encodeSet(input, ' "<>`');
380
+ }
381
+ const host = percentDecode(input).toLowerCase();
382
+ if (host === '') throw null;
383
+ // Internationalized names need IDNA (punycode): fail closed rather than send a wrong host.
384
+ if (/[^\x00-\x7f]/.test(host)) throw new TypeError(`Failed to construct 'URL': Invalid URL (non-ASCII host names are not supported on native targets yet)`);
385
+ if (/[\0\t\n\r #%/:<>?@[\\\]^|]/.test(host)) throw null;
386
+ // IPv4 in decimal / hex / octal parts.
387
+ const parts = host.split('.');
388
+ if (parts[parts.length - 1] === '') parts.pop();
389
+ if (parts.length && /^(0x[0-9a-f]*|\d+)$/.test(parts[parts.length - 1])) {
390
+ if (parts.length > 4) throw null;
391
+ const nums = parts.map((p) => {
392
+ if (/^0x[0-9a-f]*$/.test(p)) return p.length === 2 ? 0 : parseInt(p.slice(2), 16);
393
+ if (/^0[0-7]+$/.test(p)) return parseInt(p.slice(1), 8);
394
+ if (/^\d+$/.test(p) && !/^0\d/.test(p)) return parseInt(p, 10);
395
+ throw null;
396
+ });
397
+ const last = nums.pop();
398
+ if (nums.some((n) => n > 255) || last >= 256 ** (4 - nums.length)) throw null;
399
+ let v = last;
400
+ nums.forEach((n, i) => { v += n * 256 ** (3 - i); });
401
+ return [v >>> 24, (v >>> 16) & 255, (v >>> 8) & 255, v & 255].join('.');
402
+ }
403
+ return host;
404
+ }
405
+
406
+ // Resolves `.` and `..` segments; a trailing one leaves an empty last segment (`/a/`).
407
+ function normalizePath(segments) {
408
+ const out = [];
409
+ segments.forEach((seg, i) => {
410
+ const s = seg.toLowerCase();
411
+ const last = i === segments.length - 1;
412
+ if (s === '..' || s === '.%2e' || s === '%2e.' || s === '%2e%2e') {
413
+ if (out.length) out.pop();
414
+ if (last) out.push('');
415
+ } else if (s === '.' || s === '%2e') {
416
+ if (last) out.push('');
417
+ } else out.push(seg);
418
+ });
419
+ return out;
420
+ }
421
+
422
+ function parseURL(input, base) {
423
+ let s = String(input).replace(/^[\0- ]+|[\0- ]+$/g, '').replace(/[\t\n\r]/g, '');
424
+ const m = /^([a-zA-Z][a-zA-Z0-9+\-.]*):/.exec(s);
425
+ let r;
426
+ if (m) {
427
+ const protocol = m[1].toLowerCase() + ':';
428
+ const rest = s.slice(m[0].length);
429
+ const special = protocol in SPECIAL;
430
+ if (special) {
431
+ if (base && base.protocol === protocol && !/^[/\\]/.test(rest)) return resolve(rest, base);
432
+ r = parseAuthorityAndPath(protocol, rest.replace(/^[/\\]*/, ''), true);
433
+ } else if (rest.startsWith('//')) {
434
+ r = parseAuthorityAndPath(protocol, rest.slice(2), false);
435
+ } else {
436
+ // Opaque path (mailto:, data:, ...) or a path-only URL.
437
+ const split = splitQueryHash(rest, false);
438
+ const path = rest.startsWith('/') ? '/' + normalizePath(split.path.slice(1).split('/')).map(encPath).join('/') : encodeC0(split.path);
439
+ r = { protocol, username: '', password: '', hostname: '', port: '', auth: false, pathname: path, search: split.search, hash: split.hash, opaque: !rest.startsWith('/') };
440
+ }
441
+ } else {
442
+ if (!base) throw null;
443
+ r = resolve(s, base);
444
+ }
445
+ return r;
446
+ }
447
+
448
+ function splitQueryHash(rest, special) {
449
+ let hash = '', search = '';
450
+ const h = rest.indexOf('#');
451
+ if (h >= 0) { hash = rest.slice(h + 1); rest = rest.slice(0, h); }
452
+ const q = rest.indexOf('?');
453
+ if (q >= 0) { search = rest.slice(q + 1); rest = rest.slice(0, q); }
454
+ return {
455
+ path: rest,
456
+ search: q >= 0 ? '?' + keepEscapes(encodeSet(search, special ? SPECIAL_QUERY_SET : QUERY_SET)) : '',
457
+ hash: h >= 0 ? '#' + keepEscapes(encodeSet(hash, FRAGMENT_SET)) : '',
458
+ };
459
+ }
460
+
461
+ function parseAuthorityAndPath(protocol, rest, special) {
462
+ const end = rest.search(special ? /[/\\?#]/ : /[/?#]/);
463
+ const authority = end < 0 ? rest : rest.slice(0, end);
464
+ const after = end < 0 ? '' : rest.slice(end);
465
+ let username = '', password = '', hostport = authority;
466
+ const at = authority.lastIndexOf('@');
467
+ if (at >= 0) {
468
+ const info = authority.slice(0, at);
469
+ hostport = authority.slice(at + 1);
470
+ const colon = info.indexOf(':');
471
+ username = keepEscapes(encodeSet(colon < 0 ? info : info.slice(0, colon), USERINFO_SET));
472
+ password = colon < 0 ? '' : keepEscapes(encodeSet(info.slice(colon + 1), USERINFO_SET));
473
+ }
474
+ let hostname = hostport, port = '';
475
+ const pm = /:(\d*)$/.exec(hostport);
476
+ if (pm && !/^\[[^\]]*$/.test(hostport.slice(0, pm.index))) {
477
+ hostname = hostport.slice(0, pm.index);
478
+ if (pm[1] !== '') {
479
+ const n = parseInt(pm[1], 10);
480
+ if (n > 65535) throw null;
481
+ port = String(n) === SPECIAL[protocol] ? '' : String(n);
482
+ }
483
+ } else if (/:[^\]]*$/.test(hostport) && hostport[0] !== '[') throw null;
484
+ if (hostname === '' && special && protocol !== 'file:') throw null;
485
+ hostname = hostname === '' ? '' : parseHost(hostname, special);
486
+ const split = splitQueryHash(special ? after.replace(/\\/g, (c, i) => (after.slice(0, i).match(/[?#]/) ? c : '/')) : after, special);
487
+ let segments = split.path === '' ? (special ? [''] : []) : split.path.slice(1).split('/');
488
+ segments = normalizePath(segments);
489
+ const pathname = split.path === '' && !special ? '' : '/' + segments.map(encPath).join('/');
490
+ return { protocol, username, password, hostname, port, auth: true, pathname, search: split.search, hash: split.hash, opaque: false };
491
+ }
492
+
493
+ function resolve(rel, base) {
494
+ const special = base.protocol in SPECIAL;
495
+ const r = { ...base, hash: '' };
496
+ if (base.opaque) {
497
+ if (rel[0] !== '#') throw null;
498
+ r.hash = splitQueryHash(rel, special).hash;
499
+ return r;
500
+ }
501
+ if (rel === '') return r;
502
+ if (/^[/\\]{2}/.test(rel) && (special || rel.startsWith('//'))) return parseAuthorityAndPath(base.protocol, rel.slice(2), special);
503
+ if (rel[0] === '#') { r.hash = splitQueryHash(rel, special).hash; return r; }
504
+ if (rel[0] === '?') {
505
+ const split = splitQueryHash(rel, special);
506
+ r.search = split.search;
507
+ r.hash = split.hash;
508
+ return r;
509
+ }
510
+ const split = splitQueryHash(special ? rel.replace(/\\/g, '/') : rel, special);
511
+ let segments;
512
+ if (split.path[0] === '/') segments = split.path.slice(1).split('/');
513
+ else {
514
+ const dir = base.pathname.split('/').slice(1, -1);
515
+ segments = dir.concat(split.path.split('/'));
516
+ }
517
+ r.pathname = '/' + normalizePath(segments).map(encPath).join('/');
518
+ r.search = split.search;
519
+ r.hash = split.hash;
520
+ return r;
521
+ }
522
+
523
+ const invalid = (input) => new TypeError(`Failed to construct 'URL': Invalid URL${input === undefined ? '' : ` '${input}'`}`);
524
+
525
+ class URL {
526
+ constructor(url, base) {
527
+ let b;
528
+ if (base !== undefined) {
529
+ try { b = parseURL(base instanceof URL ? base.href : base); } catch (e) { throw e instanceof TypeError ? e : invalid(base); }
530
+ }
531
+ try { this[S] = parseURL(url instanceof URL ? url.href : url, b); } catch (e) { throw e instanceof TypeError ? e : invalid(url); }
532
+ const params = new URLSearchParams(this[S].search);
533
+ params[S].update = () => {
534
+ const q = params.toString();
535
+ this[S].search = q ? '?' + q : '';
536
+ };
537
+ this[S].params = params;
538
+ }
539
+ static canParse(url, base) { try { new URL(url, base); return true; } catch { return false; } }
540
+ static parse(url, base) { try { return new URL(url, base); } catch { return null; } }
541
+ get href() {
542
+ const r = this[S];
543
+ let auth = '';
544
+ if (r.auth) {
545
+ auth = '//';
546
+ if (r.username || r.password) auth += r.username + (r.password ? ':' + r.password : '') + '@';
547
+ auth += r.hostname + (r.port ? ':' + r.port : '');
548
+ } else if (!r.opaque && r.pathname.startsWith('//')) auth = '/.';
549
+ return r.protocol + auth + r.pathname + r.search + r.hash;
550
+ }
551
+ set href(v) {
552
+ const r = parseURL(v);
553
+ Object.assign(this[S], r);
554
+ this[S].params[S].list = parseForm(r.search.slice(1));
555
+ }
556
+ get origin() {
557
+ const r = this[S];
558
+ if (r.protocol in SPECIAL && r.protocol !== 'file:') return r.protocol + '//' + r.hostname + (r.port ? ':' + r.port : '');
559
+ return 'null';
560
+ }
561
+ get protocol() { return this[S].protocol; }
562
+ set protocol(v) {
563
+ const p = String(v).replace(/:.*$/, '').toLowerCase() + ':';
564
+ if (!/^[a-z][a-z0-9+\-.]*:$/.test(p) || (p in SPECIAL) !== (this[S].protocol in SPECIAL)) return;
565
+ this[S].protocol = p;
566
+ if (this[S].port === SPECIAL[p]) this[S].port = '';
567
+ }
568
+ get username() { return this[S].username; }
569
+ set username(v) { if (this[S].hostname) this[S].username = keepEscapes(encodeSet(String(v), USERINFO_SET)); }
570
+ get password() { return this[S].password; }
571
+ set password(v) { if (this[S].hostname) this[S].password = keepEscapes(encodeSet(String(v), USERINFO_SET)); }
572
+ get host() { const r = this[S]; return r.hostname + (r.port ? ':' + r.port : ''); }
573
+ set host(v) {
574
+ if (this[S].opaque) return;
575
+ try {
576
+ const r = parseAuthorityAndPath(this[S].protocol, String(v).replace(/[/\\?#].*$/, ''), this[S].protocol in SPECIAL);
577
+ this[S].hostname = r.hostname;
578
+ if (/:\d+$/.test(String(v))) this[S].port = r.port;
579
+ } catch {}
580
+ }
581
+ get hostname() { return this[S].hostname; }
582
+ set hostname(v) {
583
+ if (this[S].opaque) return;
584
+ try { this[S].hostname = parseHost(String(v).replace(/[:/\\?#].*$/, ''), this[S].protocol in SPECIAL); } catch {}
585
+ }
586
+ get port() { return this[S].port; }
587
+ set port(v) {
588
+ const m = /^\d*/.exec(String(v))[0];
589
+ if (!this[S].hostname || this[S].protocol === 'file:') return;
590
+ if (m === '') { if (String(v) === '') this[S].port = ''; return; }
591
+ const n = parseInt(m, 10);
592
+ if (n > 65535) return;
593
+ this[S].port = String(n) === SPECIAL[this[S].protocol] ? '' : String(n);
594
+ }
595
+ get pathname() { return this[S].pathname; }
596
+ set pathname(v) {
597
+ if (this[S].opaque) return;
598
+ const special = this[S].protocol in SPECIAL;
599
+ let p = String(v);
600
+ if (special) p = p.replace(/\\/g, '/');
601
+ const segs = (p[0] === '/' ? p.slice(1) : p).split('/');
602
+ this[S].pathname = '/' + normalizePath(segs).map(encPath).join('/');
603
+ }
604
+ get search() { return this[S].search.length > 1 ? this[S].search : ''; }
605
+ set search(v) {
606
+ let s = String(v);
607
+ if (s[0] === '?') s = s.slice(1);
608
+ this[S].search = s === '' ? '' : '?' + keepEscapes(encodeSet(s, this[S].protocol in SPECIAL ? SPECIAL_QUERY_SET : QUERY_SET));
609
+ this[S].params[S].list = parseForm(s);
610
+ }
611
+ get searchParams() { return this[S].params; }
612
+ get hash() { return this[S].hash.length > 1 ? this[S].hash : ''; }
613
+ set hash(v) {
614
+ let s = String(v);
615
+ if (s[0] === '#') s = s.slice(1);
616
+ this[S].hash = s === '' ? '' : '#' + keepEscapes(encodeSet(s, FRAGMENT_SET));
617
+ }
618
+ toString() { return this.href; }
619
+ toJSON() { return this.href; }
620
+ }
621
+ Object.defineProperty(URL.prototype, Symbol.toStringTag, { value: 'URL' });
622
+
623
+ // ---------------------------------------------------------------- Blob
624
+
625
+ class Blob {
626
+ constructor(parts = [], options = {}) {
627
+ const chunks = [];
628
+ for (const p of Array.from(parts)) {
629
+ if (p instanceof Blob) chunks.push(p[S].bytes);
630
+ else if (p instanceof ArrayBuffer || ArrayBuffer.isView(p)) chunks.push(bytesOf(p).slice());
631
+ else chunks.push(encoder.encode(String(p)));
632
+ }
633
+ const size = chunks.reduce((n, c) => n + c.length, 0);
634
+ const bytes = new Uint8Array(size);
635
+ let at = 0;
636
+ for (const c of chunks) { bytes.set(c, at); at += c.length; }
637
+ const type = options && options.type !== undefined ? String(options.type) : '';
638
+ this[S] = { bytes, type: /[^\x20-\x7e]/.test(type) ? '' : type.toLowerCase() };
639
+ }
640
+ get size() { return this[S].bytes.length; }
641
+ get type() { return this[S].type; }
642
+ slice(start = 0, end = this.size, type = '') {
643
+ const n = this.size;
644
+ const clamp = (v) => (v < 0 ? Math.max(n + v, 0) : Math.min(v, n));
645
+ const b = new Blob([], { type });
646
+ b[S].bytes = this[S].bytes.slice(clamp(start), Math.max(clamp(start), clamp(end)));
647
+ return b;
648
+ }
649
+ text() { return Promise.resolve(decoder.decode(this[S].bytes)); }
650
+ arrayBuffer() { return Promise.resolve(this[S].bytes.slice().buffer); }
651
+ bytes() { return Promise.resolve(this[S].bytes.slice()); }
652
+ stream() { throw UNSUPPORTED('Blob.stream() (ReadableStream)'); }
653
+ }
654
+ Object.defineProperty(Blob.prototype, Symbol.toStringTag, { value: 'Blob' });
655
+
656
+ define('URLSearchParams', URLSearchParams);
657
+ define('URL', URL);
658
+ define('Blob', Blob);
659
+ define('AbortSignal', AbortSignal);
660
+ define('AbortController', AbortController);
661
+
662
+ // ---------------------------------------------------------------- Headers
663
+
664
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
665
+ const FORBIDDEN = new Set(['accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method',
666
+ 'connection', 'content-length', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer',
667
+ 'set-cookie', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'via']);
668
+ const forbiddenRequest = (n) => FORBIDDEN.has(n) || n.startsWith('proxy-') || n.startsWith('sec-');
669
+ const headerName = (n) => {
670
+ n = String(n);
671
+ if (!TOKEN.test(n)) throw new TypeError(`Headers: Invalid name '${n}'`);
672
+ return n.toLowerCase();
673
+ };
674
+ const headerValue = (v) => {
675
+ v = String(v).replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, '');
676
+ if (/[\0\n\r]/.test(v)) throw new TypeError(`Headers: Invalid value '${v}'`);
677
+ return v;
678
+ };
679
+
680
+ class Headers {
681
+ constructor(init) {
682
+ this[S] = { map: new Map(), guard: 'none' };
683
+ fillHeaders(this, init);
684
+ }
685
+ append(name, value) {
686
+ name = headerName(name);
687
+ value = headerValue(value);
688
+ if (!allowed(this, name)) return;
689
+ const m = this[S].map;
690
+ if (m.has(name)) m.get(name).push(value);
691
+ else m.set(name, [value]);
692
+ }
693
+ delete(name) {
694
+ name = headerName(name);
695
+ if (!allowed(this, name)) return;
696
+ this[S].map.delete(name);
697
+ }
698
+ get(name) {
699
+ const v = this[S].map.get(headerName(name));
700
+ return v ? v.join(', ') : null;
701
+ }
702
+ getSetCookie() { return (this[S].map.get('set-cookie') || []).slice(); }
703
+ has(name) { return this[S].map.has(headerName(name)); }
704
+ set(name, value) {
705
+ name = headerName(name);
706
+ value = headerValue(value);
707
+ if (!allowed(this, name)) return;
708
+ this[S].map.set(name, [value]);
709
+ }
710
+ forEach(fn, thisArg) { for (const [k, v] of this) fn.call(thisArg, v, k, this); }
711
+ *entries() {
712
+ const names = [...this[S].map.keys()].sort();
713
+ for (const n of names) {
714
+ const v = this[S].map.get(n);
715
+ if (!v) continue;
716
+ if (n === 'set-cookie') for (const c of v) yield [n, c];
717
+ else yield [n, v.join(', ')];
718
+ }
719
+ }
720
+ *keys() { for (const [k] of this) yield k; }
721
+ *values() { for (const [, v] of this) yield v; }
722
+ [Symbol.iterator]() { return this.entries(); }
723
+ }
724
+ Object.defineProperty(Headers.prototype, Symbol.toStringTag, { value: 'Headers' });
725
+
726
+ function allowed(h, name) {
727
+ const guard = h[S].guard;
728
+ if (guard === 'immutable') throw new TypeError('Headers are immutable');
729
+ if (guard === 'request' && forbiddenRequest(name)) return false;
730
+ if (guard === 'response' && (name === 'set-cookie' || name === 'set-cookie2')) return false;
731
+ return true;
732
+ }
733
+
734
+ function fillHeaders(h, init) {
735
+ if (init == null) return;
736
+ if (init instanceof Headers) {
737
+ for (const [k, v] of init[S].map) for (const x of v) h.append(k, x);
738
+ } else if (typeof init === 'object' && typeof init[Symbol.iterator] === 'function') {
739
+ for (const pair of init) {
740
+ const p = Array.from(pair);
741
+ if (p.length !== 2) throw new TypeError("Failed to construct 'Headers': Invalid value");
742
+ h.append(p[0], p[1]);
743
+ }
744
+ } else if (typeof init === 'object') {
745
+ for (const k of Object.keys(init)) h.append(k, init[k]);
746
+ } else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(record<ByteString, ByteString> or sequence<sequence<ByteString>>)'.");
747
+ }
748
+
749
+ function guarded(guard, init) {
750
+ const h = new Headers();
751
+ h[S].guard = guard === 'immutable' ? 'none' : guard;
752
+ fillHeaders(h, init);
753
+ h[S].guard = guard;
754
+ return h;
755
+ }
756
+
757
+ // ---------------------------------------------------------------- bodies
758
+
759
+ // A body: {bytes?: Uint8Array, text?: string, wait?: Promise} \u2014 `wait` resolves (to a body)
760
+ // when a fetched body arrives after the head.
761
+ function extractBody(init) {
762
+ if (init == null) return { body: null, type: null };
763
+ if (typeof init === 'string') return { body: { text: init }, type: 'text/plain;charset=UTF-8' };
764
+ if (init instanceof URLSearchParams) return { body: { text: init.toString() }, type: 'application/x-www-form-urlencoded;charset=UTF-8' };
765
+ if (init instanceof Blob) return { body: { bytes: init[S].bytes.slice() }, type: init.type || null };
766
+ if (init instanceof ArrayBuffer || ArrayBuffer.isView(init)) return { body: { bytes: bytesOf(init).slice() }, type: null };
767
+ if (typeof g.FormData !== 'undefined' && init instanceof g.FormData) throw UNSUPPORTED('A FormData body');
768
+ if (typeof init.getReader === 'function' || typeof init[Symbol.asyncIterator] === 'function') throw UNSUPPORTED('A ReadableStream body');
769
+ return { body: { text: String(init) }, type: 'text/plain;charset=UTF-8' };
770
+ }
771
+
772
+ const bodyBytes = (b) => (b.bytes ? b.bytes : (b.bytes = encoder.encode(b.text)));
773
+ const bodyText = (b) => (b.text !== undefined ? b.text : decoder.decode(b.bytes));
774
+
775
+ function consume(self, read) {
776
+ const s = self[S];
777
+ if (s.used) return Promise.reject(new TypeError('Body is unusable: Body has already been read'));
778
+ if (s.body === null) return Promise.resolve(read({ bytes: new Uint8Array(0), text: '' }));
779
+ s.used = true;
780
+ const ready = s.body.wait ? s.body.wait : Promise.resolve(s.body);
781
+ return ready.then(read);
782
+ }
783
+
784
+ const BodyMixin = {
785
+ get bodyUsed() { return this[S].used; },
786
+ get body() {
787
+ if (this[S].body === null) return null;
788
+ throw UNSUPPORTED(`${this instanceof Request ? 'Request' : 'Response'}.body (ReadableStream)`);
789
+ },
790
+ text() { return consume(this, bodyText); },
791
+ json() { return consume(this, (b) => JSON.parse(bodyText(b))); },
792
+ arrayBuffer() { return consume(this, (b) => bodyBytes(b).slice().buffer); },
793
+ bytes() { return consume(this, (b) => bodyBytes(b).slice()); },
794
+ blob() {
795
+ const type = this.headers.get('content-type') || '';
796
+ return consume(this, (b) => new Blob([bodyBytes(b)], { type }));
797
+ },
798
+ formData() { return Promise.reject(UNSUPPORTED('formData()')); },
799
+ };
800
+ function mixBody(C) {
801
+ for (const k of Object.getOwnPropertyNames(BodyMixin)) Object.defineProperty(C.prototype, k, Object.getOwnPropertyDescriptor(BodyMixin, k));
802
+ }
803
+ function cloneBody(b) {
804
+ if (b === null) return null;
805
+ if (b.wait) {
806
+ const wait = b.wait.then((x) => ({ text: x.text, bytes: x.bytes && x.bytes.slice() }));
807
+ wait.catch(() => {});
808
+ return { wait };
809
+ }
810
+ return { text: b.text, bytes: b.bytes && b.bytes.slice() };
811
+ }
812
+
813
+ // ---------------------------------------------------------------- Request
814
+
815
+ const METHODS = { DELETE: 1, GET: 1, HEAD: 1, OPTIONS: 1, POST: 1, PUT: 1, PATCH: 0 };
816
+ const parseRequestURL = (input) => {
817
+ try {
818
+ const u = new URL(input);
819
+ if (u.username || u.password) throw new TypeError(`Failed to construct 'Request': Request cannot be constructed from a URL that includes credentials: ${input}`);
820
+ return u.href;
821
+ } catch (e) {
822
+ if (e instanceof TypeError && /credentials|not supported on native targets/.test(e.message)) throw e;
823
+ throw new TypeError(`Failed to construct 'Request': Failed to parse URL from ${input}`);
824
+ }
825
+ };
826
+
827
+ class Request {
828
+ constructor(input, init = {}) {
829
+ init = init || {};
830
+ let base = null;
831
+ if (input instanceof Request) base = input[S];
832
+ const url = base ? base.url : parseRequestURL(String(input));
833
+ let method = init.method !== undefined ? String(init.method) : base ? base.method : 'GET';
834
+ if (!TOKEN.test(method)) throw new TypeError(`Failed to construct 'Request': '${method}' is not a valid HTTP method.`);
835
+ const upper = method.toUpperCase();
836
+ if (upper === 'CONNECT' || upper === 'TRACE' || upper === 'TRACK') throw new TypeError(`Failed to construct 'Request': '${method}' HTTP method is unsupported.`);
837
+ if (upper in METHODS && METHODS[upper]) method = upper;
838
+ const redirect = init.redirect !== undefined ? String(init.redirect) : base ? base.redirect : 'follow';
839
+ if (!['follow', 'error', 'manual'].includes(redirect)) throw new TypeError(`Failed to construct 'Request': The provided value '${redirect}' is not a valid enum value of type RequestRedirect.`);
840
+ const signal = init.signal !== undefined ? init.signal : base ? base.signal : null;
841
+ if (signal != null && !(signal instanceof AbortSignal)) throw new TypeError("Failed to construct 'Request': member signal is not of type AbortSignal.");
842
+ const headers = guarded('request', init.headers !== undefined ? init.headers : base ? base.headers : undefined);
843
+ let body = null;
844
+ if (init.body != null) {
845
+ if (method === 'GET' || method === 'HEAD') throw new TypeError("Failed to construct 'Request': Request with GET/HEAD method cannot have body.");
846
+ const ex = extractBody(init.body);
847
+ body = ex.body;
848
+ if (ex.type && !headers.has('content-type')) headers.append('content-type', ex.type);
849
+ } else if (base && base.body !== null && init.body === undefined) {
850
+ if (base.used) throw new TypeError("Failed to construct 'Request': Cannot construct a Request with a Request object that has already been used.");
851
+ if (method === 'GET' || method === 'HEAD') throw new TypeError("Failed to construct 'Request': Request with GET/HEAD method cannot have body.");
852
+ body = base.body;
853
+ base.used = true;
854
+ }
855
+ this[S] = {
856
+ url, method, headers, body, used: false, redirect,
857
+ signal: signal ? AbortSignal.any([signal]) : new AbortSignal(KEY),
858
+ credentials: init.credentials !== undefined ? String(init.credentials) : base ? base.credentials : 'same-origin',
859
+ mode: init.mode !== undefined ? String(init.mode) : base ? base.mode : 'cors',
860
+ cache: init.cache !== undefined ? String(init.cache) : base ? base.cache : 'default',
861
+ referrer: base ? base.referrer : 'about:client',
862
+ referrerPolicy: init.referrerPolicy !== undefined ? String(init.referrerPolicy) : base ? base.referrerPolicy : '',
863
+ integrity: init.integrity !== undefined ? String(init.integrity) : base ? base.integrity : '',
864
+ keepalive: init.keepalive !== undefined ? !!init.keepalive : base ? base.keepalive : false,
865
+ };
866
+ }
867
+ get url() { return this[S].url; }
868
+ get method() { return this[S].method; }
869
+ get headers() { return this[S].headers; }
870
+ get signal() { return this[S].signal; }
871
+ get redirect() { return this[S].redirect; }
872
+ get credentials() { return this[S].credentials; }
873
+ get mode() { return this[S].mode; }
874
+ get cache() { return this[S].cache; }
875
+ get referrer() { return this[S].referrer; }
876
+ get referrerPolicy() { return this[S].referrerPolicy; }
877
+ get integrity() { return this[S].integrity; }
878
+ get keepalive() { return this[S].keepalive; }
879
+ get destination() { return ''; }
880
+ clone() {
881
+ if (this[S].used) throw new TypeError("Failed to execute 'clone' on 'Request': Request body is already used");
882
+ const r = new Request(this, { body: null });
883
+ r[S].body = cloneBody(this[S].body);
884
+ r[S].method = this[S].method;
885
+ return r;
886
+ }
887
+ }
888
+ mixBody(Request);
889
+ Object.defineProperty(Request.prototype, Symbol.toStringTag, { value: 'Request' });
890
+
891
+ // ---------------------------------------------------------------- Response
892
+
893
+ const NULL_BODY = new Set([101, 103, 204, 205, 304]);
894
+ const REDIRECT = new Set([301, 302, 303, 307, 308]);
895
+
896
+ class Response {
897
+ constructor(body = null, init = {}) {
898
+ init = init || {};
899
+ const status = init.status !== undefined ? Number(init.status) : 200;
900
+ if (!(status >= 200 && status <= 599) || Math.floor(status) !== status) throw new RangeError(`Failed to construct 'Response': The status provided (${init.status}) is outside the range [200, 599].`);
901
+ const statusText = init.statusText !== undefined ? String(init.statusText) : '';
902
+ if (/[^\t\x20-\x7e\x80-\xff]/.test(statusText)) throw new TypeError("Failed to construct 'Response': Invalid statusText");
903
+ const headers = guarded('response', init.headers);
904
+ let b = null;
905
+ if (body != null) {
906
+ if (NULL_BODY.has(status)) throw new TypeError("Failed to construct 'Response': Response with null body status cannot have body");
907
+ const ex = extractBody(body);
908
+ b = ex.body;
909
+ if (ex.type && !headers.has('content-type')) headers.append('content-type', ex.type);
910
+ }
911
+ this[S] = { status, statusText, headers, body: b, used: false, type: 'default', url: '', redirected: false };
912
+ }
913
+ static error() {
914
+ const r = new Response(null, { status: 200 });
915
+ Object.assign(r[S], { status: 0, type: 'error', headers: guarded('immutable') });
916
+ return r;
917
+ }
918
+ static json(data, init = {}) {
919
+ const text = JSON.stringify(data);
920
+ if (text === undefined) throw new TypeError("Failed to execute 'json' on 'Response': The data provided cannot be converted to JSON.");
921
+ const headers = new Headers(init && init.headers);
922
+ if (!headers.has('content-type')) headers.set('content-type', 'application/json');
923
+ return new Response(text, { ...init, headers });
924
+ }
925
+ static redirect(url, status = 302) {
926
+ const href = new URL(url).href;
927
+ if (!REDIRECT.has(status)) throw new RangeError("Failed to execute 'redirect' on 'Response': Invalid status code");
928
+ const r = new Response(null, { status, headers: { location: href } });
929
+ r[S].headers[S].guard = 'immutable';
930
+ return r;
931
+ }
932
+ get type() { return this[S].type; }
933
+ get url() { return this[S].url; }
934
+ get redirected() { return this[S].redirected; }
935
+ get status() { return this[S].status; }
936
+ get ok() { return this[S].status >= 200 && this[S].status <= 299; }
937
+ get statusText() { return this[S].statusText; }
938
+ get headers() { return this[S].headers; }
939
+ clone() {
940
+ if (this[S].used) throw new TypeError("Failed to execute 'clone' on 'Response': Response body is already used");
941
+ const r = new Response(null);
942
+ const headers = guarded(this[S].headers[S].guard, this[S].headers);
943
+ r[S] = { ...this[S], headers, body: cloneBody(this[S].body), used: false };
944
+ return r;
945
+ }
946
+ }
947
+ mixBody(Response);
948
+ Object.defineProperty(Response.prototype, Symbol.toStringTag, { value: 'Response' });
949
+
950
+ define('Headers', Headers);
951
+ define('Request', Request);
952
+ define('Response', Response);
953
+
954
+ // ---------------------------------------------------------------- fetch
955
+
956
+ let nextId = 1;
957
+ const inflight = new Map();
958
+
959
+ function wireBody(b) {
960
+ if (b === null) return null;
961
+ if (b.text !== undefined) return { text: b.text };
962
+ return { latin1: bytesToLatin1(b.bytes) };
963
+ }
964
+ function fromWire(b) {
965
+ if (!b) return { text: '' };
966
+ if (typeof b.text === 'string') return { text: b.text };
967
+ return { bytes: latin1ToBytes(b.latin1 || '') };
968
+ }
969
+
970
+ function fetch(input, init) {
971
+ return new Promise((resolve, reject) => {
972
+ let request;
973
+ try {
974
+ request = new Request(input, init);
975
+ } catch (e) {
976
+ reject(e);
977
+ return;
978
+ }
979
+ const r = request[S];
980
+ const signal = r.signal;
981
+ if (signal.aborted) {
982
+ reject(signal.reason);
983
+ return;
984
+ }
985
+ if (!/^https?:$/.test(new URL(r.url).protocol)) {
986
+ reject(new TypeError(`Failed to fetch: the URL scheme of ${r.url} is not supported on native targets (http and https only)`));
987
+ return;
988
+ }
989
+ if (r.redirect === 'manual') {
990
+ reject(UNSUPPORTED("fetch with redirect: 'manual'"));
991
+ return;
992
+ }
993
+ if (!post) {
994
+ reject(new TypeError('Failed to fetch: there is no network while the build-time snapshot is baked (fetch from an effect or an event, not during render)'));
995
+ return;
996
+ }
997
+ if (r.body && r.body.wait) {
998
+ reject(UNSUPPORTED('A streamed request body'));
999
+ return;
1000
+ }
1001
+ if (r.body) r.used = true;
1002
+ const id = nextId++;
1003
+ const state = { request, resolve, reject, response: null, settleBody: null };
1004
+ const onAbort = () => {
1005
+ if (inflight.get(id) !== state) return;
1006
+ inflight.delete(id);
1007
+ post('net', JSON.stringify({ op: 'abort', id }));
1008
+ if (state.response) state.settleBody(false, signal.reason);
1009
+ else reject(signal.reason);
1010
+ };
1011
+ state.done = () => {
1012
+ inflight.delete(id);
1013
+ signal[S].algorithms.delete(onAbort);
1014
+ };
1015
+ signal[S].algorithms.add(onAbort);
1016
+ inflight.set(id, state);
1017
+ // fetch adds `Accept: */*` when the request has none (not visible in request.headers).
1018
+ const headers = [...r.headers];
1019
+ if (!r.headers.has('accept')) headers.push(['accept', '*/*']);
1020
+ post('net', JSON.stringify({ op: 'fetch', id, method: r.method, url: r.url, headers, body: wireBody(r.body) }));
1021
+ });
1022
+ }
1023
+
1024
+ g.__bakeNet = (id, event) => {
1025
+ const state = inflight.get(id);
1026
+ if (!state) return true;
1027
+ if (event.type === 'head') {
1028
+ const r = state.request[S];
1029
+ if (r.redirect === 'error' && event.redirected) {
1030
+ state.done();
1031
+ post('net', JSON.stringify({ op: 'abort', id }));
1032
+ state.reject(new TypeError('Failed to fetch: the response was redirected and the request has redirect: error'));
1033
+ return true;
1034
+ }
1035
+ const response = new Response(null);
1036
+ let body = null;
1037
+ if (r.method !== 'HEAD' && !NULL_BODY.has(event.status)) {
1038
+ if (event.body) body = fromWire(event.body);
1039
+ else {
1040
+ let settle;
1041
+ const wait = new Promise((res, rej) => { settle = (ok, v) => (ok ? res(v) : rej(v)); });
1042
+ wait.catch(() => {});
1043
+ body = { wait };
1044
+ state.settleBody = settle;
1045
+ }
1046
+ }
1047
+ response[S] = {
1048
+ status: event.status, statusText: event.statusText || '', body, used: false, type: 'basic',
1049
+ url: event.url || r.url, redirected: !!event.redirected,
1050
+ headers: guarded('immutable', event.headers || []),
1051
+ };
1052
+ state.response = response;
1053
+ if (!state.settleBody) state.done();
1054
+ else state.settleBody = ((settle) => (ok, v) => { state.done(); settle(ok, v); })(state.settleBody);
1055
+ state.resolve(response);
1056
+ } else if (event.type === 'body') {
1057
+ if (state.settleBody) state.settleBody(true, fromWire(event.body));
1058
+ else state.done();
1059
+ } else {
1060
+ const error = new TypeError(event.message || 'Failed to fetch');
1061
+ if (state.settleBody) state.settleBody(false, error);
1062
+ else {
1063
+ state.done();
1064
+ state.reject(error);
1065
+ }
1066
+ }
1067
+ return true;
1068
+ };
1069
+
1070
+ define('fetch', fetch);
1071
+ }