This repository has been archived by the owner on Jan 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathipc.js
1175 lines (993 loc) · 28 KB
/
ipc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module IPC
*
* This is a low level API which you don't need unless you are implementing
* a library on top of Socket SDK. A Socket SDK app has two or three processes.
*
* - The `Render` process, the UI where the HTML, CSS and JS is run.
* - The `Bridge` process, the thin layer of code that managers everything.
* - The `Main` processs, for apps that need to run heavier compute jobs. And
* unlike electron it's optional.
*
* The Bridge process manages the Render and Main process, it may also broker
* data between them.
*
* The Binding process uses standard input and output as a way to communicate.
* Data written to the write-end of the pipe is buffered by the OS until it is
* read from the read-end of the pipe.
*
* The IPC protocol uses a simple URI-like scheme. Data is passed as
* ArrayBuffers.
*
* ```
* ipc://command?key1=value1&key2=value2...
* ```
*/
/* global window */
import {
AbortError,
InternalError,
TimeoutError
} from './errors.js'
import {
isBufferLike,
isPlainObject,
format,
parseJSON
} from './util.js'
import * as errors from './errors.js'
import { Buffer } from './buffer.js'
import console from './console.js'
let nextSeq = 1
export async function postMessage (...args) {
return await window?.__ipc?.postMessage(...args)
}
function initializeXHRIntercept () {
if (typeof window === 'undefined') return
const { send, open } = window.XMLHttpRequest.prototype
const B5_PREFIX_BUFFER = new Uint8Array([0x62, 0x35]) // literally, 'b5'
const encoder = new TextEncoder()
Object.assign(window.XMLHttpRequest.prototype, {
open (method, url, ...args) {
try {
this.readyState = window.XMLHttpRequest.OPENED
} catch (_) {}
this.method = method
this.url = new URL(url)
this.seq = this.url.searchParams.get('seq')
return open.call(this, method, url, ...args)
},
async send (body) {
const { method, seq, url } = this
const index = window.__args.index
if (url?.protocol === 'ipc:') {
if (
/put|post/i.test(method) &&
typeof body !== 'undefined' &&
typeof seq !== 'undefined'
) {
if (/android/i.test(window.__args.os)) {
await postMessage(`ipc://buffer.map?seq=${seq}`, body)
body = null
}
if (/linux/i.test(window.__args.os)) {
if (body?.buffer instanceof ArrayBuffer) {
const header = new Uint8Array(24)
const buffer = new Uint8Array(
B5_PREFIX_BUFFER.length +
header.length +
body.length
)
header.set(encoder.encode(index))
header.set(encoder.encode(seq), 4)
// <type> | <header> | <body>
// "b5"(2) | index(2) + seq(2) | body(n)
buffer.set(B5_PREFIX_BUFFER)
buffer.set(header, B5_PREFIX_BUFFER.length)
buffer.set(body, B5_PREFIX_BUFFER.length + header.length)
let data = []
const quota = 64 * 1024
for (let i = 0; i < buffer.length; i += quota) {
data.push(String.fromCharCode(...buffer.subarray(i, i + quota)))
}
data = data.join('')
try {
data = decodeURIComponent(escape(data))
} catch (_) {}
await postMessage(data)
}
body = null
}
}
}
return send.call(this, body)
}
})
}
if (typeof window !== 'undefined') {
initializeXHRIntercept()
document.addEventListener('DOMContentLoaded', () => {
queueMicrotask(async () => {
try {
await send('platform.event', 'domcontentloaded')
} catch (err) {
console.error('ERR:', err)
}
})
})
}
function getErrorClass (type, fallback) {
if (typeof window !== 'undefined' && typeof window[type] === 'function') {
return window[type]
}
if (typeof errors[type] === 'function') {
return errors[type]
}
return fallback || Error
}
function getRequestResponseText (request) {
try {
// can throw `InvalidStateError` error
return request?.responseText
} catch (_) {}
return null
}
function getRequestResponse (request) {
if (!request) return null
const { responseType } = request
let response = null
if (!responseType || responseType === 'text') {
// `responseText` could be an accessor which could throw an
// `InvalidStateError` error when accessed when `responseType` is anything
// but empty or `'text'`
// @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions}
const responseText = getRequestResponseText(request)
if (responseText) {
response = responseText
// maybe json for unspecified response types
if (!responseType) {
const json = parseJSON(response)
if (json) {
response = json
}
}
}
}
if (responseType === 'json') {
response = parseJSON(request.response)
}
if (responseType === 'arraybuffer') {
if (
request.response instanceof ArrayBuffer ||
typeof request.response === 'string' ||
isBufferLike(request.response)
) {
response = Buffer.from(request.response)
}
// maybe json in buffered response
const json = parseJSON(response)
if ((isPlainObject(json?.data) && json?.source) || isPlainObject(json?.err)) {
response = json
}
}
// try using `statusText` for stubbed response
if (!response) {
// defaults:
// `400...499: errors.NotAllowedError`
// `500...599: errors.InternalError`
const statusCodeToErrorCode = {
400: errors.BadRequestError,
403: errors.InvalidAccessError,
404: errors.NotFoundError,
408: errors.TimeoutError,
501: errors.NotSupportedError,
502: errors.NetworkError,
504: errors.TimeoutError
}
const { status, responseURL, statusText } = request
const message = Message.from(responseURL?.replace('http:', Message.PROTOCOL))
const source = message.command
if (status >= 100 && status < 400) {
const data = { status: statusText }
return { source, data }
} else if (status >= 400 && status < 499) {
const ErrorType = statusCodeToErrorCode[status] || errors.NotAllowedError
const err = new ErrorType(statusText || status)
err.url = responseURL
return { source, err }
} else if (status >= 500 && status < 599) {
const ErrorType = statusCodeToErrorCode[status] || errors.InternalError
const err = new ErrorType(statusText || status)
err.url = responseURL
return { source, err }
}
}
return response
}
function maybeMakeError (error, caller) {
const errors = {
AbortError: getErrorClass('AbortError'),
AggregateError: getErrorClass('AggregateError'),
EncodingError: getErrorClass('EncodingError'),
IndexSizeError: getErrorClass('IndexSizeError'),
InternalError,
InvalidAccessError: getErrorClass('InvalidAccessError'),
NetworkError: getErrorClass('NetworkError'),
NotAllowedError: getErrorClass('NotAllowedError'),
NotFoundError: getErrorClass('NotFoundError'),
NotSupportedError: getErrorClass('NotSupportedError'),
OperationError: getErrorClass('OperationError'),
RangeError: getErrorClass('RangeError'),
TimeoutError,
TypeError: getErrorClass('TypeError'),
URIError: getErrorClass('URIError')
}
if (!error) {
return null
}
if (error instanceof Error) {
return error
}
error = { ...error }
const type = error.type || 'Error'
const code = error.code
let err = null
delete error.type
if (type in errors) {
err = new errors[type](error.message || '')
} else {
for (const E of Object.values(errors)) {
if ((E.code && type === E.code) || (code && code === E.code)) {
err = new E(error.message || '')
break
}
}
}
if (!err) {
err = new Error(error.message || '')
}
// assign extra data to `err` like an error `code`
for (const key in error) {
try {
err[key] = error[key]
} catch (_) {}
}
if (
typeof Error.captureStackTrace === 'function' &&
typeof caller === 'function'
) {
Error.captureStackTrace(err, caller)
}
return err
}
function createUri (protocol, command) {
if (typeof window === 'object' && window?.__args.os === 'win32') {
protocol = 'http:'
}
return `${protocol}//${command}`
}
/**
* Represents an OK IPC status.
*/
export const OK = 0
/**
* Represents an ERROR IPC status.
*/
export const ERROR = 1
/**
* Timeout in milliseconds for IPC requests.
*/
export const TIMEOUT = 32 * 1000
/**
* Symbol for the `ipc.debug.enabled` property
*/
export const kDebugEnabled = Symbol.for('ipc.debug.enabled')
/**
* Parses `seq` as integer value
* @param {string|number} seq
* @param {object=} [options]
* @param {boolean} [options.bigint = false]
*/
export function parseSeq (seq, options) {
const value = String(seq).replace(/^R/i, '').replace(/n$/, '')
return options?.bigint === true ? BigInt(value) : parseInt(value)
}
/**
* If `debug.enabled === true`, then debug output will be printed to console.
* @param {(boolean)} [enable]
* @return {boolean}
*/
export function debug (enable) {
if (enable === true) {
debug.enabled = true
} else if (enable === false) {
debug.enabled = false
}
return debug.enabled
}
debug.log = () => undefined
Object.defineProperty(debug, 'enabled', {
enumerable: false,
set (value) {
debug[kDebugEnabled] = Boolean(value)
},
get () {
if (debug[kDebugEnabled] === undefined) {
return typeof window === 'undefined'
? false
: Boolean(window?.__args?.debug)
}
return debug[kDebugEnabled]
}
})
/**
* A container for a IPC message based on a `ipc://` URI scheme.
*/
export class Message extends URL {
/**
* The expected protocol for an IPC message.
*/
static get PROTOCOL () {
return 'ipc:'
}
/**
* Creates a `Message` instance from a variety of input.
* @param {string|URL|Message|Buffer|object} input
* @param {(object|string|URLSearchParams)=} [params]
* @return {Message}
*/
static from (input, params, bytes) {
const protocol = this.PROTOCOL
if (isBufferLike(input)) {
input = Buffer.from(input).toString()
}
if (isBufferLike(params)) {
bytes = Buffer.from(params)
params = null
} else if (bytes) {
bytes = Buffer.from(bytes)
}
if (input instanceof Message) {
const message = new this(String(input))
if (typeof params === 'object') {
const entries = params.entries ? params.entries() : Object.entries(params)
for (const [key, value] of entries) {
message.set(key, value)
}
}
return message
} else if (isPlainObject(input)) {
return new this(
`${input.protocol || protocol}//${input.command}?${new URLSearchParams({ ...input.params, ...params })}`,
bytes
)
}
if (typeof input === 'string' && params) {
return new this(`${protocol}//${input}?${new URLSearchParams(params)}`, bytes)
}
// coerce input into a string
const string = String(input)
if (string.startsWith(`${protocol}//`)) {
return new this(string, bytes)
}
return new this(`${protocol}//${input}`, bytes)
}
/**
* Predicate to determine if `input` is valid for constructing
* a new `Message` instance.
* @param {string|URL|Message|Buffer|object} input
* @return {boolean}
*/
static isValidInput (input) {
const protocol = this.PROTOCOL
const string = String(input)
return (
string.startsWith(`${protocol}//`) &&
string.length > protocol.length + 2
)
}
/**
* `Message` class constructor.
* @protected
* @param {string|URL} input
*/
constructor (input, bytes) {
super(input)
if (this.protocol !== this.constructor.PROTOCOL) {
throw new TypeError(format(
'Invalid protocol in input. Expected \'%s\' but got \'%s\'',
this.constructor.PROTOCOL, this.protocol
))
}
this.bytes = bytes || null
const properties = Object.getOwnPropertyDescriptors(Message.prototype)
Object.defineProperties(this, {
command: { ...properties.command, enumerable: true },
seq: { ...properties.seq, enumerable: true },
index: { ...properties.index, enumerable: true },
id: { ...properties.id, enumerable: true },
value: { ...properties.value, enumerable: true },
params: { ...properties.params, enumerable: true }
})
}
/**
* Computed IPC message name.
*/
get command () {
// TODO(jwerle): issue deprecation notice
return this.name
}
/**
* Computed IPC message name.
*/
get name () {
return this.hostname || this.host || this.pathname.slice(2)
}
/**
* Computed `id` value for the command.
*/
get id () {
return this.has('id') ? this.get('id') : null
}
/**
* Computed `seq` (sequence) value for the command.
*/
get seq () {
return this.has('seq') ? this.get('seq') : null
}
/**
* Computed message value potentially given in message parameters.
* This value is automatically decoded, but not treated as JSON.
*/
get value () {
return this.get('value') ?? null
}
/**
* Computed `index` value for the command potentially referring to
* the window index the command is scoped to or originating from. If not
* specified in the message parameters, then this value defaults to `-1`.
*/
get index () {
const index = this.get('index')
if (index !== undefined) {
const value = parseInt(index)
if (Number.isFinite(value)) {
return value
}
}
return -1
}
/**
* Computed value parsed as JSON. This value is `null` if the value is not present
* or it is invalid JSON.
*/
get json () {
return parseJSON(this.value)
}
/**
* Computed readonly object of message parameters.
*/
get params () {
return Object.fromEntries(this.entries())
}
/**
* Returns computed parameters as entries
* @return {Array<Array<string,mixed>>}
*/
entries () {
return Array.from(this.searchParams.entries()).map(([key, value]) => {
return [key, parseJSON(value) || value]
})
}
/**
* Set a parameter `value` by `key`.
* @param {string} key
* @param {mixed} value
*/
set (key, value) {
if (value && typeof value === 'object') {
value = JSON.stringify(value)
}
return this.searchParams.set(key, value)
}
/**
* Get a parameter value by `key`.
* @param {string} key
* @param {mixed} defaultValue
* @return {mixed}
*/
get (key, defaultValue) {
if (!this.has(key)) {
return defaultValue
}
const value = this.searchParams.get(key)
const json = value && parseJSON(value)
if (json === null || json === undefined) {
return value
}
return json
}
/**
* Delete a parameter by `key`.
* @param {string} key
* @return {boolean}
*/
delete (key) {
if (this.has(key)) {
return this.searchParams.delete(key)
}
return false
}
/**
* Computed parameter keys.
* @return {Array<string>}
*/
keys () {
return Array.from(this.searchParams.keys())
}
/**
* Computed parameter values.
* @return {Array<mixed>}
*/
values () {
return Array.from(this.searchParams.values()).map(parseJSON)
}
/**
* Predicate to determine if parameter `key` is present in parameters.
* @param {string} key
* @return {boolean}
*/
has (key) {
return this.searchParams.has(key)
}
/**
* Converts a `Message` instance into a plain JSON object.
*/
toJSON () {
const { protocol, command, params } = this
return { protocol, command, params }
}
}
/**
* A result type used internally for handling
* IPC result values from the native layer that are in the form
* of `{ err?, data? }`. The `data` and `err` properties on this
* type of object are in tuple form and be accessed at `[data?,err?]`
*/
export class Result {
/**
* Creates a `Result` instance from input that may be an object
* like `{ err?, data? }`, an `Error` instance, or just `data`.
* @param {(object|Error|mixed)=} result
* @param {Error=} [maybeError]
* @param {string=} [maybeSource]
* @return {Result}
*/
static from (result, maybeError, maybeSource, ...args) {
if (result instanceof Result) {
if (!result.source && maybeSource) {
result.source = maybeSource
}
if (!result.err && maybeError) {
result.err = maybeError
}
return result
}
if (result instanceof Error) {
result = { err: result }
}
if (!maybeSource && typeof maybeError === 'string') {
maybeSource = maybeError
maybeError = null
}
const err = maybeMakeError(result?.err || maybeError || null, Result.from)
const data = !err && result?.data !== null && result?.data !== undefined
? result.data
: (!err ? result : null)
const source = result?.source || maybeSource || null
return new this(err, data, source, ...args)
}
/**
* `Result` class constructor.
* @private
* @param {Error=} [err = null]
* @param {object=} [data = null]
* @param {string=} [source = undefined]
*/
constructor (err, data, source) {
this.err = typeof err !== 'undefined' ? err : null
this.data = typeof data !== 'undefined' ? data : null
this.source = typeof source === 'string' && source.length
? source
: undefined
Object.defineProperty(this, 0, {
get: () => this.err,
enumerable: false,
configurable: false
})
Object.defineProperty(this, 1, {
get: () => this.data,
enumerable: false,
configurable: false
})
Object.defineProperty(this, 2, {
get: () => this.source,
enumerable: false,
configurable: false
})
}
/**
* Computed result length.
*/
get length () {
return [...this].filter((v) => v !== undefined).length
}
/**
* Generator for an `Iterable` interface over this instance.
* @ignore
*/
* [Symbol.iterator] () {
yield this.err
yield this.data
yield this.source
}
}
/**
* Waits for the native IPC layer to be ready and exposed on the
* global window object.
*/
export async function ready () {
return await new Promise((resolve, reject) => {
if (typeof window === 'undefined') {
return reject(new TypeError('Global window object is not defined.'))
}
return loop()
function loop () {
if (window.__args) {
queueMicrotask(resolve)
} else {
queueMicrotask(loop)
}
}
})
}
/**
* Sends a synchronous IPC command over XHR returning a `Result`
* upon success or error.
* @param {string} command
* @param {(object|string)=} params
* @return {Result}
*/
export function sendSync (command, params) {
if (typeof window === 'undefined') {
if (debug.enabled) {
debug.log('Global window object is not defined')
}
return {}
}
const protocol = Message.PROTOCOL
const request = new window.XMLHttpRequest()
const index = window.__args.index ?? 0
const seq = nextSeq++
const uri = createUri(protocol, command)
params = new URLSearchParams(params)
params.set('index', index)
params.set('seq', 'R' + seq)
const query = `?${params}`
if (debug.enabled) {
debug.log('ipc.sendSync: %s', uri + query)
}
request.open('GET', uri + query, false)
request.setRequestHeader('x-ipc-request', command)
request.send()
const result = Result.from(getRequestResponse(request), null, command)
if (debug.enabled) {
debug.log('ipc.sendSync: (resolved)', command, result)
}
return result
}
/**
* Emit event to be dispatched on `window` object.
* @param {string} name
* @param {Mixed} value
* @param {EventTarget=} [target = window]
* @param {Object=} options
*/
export async function emit (name, value, target, options) {
let detail = value
await ready()
if (debug.enabled) {
debug.log('ipc.emit:', name, value, target, options)
}
if (typeof value === 'string') {
try {
detail = decodeURIComponent(value)
detail = JSON.parse(detail)
} catch (err) {
// consider okay here because if detail is defined then
// `decodeURIComponent(value)` was successful and `JSON.parse(value)`
// was not: there could be bad/unsupported unicode in `value`
if (!detail) {
console.error(`${err.message} (${value})`)
return
}
}
}
const event = new window.CustomEvent(name, { detail, ...options })
if (target) {
target.dispatchEvent(event)
} else {
window.dispatchEvent(event)
}
}
/**
* Resolves a request by `seq` with possible value.
* @param {string} seq
* @param {Mixed} value
*/
export async function resolve (seq, value) {
await ready()
if (debug.enabled) {
debug.log('ipc.resolve:', seq, value)
}
const index = window.__args.index
const eventName = `resolve-${index}-${seq}`
const event = new window.CustomEvent(eventName, { detail: value })
window.dispatchEvent(event)
}
/**
* Sends an async IPC command request with parameters.
* @param {string} command
* @param {Mixed=} value
* @return {Promise<Result>}
*/
export async function send (command, value) {
await ready()
if (debug.enabled) {
debug.log('ipc.send:', command, value)
}
const seq = 'R' + nextSeq++
const index = value?.index ?? window.__args.index
let serialized = ''
try {
if (value !== undefined && ({}).toString.call(value) !== '[object Object]') {
value = { value }
}
const params = {
...value,
index,
seq
}
serialized = new URLSearchParams(params).toString()
serialized = serialized.replace(/\+/g, '%20')
} catch (err) {
console.error(`${err.message} (${serialized})`)
return Promise.reject(err.message)
}
postMessage(`ipc://${command}?${serialized}`)
return await new Promise((resolve) => {
const event = `resolve-${index}-${seq}`
window.addEventListener(event, onresolve, { once: true })
function onresolve (event) {
const result = Result.from(event.detail, null, command)
if (debug.enabled) {
debug.log('ipc.send: (resolved)', command, result)
}
resolve(result)
}
})
}
/**
* Sends an async IPC command request with parameters and buffered bytes.
* @param {string} command
* @param {object=} params
* @param {(Buffer|TypeArray|ArrayBuffer|string|Array)=} buffer
* @param {object=} options
*/
export async function write (command, params, buffer, options) {
if (typeof window === 'undefined') {
debug.log('Global window object is not defined')
return {}
}
await ready()
const protocol = Message.PROTOCOL
const request = new window.XMLHttpRequest()
const signal = options?.signal
const index = window.__args.index ?? 0
const seq = nextSeq++
const uri = createUri(protocol, command)
let resolved = false
let aborted = false
let timeout = null
if (signal) {
if (signal.aborted) {
return Result.from(null, new AbortError(signal), command)
}
signal.addEventListener('abort', () => {
if (!aborted && !resolved) {
aborted = true
request.abort()
}
})
}
params = new URLSearchParams(params)
params.set('index', index)
params.set('seq', 'R' + seq)
const query = `?${params}`
request.open('POST', uri + query, true)
request.setRequestHeader('x-ipc-request', command)
await request.send(buffer || null)
if (debug.enabled) {
debug.log('ipc.write:', uri + query, buffer || null)
}
return await new Promise((resolve) => {
if (options?.timeout) {
timeout = setTimeout(() => {
resolve(Result.from(null, new TimeoutError('ipc.write timedout'), command))
request.abort()
}, typeof options.timeout === 'number' ? options.timeout : TIMEOUT)
}
request.onabort = () => {
aborted = true
if (options?.timeout) {
clearTimeout(timeout)
}
resolve(Result.from(null, new AbortError(signal), command))
}
request.onreadystatechange = () => {
if (aborted) {
return
}
if (request.readyState === window.XMLHttpRequest.DONE) {
resolved = true
clearTimeout(timeout)
const result = Result.from(getRequestResponse(request), null, command)
if (debug.enabled) {
debug.log('ipc.write: (resolved)', command, result)