@pigeonmal/react-native-nitro-fetch 0.1.6

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 (104) hide show
  1. package/NitroFetch.podspec +30 -0
  2. package/android/CMakeLists.txt +70 -0
  3. package/android/build.gradle +130 -0
  4. package/android/gradle.properties +5 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/cpp/cpp-adapter.cpp +6 -0
  7. package/android/src/main/java/com/margelo/nitro/nitrofetch/AutoPrefetcher.kt +72 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrofetch/FetchCache.kt +58 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrofetch/NativeStorage.kt +102 -0
  10. package/android/src/main/java/com/margelo/nitro/nitrofetch/NitroFetch.kt +94 -0
  11. package/android/src/main/java/com/margelo/nitro/nitrofetch/NitroFetchClient.kt +331 -0
  12. package/android/src/main/java/com/margelo/nitro/nitrofetch/NitroFetchPackage.kt +22 -0
  13. package/ios/FetchCache.swift +56 -0
  14. package/ios/NativeStorage.swift +61 -0
  15. package/ios/NitroAutoPrefetcher.swift +45 -0
  16. package/ios/NitroBootstrap.mm +27 -0
  17. package/ios/NitroFetch.swift +9 -0
  18. package/ios/NitroFetchClient.swift +230 -0
  19. package/lib/module/NitroFetch.nitro.js +4 -0
  20. package/lib/module/NitroFetch.nitro.js.map +1 -0
  21. package/lib/module/NitroInstances.js +8 -0
  22. package/lib/module/NitroInstances.js.map +1 -0
  23. package/lib/module/fetch.js +522 -0
  24. package/lib/module/fetch.js.map +1 -0
  25. package/lib/module/index.js +12 -0
  26. package/lib/module/index.js.map +1 -0
  27. package/lib/module/package.json +1 -0
  28. package/lib/module/type.js +2 -0
  29. package/lib/module/type.js.map +1 -0
  30. package/lib/typescript/package.json +1 -0
  31. package/lib/typescript/src/NitroFetch.nitro.d.ts +48 -0
  32. package/lib/typescript/src/NitroFetch.nitro.d.ts.map +1 -0
  33. package/lib/typescript/src/NitroInstances.d.ts +5 -0
  34. package/lib/typescript/src/NitroInstances.d.ts.map +1 -0
  35. package/lib/typescript/src/fetch.d.ts +28 -0
  36. package/lib/typescript/src/fetch.d.ts.map +1 -0
  37. package/lib/typescript/src/index.d.ts +6 -0
  38. package/lib/typescript/src/index.d.ts.map +1 -0
  39. package/lib/typescript/src/type.d.ts +4 -0
  40. package/lib/typescript/src/type.d.ts.map +1 -0
  41. package/nitro.json +25 -0
  42. package/nitrogen/generated/android/c++/JHybridNativeStorageSpec.cpp +54 -0
  43. package/nitrogen/generated/android/c++/JHybridNativeStorageSpec.hpp +66 -0
  44. package/nitrogen/generated/android/c++/JHybridNitroFetchClientSpec.cpp +96 -0
  45. package/nitrogen/generated/android/c++/JHybridNitroFetchClientSpec.hpp +66 -0
  46. package/nitrogen/generated/android/c++/JHybridNitroFetchSpec.cpp +49 -0
  47. package/nitrogen/generated/android/c++/JHybridNitroFetchSpec.hpp +64 -0
  48. package/nitrogen/generated/android/c++/JNitroHeader.hpp +57 -0
  49. package/nitrogen/generated/android/c++/JNitroRequest.hpp +100 -0
  50. package/nitrogen/generated/android/c++/JNitroRequestMethod.hpp +74 -0
  51. package/nitrogen/generated/android/c++/JNitroResponse.hpp +102 -0
  52. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/HybridNativeStorageSpec.kt +60 -0
  53. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/HybridNitroFetchClientSpec.kt +60 -0
  54. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/HybridNitroFetchSpec.kt +52 -0
  55. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/NitroHeader.kt +32 -0
  56. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/NitroRequest.kt +47 -0
  57. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/NitroRequestMethod.kt +26 -0
  58. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/NitroResponse.kt +50 -0
  59. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrofetch/nitrofetchOnLoad.kt +35 -0
  60. package/nitrogen/generated/android/nitrofetch+autolinking.cmake +85 -0
  61. package/nitrogen/generated/android/nitrofetch+autolinking.gradle +27 -0
  62. package/nitrogen/generated/android/nitrofetchOnLoad.cpp +64 -0
  63. package/nitrogen/generated/android/nitrofetchOnLoad.hpp +25 -0
  64. package/nitrogen/generated/ios/NitroFetch+autolinking.rb +60 -0
  65. package/nitrogen/generated/ios/NitroFetch-Swift-Cxx-Bridge.cpp +90 -0
  66. package/nitrogen/generated/ios/NitroFetch-Swift-Cxx-Bridge.hpp +321 -0
  67. package/nitrogen/generated/ios/NitroFetch-Swift-Cxx-Umbrella.hpp +69 -0
  68. package/nitrogen/generated/ios/NitroFetchAutolinking.mm +49 -0
  69. package/nitrogen/generated/ios/NitroFetchAutolinking.swift +55 -0
  70. package/nitrogen/generated/ios/c++/HybridNativeStorageSpecSwift.cpp +11 -0
  71. package/nitrogen/generated/ios/c++/HybridNativeStorageSpecSwift.hpp +85 -0
  72. package/nitrogen/generated/ios/c++/HybridNitroFetchClientSpecSwift.cpp +11 -0
  73. package/nitrogen/generated/ios/c++/HybridNitroFetchClientSpecSwift.hpp +103 -0
  74. package/nitrogen/generated/ios/c++/HybridNitroFetchSpecSwift.cpp +11 -0
  75. package/nitrogen/generated/ios/c++/HybridNitroFetchSpecSwift.hpp +75 -0
  76. package/nitrogen/generated/ios/swift/Func_void.swift +47 -0
  77. package/nitrogen/generated/ios/swift/Func_void_NitroResponse.swift +47 -0
  78. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +47 -0
  79. package/nitrogen/generated/ios/swift/HybridNativeStorageSpec.swift +51 -0
  80. package/nitrogen/generated/ios/swift/HybridNativeStorageSpec_cxx.swift +145 -0
  81. package/nitrogen/generated/ios/swift/HybridNitroFetchClientSpec.swift +51 -0
  82. package/nitrogen/generated/ios/swift/HybridNitroFetchClientSpec_cxx.swift +161 -0
  83. package/nitrogen/generated/ios/swift/HybridNitroFetchSpec.swift +49 -0
  84. package/nitrogen/generated/ios/swift/HybridNitroFetchSpec_cxx.swift +126 -0
  85. package/nitrogen/generated/ios/swift/NitroHeader.swift +46 -0
  86. package/nitrogen/generated/ios/swift/NitroRequest.swift +206 -0
  87. package/nitrogen/generated/ios/swift/NitroRequestMethod.swift +60 -0
  88. package/nitrogen/generated/ios/swift/NitroResponse.swift +162 -0
  89. package/nitrogen/generated/shared/c++/HybridNativeStorageSpec.cpp +23 -0
  90. package/nitrogen/generated/shared/c++/HybridNativeStorageSpec.hpp +64 -0
  91. package/nitrogen/generated/shared/c++/HybridNitroFetchClientSpec.cpp +23 -0
  92. package/nitrogen/generated/shared/c++/HybridNitroFetchClientSpec.hpp +69 -0
  93. package/nitrogen/generated/shared/c++/HybridNitroFetchSpec.cpp +21 -0
  94. package/nitrogen/generated/shared/c++/HybridNitroFetchSpec.hpp +64 -0
  95. package/nitrogen/generated/shared/c++/NitroHeader.hpp +71 -0
  96. package/nitrogen/generated/shared/c++/NitroRequest.hpp +98 -0
  97. package/nitrogen/generated/shared/c++/NitroRequestMethod.hpp +96 -0
  98. package/nitrogen/generated/shared/c++/NitroResponse.hpp +99 -0
  99. package/package.json +162 -0
  100. package/src/NitroFetch.nitro.ts +67 -0
  101. package/src/NitroInstances.ts +14 -0
  102. package/src/fetch.ts +603 -0
  103. package/src/index.tsx +17 -0
  104. package/src/type.ts +3 -0
package/src/fetch.ts ADDED
@@ -0,0 +1,603 @@
1
+ import type {
2
+ NitroFetch as NitroFetchModule,
3
+ NitroHeader,
4
+ NitroRequest,
5
+ NitroResponse,
6
+ } from './NitroFetch.nitro';
7
+ import {
8
+ boxedNitroFetch,
9
+ NitroFetch as NitroFetchSingleton,
10
+ } from './NitroInstances';
11
+ import { NativeStorage as NativeStorageSingleton } from './NitroInstances';
12
+ import { NitroRequestInit } from './type';
13
+
14
+ // No base64: pass strings/ArrayBuffers directly
15
+
16
+ function headersToPairs(headers?: HeadersInit): NitroHeader[] | undefined {
17
+ 'worklet';
18
+ if (!headers) return undefined;
19
+ const pairs: NitroHeader[] = [];
20
+ if (headers instanceof Headers) {
21
+ headers.forEach((v, k) => pairs.push({ key: k, value: v }));
22
+ return pairs;
23
+ }
24
+ if (Array.isArray(headers)) {
25
+ // Convert tuple pairs to objects if needed
26
+ for (const entry of headers as any[]) {
27
+ if (Array.isArray(entry) && entry.length >= 2) {
28
+ pairs.push({ key: String(entry[0]), value: String(entry[1]) });
29
+ } else if (
30
+ entry &&
31
+ typeof entry === 'object' &&
32
+ 'key' in entry &&
33
+ 'value' in entry
34
+ ) {
35
+ pairs.push(entry as NitroHeader);
36
+ }
37
+ }
38
+ return pairs;
39
+ }
40
+ // Check if it's a plain object (Record<string, string>) first
41
+ // Plain objects don't have forEach, so check for its absence
42
+ if (typeof headers === 'object' && headers !== null) {
43
+ // Check if it's a Headers instance by checking for forEach method
44
+ const hasForEach = typeof (headers as any).forEach === 'function';
45
+
46
+ if (hasForEach) {
47
+ // Headers-like object (duck typing)
48
+ (headers as any).forEach((v: string, k: string) =>
49
+ pairs.push({ key: k, value: v })
50
+ );
51
+ return pairs;
52
+ } else {
53
+ // Plain object (Record<string, string>)
54
+ // Use Object.keys to iterate since Object.entries might not work in worklets
55
+ const keys = Object.keys(headers);
56
+ for (let i = 0; i < keys.length; i++) {
57
+ const k = keys[i];
58
+ const v = (headers as Record<string, string>)[k];
59
+ if (v !== undefined) {
60
+ pairs.push({ key: k, value: String(v) });
61
+ }
62
+ }
63
+ return pairs;
64
+ }
65
+ }
66
+ return pairs;
67
+ }
68
+
69
+ function normalizeBody(
70
+ body: BodyInit | null | undefined
71
+ ): { bodyString?: string; bodyBytes?: ArrayBuffer } | undefined {
72
+ 'worklet';
73
+ if (body == null) return undefined;
74
+ if (typeof body === 'string') return { bodyString: body };
75
+ if (body instanceof URLSearchParams) return { bodyString: body.toString() };
76
+ if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer)
77
+ return { bodyBytes: body };
78
+ if (ArrayBuffer.isView(body)) {
79
+ const view = body as ArrayBufferView;
80
+ // Pass a copy/slice of the underlying bytes without base64
81
+ return {
82
+ //@ts-ignore
83
+ bodyBytes: view.buffer.slice(
84
+ view.byteOffset,
85
+ view.byteOffset + view.byteLength
86
+ ),
87
+ };
88
+ }
89
+ // TODO: Blob/FormData support can be added later
90
+ throw new Error('Unsupported body type for nitro fetch');
91
+ }
92
+
93
+ const NitroFetchHybrid: NitroFetchModule = NitroFetchSingleton;
94
+
95
+ let client: ReturnType<NitroFetchModule['createClient']> | undefined;
96
+
97
+ function ensureClient() {
98
+ if (client) return client;
99
+ try {
100
+ client = NitroFetchHybrid.createClient();
101
+ } catch (err) {
102
+ console.error('Failed to create NitroFetch client', err);
103
+ // native not ready; keep undefined
104
+ }
105
+ return client;
106
+ }
107
+
108
+ function buildNitroRequest(
109
+ input: RequestInfo | URL,
110
+ init?: NitroRequestInit
111
+ ): NitroRequest {
112
+ 'worklet';
113
+ let url: string;
114
+ let method: string | undefined;
115
+ let headersInit: HeadersInit | undefined;
116
+ let body: BodyInit | null | undefined;
117
+
118
+ if (typeof input === 'string' || input instanceof URL) {
119
+ url = String(input);
120
+ method = init?.method;
121
+ headersInit = init?.headers;
122
+ body = init?.body ?? null;
123
+ } else {
124
+ // Request object
125
+ url = input.url;
126
+ method = input.method;
127
+ headersInit = input.headers as any;
128
+ // Clone body if needed – Request objects in RN typically allow direct access
129
+ body = init?.body ?? null;
130
+ }
131
+
132
+ const headers = headersToPairs(headersInit);
133
+ const normalized = normalizeBody(body);
134
+
135
+ return {
136
+ url,
137
+ method: (method?.toUpperCase() as any) ?? 'GET',
138
+ headers,
139
+ bodyString: normalized?.bodyString,
140
+ // Only include bodyBytes when provided to avoid signaling upload data unintentionally
141
+ bodyBytes: undefined as any,
142
+ followRedirects: true,
143
+ timeoutMs: init?.timeoutMs,
144
+ };
145
+ }
146
+
147
+ // Pure JS version of buildNitroRequest that doesnt use anything that breaks worklets. TODO: Merge this to use Same logic for Worklets and normal Fetch
148
+ function headersToPairsPure(headers?: HeadersInit): NitroHeader[] | undefined {
149
+ 'worklet';
150
+ if (!headers) return undefined;
151
+ const pairs: NitroHeader[] = [];
152
+
153
+ if (Array.isArray(headers)) {
154
+ // Convert tuple pairs to objects if needed
155
+ for (const entry of headers as any[]) {
156
+ if (Array.isArray(entry) && entry.length >= 2) {
157
+ pairs.push({ key: String(entry[0]), value: String(entry[1]) });
158
+ } else if (
159
+ entry &&
160
+ typeof entry === 'object' &&
161
+ 'key' in entry &&
162
+ 'value' in entry
163
+ ) {
164
+ pairs.push(entry as NitroHeader);
165
+ }
166
+ }
167
+ return pairs;
168
+ }
169
+
170
+ // Check if it's a plain object (Record<string, string>) first
171
+ // Plain objects don't have forEach, so check for its absence
172
+ if (typeof headers === 'object' && headers !== null) {
173
+ // Check if it's a Headers instance by checking for forEach method
174
+ const hasForEach = typeof (headers as any).forEach === 'function';
175
+
176
+ if (hasForEach) {
177
+ // Headers-like object (duck typing)
178
+ (headers as any).forEach((v: string, k: string) =>
179
+ pairs.push({ key: k, value: v })
180
+ );
181
+ return pairs;
182
+ } else {
183
+ // Plain object (Record<string, string>)
184
+ // Use Object.keys to iterate since Object.entries might not work in worklets
185
+ const keys = Object.keys(headers);
186
+ for (let i = 0; i < keys.length; i++) {
187
+ const k = keys[i];
188
+ const v = (headers as Record<string, string>)[k];
189
+ if (v !== undefined) {
190
+ pairs.push({ key: k, value: String(v) });
191
+ }
192
+ }
193
+ return pairs;
194
+ }
195
+ }
196
+
197
+ return pairs;
198
+ }
199
+ // Pure JS version of buildNitroRequest that doesnt use anything that breaks worklets
200
+ function normalizeBodyPure(
201
+ body: BodyInit | null | undefined
202
+ ): { bodyString?: string; bodyBytes?: ArrayBuffer } | undefined {
203
+ 'worklet';
204
+ if (body == null) return undefined;
205
+ if (typeof body === 'string') return { bodyString: body };
206
+
207
+ // Check for URLSearchParams (duck typing)
208
+ // It should be an object, have a toString method, and typically append/delete methods
209
+ // But mainly we care about toString() returning the query string
210
+ if (
211
+ typeof body === 'object' &&
212
+ body !== null &&
213
+ typeof (body as any).toString === 'function' &&
214
+ Object.prototype.toString.call(body) === '[object URLSearchParams]'
215
+ ) {
216
+ return { bodyString: body.toString() };
217
+ }
218
+
219
+ // Check for ArrayBuffer (using toString tag to avoid instanceof)
220
+ if (
221
+ typeof ArrayBuffer !== 'undefined' &&
222
+ Object.prototype.toString.call(body) === '[object ArrayBuffer]'
223
+ ) {
224
+ return { bodyBytes: body as ArrayBuffer };
225
+ }
226
+
227
+ if (ArrayBuffer.isView(body)) {
228
+ const view = body as ArrayBufferView;
229
+ // Pass a copy/slice of the underlying bytes without base64
230
+ return {
231
+ //@ts-ignore
232
+ bodyBytes: view.buffer.slice(
233
+ view.byteOffset,
234
+ view.byteOffset + view.byteLength
235
+ ),
236
+ };
237
+ }
238
+ // TODO: Blob/FormData support can be added later
239
+ throw new Error('Unsupported body type for nitro fetch');
240
+ }
241
+ // Pure JS version of buildNitroRequest that doesnt use anything that breaks worklets
242
+ export function buildNitroRequestPure(
243
+ input: RequestInfo | URL,
244
+ init?: NitroRequestInit
245
+ ): NitroRequest {
246
+ 'worklet';
247
+ let url: string;
248
+ let method: string | undefined;
249
+ let headersInit: HeadersInit | undefined;
250
+ let body: BodyInit | null | undefined;
251
+
252
+ // Check if input is URL-like without instanceof
253
+ const isUrlObject =
254
+ typeof input === 'object' &&
255
+ input !== null &&
256
+ Object.prototype.toString.call(input) === '[object URL]';
257
+
258
+ if (typeof input === 'string' || isUrlObject) {
259
+ url = String(input);
260
+ method = init?.method;
261
+ headersInit = init?.headers;
262
+ body = init?.body ?? null;
263
+ } else {
264
+ // Request object
265
+ const req = input as Request;
266
+ url = req.url;
267
+ method = req.method;
268
+ headersInit = req.headers;
269
+ // Clone body if needed – Request objects in RN typically allow direct access
270
+ body = init?.body ?? null;
271
+ }
272
+
273
+ const headers = headersToPairsPure(headersInit);
274
+ const normalized = normalizeBodyPure(body);
275
+
276
+ return {
277
+ url,
278
+ method: (method?.toUpperCase() as any) ?? 'GET',
279
+ headers,
280
+ bodyString: normalized?.bodyString,
281
+ // Only include bodyBytes when provided to avoid signaling upload data unintentionally
282
+ bodyBytes: undefined as any,
283
+ followRedirects: true,
284
+ };
285
+ }
286
+
287
+ async function nitroFetchRaw(
288
+ input: RequestInfo | URL,
289
+ init?: NitroRequestInit
290
+ ): Promise<NitroResponse> {
291
+ const hasNative =
292
+ typeof (NitroFetchHybrid as any)?.createClient === 'function';
293
+ if (!hasNative) {
294
+ // Fallback path not supported for raw; use global fetch and synthesize minimal shape
295
+ // @ts-ignore: global fetch exists in RN
296
+ const res = await fetch(input as any, init);
297
+ const url = (res as any).url ?? String(input);
298
+ const bytes = await res.arrayBuffer();
299
+ const headers: NitroHeader[] = [];
300
+ res.headers.forEach((v, k) => headers.push({ key: k, value: v }));
301
+ return {
302
+ url,
303
+ status: res.status,
304
+ statusText: res.statusText,
305
+ ok: res.ok,
306
+ redirected: (res as any).redirected ?? false,
307
+ headers,
308
+ bodyBytes: bytes,
309
+ bodyString: undefined,
310
+ } as any as NitroResponse; // bleee
311
+ }
312
+
313
+ const req = buildNitroRequest(input, init);
314
+ ensureClient();
315
+ if (!client || typeof (client as any).request !== 'function')
316
+ throw new Error('NitroFetch client not available');
317
+ const res: NitroResponse = await client.request(req);
318
+ return res;
319
+ }
320
+
321
+ // Simple Headers-like class that supports get() method
322
+ class NitroHeaders {
323
+ private _headers: Map<string, string>;
324
+
325
+ constructor(headers: NitroHeader[]) {
326
+ this._headers = new Map();
327
+ for (const { key, value } of headers) {
328
+ // Headers are case-insensitive, normalize to lowercase
329
+ this._headers.set(key.toLowerCase(), value);
330
+ }
331
+ }
332
+
333
+ get(name: string): string | null {
334
+ return this._headers.get(name.toLowerCase()) ?? null;
335
+ }
336
+
337
+ has(name: string): boolean {
338
+ return this._headers.has(name.toLowerCase());
339
+ }
340
+
341
+ forEach(callback: (value: string, key: string) => void): void {
342
+ this._headers.forEach(callback);
343
+ }
344
+
345
+ entries(): IterableIterator<[string, string]> {
346
+ return this._headers.entries();
347
+ }
348
+
349
+ keys(): IterableIterator<string> {
350
+ return this._headers.keys();
351
+ }
352
+
353
+ values(): IterableIterator<string> {
354
+ return this._headers.values();
355
+ }
356
+ }
357
+
358
+ export async function nitroFetch(
359
+ input: RequestInfo | URL,
360
+ init?: NitroRequestInit
361
+ ): Promise<Response> {
362
+ const res = await nitroFetchRaw(input, init);
363
+
364
+ const headersObj = new NitroHeaders(res.headers);
365
+
366
+ const bodyBytes = res.bodyBytes;
367
+ const bodyString = res.bodyString;
368
+
369
+ const makeLight = (): any => ({
370
+ url: res.url,
371
+ ok: res.ok,
372
+ status: res.status,
373
+ statusText: res.statusText,
374
+ redirected: res.redirected,
375
+ headers: headersObj,
376
+ arrayBuffer: async () => bodyBytes,
377
+ text: async () => bodyString,
378
+ json: async () => JSON.parse(bodyString ?? '{}'),
379
+ clone: () => makeLight(),
380
+ });
381
+
382
+ const light: any = makeLight();
383
+ return light as Response;
384
+ }
385
+
386
+ // Start a native prefetch. Requires a `prefetchKey` header on the request.
387
+ export async function prefetch(
388
+ input: RequestInfo | URL,
389
+ init?: NitroRequestInit
390
+ ): Promise<void> {
391
+ // If native implementation is not present yet, do nothing
392
+ const hasNative =
393
+ typeof (NitroFetchHybrid as any)?.createClient === 'function';
394
+ if (!hasNative) return;
395
+
396
+ // Build NitroRequest and ensure prefetchKey header exists
397
+ const req = buildNitroRequest(input, init);
398
+ const hasKey =
399
+ req.headers?.some((h) => h.key.toLowerCase() === 'prefetchkey') ?? false;
400
+ // Also support passing prefetchKey via non-standard field on init
401
+ const fromInit = (init as any)?.prefetchKey as string | undefined;
402
+ if (!hasKey && fromInit) {
403
+ req.headers = (req.headers ?? []).concat([
404
+ { key: 'prefetchKey', value: fromInit },
405
+ ]);
406
+ }
407
+ const finalHasKey = req.headers?.some(
408
+ (h) => h.key.toLowerCase() === 'prefetchkey'
409
+ );
410
+ if (!finalHasKey) {
411
+ throw new Error('prefetch requires a "prefetchKey" header');
412
+ }
413
+
414
+ // Ensure client and call native prefetch
415
+ ensureClient();
416
+ if (!client || typeof (client as any).prefetch !== 'function') return;
417
+ await client.prefetch(req);
418
+ }
419
+
420
+ // Persist a request to storage so native can prefetch it on app start.
421
+ export async function prefetchOnAppStart(
422
+ input: RequestInfo | URL,
423
+ init?: NitroRequestInit & { prefetchKey?: string }
424
+ ): Promise<void> {
425
+ // Resolve request and prefetchKey
426
+ const req = buildNitroRequest(input, init);
427
+ const fromHeader = req.headers?.find(
428
+ (h) => h.key.toLowerCase() === 'prefetchkey'
429
+ )?.value;
430
+ const fromInit = (init as any)?.prefetchKey as string | undefined;
431
+ const prefetchKey = fromHeader ?? fromInit;
432
+ if (!prefetchKey) {
433
+ throw new Error(
434
+ 'prefetchOnAppStart requires a "prefetchKey" (header or init.prefetchKey)'
435
+ );
436
+ }
437
+
438
+ // Convert headers to a plain object for storage
439
+ const headersObj = (req.headers ?? []).reduce(
440
+ (acc, { key, value }) => {
441
+ acc[String(key)] = String(value);
442
+ return acc;
443
+ },
444
+ {} as Record<string, string>
445
+ );
446
+
447
+ const entry = {
448
+ url: req.url,
449
+ prefetchKey,
450
+ headers: headersObj,
451
+ } as const;
452
+
453
+ // Write or append to storage queue
454
+ try {
455
+ const KEY = 'nitrofetch_autoprefetch_queue';
456
+ let arr: any[] = [];
457
+ try {
458
+ const raw = NativeStorageSingleton.getString(
459
+ 'nitrofetch_autoprefetch_queue'
460
+ );
461
+ if (raw) arr = JSON.parse(raw);
462
+ if (!Array.isArray(arr)) arr = [];
463
+ } catch {
464
+ arr = [];
465
+ }
466
+ if (arr.some((e) => e && e.prefetchKey === prefetchKey)) {
467
+ arr = arr.filter((e) => e && e.prefetchKey !== prefetchKey);
468
+ }
469
+ arr.push(entry);
470
+ NativeStorageSingleton.setString(KEY, JSON.stringify(arr));
471
+ } catch (e) {
472
+ console.warn('Failed to persist prefetch queue', e);
473
+ }
474
+ }
475
+
476
+ // Remove one entry (by prefetchKey) from the auto-prefetch queue.
477
+ export async function removeFromAutoPrefetch(
478
+ prefetchKey: string
479
+ ): Promise<void> {
480
+ try {
481
+ const KEY = 'nitrofetch_autoprefetch_queue';
482
+ let arr: any[] = [];
483
+ try {
484
+ const raw = NativeStorageSingleton.getString(
485
+ 'nitrofetch_autoprefetch_queue'
486
+ );
487
+ if (raw) arr = JSON.parse(raw);
488
+ if (!Array.isArray(arr)) arr = [];
489
+ } catch {
490
+ arr = [];
491
+ }
492
+ const next = arr.filter((e) => e && e.prefetchKey !== prefetchKey);
493
+ if (next.length === 0) {
494
+ NativeStorageSingleton.removeString(KEY);
495
+ } else if (next.length !== arr.length) {
496
+ NativeStorageSingleton.setString(KEY, JSON.stringify(next));
497
+ }
498
+ } catch (e) {
499
+ console.warn('Failed to remove from prefetch queue', e);
500
+ }
501
+ }
502
+
503
+ // Remove all entries from the auto-prefetch queue.
504
+ export async function removeAllFromAutoprefetch(): Promise<void> {
505
+ const KEY = 'nitrofetch_autoprefetch_queue';
506
+ NativeStorageSingleton.setString(KEY, JSON.stringify([]));
507
+ }
508
+
509
+ // Optional off-thread processing using react-native-worklets-core
510
+ export type NitroWorkletMapper<T> = (payload: {
511
+ url: string;
512
+ status: number;
513
+ statusText: string;
514
+ ok: boolean;
515
+ redirected: boolean;
516
+ headers: NitroHeader[];
517
+ bodyBytes?: ArrayBuffer;
518
+ bodyString?: string;
519
+ }) => T;
520
+
521
+ let nitroRuntime: any | undefined;
522
+ let WorkletsRef: any | undefined;
523
+ function ensureWorkletRuntime(name = 'nitro-fetch'): any | undefined {
524
+ try {
525
+ const { Worklets } = require('react-native-worklets-core');
526
+ nitroRuntime = nitroRuntime ?? Worklets.createContext(name);
527
+ return nitroRuntime;
528
+ } catch {
529
+ console.warn('react-native-worklets-core not available');
530
+ return undefined;
531
+ }
532
+ }
533
+
534
+ function getWorklets(): any | undefined {
535
+ try {
536
+ if (WorkletsRef) return WorkletsRef;
537
+
538
+ const { Worklets } = require('react-native-worklets-core');
539
+ WorkletsRef = Worklets;
540
+ return WorkletsRef;
541
+ } catch {
542
+ console.warn('react-native-worklets-core not available');
543
+ return undefined;
544
+ }
545
+ }
546
+
547
+ export async function nitroFetchOnWorklet<T>(
548
+ input: RequestInfo | URL,
549
+ init: NitroRequestInit | undefined,
550
+ mapWorklet: NitroWorkletMapper<T>,
551
+ options?: { preferBytes?: boolean; runtimeName?: string }
552
+ ): Promise<T> {
553
+ const preferBytes = options?.preferBytes === true; // default true
554
+ let rt: any | undefined;
555
+ let Worklets: any | undefined;
556
+ try {
557
+ rt = ensureWorkletRuntime(options?.runtimeName);
558
+ Worklets = getWorklets();
559
+ } catch (e) {
560
+ console.error('nitroFetchOnWorklet: setup failed', e);
561
+ }
562
+
563
+ // Fallback: if runtime is not available, do the work on JS
564
+ if (!rt || !Worklets || typeof rt.runAsync !== 'function') {
565
+ console.warn('nitroFetchOnWorklet: no runtime, mapping on JS thread');
566
+ const res = await nitroFetchRaw(input, init);
567
+ const payload = {
568
+ url: res.url,
569
+ status: res.status,
570
+ statusText: res.statusText,
571
+ ok: res.ok,
572
+ redirected: res.redirected,
573
+ headers: res.headers,
574
+ bodyBytes: preferBytes ? res.bodyBytes : undefined,
575
+ bodyString: preferBytes ? undefined : res.bodyString,
576
+ } as const;
577
+ return mapWorklet(payload as any);
578
+ }
579
+ return await rt.runAsync(() => {
580
+ 'worklet';
581
+ const unboxedNitroFetch = boxedNitroFetch.unbox();
582
+ const unboxedClient = unboxedNitroFetch.createClient();
583
+ const request = buildNitroRequestPure(input, init);
584
+ const res = unboxedClient.requestSync(request);
585
+ const payload = {
586
+ url: res.url,
587
+ status: res.status,
588
+ statusText: res.statusText,
589
+ ok: res.ok,
590
+ redirected: res.redirected,
591
+ headers: res.headers,
592
+ bodyBytes: preferBytes ? res.bodyBytes : undefined,
593
+ bodyString: preferBytes ? undefined : res.bodyString,
594
+ } as const;
595
+
596
+ return mapWorklet(payload as any);
597
+ });
598
+ }
599
+
600
+ export const x = ensureWorkletRuntime();
601
+ export const y = getWorklets();
602
+
603
+ export type { NitroRequest, NitroResponse } from './NitroFetch.nitro';
package/src/index.tsx ADDED
@@ -0,0 +1,17 @@
1
+ export {
2
+ nitroFetch as fetch,
3
+ nitroFetchOnWorklet,
4
+ prefetch,
5
+ prefetchOnAppStart,
6
+ removeFromAutoPrefetch,
7
+ removeAllFromAutoprefetch,
8
+ } from './fetch';
9
+ export type { NitroRequest, NitroResponse } from './fetch';
10
+ export { NitroFetch } from './NitroInstances';
11
+ import './fetch';
12
+
13
+ // Keep legacy export to avoid breaking any local tests/usages during scaffolding.
14
+ // Will be removed once native Cronet path is ready.
15
+ export function multiply(a: number, b: number): number {
16
+ return a * b;
17
+ }
package/src/type.ts ADDED
@@ -0,0 +1,3 @@
1
+ export type NitroRequestInit = RequestInit & {
2
+ timeoutMs?: number;
3
+ };