@nativue/core 0.5.0 → 0.7.0

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.
package/src/xhr.ts ADDED
@@ -0,0 +1,414 @@
1
+ // XMLHttpRequest and FormData, like the browser's: native runs the request, and its progress comes back as
2
+ // events through __networkEvent. fetch and libraries like axios build on it.
3
+ import { fromByteArray, toByteArray } from 'base64-js'
4
+ import { Blob, bytesOf, File } from './blob'
5
+ import { Event, EventTarget, ProgressEvent } from './events'
6
+ import { URLSearchParams } from './url'
7
+ import type {
8
+ NativeBlob,
9
+ NativeFormDataPart,
10
+ NativeRequestBody,
11
+ NetworkEventPayloads,
12
+ } from './types'
13
+
14
+ const native = globalThis.__native
15
+
16
+ const UNSENT = 0
17
+ const OPENED = 1
18
+ const HEADERS_RECEIVED = 2
19
+ const LOADING = 3
20
+ const DONE = 4
21
+
22
+ // 'document' isn't supported.
23
+ export type XMLHttpRequestResponseType = '' | 'text' | 'json' | 'arraybuffer' | 'blob'
24
+
25
+ const SUPPORTED_RESPONSE_TYPES = new Set(['', 'text', 'json', 'arraybuffer', 'blob'])
26
+
27
+ type EventHandler<EventType = Event> = ((event: EventType) => void) | null
28
+
29
+ /** A file to upload: where it is on the device, and the name and type the server gets. */
30
+ export interface FormDataFile {
31
+ uri: string
32
+ name?: string
33
+ type?: string
34
+ }
35
+
36
+ type FormDataValue = string | FormDataFile | Blob
37
+
38
+ export class FormData {
39
+ private readonly entries: [string, FormDataValue][] = []
40
+ private readonly filenames = new Map<Blob, string>()
41
+
42
+ /** `filename` names a Blob's file (a File has its own name). */
43
+ append(name: string, value: FormDataValue | number | boolean, filename?: string): void {
44
+ this.entries.push([name, typeof value === 'object' ? value : String(value)])
45
+ if (value instanceof Blob && filename !== undefined) this.filenames.set(value, filename)
46
+ }
47
+
48
+ set(name: string, value: FormDataValue | number | boolean, filename?: string): void {
49
+ this.delete(name)
50
+ this.append(name, value, filename)
51
+ }
52
+
53
+ get(name: string): FormDataValue | null {
54
+ return this.entries.find(([entryName]) => entryName === name)?.[1] ?? null
55
+ }
56
+
57
+ getAll(name: string): FormDataValue[] {
58
+ return this.entries.filter(([entryName]) => entryName === name).map(([, value]) => value)
59
+ }
60
+
61
+ has(name: string): boolean {
62
+ return this.entries.some(([entryName]) => entryName === name)
63
+ }
64
+
65
+ delete(name: string): void {
66
+ const remaining = this.entries.filter(([entryName]) => entryName !== name)
67
+
68
+ this.entries.splice(0, this.entries.length, ...remaining)
69
+ }
70
+
71
+ forEach(callback: (value: FormDataValue, name: string, formData: FormData) => void): void {
72
+ this.entries.forEach(([name, value]) => callback(value, name, this))
73
+ }
74
+
75
+ /** What native turns into a multipart/form-data body. */
76
+ toNativeParts(): NativeFormDataPart[] {
77
+ return this.entries.map(([name, value]) => {
78
+ if (typeof value === 'string') return { name, value }
79
+ if (value instanceof Blob) {
80
+ const filename = this.filenames.get(value) ?? (value instanceof File ? value.name : 'blob')
81
+ const type = value.type || 'application/octet-stream'
82
+
83
+ return { name, blob: value.data, filename, type }
84
+ }
85
+
86
+ const filename = value.name ?? 'file'
87
+ const type = value.type ?? 'application/octet-stream'
88
+
89
+ return { name, uri: value.uri, filename, type }
90
+ })
91
+ }
92
+ }
93
+
94
+ export type XMLHttpRequestBody =
95
+ | string
96
+ | FormData
97
+ | URLSearchParams
98
+ | Blob
99
+ | ArrayBuffer
100
+ | ArrayBufferView
101
+ | { uri: string }
102
+ | null
103
+ | undefined
104
+
105
+ function nativeBody(body: XMLHttpRequestBody): NativeRequestBody {
106
+ if (body == null) return null
107
+ if (typeof body === 'string') return { string: body }
108
+ if (body instanceof FormData) return { formData: body.toNativeParts() }
109
+ if (body instanceof URLSearchParams) return { string: body.toString() }
110
+ if (body instanceof Blob) return { blob: body.data }
111
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
112
+ return { base64: fromByteArray(bytesOf(body)) }
113
+ }
114
+ if ('uri' in body) return { uri: body.uri }
115
+
116
+ return { string: String(body) }
117
+ }
118
+
119
+ let nextRequestId = 1
120
+ const requestsById = new Map<number, XMLHttpRequest>()
121
+
122
+ /** Where upload progress goes: `xhr.upload.onprogress`. */
123
+ export class XMLHttpRequestUpload extends EventTarget {
124
+ onloadstart: EventHandler<ProgressEvent> = null
125
+ onprogress: EventHandler<ProgressEvent> = null
126
+ onload: EventHandler<ProgressEvent> = null
127
+ onloadend: EventHandler<ProgressEvent> = null
128
+ onerror: EventHandler<ProgressEvent> = null
129
+ onabort: EventHandler<ProgressEvent> = null
130
+ ontimeout: EventHandler<ProgressEvent> = null
131
+ }
132
+
133
+ export class XMLHttpRequest extends EventTarget {
134
+ static readonly UNSENT = UNSENT
135
+ static readonly OPENED = OPENED
136
+ static readonly HEADERS_RECEIVED = HEADERS_RECEIVED
137
+ static readonly LOADING = LOADING
138
+ static readonly DONE = DONE
139
+ readonly UNSENT = UNSENT
140
+ readonly OPENED = OPENED
141
+ readonly HEADERS_RECEIVED = HEADERS_RECEIVED
142
+ readonly LOADING = LOADING
143
+ readonly DONE = DONE
144
+
145
+ readyState = UNSENT
146
+ status = 0
147
+ statusText = ''
148
+ responseURL = ''
149
+ /** In milliseconds; 0 waits for as long as the platform does. */
150
+ timeout = 0
151
+ /** Sends and stores cookies. */
152
+ withCredentials = true
153
+ readonly upload = new XMLHttpRequestUpload()
154
+
155
+ onreadystatechange: EventHandler = null
156
+ onloadstart: EventHandler<ProgressEvent> = null
157
+ onprogress: EventHandler<ProgressEvent> = null
158
+ onload: EventHandler<ProgressEvent> = null
159
+ onloadend: EventHandler<ProgressEvent> = null
160
+ onerror: EventHandler<ProgressEvent> = null
161
+ onabort: EventHandler<ProgressEvent> = null
162
+ ontimeout: EventHandler<ProgressEvent> = null
163
+
164
+ private method = 'GET'
165
+ private url = ''
166
+ private requestHeaders: Record<string, string> = {}
167
+ private responseHeaders: Record<string, string> = {}
168
+ private chosenResponseType: XMLHttpRequestResponseType = ''
169
+ /** Text, or base64 for 'arraybuffer'. */
170
+ private rawResponse = ''
171
+ private blobResponse: Blob | null = null
172
+ // Held until the request ends, so a Blob being uploaded isn't collected (and released) meanwhile.
173
+ private sentBody: XMLHttpRequestBody = null
174
+ private parsedResponse: unknown = undefined
175
+ private requestId: number | null = null
176
+ private sent = false
177
+ private aborted = false
178
+ private failed = false
179
+ private timedOut = false
180
+
181
+ get responseType(): XMLHttpRequestResponseType {
182
+ return this.chosenResponseType
183
+ }
184
+
185
+ set responseType(responseType: XMLHttpRequestResponseType) {
186
+ if (this.sent) throw new Error("responseType can't change once the request is sent")
187
+ if (!SUPPORTED_RESPONSE_TYPES.has(responseType)) {
188
+ console.warn(`XMLHttpRequest: responseType '${responseType}' is not supported`)
189
+ return
190
+ }
191
+
192
+ this.chosenResponseType = responseType
193
+ }
194
+
195
+ get responseText(): string {
196
+ if (!this.returnsText()) {
197
+ throw new Error(`responseText is only available when responseType is '' or 'text'`)
198
+ }
199
+
200
+ return this.readyState < LOADING ? '' : this.rawResponse
201
+ }
202
+
203
+ get response(): unknown {
204
+ if (this.returnsText()) return this.readyState < LOADING || this.failed ? '' : this.rawResponse
205
+ if (this.readyState !== DONE || this.failed) return null
206
+
207
+ this.parsedResponse ??= this.parseResponse()
208
+
209
+ return this.parsedResponse
210
+ }
211
+
212
+ open(method: string, url: string | { toString(): string }, async = true): void {
213
+ if (!async) throw new Error('Synchronous requests are not supported')
214
+
215
+ this.resetResponse()
216
+ this.method = method.toUpperCase()
217
+ this.url = String(url)
218
+ this.requestHeaders = {}
219
+ this.sent = false
220
+ this.aborted = false
221
+ this.setReadyState(OPENED)
222
+ }
223
+
224
+ setRequestHeader(name: string, value: string): void {
225
+ if (this.readyState !== OPENED || this.sent)
226
+ throw new Error('The request must be opened, not sent')
227
+
228
+ const key = name.toLowerCase()
229
+ const existing = this.requestHeaders[key]
230
+ this.requestHeaders[key] = existing === undefined ? String(value) : `${existing}, ${value}`
231
+ }
232
+
233
+ getResponseHeader(name: string): string | null {
234
+ return this.responseHeaders[name.toLowerCase()] ?? null
235
+ }
236
+
237
+ getAllResponseHeaders(): string {
238
+ const names = Object.keys(this.responseHeaders).sort()
239
+
240
+ return names.map((name) => `${name}: ${this.responseHeaders[name]}\r\n`).join('')
241
+ }
242
+
243
+ // Charsets and MIME sniffing are native's: the response arrives already decoded.
244
+ overrideMimeType(): void {}
245
+
246
+ send(body: XMLHttpRequestBody = null): void {
247
+ if (this.readyState !== OPENED || this.sent)
248
+ throw new Error('The request must be opened, not sent')
249
+
250
+ this.sent = true
251
+ this.sentBody = body
252
+ if (body instanceof URLSearchParams && !('content-type' in this.requestHeaders)) {
253
+ this.requestHeaders['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
254
+ }
255
+ const requestId = nextRequestId++
256
+ this.requestId = requestId
257
+ requestsById.set(requestId, this)
258
+
259
+ this.dispatchProgress(this, 'loadstart', 0, 0)
260
+ native.sendRequest(requestId, {
261
+ method: this.method,
262
+ url: this.url,
263
+ headers: this.requestHeaders,
264
+ body: nativeBody(body),
265
+ responseType: this.nativeResponseType(),
266
+ incrementalUpdates: this.wantsIncrementalUpdates(),
267
+ timeout: this.timeout,
268
+ withCredentials: this.withCredentials,
269
+ })
270
+ }
271
+
272
+ abort(): void {
273
+ this.aborted = true
274
+ if (this.requestId !== null) {
275
+ native.abortRequest(this.requestId)
276
+ this.forgetRequest()
277
+ }
278
+
279
+ const inFlight = this.sent && this.readyState !== DONE
280
+ if (inFlight) {
281
+ this.resetResponse()
282
+ this.setReadyState(DONE)
283
+ }
284
+ this.readyState = UNSENT
285
+ }
286
+
287
+ /** From native, through __networkEvent. */
288
+ handleNetworkEvent<Name extends keyof NetworkEventPayloads>(
289
+ eventName: Name,
290
+ payload: NetworkEventPayloads[Name],
291
+ ): void {
292
+ const handlers: { [EventName in keyof NetworkEventPayloads]: (payload: any) => void } = {
293
+ uploadprogress: ({ loaded, total }) =>
294
+ this.dispatchProgress(this.upload, 'progress', loaded, total),
295
+ response: ({ status, headers, url }) => this.receiveResponse(status, headers, url),
296
+ data: ({ data }) => this.receiveData(data),
297
+ incrementaldata: ({ text, loaded, total }) =>
298
+ this.receiveIncrementalData(text, loaded, total),
299
+ progress: ({ loaded, total }) => this.dispatchProgress(this, 'progress', loaded, total),
300
+ complete: ({ error, timedOut }) => this.complete(error, timedOut),
301
+ }
302
+
303
+ handlers[eventName](payload)
304
+ }
305
+
306
+ private receiveResponse(status: number, headers: Record<string, string>, url: string) {
307
+ this.status = status
308
+ this.responseURL = url
309
+ this.responseHeaders = Object.fromEntries(
310
+ Object.entries(headers).map(([name, value]) => [name.toLowerCase(), String(value)]),
311
+ )
312
+ this.setReadyState(HEADERS_RECEIVED)
313
+ }
314
+
315
+ private receiveData(data: string | NativeBlob) {
316
+ if (typeof data === 'string') this.rawResponse = data
317
+ else this.blobResponse = Blob.fromNative(data)
318
+ this.parsedResponse = undefined
319
+ this.setReadyState(LOADING)
320
+ }
321
+
322
+ private receiveIncrementalData(text: string, loaded: number, total: number) {
323
+ this.rawResponse += text
324
+ this.setReadyState(LOADING)
325
+ this.dispatchProgress(this, 'progress', loaded, total)
326
+ }
327
+
328
+ private complete(error: string | null, timedOut: boolean) {
329
+ this.forgetRequest()
330
+ if (error) {
331
+ this.failed = true
332
+ this.timedOut = timedOut
333
+ if (this.returnsText()) this.rawResponse = ''
334
+ }
335
+
336
+ this.setReadyState(DONE)
337
+ }
338
+
339
+ // Readystatechange on every change; once DONE, the event that tells how it ended, then loadend.
340
+ private setReadyState(readyState: number) {
341
+ this.readyState = readyState
342
+ this.dispatchEvent(new Event('readystatechange'))
343
+ if (readyState !== DONE) return
344
+
345
+ const outcome = this.aborted
346
+ ? 'abort'
347
+ : this.timedOut
348
+ ? 'timeout'
349
+ : this.failed
350
+ ? 'error'
351
+ : 'load'
352
+ const length = this.blobResponse?.size ?? this.rawResponse.length
353
+ this.dispatchProgress(this, outcome, length, length)
354
+ this.dispatchProgress(this, 'loadend', length, length)
355
+ }
356
+
357
+ private dispatchProgress(target: EventTarget, type: string, loaded: number, total: number) {
358
+ target.dispatchEvent(new ProgressEvent(type, { lengthComputable: total > 0, loaded, total }))
359
+ }
360
+
361
+ // Sending every chunk of a large download to JS costs: only when someone watches the progress.
362
+ private wantsIncrementalUpdates(): boolean {
363
+ return (
364
+ this.onprogress !== null ||
365
+ this.onreadystatechange !== null ||
366
+ this.hasListeners('progress') ||
367
+ this.hasListeners('readystatechange')
368
+ )
369
+ }
370
+
371
+ private nativeResponseType() {
372
+ if (this.chosenResponseType === 'arraybuffer') return 'base64'
373
+ if (this.chosenResponseType === 'blob') return 'blob'
374
+
375
+ return 'text'
376
+ }
377
+
378
+ private returnsText(): boolean {
379
+ return this.chosenResponseType === '' || this.chosenResponseType === 'text'
380
+ }
381
+
382
+ private parseResponse(): unknown {
383
+ if (this.chosenResponseType === 'blob') return this.blobResponse
384
+ if (this.chosenResponseType === 'arraybuffer') return toByteArray(this.rawResponse).buffer
385
+
386
+ try {
387
+ return JSON.parse(this.rawResponse)
388
+ } catch {
389
+ return null
390
+ }
391
+ }
392
+
393
+ private resetResponse() {
394
+ this.status = 0
395
+ this.statusText = ''
396
+ this.responseURL = ''
397
+ this.responseHeaders = {}
398
+ this.rawResponse = ''
399
+ this.blobResponse = null
400
+ this.parsedResponse = undefined
401
+ this.failed = false
402
+ this.timedOut = false
403
+ }
404
+
405
+ private forgetRequest() {
406
+ if (this.requestId !== null) requestsById.delete(this.requestId)
407
+ this.requestId = null
408
+ this.sentBody = null
409
+ }
410
+ }
411
+
412
+ globalThis.__networkEvent = (requestId, eventName, payload) => {
413
+ requestsById.get(requestId)?.handleNetworkEvent(eventName, payload as never)
414
+ }