@fingerprint79/react-native 0.0.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 (52) hide show
  1. package/README.md +145 -0
  2. package/android/build.gradle +59 -0
  3. package/android/src/main/AndroidManifest.xml +8 -0
  4. package/android/src/main/java/com/fingerprint79/rn/FpRnModule.kt +121 -0
  5. package/android/src/main/java/com/fingerprint79/rn/FpRnPackage.kt +19 -0
  6. package/dist/.tsbuildinfo-build +1 -0
  7. package/dist/client.d.ts +13 -0
  8. package/dist/client.d.ts.map +1 -0
  9. package/dist/context.d.ts +17 -0
  10. package/dist/context.d.ts.map +1 -0
  11. package/dist/hooks.d.ts +27 -0
  12. package/dist/hooks.d.ts.map +1 -0
  13. package/dist/index.cjs +3717 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.d.ts +20 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.mjs +3717 -0
  18. package/dist/index.mjs.map +1 -0
  19. package/dist/native.d.ts +9 -0
  20. package/dist/native.d.ts.map +1 -0
  21. package/dist/signals/hardware.d.ts +11 -0
  22. package/dist/signals/hardware.d.ts.map +1 -0
  23. package/dist/signals/index.d.ts +3 -0
  24. package/dist/signals/index.d.ts.map +1 -0
  25. package/dist/signals/intl.d.ts +5 -0
  26. package/dist/signals/intl.d.ts.map +1 -0
  27. package/dist/signals/mobile.d.ts +24 -0
  28. package/dist/signals/mobile.d.ts.map +1 -0
  29. package/dist/signals/network.d.ts +5 -0
  30. package/dist/signals/network.d.ts.map +1 -0
  31. package/dist/signals/persistence.d.ts +17 -0
  32. package/dist/signals/persistence.d.ts.map +1 -0
  33. package/dist/types.d.ts +50 -0
  34. package/dist/types.d.ts.map +1 -0
  35. package/fingerprint79-react-native.podspec +26 -0
  36. package/ios/FpRnModule.m +16 -0
  37. package/ios/FpRnModule.swift +134 -0
  38. package/package.json +91 -0
  39. package/react-native.config.js +18 -0
  40. package/src/client.ts +89 -0
  41. package/src/context.tsx +82 -0
  42. package/src/hooks.ts +116 -0
  43. package/src/index.ts +20 -0
  44. package/src/native.ts +39 -0
  45. package/src/signals/hardware.ts +36 -0
  46. package/src/signals/index.ts +44 -0
  47. package/src/signals/intl.ts +63 -0
  48. package/src/signals/mobile.ts +23 -0
  49. package/src/signals/network.ts +51 -0
  50. package/src/signals/persistence.ts +77 -0
  51. package/src/signals/signals.test.ts +111 -0
  52. package/src/types.ts +54 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,3717 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ import { jsx } from "react/jsx-runtime";
5
+ import { useMemo, useState, useEffect, createContext, useContext, useCallback } from "react";
6
+ import { Dimensions, PixelRatio, Platform, NativeModules, I18nManager } from "react-native";
7
+ let decoder;
8
+ try {
9
+ decoder = new TextDecoder();
10
+ } catch (error) {
11
+ }
12
+ let src;
13
+ let srcEnd;
14
+ let position$1 = 0;
15
+ const LEGACY_RECORD_INLINE_ID = 105;
16
+ const RECORD_DEFINITIONS_ID = 57342;
17
+ const RECORD_INLINE_ID = 57343;
18
+ const BUNDLED_STRINGS_ID = 57337;
19
+ const PACKED_REFERENCE_TAG_ID = 6;
20
+ const STOP_CODE = {};
21
+ let maxArraySize = 11281e4;
22
+ let maxMapSize = 1681e4;
23
+ let currentDecoder = {};
24
+ let currentStructures;
25
+ let srcString;
26
+ let srcStringStart = 0;
27
+ let srcStringEnd = 0;
28
+ let bundledStrings$1;
29
+ let referenceMap;
30
+ let currentExtensions = [];
31
+ let currentExtensionRanges = [];
32
+ let packedValues;
33
+ let dataView;
34
+ let restoreMapsAsObject;
35
+ let defaultOptions = {
36
+ useRecords: false,
37
+ mapsAsObjects: true
38
+ };
39
+ let sequentialMode = false;
40
+ let inlineObjectReadThreshold = 2;
41
+ try {
42
+ new Function("");
43
+ } catch (error) {
44
+ inlineObjectReadThreshold = Infinity;
45
+ }
46
+ class Decoder {
47
+ constructor(options) {
48
+ if (options) {
49
+ if ((options.keyMap || options._keyMap) && !options.useRecords) {
50
+ options.useRecords = false;
51
+ options.mapsAsObjects = true;
52
+ }
53
+ if (options.useRecords === false && options.mapsAsObjects === void 0)
54
+ options.mapsAsObjects = true;
55
+ if (options.getStructures)
56
+ options.getShared = options.getStructures;
57
+ if (options.getShared && !options.structures)
58
+ (options.structures = []).uninitialized = true;
59
+ if (options.keyMap) {
60
+ this.mapKey = /* @__PURE__ */ new Map();
61
+ for (let [k, v] of Object.entries(options.keyMap)) this.mapKey.set(v, k);
62
+ }
63
+ }
64
+ Object.assign(this, options);
65
+ }
66
+ /*
67
+ decodeKey(key) {
68
+ return this.keyMap
69
+ ? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key
70
+ : key
71
+ }
72
+ */
73
+ decodeKey(key) {
74
+ return this.keyMap ? this.mapKey.get(key) || key : key;
75
+ }
76
+ encodeKey(key) {
77
+ return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key;
78
+ }
79
+ encodeKeys(rec) {
80
+ if (!this._keyMap) return rec;
81
+ let map = /* @__PURE__ */ new Map();
82
+ for (let [k, v] of Object.entries(rec)) map.set(this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k, v);
83
+ return map;
84
+ }
85
+ decodeKeys(map) {
86
+ if (!this._keyMap || map.constructor.name != "Map") return map;
87
+ if (!this._mapKey) {
88
+ this._mapKey = /* @__PURE__ */ new Map();
89
+ for (let [k, v] of Object.entries(this._keyMap)) this._mapKey.set(v, k);
90
+ }
91
+ let res = {};
92
+ map.forEach((v, k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v);
93
+ return res;
94
+ }
95
+ mapDecode(source, end) {
96
+ let res = this.decode(source);
97
+ if (this._keyMap) {
98
+ switch (res.constructor.name) {
99
+ case "Array":
100
+ return res.map((r) => this.decodeKeys(r));
101
+ }
102
+ }
103
+ return res;
104
+ }
105
+ decode(source, end) {
106
+ if (src) {
107
+ return saveState(() => {
108
+ clearSource();
109
+ return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end);
110
+ });
111
+ }
112
+ srcEnd = end > -1 ? end : source.length;
113
+ position$1 = 0;
114
+ srcStringEnd = 0;
115
+ srcString = null;
116
+ bundledStrings$1 = null;
117
+ src = source;
118
+ try {
119
+ dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
120
+ } catch (error) {
121
+ src = null;
122
+ if (source instanceof Uint8Array)
123
+ throw error;
124
+ throw new Error("Source must be a Uint8Array or Buffer but was a " + (source && typeof source == "object" ? source.constructor.name : typeof source));
125
+ }
126
+ if (this instanceof Decoder) {
127
+ currentDecoder = this;
128
+ packedValues = this.sharedValues && (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) : this.sharedValues);
129
+ if (this.structures) {
130
+ currentStructures = this.structures;
131
+ return checkedRead();
132
+ } else if (!currentStructures || currentStructures.length > 0) {
133
+ currentStructures = [];
134
+ }
135
+ } else {
136
+ currentDecoder = defaultOptions;
137
+ if (!currentStructures || currentStructures.length > 0)
138
+ currentStructures = [];
139
+ packedValues = null;
140
+ }
141
+ return checkedRead();
142
+ }
143
+ decodeMultiple(source, forEach) {
144
+ let values, lastPosition = 0;
145
+ try {
146
+ let size = source.length;
147
+ sequentialMode = true;
148
+ let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size);
149
+ if (forEach) {
150
+ if (forEach(value) === false) {
151
+ return;
152
+ }
153
+ while (position$1 < size) {
154
+ lastPosition = position$1;
155
+ if (forEach(checkedRead()) === false) {
156
+ return;
157
+ }
158
+ }
159
+ } else {
160
+ values = [value];
161
+ while (position$1 < size) {
162
+ lastPosition = position$1;
163
+ values.push(checkedRead());
164
+ }
165
+ return values;
166
+ }
167
+ } catch (error) {
168
+ error.lastPosition = lastPosition;
169
+ error.values = values;
170
+ throw error;
171
+ } finally {
172
+ sequentialMode = false;
173
+ clearSource();
174
+ }
175
+ }
176
+ }
177
+ function checkedRead() {
178
+ try {
179
+ let result = read();
180
+ if (bundledStrings$1) {
181
+ if (position$1 >= bundledStrings$1.postBundlePosition) {
182
+ let error = new Error("Unexpected bundle position");
183
+ error.incomplete = true;
184
+ throw error;
185
+ }
186
+ position$1 = bundledStrings$1.postBundlePosition;
187
+ bundledStrings$1 = null;
188
+ }
189
+ if (position$1 == srcEnd) {
190
+ currentStructures = null;
191
+ src = null;
192
+ if (referenceMap)
193
+ referenceMap = null;
194
+ } else if (position$1 > srcEnd) {
195
+ let error = new Error("Unexpected end of CBOR data");
196
+ error.incomplete = true;
197
+ throw error;
198
+ } else if (!sequentialMode) {
199
+ throw new Error("Data read, but end of buffer not reached");
200
+ }
201
+ return result;
202
+ } catch (error) {
203
+ clearSource();
204
+ if (error instanceof RangeError || error.message.startsWith("Unexpected end of buffer")) {
205
+ error.incomplete = true;
206
+ }
207
+ throw error;
208
+ }
209
+ }
210
+ function read() {
211
+ let token = src[position$1++];
212
+ let majorType = token >> 5;
213
+ token = token & 31;
214
+ if (token > 23) {
215
+ switch (token) {
216
+ case 24:
217
+ token = src[position$1++];
218
+ break;
219
+ case 25:
220
+ if (majorType == 7) {
221
+ return getFloat16();
222
+ }
223
+ token = dataView.getUint16(position$1);
224
+ position$1 += 2;
225
+ break;
226
+ case 26:
227
+ if (majorType == 7) {
228
+ let value = dataView.getFloat32(position$1);
229
+ if (currentDecoder.useFloat32 > 2) {
230
+ let multiplier = mult10[(src[position$1] & 127) << 1 | src[position$1 + 1] >> 7];
231
+ position$1 += 4;
232
+ return (multiplier * value + (value > 0 ? 0.5 : -0.5) >> 0) / multiplier;
233
+ }
234
+ position$1 += 4;
235
+ return value;
236
+ }
237
+ token = dataView.getUint32(position$1);
238
+ position$1 += 4;
239
+ if (majorType === 1) return -1 - token;
240
+ break;
241
+ case 27:
242
+ if (majorType == 7) {
243
+ let value = dataView.getFloat64(position$1);
244
+ position$1 += 8;
245
+ return value;
246
+ }
247
+ if (majorType > 1) {
248
+ if (dataView.getUint32(position$1) > 0)
249
+ throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");
250
+ token = dataView.getUint32(position$1 + 4);
251
+ } else if (currentDecoder.int64AsNumber) {
252
+ token = dataView.getUint32(position$1) * 4294967296;
253
+ token += dataView.getUint32(position$1 + 4);
254
+ } else token = dataView.getBigUint64(position$1);
255
+ position$1 += 8;
256
+ break;
257
+ case 31:
258
+ switch (majorType) {
259
+ case 2:
260
+ case 3:
261
+ throw new Error("Indefinite length not supported for byte or text strings");
262
+ case 4:
263
+ let array = [];
264
+ let value, i = 0;
265
+ while ((value = read()) != STOP_CODE) {
266
+ if (i >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`);
267
+ array[i++] = value;
268
+ }
269
+ return majorType == 4 ? array : majorType == 3 ? array.join("") : Buffer.concat(array);
270
+ case 5:
271
+ let key;
272
+ if (currentDecoder.mapsAsObjects) {
273
+ let object = {};
274
+ let i2 = 0;
275
+ if (currentDecoder.keyMap) {
276
+ while ((key = read()) != STOP_CODE) {
277
+ if (i2++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`);
278
+ object[safeKey(currentDecoder.decodeKey(key))] = read();
279
+ }
280
+ } else {
281
+ while ((key = read()) != STOP_CODE) {
282
+ if (i2++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`);
283
+ object[safeKey(key)] = read();
284
+ }
285
+ }
286
+ return object;
287
+ } else {
288
+ if (restoreMapsAsObject) {
289
+ currentDecoder.mapsAsObjects = true;
290
+ restoreMapsAsObject = false;
291
+ }
292
+ let map = /* @__PURE__ */ new Map();
293
+ if (currentDecoder.keyMap) {
294
+ let i2 = 0;
295
+ while ((key = read()) != STOP_CODE) {
296
+ if (i2++ >= maxMapSize) {
297
+ throw new Error(`Map size exceeds ${maxMapSize}`);
298
+ }
299
+ map.set(currentDecoder.decodeKey(key), read());
300
+ }
301
+ } else {
302
+ let i2 = 0;
303
+ while ((key = read()) != STOP_CODE) {
304
+ if (i2++ >= maxMapSize) {
305
+ throw new Error(`Map size exceeds ${maxMapSize}`);
306
+ }
307
+ map.set(key, read());
308
+ }
309
+ }
310
+ return map;
311
+ }
312
+ case 7:
313
+ return STOP_CODE;
314
+ default:
315
+ throw new Error("Invalid major type for indefinite length " + majorType);
316
+ }
317
+ default:
318
+ throw new Error("Unknown token " + token);
319
+ }
320
+ }
321
+ switch (majorType) {
322
+ case 0:
323
+ return token;
324
+ case 1:
325
+ return ~token;
326
+ case 2:
327
+ return readBin(token);
328
+ case 3:
329
+ if (srcStringEnd >= position$1) {
330
+ return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart);
331
+ }
332
+ if (srcStringEnd == 0 && srcEnd < 140 && token < 32) {
333
+ let string = token < 16 ? shortStringInJS(token) : longStringInJS(token);
334
+ if (string != null)
335
+ return string;
336
+ }
337
+ return readFixedString(token);
338
+ case 4:
339
+ if (token >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`);
340
+ let array = new Array(token);
341
+ for (let i = 0; i < token; i++) array[i] = read();
342
+ return array;
343
+ case 5:
344
+ if (token >= maxMapSize) throw new Error(`Map size exceeds ${maxArraySize}`);
345
+ if (currentDecoder.mapsAsObjects) {
346
+ let object = {};
347
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read();
348
+ else for (let i = 0; i < token; i++) object[safeKey(read())] = read();
349
+ return object;
350
+ } else {
351
+ if (restoreMapsAsObject) {
352
+ currentDecoder.mapsAsObjects = true;
353
+ restoreMapsAsObject = false;
354
+ }
355
+ let map = /* @__PURE__ */ new Map();
356
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()), read());
357
+ else for (let i = 0; i < token; i++) map.set(read(), read());
358
+ return map;
359
+ }
360
+ case 6:
361
+ if (token >= BUNDLED_STRINGS_ID) {
362
+ let structure = currentStructures[token & 8191];
363
+ if (structure) {
364
+ if (!structure.read) structure.read = createStructureReader(structure);
365
+ return structure.read();
366
+ }
367
+ if (token < 65536) {
368
+ if (token == RECORD_INLINE_ID) {
369
+ let length = readJustLength();
370
+ let id = read();
371
+ let structure2 = read();
372
+ recordDefinition(id, structure2);
373
+ let object = {};
374
+ if (currentDecoder.keyMap) for (let i = 2; i < length; i++) {
375
+ let key = currentDecoder.decodeKey(structure2[i - 2]);
376
+ object[safeKey(key)] = read();
377
+ }
378
+ else for (let i = 2; i < length; i++) {
379
+ let key = structure2[i - 2];
380
+ object[safeKey(key)] = read();
381
+ }
382
+ return object;
383
+ } else if (token == RECORD_DEFINITIONS_ID) {
384
+ let length = readJustLength();
385
+ let id = read();
386
+ for (let i = 2; i < length; i++) {
387
+ recordDefinition(id++, read());
388
+ }
389
+ return read();
390
+ } else if (token == BUNDLED_STRINGS_ID) {
391
+ return readBundleExt();
392
+ }
393
+ if (currentDecoder.getShared) {
394
+ loadShared();
395
+ structure = currentStructures[token & 8191];
396
+ if (structure) {
397
+ if (!structure.read)
398
+ structure.read = createStructureReader(structure);
399
+ return structure.read();
400
+ }
401
+ }
402
+ }
403
+ }
404
+ let extension = currentExtensions[token];
405
+ if (extension) {
406
+ if (extension.handlesRead)
407
+ return extension(read);
408
+ else
409
+ return extension(read());
410
+ } else {
411
+ let input = read();
412
+ for (let i = 0; i < currentExtensionRanges.length; i++) {
413
+ let value = currentExtensionRanges[i](token, input);
414
+ if (value !== void 0)
415
+ return value;
416
+ }
417
+ return new Tag(input, token);
418
+ }
419
+ case 7:
420
+ switch (token) {
421
+ case 20:
422
+ return false;
423
+ case 21:
424
+ return true;
425
+ case 22:
426
+ return null;
427
+ case 23:
428
+ return;
429
+ case 31:
430
+ default:
431
+ let packedValue = (packedValues || getPackedValues())[token];
432
+ if (packedValue !== void 0)
433
+ return packedValue;
434
+ throw new Error("Unknown token " + token);
435
+ }
436
+ default:
437
+ if (isNaN(token)) {
438
+ let error = new Error("Unexpected end of CBOR data");
439
+ error.incomplete = true;
440
+ throw error;
441
+ }
442
+ throw new Error("Unknown CBOR token " + token);
443
+ }
444
+ }
445
+ const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
446
+ function createStructureReader(structure) {
447
+ if (!structure) throw new Error("Structure is required in record definition");
448
+ function readObject() {
449
+ let length = src[position$1++];
450
+ length = length & 31;
451
+ if (length > 23) {
452
+ switch (length) {
453
+ case 24:
454
+ length = src[position$1++];
455
+ break;
456
+ case 25:
457
+ length = dataView.getUint16(position$1);
458
+ position$1 += 2;
459
+ break;
460
+ case 26:
461
+ length = dataView.getUint32(position$1);
462
+ position$1 += 4;
463
+ break;
464
+ default:
465
+ throw new Error("Expected array header, but got " + src[position$1 - 1]);
466
+ }
467
+ }
468
+ let compiledReader = this.compiledReader;
469
+ while (compiledReader) {
470
+ if (compiledReader.propertyCount === length)
471
+ return compiledReader(read);
472
+ compiledReader = compiledReader.next;
473
+ }
474
+ if (this.slowReads++ >= inlineObjectReadThreshold) {
475
+ let array = this.length == length ? this : this.slice(0, length);
476
+ compiledReader = currentDecoder.keyMap ? new Function("r", "return {" + array.map((k) => currentDecoder.decodeKey(k)).map((k) => validName.test(k) ? safeKey(k) + ":r()" : "[" + JSON.stringify(k) + "]:r()").join(",") + "}") : new Function("r", "return {" + array.map((key) => validName.test(key) ? safeKey(key) + ":r()" : "[" + JSON.stringify(key) + "]:r()").join(",") + "}");
477
+ if (this.compiledReader)
478
+ compiledReader.next = this.compiledReader;
479
+ compiledReader.propertyCount = length;
480
+ this.compiledReader = compiledReader;
481
+ return compiledReader(read);
482
+ }
483
+ let object = {};
484
+ if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read();
485
+ else for (let i = 0; i < length; i++) {
486
+ object[safeKey(this[i])] = read();
487
+ }
488
+ return object;
489
+ }
490
+ structure.slowReads = 0;
491
+ return readObject;
492
+ }
493
+ function safeKey(key) {
494
+ if (typeof key === "string") return key === "__proto__" ? "__proto_" : key;
495
+ if (typeof key === "number" || typeof key === "boolean" || typeof key === "bigint") return key.toString();
496
+ if (key == null) return key + "";
497
+ throw new Error("Invalid property name type " + typeof key);
498
+ }
499
+ let readFixedString = readStringJS;
500
+ function readStringJS(length) {
501
+ let result;
502
+ if (length < 16) {
503
+ if (result = shortStringInJS(length))
504
+ return result;
505
+ }
506
+ if (length > 64 && decoder)
507
+ return decoder.decode(src.subarray(position$1, position$1 += length));
508
+ const end = position$1 + length;
509
+ const units = [];
510
+ result = "";
511
+ while (position$1 < end) {
512
+ const byte1 = src[position$1++];
513
+ if ((byte1 & 128) === 0) {
514
+ units.push(byte1);
515
+ } else if ((byte1 & 224) === 192) {
516
+ const byte2 = src[position$1++] & 63;
517
+ const codePoint = (byte1 & 31) << 6 | byte2;
518
+ if (codePoint < 128) {
519
+ units.push(65533);
520
+ } else {
521
+ units.push(codePoint);
522
+ }
523
+ } else if ((byte1 & 240) === 224) {
524
+ const byte2 = src[position$1++] & 63;
525
+ const byte3 = src[position$1++] & 63;
526
+ const codePoint = (byte1 & 31) << 12 | byte2 << 6 | byte3;
527
+ if (codePoint < 2048 || codePoint >= 55296 && codePoint <= 57343) {
528
+ units.push(65533);
529
+ } else {
530
+ units.push(codePoint);
531
+ }
532
+ } else if ((byte1 & 248) === 240) {
533
+ const byte2 = src[position$1++] & 63;
534
+ const byte3 = src[position$1++] & 63;
535
+ const byte4 = src[position$1++] & 63;
536
+ let unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4;
537
+ if (unit < 65536 || unit > 1114111) {
538
+ units.push(65533);
539
+ } else if (unit > 65535) {
540
+ unit -= 65536;
541
+ units.push(unit >>> 10 & 1023 | 55296);
542
+ unit = 56320 | unit & 1023;
543
+ units.push(unit);
544
+ } else {
545
+ units.push(unit);
546
+ }
547
+ } else {
548
+ units.push(65533);
549
+ }
550
+ if (units.length >= 4096) {
551
+ result += fromCharCode.apply(String, units);
552
+ units.length = 0;
553
+ }
554
+ }
555
+ if (units.length > 0) {
556
+ result += fromCharCode.apply(String, units);
557
+ }
558
+ return result;
559
+ }
560
+ let fromCharCode = String.fromCharCode;
561
+ function longStringInJS(length) {
562
+ let start = position$1;
563
+ let bytes = new Array(length);
564
+ for (let i = 0; i < length; i++) {
565
+ const byte = src[position$1++];
566
+ if ((byte & 128) > 0) {
567
+ position$1 = start;
568
+ return;
569
+ }
570
+ bytes[i] = byte;
571
+ }
572
+ return fromCharCode.apply(String, bytes);
573
+ }
574
+ function shortStringInJS(length) {
575
+ if (length < 4) {
576
+ if (length < 2) {
577
+ if (length === 0)
578
+ return "";
579
+ else {
580
+ let a = src[position$1++];
581
+ if ((a & 128) > 1) {
582
+ position$1 -= 1;
583
+ return;
584
+ }
585
+ return fromCharCode(a);
586
+ }
587
+ } else {
588
+ let a = src[position$1++];
589
+ let b = src[position$1++];
590
+ if ((a & 128) > 0 || (b & 128) > 0) {
591
+ position$1 -= 2;
592
+ return;
593
+ }
594
+ if (length < 3)
595
+ return fromCharCode(a, b);
596
+ let c = src[position$1++];
597
+ if ((c & 128) > 0) {
598
+ position$1 -= 3;
599
+ return;
600
+ }
601
+ return fromCharCode(a, b, c);
602
+ }
603
+ } else {
604
+ let a = src[position$1++];
605
+ let b = src[position$1++];
606
+ let c = src[position$1++];
607
+ let d = src[position$1++];
608
+ if ((a & 128) > 0 || (b & 128) > 0 || (c & 128) > 0 || (d & 128) > 0) {
609
+ position$1 -= 4;
610
+ return;
611
+ }
612
+ if (length < 6) {
613
+ if (length === 4)
614
+ return fromCharCode(a, b, c, d);
615
+ else {
616
+ let e = src[position$1++];
617
+ if ((e & 128) > 0) {
618
+ position$1 -= 5;
619
+ return;
620
+ }
621
+ return fromCharCode(a, b, c, d, e);
622
+ }
623
+ } else if (length < 8) {
624
+ let e = src[position$1++];
625
+ let f = src[position$1++];
626
+ if ((e & 128) > 0 || (f & 128) > 0) {
627
+ position$1 -= 6;
628
+ return;
629
+ }
630
+ if (length < 7)
631
+ return fromCharCode(a, b, c, d, e, f);
632
+ let g = src[position$1++];
633
+ if ((g & 128) > 0) {
634
+ position$1 -= 7;
635
+ return;
636
+ }
637
+ return fromCharCode(a, b, c, d, e, f, g);
638
+ } else {
639
+ let e = src[position$1++];
640
+ let f = src[position$1++];
641
+ let g = src[position$1++];
642
+ let h = src[position$1++];
643
+ if ((e & 128) > 0 || (f & 128) > 0 || (g & 128) > 0 || (h & 128) > 0) {
644
+ position$1 -= 8;
645
+ return;
646
+ }
647
+ if (length < 10) {
648
+ if (length === 8)
649
+ return fromCharCode(a, b, c, d, e, f, g, h);
650
+ else {
651
+ let i = src[position$1++];
652
+ if ((i & 128) > 0) {
653
+ position$1 -= 9;
654
+ return;
655
+ }
656
+ return fromCharCode(a, b, c, d, e, f, g, h, i);
657
+ }
658
+ } else if (length < 12) {
659
+ let i = src[position$1++];
660
+ let j = src[position$1++];
661
+ if ((i & 128) > 0 || (j & 128) > 0) {
662
+ position$1 -= 10;
663
+ return;
664
+ }
665
+ if (length < 11)
666
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j);
667
+ let k = src[position$1++];
668
+ if ((k & 128) > 0) {
669
+ position$1 -= 11;
670
+ return;
671
+ }
672
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k);
673
+ } else {
674
+ let i = src[position$1++];
675
+ let j = src[position$1++];
676
+ let k = src[position$1++];
677
+ let l = src[position$1++];
678
+ if ((i & 128) > 0 || (j & 128) > 0 || (k & 128) > 0 || (l & 128) > 0) {
679
+ position$1 -= 12;
680
+ return;
681
+ }
682
+ if (length < 14) {
683
+ if (length === 12)
684
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l);
685
+ else {
686
+ let m = src[position$1++];
687
+ if ((m & 128) > 0) {
688
+ position$1 -= 13;
689
+ return;
690
+ }
691
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m);
692
+ }
693
+ } else {
694
+ let m = src[position$1++];
695
+ let n = src[position$1++];
696
+ if ((m & 128) > 0 || (n & 128) > 0) {
697
+ position$1 -= 14;
698
+ return;
699
+ }
700
+ if (length < 15)
701
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
702
+ let o = src[position$1++];
703
+ if ((o & 128) > 0) {
704
+ position$1 -= 15;
705
+ return;
706
+ }
707
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
708
+ }
709
+ }
710
+ }
711
+ }
712
+ }
713
+ function readBin(length) {
714
+ return currentDecoder.copyBuffers ? (
715
+ // specifically use the copying slice (not the node one)
716
+ Uint8Array.prototype.slice.call(src, position$1, position$1 += length)
717
+ ) : src.subarray(position$1, position$1 += length);
718
+ }
719
+ let f32Array = new Float32Array(1);
720
+ let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
721
+ function getFloat16() {
722
+ let byte0 = src[position$1++];
723
+ let byte1 = src[position$1++];
724
+ let exponent = (byte0 & 127) >> 2;
725
+ if (exponent === 31) {
726
+ if (byte1 || byte0 & 3)
727
+ return NaN;
728
+ return byte0 & 128 ? -Infinity : Infinity;
729
+ }
730
+ if (exponent === 0) {
731
+ let abs = ((byte0 & 3) << 8 | byte1) / (1 << 24);
732
+ return byte0 & 128 ? -abs : abs;
733
+ }
734
+ u8Array[3] = byte0 & 128 | // sign bit
735
+ (exponent >> 1) + 56;
736
+ u8Array[2] = (byte0 & 7) << 5 | // last exponent bit and first two mantissa bits
737
+ byte1 >> 3;
738
+ u8Array[1] = byte1 << 5;
739
+ u8Array[0] = 0;
740
+ return f32Array[0];
741
+ }
742
+ new Array(4096);
743
+ class Tag {
744
+ constructor(value, tag) {
745
+ this.value = value;
746
+ this.tag = tag;
747
+ }
748
+ }
749
+ currentExtensions[0] = (dateString) => {
750
+ return new Date(dateString);
751
+ };
752
+ currentExtensions[1] = (epochSec) => {
753
+ return new Date(Math.round(epochSec * 1e3));
754
+ };
755
+ currentExtensions[2] = (buffer) => {
756
+ let value = BigInt(0);
757
+ for (let i = 0, l = buffer.byteLength; i < l; i++) {
758
+ value = BigInt(buffer[i]) + (value << BigInt(8));
759
+ }
760
+ return value;
761
+ };
762
+ currentExtensions[3] = (buffer) => {
763
+ return BigInt(-1) - currentExtensions[2](buffer);
764
+ };
765
+ currentExtensions[4] = (fraction) => {
766
+ return +(fraction[1] + "e" + fraction[0]);
767
+ };
768
+ currentExtensions[5] = (fraction) => {
769
+ return fraction[1] * Math.exp(fraction[0] * Math.log(2));
770
+ };
771
+ const recordDefinition = (id, structure) => {
772
+ id = id - 57344;
773
+ let existingStructure = currentStructures[id];
774
+ if (existingStructure && existingStructure.isShared) {
775
+ (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
776
+ }
777
+ currentStructures[id] = structure;
778
+ structure.read = createStructureReader(structure);
779
+ };
780
+ currentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => {
781
+ let length = data.length;
782
+ let structure = data[1];
783
+ recordDefinition(data[0], structure);
784
+ let object = {};
785
+ for (let i = 2; i < length; i++) {
786
+ let key = structure[i - 2];
787
+ object[safeKey(key)] = data[i];
788
+ }
789
+ return object;
790
+ };
791
+ currentExtensions[14] = (value) => {
792
+ if (bundledStrings$1)
793
+ return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 += value);
794
+ return new Tag(value, 14);
795
+ };
796
+ currentExtensions[15] = (value) => {
797
+ if (bundledStrings$1)
798
+ return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value);
799
+ return new Tag(value, 15);
800
+ };
801
+ let glbl = { Error, RegExp };
802
+ currentExtensions[27] = (data) => {
803
+ return (glbl[data[0]] || Error)(data[1], data[2]);
804
+ };
805
+ const packedTable = (read2) => {
806
+ if (src[position$1++] != 132) {
807
+ let error = new Error("Packed values structure must be followed by a 4 element array");
808
+ if (src.length < position$1)
809
+ error.incomplete = true;
810
+ throw error;
811
+ }
812
+ let newPackedValues = read2();
813
+ if (!newPackedValues || !newPackedValues.length) {
814
+ let error = new Error("Packed values structure must be followed by a 4 element array");
815
+ error.incomplete = true;
816
+ throw error;
817
+ }
818
+ packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues;
819
+ packedValues.prefixes = read2();
820
+ packedValues.suffixes = read2();
821
+ return read2();
822
+ };
823
+ packedTable.handlesRead = true;
824
+ currentExtensions[51] = packedTable;
825
+ currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => {
826
+ if (!packedValues) {
827
+ if (currentDecoder.getShared)
828
+ loadShared();
829
+ else
830
+ return new Tag(data, PACKED_REFERENCE_TAG_ID);
831
+ }
832
+ if (typeof data == "number")
833
+ return packedValues[16 + (data >= 0 ? 2 * data : -2 * data - 1)];
834
+ let error = new Error("No support for non-integer packed references yet");
835
+ if (data === void 0)
836
+ error.incomplete = true;
837
+ throw error;
838
+ };
839
+ currentExtensions[28] = (read2) => {
840
+ if (!referenceMap) {
841
+ referenceMap = /* @__PURE__ */ new Map();
842
+ referenceMap.id = 0;
843
+ }
844
+ let id = referenceMap.id++;
845
+ let startingPosition = position$1;
846
+ let token = src[position$1];
847
+ let target2;
848
+ if (token >> 5 == 4)
849
+ target2 = [];
850
+ else
851
+ target2 = {};
852
+ let refEntry = { target: target2 };
853
+ referenceMap.set(id, refEntry);
854
+ let targetProperties = read2();
855
+ if (refEntry.used) {
856
+ if (Object.getPrototypeOf(target2) !== Object.getPrototypeOf(targetProperties)) {
857
+ position$1 = startingPosition;
858
+ target2 = targetProperties;
859
+ referenceMap.set(id, { target: target2 });
860
+ targetProperties = read2();
861
+ }
862
+ return Object.assign(target2, targetProperties);
863
+ }
864
+ refEntry.target = targetProperties;
865
+ return targetProperties;
866
+ };
867
+ currentExtensions[28].handlesRead = true;
868
+ currentExtensions[29] = (id) => {
869
+ let refEntry = referenceMap.get(id);
870
+ refEntry.used = true;
871
+ return refEntry.target;
872
+ };
873
+ currentExtensions[258] = (array) => new Set(array);
874
+ (currentExtensions[259] = (read2) => {
875
+ if (currentDecoder.mapsAsObjects) {
876
+ currentDecoder.mapsAsObjects = false;
877
+ restoreMapsAsObject = true;
878
+ }
879
+ return read2();
880
+ }).handlesRead = true;
881
+ function combine(a, b) {
882
+ if (typeof a === "string")
883
+ return a + b;
884
+ if (a instanceof Array)
885
+ return a.concat(b);
886
+ return Object.assign({}, a, b);
887
+ }
888
+ function getPackedValues() {
889
+ if (!packedValues) {
890
+ if (currentDecoder.getShared)
891
+ loadShared();
892
+ else
893
+ throw new Error("No packed values available");
894
+ }
895
+ return packedValues;
896
+ }
897
+ const SHARED_DATA_TAG_ID = 1399353956;
898
+ currentExtensionRanges.push((tag, input) => {
899
+ if (tag >= 225 && tag <= 255)
900
+ return combine(getPackedValues().prefixes[tag - 224], input);
901
+ if (tag >= 28704 && tag <= 32767)
902
+ return combine(getPackedValues().prefixes[tag - 28672], input);
903
+ if (tag >= 1879052288 && tag <= 2147483647)
904
+ return combine(getPackedValues().prefixes[tag - 1879048192], input);
905
+ if (tag >= 216 && tag <= 223)
906
+ return combine(input, getPackedValues().suffixes[tag - 216]);
907
+ if (tag >= 27647 && tag <= 28671)
908
+ return combine(input, getPackedValues().suffixes[tag - 27639]);
909
+ if (tag >= 1811940352 && tag <= 1879048191)
910
+ return combine(input, getPackedValues().suffixes[tag - 1811939328]);
911
+ if (tag == SHARED_DATA_TAG_ID) {
912
+ return {
913
+ packedValues,
914
+ structures: currentStructures.slice(0),
915
+ version: input
916
+ };
917
+ }
918
+ if (tag == 55799)
919
+ return input;
920
+ });
921
+ const isLittleEndianMachine$1 = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
922
+ const typedArrays = [
923
+ Uint8Array,
924
+ Uint8ClampedArray,
925
+ Uint16Array,
926
+ Uint32Array,
927
+ typeof BigUint64Array == "undefined" ? { name: "BigUint64Array" } : BigUint64Array,
928
+ Int8Array,
929
+ Int16Array,
930
+ Int32Array,
931
+ typeof BigInt64Array == "undefined" ? { name: "BigInt64Array" } : BigInt64Array,
932
+ Float32Array,
933
+ Float64Array
934
+ ];
935
+ const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86];
936
+ for (let i = 0; i < typedArrays.length; i++) {
937
+ registerTypedArray(typedArrays[i], typedArrayTags[i]);
938
+ }
939
+ function registerTypedArray(TypedArray, tag) {
940
+ let dvMethod = "get" + TypedArray.name.slice(0, -5);
941
+ let bytesPerElement;
942
+ if (typeof TypedArray === "function")
943
+ bytesPerElement = TypedArray.BYTES_PER_ELEMENT;
944
+ else
945
+ TypedArray = null;
946
+ for (let littleEndian = 0; littleEndian < 2; littleEndian++) {
947
+ if (!littleEndian && bytesPerElement == 1)
948
+ continue;
949
+ let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : bytesPerElement == 8 ? 3 : 0;
950
+ currentExtensions[littleEndian ? tag : tag - 4] = bytesPerElement == 1 || littleEndian == isLittleEndianMachine$1 ? (buffer) => {
951
+ if (!TypedArray)
952
+ throw new Error("Could not find typed array for code " + tag);
953
+ if (!currentDecoder.copyBuffers) {
954
+ if (bytesPerElement === 1 || bytesPerElement === 2 && !(buffer.byteOffset & 1) || bytesPerElement === 4 && !(buffer.byteOffset & 3) || bytesPerElement === 8 && !(buffer.byteOffset & 7))
955
+ return new TypedArray(buffer.buffer, buffer.byteOffset, buffer.byteLength >> sizeShift);
956
+ }
957
+ return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer);
958
+ } : (buffer) => {
959
+ if (!TypedArray)
960
+ throw new Error("Could not find typed array for code " + tag);
961
+ let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
962
+ let elements = buffer.length >> sizeShift;
963
+ let ta = new TypedArray(elements);
964
+ let method = dv[dvMethod];
965
+ for (let i = 0; i < elements; i++) {
966
+ ta[i] = method.call(dv, i << sizeShift, littleEndian);
967
+ }
968
+ return ta;
969
+ };
970
+ }
971
+ }
972
+ function readBundleExt() {
973
+ let length = readJustLength();
974
+ let bundlePosition = position$1 + read();
975
+ for (let i = 2; i < length; i++) {
976
+ let bundleLength = readJustLength();
977
+ position$1 += bundleLength;
978
+ }
979
+ let dataPosition = position$1;
980
+ position$1 = bundlePosition;
981
+ bundledStrings$1 = [readStringJS(readJustLength()), readStringJS(readJustLength())];
982
+ bundledStrings$1.position0 = 0;
983
+ bundledStrings$1.position1 = 0;
984
+ bundledStrings$1.postBundlePosition = position$1;
985
+ position$1 = dataPosition;
986
+ return read();
987
+ }
988
+ function readJustLength() {
989
+ let token = src[position$1++] & 31;
990
+ if (token > 23) {
991
+ switch (token) {
992
+ case 24:
993
+ token = src[position$1++];
994
+ break;
995
+ case 25:
996
+ token = dataView.getUint16(position$1);
997
+ position$1 += 2;
998
+ break;
999
+ case 26:
1000
+ token = dataView.getUint32(position$1);
1001
+ position$1 += 4;
1002
+ break;
1003
+ }
1004
+ }
1005
+ return token;
1006
+ }
1007
+ function loadShared() {
1008
+ if (currentDecoder.getShared) {
1009
+ let sharedData = saveState(() => {
1010
+ src = null;
1011
+ return currentDecoder.getShared();
1012
+ }) || {};
1013
+ let updatedStructures = sharedData.structures || [];
1014
+ currentDecoder.sharedVersion = sharedData.version;
1015
+ packedValues = currentDecoder.sharedValues = sharedData.packedValues;
1016
+ if (currentStructures === true)
1017
+ currentDecoder.structures = currentStructures = updatedStructures;
1018
+ else
1019
+ currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures));
1020
+ }
1021
+ }
1022
+ function saveState(callback) {
1023
+ let savedSrcEnd = srcEnd;
1024
+ let savedPosition = position$1;
1025
+ let savedSrcStringStart = srcStringStart;
1026
+ let savedSrcStringEnd = srcStringEnd;
1027
+ let savedSrcString = srcString;
1028
+ let savedReferenceMap = referenceMap;
1029
+ let savedBundledStrings = bundledStrings$1;
1030
+ let savedSrc = new Uint8Array(src.slice(0, srcEnd));
1031
+ let savedStructures = currentStructures;
1032
+ let savedDecoder = currentDecoder;
1033
+ let savedSequentialMode = sequentialMode;
1034
+ let value = callback();
1035
+ srcEnd = savedSrcEnd;
1036
+ position$1 = savedPosition;
1037
+ srcStringStart = savedSrcStringStart;
1038
+ srcStringEnd = savedSrcStringEnd;
1039
+ srcString = savedSrcString;
1040
+ referenceMap = savedReferenceMap;
1041
+ bundledStrings$1 = savedBundledStrings;
1042
+ src = savedSrc;
1043
+ sequentialMode = savedSequentialMode;
1044
+ currentStructures = savedStructures;
1045
+ currentDecoder = savedDecoder;
1046
+ dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1047
+ return value;
1048
+ }
1049
+ function clearSource() {
1050
+ src = null;
1051
+ referenceMap = null;
1052
+ currentStructures = null;
1053
+ }
1054
+ const mult10 = new Array(147);
1055
+ for (let i = 0; i < 256; i++) {
1056
+ mult10[i] = +("1e" + Math.floor(45.15 - i * 0.30103));
1057
+ }
1058
+ let defaultDecoder = new Decoder({ useRecords: false });
1059
+ defaultDecoder.decode;
1060
+ defaultDecoder.decodeMultiple;
1061
+ let textEncoder;
1062
+ try {
1063
+ textEncoder = new TextEncoder();
1064
+ } catch (error) {
1065
+ }
1066
+ let extensions, extensionClasses;
1067
+ const Buffer$1 = typeof globalThis === "object" && globalThis.Buffer;
1068
+ const hasNodeBuffer = typeof Buffer$1 !== "undefined";
1069
+ const ByteArrayAllocate = hasNodeBuffer ? Buffer$1.allocUnsafeSlow : Uint8Array;
1070
+ const ByteArray = hasNodeBuffer ? Buffer$1 : Uint8Array;
1071
+ const MAX_STRUCTURES = 256;
1072
+ const MAX_BUFFER_SIZE = hasNodeBuffer ? 4294967296 : 2144337920;
1073
+ let throwOnIterable;
1074
+ let target;
1075
+ let targetView;
1076
+ let position = 0;
1077
+ let safeEnd;
1078
+ let bundledStrings = null;
1079
+ const MAX_BUNDLE_SIZE = 61440;
1080
+ const hasNonLatin = /[\u0080-\uFFFF]/;
1081
+ const RECORD_SYMBOL = Symbol("record-id");
1082
+ class Encoder extends Decoder {
1083
+ constructor(options) {
1084
+ super(options);
1085
+ this.offset = 0;
1086
+ let start;
1087
+ let sharedStructures;
1088
+ let hasSharedUpdate;
1089
+ let structures;
1090
+ let referenceMap2;
1091
+ options = options || {};
1092
+ let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position2) {
1093
+ return target.utf8Write(string, position2, target.byteLength - position2);
1094
+ } : textEncoder && textEncoder.encodeInto ? function(string, position2) {
1095
+ return textEncoder.encodeInto(string, target.subarray(position2)).written;
1096
+ } : false;
1097
+ let encoder = this;
1098
+ let hasSharedStructures = options.structures || options.saveStructures;
1099
+ let maxSharedStructures = options.maxSharedStructures;
1100
+ if (maxSharedStructures == null)
1101
+ maxSharedStructures = hasSharedStructures ? 128 : 0;
1102
+ if (maxSharedStructures > 8190)
1103
+ throw new Error("Maximum maxSharedStructure is 8190");
1104
+ let isSequential = options.sequential;
1105
+ if (isSequential) {
1106
+ maxSharedStructures = 0;
1107
+ }
1108
+ if (!this.structures)
1109
+ this.structures = [];
1110
+ if (this.saveStructures)
1111
+ this.saveShared = this.saveStructures;
1112
+ let samplingPackedValues, packedObjectMap2, sharedValues = options.sharedValues;
1113
+ let sharedPackedObjectMap2;
1114
+ if (sharedValues) {
1115
+ sharedPackedObjectMap2 = /* @__PURE__ */ Object.create(null);
1116
+ for (let i = 0, l = sharedValues.length; i < l; i++) {
1117
+ sharedPackedObjectMap2[sharedValues[i]] = i;
1118
+ }
1119
+ }
1120
+ let recordIdsToRemove = [];
1121
+ let transitionsCount = 0;
1122
+ let serializationsSinceTransitionRebuild = 0;
1123
+ this.mapEncode = function(value, encodeOptions) {
1124
+ if (this._keyMap && !this._mapped) {
1125
+ switch (value.constructor.name) {
1126
+ case "Array":
1127
+ value = value.map((r) => this.encodeKeys(r));
1128
+ break;
1129
+ }
1130
+ }
1131
+ return this.encode(value, encodeOptions);
1132
+ };
1133
+ this.encode = function(value, encodeOptions) {
1134
+ if (!target) {
1135
+ target = new ByteArrayAllocate(8192);
1136
+ targetView = new DataView(target.buffer, 0, 8192);
1137
+ position = 0;
1138
+ }
1139
+ safeEnd = target.length - 10;
1140
+ if (safeEnd - position < 2048) {
1141
+ target = new ByteArrayAllocate(target.length);
1142
+ targetView = new DataView(target.buffer, 0, target.length);
1143
+ safeEnd = target.length - 10;
1144
+ position = 0;
1145
+ } else if (encodeOptions === REUSE_BUFFER_MODE)
1146
+ position = position + 7 & 2147483640;
1147
+ start = position;
1148
+ if (encoder.useSelfDescribedHeader) {
1149
+ targetView.setUint32(position, 3654940416);
1150
+ position += 3;
1151
+ }
1152
+ referenceMap2 = encoder.structuredClone ? /* @__PURE__ */ new Map() : null;
1153
+ if (encoder.bundleStrings && typeof value !== "string") {
1154
+ bundledStrings = [];
1155
+ bundledStrings.size = Infinity;
1156
+ } else
1157
+ bundledStrings = null;
1158
+ sharedStructures = encoder.structures;
1159
+ if (sharedStructures) {
1160
+ if (sharedStructures.uninitialized) {
1161
+ let sharedData = encoder.getShared() || {};
1162
+ encoder.structures = sharedStructures = sharedData.structures || [];
1163
+ encoder.sharedVersion = sharedData.version;
1164
+ let sharedValues2 = encoder.sharedValues = sharedData.packedValues;
1165
+ if (sharedValues2) {
1166
+ sharedPackedObjectMap2 = {};
1167
+ for (let i = 0, l = sharedValues2.length; i < l; i++)
1168
+ sharedPackedObjectMap2[sharedValues2[i]] = i;
1169
+ }
1170
+ }
1171
+ let sharedStructuresLength = sharedStructures.length;
1172
+ if (sharedStructuresLength > maxSharedStructures && !isSequential)
1173
+ sharedStructuresLength = maxSharedStructures;
1174
+ if (!sharedStructures.transitions) {
1175
+ sharedStructures.transitions = /* @__PURE__ */ Object.create(null);
1176
+ for (let i = 0; i < sharedStructuresLength; i++) {
1177
+ let keys = sharedStructures[i];
1178
+ if (!keys)
1179
+ continue;
1180
+ let nextTransition, transition = sharedStructures.transitions;
1181
+ for (let j = 0, l = keys.length; j < l; j++) {
1182
+ if (transition[RECORD_SYMBOL] === void 0)
1183
+ transition[RECORD_SYMBOL] = i;
1184
+ let key = keys[j];
1185
+ nextTransition = transition[key];
1186
+ if (!nextTransition) {
1187
+ nextTransition = transition[key] = /* @__PURE__ */ Object.create(null);
1188
+ }
1189
+ transition = nextTransition;
1190
+ }
1191
+ transition[RECORD_SYMBOL] = i | 1048576;
1192
+ }
1193
+ }
1194
+ if (!isSequential)
1195
+ sharedStructures.nextId = sharedStructuresLength;
1196
+ }
1197
+ if (hasSharedUpdate)
1198
+ hasSharedUpdate = false;
1199
+ structures = sharedStructures || [];
1200
+ packedObjectMap2 = sharedPackedObjectMap2;
1201
+ if (options.pack) {
1202
+ let packedValues2 = /* @__PURE__ */ new Map();
1203
+ packedValues2.values = [];
1204
+ packedValues2.encoder = encoder;
1205
+ packedValues2.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap2 ? 16 : Infinity);
1206
+ packedValues2.objectMap = sharedPackedObjectMap2 || false;
1207
+ packedValues2.samplingPackedValues = samplingPackedValues;
1208
+ findRepetitiveStrings(value, packedValues2);
1209
+ if (packedValues2.values.length > 0) {
1210
+ target[position++] = 216;
1211
+ target[position++] = 51;
1212
+ writeArrayHeader(4);
1213
+ let valuesArray = packedValues2.values;
1214
+ encode2(valuesArray);
1215
+ writeArrayHeader(0);
1216
+ writeArrayHeader(0);
1217
+ packedObjectMap2 = Object.create(sharedPackedObjectMap2 || null);
1218
+ for (let i = 0, l = valuesArray.length; i < l; i++) {
1219
+ packedObjectMap2[valuesArray[i]] = i;
1220
+ }
1221
+ }
1222
+ }
1223
+ throwOnIterable = encodeOptions & THROW_ON_ITERABLE;
1224
+ try {
1225
+ if (throwOnIterable)
1226
+ return;
1227
+ encode2(value);
1228
+ if (bundledStrings) {
1229
+ writeBundles(start, encode2);
1230
+ }
1231
+ encoder.offset = position;
1232
+ if (referenceMap2 && referenceMap2.idsToInsert) {
1233
+ position += referenceMap2.idsToInsert.length * 2;
1234
+ if (position > safeEnd)
1235
+ makeRoom(position);
1236
+ encoder.offset = position;
1237
+ let serialized = insertIds(target.subarray(start, position), referenceMap2.idsToInsert);
1238
+ referenceMap2 = null;
1239
+ return serialized;
1240
+ }
1241
+ if (encodeOptions & REUSE_BUFFER_MODE) {
1242
+ target.start = start;
1243
+ target.end = position;
1244
+ return target;
1245
+ }
1246
+ return target.subarray(start, position);
1247
+ } finally {
1248
+ if (sharedStructures) {
1249
+ if (serializationsSinceTransitionRebuild < 10)
1250
+ serializationsSinceTransitionRebuild++;
1251
+ if (sharedStructures.length > maxSharedStructures)
1252
+ sharedStructures.length = maxSharedStructures;
1253
+ if (transitionsCount > 1e4) {
1254
+ sharedStructures.transitions = null;
1255
+ serializationsSinceTransitionRebuild = 0;
1256
+ transitionsCount = 0;
1257
+ if (recordIdsToRemove.length > 0)
1258
+ recordIdsToRemove = [];
1259
+ } else if (recordIdsToRemove.length > 0 && !isSequential) {
1260
+ for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1261
+ recordIdsToRemove[i][RECORD_SYMBOL] = void 0;
1262
+ }
1263
+ recordIdsToRemove = [];
1264
+ }
1265
+ }
1266
+ if (hasSharedUpdate && encoder.saveShared) {
1267
+ if (encoder.structures.length > maxSharedStructures) {
1268
+ encoder.structures = encoder.structures.slice(0, maxSharedStructures);
1269
+ }
1270
+ let returnBuffer = target.subarray(start, position);
1271
+ if (encoder.updateSharedData() === false)
1272
+ return encoder.encode(value);
1273
+ return returnBuffer;
1274
+ }
1275
+ if (encodeOptions & RESET_BUFFER_MODE)
1276
+ position = start;
1277
+ }
1278
+ };
1279
+ this.findCommonStringsToPack = () => {
1280
+ samplingPackedValues = /* @__PURE__ */ new Map();
1281
+ if (!sharedPackedObjectMap2)
1282
+ sharedPackedObjectMap2 = /* @__PURE__ */ Object.create(null);
1283
+ return (options2) => {
1284
+ let threshold = options2 && options2.threshold || 4;
1285
+ let position2 = this.pack ? options2.maxPrivatePackedValues || 16 : 0;
1286
+ if (!sharedValues)
1287
+ sharedValues = this.sharedValues = [];
1288
+ for (let [key, status] of samplingPackedValues) {
1289
+ if (status.count > threshold) {
1290
+ sharedPackedObjectMap2[key] = position2++;
1291
+ sharedValues.push(key);
1292
+ hasSharedUpdate = true;
1293
+ }
1294
+ }
1295
+ while (this.saveShared && this.updateSharedData() === false) {
1296
+ }
1297
+ samplingPackedValues = null;
1298
+ };
1299
+ };
1300
+ const encode2 = (value) => {
1301
+ if (position > safeEnd)
1302
+ target = makeRoom(position);
1303
+ var type = typeof value;
1304
+ var length;
1305
+ if (type === "string") {
1306
+ if (packedObjectMap2) {
1307
+ let packedPosition = packedObjectMap2[value];
1308
+ if (packedPosition >= 0) {
1309
+ if (packedPosition < 16)
1310
+ target[position++] = packedPosition + 224;
1311
+ else {
1312
+ target[position++] = 198;
1313
+ if (packedPosition & 1)
1314
+ encode2(15 - packedPosition >> 1);
1315
+ else
1316
+ encode2(packedPosition - 16 >> 1);
1317
+ }
1318
+ return;
1319
+ } else if (samplingPackedValues && !options.pack) {
1320
+ let status = samplingPackedValues.get(value);
1321
+ if (status)
1322
+ status.count++;
1323
+ else
1324
+ samplingPackedValues.set(value, {
1325
+ count: 1
1326
+ });
1327
+ }
1328
+ }
1329
+ let strLength = value.length;
1330
+ if (bundledStrings && strLength >= 4 && strLength < 1024) {
1331
+ if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
1332
+ let extStart;
1333
+ let maxBytes2 = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
1334
+ if (position + maxBytes2 > safeEnd)
1335
+ target = makeRoom(position + maxBytes2);
1336
+ target[position++] = 217;
1337
+ target[position++] = 223;
1338
+ target[position++] = 249;
1339
+ target[position++] = bundledStrings.position ? 132 : 130;
1340
+ target[position++] = 26;
1341
+ extStart = position - start;
1342
+ position += 4;
1343
+ if (bundledStrings.position) {
1344
+ writeBundles(start, encode2);
1345
+ }
1346
+ bundledStrings = ["", ""];
1347
+ bundledStrings.size = 0;
1348
+ bundledStrings.position = extStart;
1349
+ }
1350
+ let twoByte = hasNonLatin.test(value);
1351
+ bundledStrings[twoByte ? 0 : 1] += value;
1352
+ target[position++] = twoByte ? 206 : 207;
1353
+ encode2(strLength);
1354
+ return;
1355
+ }
1356
+ let headerSize;
1357
+ if (strLength < 32) {
1358
+ headerSize = 1;
1359
+ } else if (strLength < 256) {
1360
+ headerSize = 2;
1361
+ } else if (strLength < 65536) {
1362
+ headerSize = 3;
1363
+ } else {
1364
+ headerSize = 5;
1365
+ }
1366
+ let maxBytes = strLength * 3;
1367
+ if (position + maxBytes > safeEnd)
1368
+ target = makeRoom(position + maxBytes);
1369
+ if (strLength < 64 || !encodeUtf8) {
1370
+ let i, c1, c2, strPosition = position + headerSize;
1371
+ for (i = 0; i < strLength; i++) {
1372
+ c1 = value.charCodeAt(i);
1373
+ if (c1 < 128) {
1374
+ target[strPosition++] = c1;
1375
+ } else if (c1 < 2048) {
1376
+ target[strPosition++] = c1 >> 6 | 192;
1377
+ target[strPosition++] = c1 & 63 | 128;
1378
+ } else if ((c1 & 64512) === 55296 && ((c2 = value.charCodeAt(i + 1)) & 64512) === 56320) {
1379
+ c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023);
1380
+ i++;
1381
+ target[strPosition++] = c1 >> 18 | 240;
1382
+ target[strPosition++] = c1 >> 12 & 63 | 128;
1383
+ target[strPosition++] = c1 >> 6 & 63 | 128;
1384
+ target[strPosition++] = c1 & 63 | 128;
1385
+ } else {
1386
+ target[strPosition++] = c1 >> 12 | 224;
1387
+ target[strPosition++] = c1 >> 6 & 63 | 128;
1388
+ target[strPosition++] = c1 & 63 | 128;
1389
+ }
1390
+ }
1391
+ length = strPosition - position - headerSize;
1392
+ } else {
1393
+ length = encodeUtf8(value, position + headerSize, maxBytes);
1394
+ }
1395
+ if (length < 24) {
1396
+ target[position++] = 96 | length;
1397
+ } else if (length < 256) {
1398
+ if (headerSize < 2) {
1399
+ target.copyWithin(position + 2, position + 1, position + 1 + length);
1400
+ }
1401
+ target[position++] = 120;
1402
+ target[position++] = length;
1403
+ } else if (length < 65536) {
1404
+ if (headerSize < 3) {
1405
+ target.copyWithin(position + 3, position + 2, position + 2 + length);
1406
+ }
1407
+ target[position++] = 121;
1408
+ target[position++] = length >> 8;
1409
+ target[position++] = length & 255;
1410
+ } else {
1411
+ if (headerSize < 5) {
1412
+ target.copyWithin(position + 5, position + 3, position + 3 + length);
1413
+ }
1414
+ target[position++] = 122;
1415
+ targetView.setUint32(position, length);
1416
+ position += 4;
1417
+ }
1418
+ position += length;
1419
+ } else if (type === "number") {
1420
+ if (!this.alwaysUseFloat && value >>> 0 === value) {
1421
+ if (value < 24) {
1422
+ target[position++] = value;
1423
+ } else if (value < 256) {
1424
+ target[position++] = 24;
1425
+ target[position++] = value;
1426
+ } else if (value < 65536) {
1427
+ target[position++] = 25;
1428
+ target[position++] = value >> 8;
1429
+ target[position++] = value & 255;
1430
+ } else {
1431
+ target[position++] = 26;
1432
+ targetView.setUint32(position, value);
1433
+ position += 4;
1434
+ }
1435
+ } else if (!this.alwaysUseFloat && value >> 0 === value) {
1436
+ if (value >= -24) {
1437
+ target[position++] = 31 - value;
1438
+ } else if (value >= -256) {
1439
+ target[position++] = 56;
1440
+ target[position++] = ~value;
1441
+ } else if (value >= -65536) {
1442
+ target[position++] = 57;
1443
+ targetView.setUint16(position, ~value);
1444
+ position += 2;
1445
+ } else {
1446
+ target[position++] = 58;
1447
+ targetView.setUint32(position, ~value);
1448
+ position += 4;
1449
+ }
1450
+ } else if (!this.alwaysUseFloat && value < 0 && value >= -4294967296 && Math.floor(value) === value) {
1451
+ target[position++] = 58;
1452
+ targetView.setUint32(position, -1 - value);
1453
+ position += 4;
1454
+ } else {
1455
+ let useFloat32;
1456
+ if ((useFloat32 = this.useFloat32) > 0 && value < 4294967296 && value >= -2147483648) {
1457
+ target[position++] = 250;
1458
+ targetView.setFloat32(position, value);
1459
+ let xShifted;
1460
+ if (useFloat32 < 4 || // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1461
+ (xShifted = value * mult10[(target[position] & 127) << 1 | target[position + 1] >> 7]) >> 0 === xShifted) {
1462
+ position += 4;
1463
+ return;
1464
+ } else
1465
+ position--;
1466
+ }
1467
+ target[position++] = 251;
1468
+ targetView.setFloat64(position, value);
1469
+ position += 8;
1470
+ }
1471
+ } else if (type === "object") {
1472
+ if (!value)
1473
+ target[position++] = 246;
1474
+ else {
1475
+ if (referenceMap2) {
1476
+ let referee = referenceMap2.get(value);
1477
+ if (referee) {
1478
+ target[position++] = 216;
1479
+ target[position++] = 29;
1480
+ target[position++] = 25;
1481
+ if (!referee.references) {
1482
+ let idsToInsert = referenceMap2.idsToInsert || (referenceMap2.idsToInsert = []);
1483
+ referee.references = [];
1484
+ idsToInsert.push(referee);
1485
+ }
1486
+ referee.references.push(position - start);
1487
+ position += 2;
1488
+ return;
1489
+ } else
1490
+ referenceMap2.set(value, { offset: position - start });
1491
+ }
1492
+ let constructor = value.constructor;
1493
+ if (constructor === Object) {
1494
+ if (this.skipFunction === true) {
1495
+ value = Object.fromEntries([...Object.keys(value).filter((x) => typeof value[x] !== "function").map((x) => [x, value[x]])]);
1496
+ }
1497
+ writeObject(value);
1498
+ } else if (constructor === Array) {
1499
+ length = value.length;
1500
+ if (length < 24) {
1501
+ target[position++] = 128 | length;
1502
+ } else {
1503
+ writeArrayHeader(length);
1504
+ }
1505
+ for (let i = 0; i < length; i++) {
1506
+ encode2(value[i]);
1507
+ }
1508
+ } else if (constructor === Map) {
1509
+ if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) {
1510
+ target[position++] = 217;
1511
+ target[position++] = 1;
1512
+ target[position++] = 3;
1513
+ }
1514
+ length = value.size;
1515
+ if (length < 24) {
1516
+ target[position++] = 160 | length;
1517
+ } else if (length < 256) {
1518
+ target[position++] = 184;
1519
+ target[position++] = length;
1520
+ } else if (length < 65536) {
1521
+ target[position++] = 185;
1522
+ target[position++] = length >> 8;
1523
+ target[position++] = length & 255;
1524
+ } else {
1525
+ target[position++] = 186;
1526
+ targetView.setUint32(position, length);
1527
+ position += 4;
1528
+ }
1529
+ if (encoder.keyMap) {
1530
+ for (let [key, entryValue] of value) {
1531
+ encode2(encoder.encodeKey(key));
1532
+ encode2(entryValue);
1533
+ }
1534
+ } else {
1535
+ for (let [key, entryValue] of value) {
1536
+ encode2(key);
1537
+ encode2(entryValue);
1538
+ }
1539
+ }
1540
+ } else {
1541
+ for (let i = 0, l = extensions.length; i < l; i++) {
1542
+ let extensionClass = extensionClasses[i];
1543
+ if (value instanceof extensionClass) {
1544
+ let extension = extensions[i];
1545
+ let tag = extension.tag;
1546
+ if (tag == void 0)
1547
+ tag = extension.getTag && extension.getTag.call(this, value);
1548
+ if (tag < 24) {
1549
+ target[position++] = 192 | tag;
1550
+ } else if (tag < 256) {
1551
+ target[position++] = 216;
1552
+ target[position++] = tag;
1553
+ } else if (tag < 65536) {
1554
+ target[position++] = 217;
1555
+ target[position++] = tag >> 8;
1556
+ target[position++] = tag & 255;
1557
+ } else if (tag > -1) {
1558
+ target[position++] = 218;
1559
+ targetView.setUint32(position, tag);
1560
+ position += 4;
1561
+ }
1562
+ extension.encode.call(this, value, encode2, makeRoom);
1563
+ return;
1564
+ }
1565
+ }
1566
+ if (value[Symbol.iterator]) {
1567
+ if (throwOnIterable) {
1568
+ let error = new Error("Iterable should be serialized as iterator");
1569
+ error.iteratorNotHandled = true;
1570
+ throw error;
1571
+ }
1572
+ target[position++] = 159;
1573
+ for (let entry of value) {
1574
+ encode2(entry);
1575
+ }
1576
+ target[position++] = 255;
1577
+ return;
1578
+ }
1579
+ if (value[Symbol.asyncIterator] || isBlob(value)) {
1580
+ let error = new Error("Iterable/blob should be serialized as iterator");
1581
+ error.iteratorNotHandled = true;
1582
+ throw error;
1583
+ }
1584
+ if (this.useToJSON && value.toJSON) {
1585
+ const json = value.toJSON();
1586
+ if (json !== value)
1587
+ return encode2(json);
1588
+ }
1589
+ writeObject(value);
1590
+ }
1591
+ }
1592
+ } else if (type === "boolean") {
1593
+ target[position++] = value ? 245 : 244;
1594
+ } else if (type === "bigint") {
1595
+ if (value < BigInt(1) << BigInt(64) && value >= 0) {
1596
+ target[position++] = 27;
1597
+ targetView.setBigUint64(position, value);
1598
+ } else if (value > -(BigInt(1) << BigInt(64)) && value < 0) {
1599
+ target[position++] = 59;
1600
+ targetView.setBigUint64(position, -value - BigInt(1));
1601
+ } else {
1602
+ if (this.largeBigIntToFloat) {
1603
+ target[position++] = 251;
1604
+ targetView.setFloat64(position, Number(value));
1605
+ } else {
1606
+ if (value >= BigInt(0))
1607
+ target[position++] = 194;
1608
+ else {
1609
+ target[position++] = 195;
1610
+ value = BigInt(-1) - value;
1611
+ }
1612
+ let bytes = [];
1613
+ while (value) {
1614
+ bytes.push(Number(value & BigInt(255)));
1615
+ value >>= BigInt(8);
1616
+ }
1617
+ writeBuffer(new Uint8Array(bytes.reverse()), makeRoom);
1618
+ return;
1619
+ }
1620
+ }
1621
+ position += 8;
1622
+ } else if (type === "undefined") {
1623
+ target[position++] = 247;
1624
+ } else {
1625
+ throw new Error("Unknown type: " + type);
1626
+ }
1627
+ };
1628
+ const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1629
+ let keys = Object.keys(object);
1630
+ let vals = Object.values(object);
1631
+ let length = keys.length;
1632
+ if (length < 24) {
1633
+ target[position++] = 160 | length;
1634
+ } else if (length < 256) {
1635
+ target[position++] = 184;
1636
+ target[position++] = length;
1637
+ } else if (length < 65536) {
1638
+ target[position++] = 185;
1639
+ target[position++] = length >> 8;
1640
+ target[position++] = length & 255;
1641
+ } else {
1642
+ target[position++] = 186;
1643
+ targetView.setUint32(position, length);
1644
+ position += 4;
1645
+ }
1646
+ if (encoder.keyMap) {
1647
+ for (let i = 0; i < length; i++) {
1648
+ encode2(encoder.encodeKey(keys[i]));
1649
+ encode2(vals[i]);
1650
+ }
1651
+ } else {
1652
+ for (let i = 0; i < length; i++) {
1653
+ encode2(keys[i]);
1654
+ encode2(vals[i]);
1655
+ }
1656
+ }
1657
+ } : (object) => {
1658
+ target[position++] = 185;
1659
+ let objectOffset = position - start;
1660
+ position += 2;
1661
+ let size = 0;
1662
+ if (encoder.keyMap) {
1663
+ for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) {
1664
+ encode2(encoder.encodeKey(key));
1665
+ encode2(object[key]);
1666
+ size++;
1667
+ }
1668
+ } else {
1669
+ for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) {
1670
+ encode2(key);
1671
+ encode2(object[key]);
1672
+ size++;
1673
+ }
1674
+ }
1675
+ target[objectOffset++ + start] = size >> 8;
1676
+ target[objectOffset + start] = size & 255;
1677
+ } : (object, skipValues) => {
1678
+ let nextTransition, transition = structures.transitions || (structures.transitions = /* @__PURE__ */ Object.create(null));
1679
+ let newTransitions = 0;
1680
+ let length = 0;
1681
+ let parentRecordId;
1682
+ let keys;
1683
+ if (this.keyMap) {
1684
+ keys = Object.keys(object).map((k) => this.encodeKey(k));
1685
+ length = keys.length;
1686
+ for (let i = 0; i < length; i++) {
1687
+ let key = keys[i];
1688
+ nextTransition = transition[key];
1689
+ if (!nextTransition) {
1690
+ nextTransition = transition[key] = /* @__PURE__ */ Object.create(null);
1691
+ newTransitions++;
1692
+ }
1693
+ transition = nextTransition;
1694
+ }
1695
+ } else {
1696
+ for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) {
1697
+ nextTransition = transition[key];
1698
+ if (!nextTransition) {
1699
+ if (transition[RECORD_SYMBOL] & 1048576) {
1700
+ parentRecordId = transition[RECORD_SYMBOL] & 65535;
1701
+ }
1702
+ nextTransition = transition[key] = /* @__PURE__ */ Object.create(null);
1703
+ newTransitions++;
1704
+ }
1705
+ transition = nextTransition;
1706
+ length++;
1707
+ }
1708
+ }
1709
+ let recordId = transition[RECORD_SYMBOL];
1710
+ if (recordId !== void 0) {
1711
+ recordId &= 65535;
1712
+ target[position++] = 217;
1713
+ target[position++] = recordId >> 8 | 224;
1714
+ target[position++] = recordId & 255;
1715
+ } else {
1716
+ if (!keys)
1717
+ keys = transition.__keys__ || (transition.__keys__ = Object.keys(object));
1718
+ if (parentRecordId === void 0) {
1719
+ recordId = structures.nextId++;
1720
+ if (!recordId) {
1721
+ recordId = 0;
1722
+ structures.nextId = 1;
1723
+ }
1724
+ if (recordId >= MAX_STRUCTURES) {
1725
+ structures.nextId = (recordId = maxSharedStructures) + 1;
1726
+ }
1727
+ } else {
1728
+ recordId = parentRecordId;
1729
+ }
1730
+ structures[recordId] = keys;
1731
+ if (recordId < maxSharedStructures) {
1732
+ target[position++] = 217;
1733
+ target[position++] = recordId >> 8 | 224;
1734
+ target[position++] = recordId & 255;
1735
+ transition = structures.transitions;
1736
+ for (let i = 0; i < length; i++) {
1737
+ if (transition[RECORD_SYMBOL] === void 0 || transition[RECORD_SYMBOL] & 1048576)
1738
+ transition[RECORD_SYMBOL] = recordId;
1739
+ transition = transition[keys[i]];
1740
+ }
1741
+ transition[RECORD_SYMBOL] = recordId | 1048576;
1742
+ hasSharedUpdate = true;
1743
+ } else {
1744
+ transition[RECORD_SYMBOL] = recordId;
1745
+ targetView.setUint32(position, 3655335680);
1746
+ position += 3;
1747
+ if (newTransitions)
1748
+ transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1749
+ if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures)
1750
+ recordIdsToRemove.shift()[RECORD_SYMBOL] = void 0;
1751
+ recordIdsToRemove.push(transition);
1752
+ writeArrayHeader(length + 2);
1753
+ encode2(57344 + recordId);
1754
+ encode2(keys);
1755
+ if (skipValues) return;
1756
+ for (let key in object)
1757
+ if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key))
1758
+ encode2(object[key]);
1759
+ return;
1760
+ }
1761
+ }
1762
+ if (length < 24) {
1763
+ target[position++] = 128 | length;
1764
+ } else {
1765
+ writeArrayHeader(length);
1766
+ }
1767
+ if (skipValues) return;
1768
+ for (let key in object)
1769
+ if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key))
1770
+ encode2(object[key]);
1771
+ };
1772
+ const makeRoom = (end) => {
1773
+ let newSize;
1774
+ if (end > 16777216) {
1775
+ if (end - start > MAX_BUFFER_SIZE)
1776
+ throw new Error("Encoded buffer would be larger than maximum buffer size");
1777
+ newSize = Math.min(
1778
+ MAX_BUFFER_SIZE,
1779
+ Math.round(Math.max((end - start) * (end > 67108864 ? 1.25 : 2), 4194304) / 4096) * 4096
1780
+ );
1781
+ } else
1782
+ newSize = (Math.max(end - start << 2, target.length - 1) >> 12) + 1 << 12;
1783
+ let newBuffer = new ByteArrayAllocate(newSize);
1784
+ targetView = new DataView(newBuffer.buffer, 0, newSize);
1785
+ if (target.copy)
1786
+ target.copy(newBuffer, 0, start, end);
1787
+ else
1788
+ newBuffer.set(target.slice(start, end));
1789
+ position -= start;
1790
+ start = 0;
1791
+ safeEnd = newBuffer.length - 10;
1792
+ return target = newBuffer;
1793
+ };
1794
+ let chunkThreshold = 100;
1795
+ let continuedChunkThreshold = 1e3;
1796
+ this.encodeAsIterable = function(value, options2) {
1797
+ return startEncoding(value, options2, encodeObjectAsIterable);
1798
+ };
1799
+ this.encodeAsAsyncIterable = function(value, options2) {
1800
+ return startEncoding(value, options2, encodeObjectAsAsyncIterable);
1801
+ };
1802
+ function* encodeObjectAsIterable(object, iterateProperties, finalIterable) {
1803
+ let constructor = object.constructor;
1804
+ if (constructor === Object) {
1805
+ let useRecords = encoder.useRecords !== false;
1806
+ if (useRecords)
1807
+ writeObject(object, true);
1808
+ else
1809
+ writeEntityLength(Object.keys(object).length, 160);
1810
+ for (let key in object) {
1811
+ let value = object[key];
1812
+ if (!useRecords) encode2(key);
1813
+ if (value && typeof value === "object") {
1814
+ if (iterateProperties[key])
1815
+ yield* encodeObjectAsIterable(value, iterateProperties[key]);
1816
+ else
1817
+ yield* tryEncode(value, iterateProperties, key);
1818
+ } else encode2(value);
1819
+ }
1820
+ } else if (constructor === Array) {
1821
+ let length = object.length;
1822
+ writeArrayHeader(length);
1823
+ for (let i = 0; i < length; i++) {
1824
+ let value = object[i];
1825
+ if (value && (typeof value === "object" || position - start > chunkThreshold)) {
1826
+ if (iterateProperties.element)
1827
+ yield* encodeObjectAsIterable(value, iterateProperties.element);
1828
+ else
1829
+ yield* tryEncode(value, iterateProperties, "element");
1830
+ } else encode2(value);
1831
+ }
1832
+ } else if (object[Symbol.iterator] && !object.buffer) {
1833
+ target[position++] = 159;
1834
+ for (let value of object) {
1835
+ if (value && (typeof value === "object" || position - start > chunkThreshold)) {
1836
+ if (iterateProperties.element)
1837
+ yield* encodeObjectAsIterable(value, iterateProperties.element);
1838
+ else
1839
+ yield* tryEncode(value, iterateProperties, "element");
1840
+ } else encode2(value);
1841
+ }
1842
+ target[position++] = 255;
1843
+ } else if (isBlob(object)) {
1844
+ writeEntityLength(object.size, 64);
1845
+ yield target.subarray(start, position);
1846
+ yield object;
1847
+ restartEncoding();
1848
+ } else if (object[Symbol.asyncIterator]) {
1849
+ target[position++] = 159;
1850
+ yield target.subarray(start, position);
1851
+ yield object;
1852
+ restartEncoding();
1853
+ target[position++] = 255;
1854
+ } else {
1855
+ encode2(object);
1856
+ }
1857
+ if (finalIterable && position > start) yield target.subarray(start, position);
1858
+ else if (position - start > chunkThreshold) {
1859
+ yield target.subarray(start, position);
1860
+ restartEncoding();
1861
+ }
1862
+ }
1863
+ function* tryEncode(value, iterateProperties, key) {
1864
+ let restart = position - start;
1865
+ try {
1866
+ encode2(value);
1867
+ if (position - start > chunkThreshold) {
1868
+ yield target.subarray(start, position);
1869
+ restartEncoding();
1870
+ }
1871
+ } catch (error) {
1872
+ if (error.iteratorNotHandled) {
1873
+ iterateProperties[key] = {};
1874
+ position = start + restart;
1875
+ yield* encodeObjectAsIterable.call(this, value, iterateProperties[key]);
1876
+ } else throw error;
1877
+ }
1878
+ }
1879
+ function restartEncoding() {
1880
+ chunkThreshold = continuedChunkThreshold;
1881
+ encoder.encode(null, THROW_ON_ITERABLE);
1882
+ }
1883
+ function startEncoding(value, options2, encodeIterable) {
1884
+ if (options2 && options2.chunkThreshold)
1885
+ chunkThreshold = continuedChunkThreshold = options2.chunkThreshold;
1886
+ else
1887
+ chunkThreshold = 100;
1888
+ if (value && typeof value === "object") {
1889
+ encoder.encode(null, THROW_ON_ITERABLE);
1890
+ return encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true);
1891
+ }
1892
+ return [encoder.encode(value)];
1893
+ }
1894
+ async function* encodeObjectAsAsyncIterable(value, iterateProperties) {
1895
+ for (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) {
1896
+ let constructor = encodedValue.constructor;
1897
+ if (constructor === ByteArray || constructor === Uint8Array)
1898
+ yield encodedValue;
1899
+ else if (isBlob(encodedValue)) {
1900
+ let reader = encodedValue.stream().getReader();
1901
+ let next;
1902
+ while (!(next = await reader.read()).done) {
1903
+ yield next.value;
1904
+ }
1905
+ } else if (encodedValue[Symbol.asyncIterator]) {
1906
+ for await (let asyncValue of encodedValue) {
1907
+ restartEncoding();
1908
+ if (asyncValue)
1909
+ yield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {}));
1910
+ else yield encoder.encode(asyncValue);
1911
+ }
1912
+ } else {
1913
+ yield encodedValue;
1914
+ }
1915
+ }
1916
+ }
1917
+ }
1918
+ useBuffer(buffer) {
1919
+ target = buffer;
1920
+ targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1921
+ position = 0;
1922
+ }
1923
+ clearSharedData() {
1924
+ if (this.structures)
1925
+ this.structures = [];
1926
+ if (this.sharedValues)
1927
+ this.sharedValues = void 0;
1928
+ }
1929
+ updateSharedData() {
1930
+ let lastVersion = this.sharedVersion || 0;
1931
+ this.sharedVersion = lastVersion + 1;
1932
+ let structuresCopy = this.structures.slice(0);
1933
+ let sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion);
1934
+ let saveResults = this.saveShared(
1935
+ sharedData,
1936
+ (existingShared) => (existingShared && existingShared.version || 0) == lastVersion
1937
+ );
1938
+ if (saveResults === false) {
1939
+ sharedData = this.getShared() || {};
1940
+ this.structures = sharedData.structures || [];
1941
+ this.sharedValues = sharedData.packedValues;
1942
+ this.sharedVersion = sharedData.version;
1943
+ this.structures.nextId = this.structures.length;
1944
+ } else {
1945
+ structuresCopy.forEach((structure, i) => this.structures[i] = structure);
1946
+ }
1947
+ return saveResults;
1948
+ }
1949
+ }
1950
+ function writeEntityLength(length, majorValue) {
1951
+ if (length < 24)
1952
+ target[position++] = majorValue | length;
1953
+ else if (length < 256) {
1954
+ target[position++] = majorValue | 24;
1955
+ target[position++] = length;
1956
+ } else if (length < 65536) {
1957
+ target[position++] = majorValue | 25;
1958
+ target[position++] = length >> 8;
1959
+ target[position++] = length & 255;
1960
+ } else {
1961
+ target[position++] = majorValue | 26;
1962
+ targetView.setUint32(position, length);
1963
+ position += 4;
1964
+ }
1965
+ }
1966
+ class SharedData {
1967
+ constructor(structures, values, version) {
1968
+ this.structures = structures;
1969
+ this.packedValues = values;
1970
+ this.version = version;
1971
+ }
1972
+ }
1973
+ function writeArrayHeader(length) {
1974
+ if (length < 24)
1975
+ target[position++] = 128 | length;
1976
+ else if (length < 256) {
1977
+ target[position++] = 152;
1978
+ target[position++] = length;
1979
+ } else if (length < 65536) {
1980
+ target[position++] = 153;
1981
+ target[position++] = length >> 8;
1982
+ target[position++] = length & 255;
1983
+ } else {
1984
+ target[position++] = 154;
1985
+ targetView.setUint32(position, length);
1986
+ position += 4;
1987
+ }
1988
+ }
1989
+ const BlobConstructor = typeof Blob === "undefined" ? function() {
1990
+ } : Blob;
1991
+ function isBlob(object) {
1992
+ if (object instanceof BlobConstructor)
1993
+ return true;
1994
+ let tag = object[Symbol.toStringTag];
1995
+ return tag === "Blob" || tag === "File";
1996
+ }
1997
+ function findRepetitiveStrings(value, packedValues2) {
1998
+ switch (typeof value) {
1999
+ case "string":
2000
+ if (value.length > 3) {
2001
+ if (packedValues2.objectMap[value] > -1 || packedValues2.values.length >= packedValues2.maxValues)
2002
+ return;
2003
+ let packedStatus = packedValues2.get(value);
2004
+ if (packedStatus) {
2005
+ if (++packedStatus.count == 2) {
2006
+ packedValues2.values.push(value);
2007
+ }
2008
+ } else {
2009
+ packedValues2.set(value, {
2010
+ count: 1
2011
+ });
2012
+ if (packedValues2.samplingPackedValues) {
2013
+ let status = packedValues2.samplingPackedValues.get(value);
2014
+ if (status)
2015
+ status.count++;
2016
+ else
2017
+ packedValues2.samplingPackedValues.set(value, {
2018
+ count: 1
2019
+ });
2020
+ }
2021
+ }
2022
+ }
2023
+ break;
2024
+ case "object":
2025
+ if (value) {
2026
+ if (value instanceof Array) {
2027
+ for (let i = 0, l = value.length; i < l; i++) {
2028
+ findRepetitiveStrings(value[i], packedValues2);
2029
+ }
2030
+ } else {
2031
+ let includeKeys = !packedValues2.encoder.useRecords;
2032
+ for (var key in value) {
2033
+ if (value.hasOwnProperty(key)) {
2034
+ if (includeKeys)
2035
+ findRepetitiveStrings(key, packedValues2);
2036
+ findRepetitiveStrings(value[key], packedValues2);
2037
+ }
2038
+ }
2039
+ }
2040
+ }
2041
+ break;
2042
+ case "function":
2043
+ console.log(value);
2044
+ }
2045
+ }
2046
+ const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
2047
+ extensionClasses = [
2048
+ Date,
2049
+ Set,
2050
+ Error,
2051
+ RegExp,
2052
+ Tag,
2053
+ ArrayBuffer,
2054
+ Uint8Array,
2055
+ Uint8ClampedArray,
2056
+ Uint16Array,
2057
+ Uint32Array,
2058
+ typeof BigUint64Array == "undefined" ? function() {
2059
+ } : BigUint64Array,
2060
+ Int8Array,
2061
+ Int16Array,
2062
+ Int32Array,
2063
+ typeof BigInt64Array == "undefined" ? function() {
2064
+ } : BigInt64Array,
2065
+ Float32Array,
2066
+ Float64Array,
2067
+ SharedData
2068
+ ];
2069
+ extensions = [
2070
+ {
2071
+ // Date
2072
+ tag: 1,
2073
+ encode(date, encode2) {
2074
+ let seconds = date.getTime() / 1e3;
2075
+ if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 4294967296) {
2076
+ target[position++] = 26;
2077
+ targetView.setUint32(position, seconds);
2078
+ position += 4;
2079
+ } else {
2080
+ target[position++] = 251;
2081
+ targetView.setFloat64(position, seconds);
2082
+ position += 8;
2083
+ }
2084
+ }
2085
+ },
2086
+ {
2087
+ // Set
2088
+ tag: 258,
2089
+ // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
2090
+ encode(set, encode2) {
2091
+ let array = Array.from(set);
2092
+ encode2(array);
2093
+ }
2094
+ },
2095
+ {
2096
+ // Error
2097
+ tag: 27,
2098
+ // http://cbor.schmorp.de/generic-object
2099
+ encode(error, encode2) {
2100
+ encode2([error.name, error.message]);
2101
+ }
2102
+ },
2103
+ {
2104
+ // RegExp
2105
+ tag: 27,
2106
+ // http://cbor.schmorp.de/generic-object
2107
+ encode(regex, encode2) {
2108
+ encode2(["RegExp", regex.source, regex.flags]);
2109
+ }
2110
+ },
2111
+ {
2112
+ // Tag
2113
+ getTag(tag) {
2114
+ return tag.tag;
2115
+ },
2116
+ encode(tag, encode2) {
2117
+ encode2(tag.value);
2118
+ }
2119
+ },
2120
+ {
2121
+ // ArrayBuffer
2122
+ encode(arrayBuffer, encode2, makeRoom) {
2123
+ writeBuffer(arrayBuffer, makeRoom);
2124
+ }
2125
+ },
2126
+ {
2127
+ // Uint8Array
2128
+ getTag(typedArray) {
2129
+ if (typedArray.constructor === Uint8Array) {
2130
+ if (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false)
2131
+ return 64;
2132
+ }
2133
+ },
2134
+ encode(typedArray, encode2, makeRoom) {
2135
+ writeBuffer(typedArray, makeRoom);
2136
+ }
2137
+ },
2138
+ typedArrayEncoder(68, 1),
2139
+ typedArrayEncoder(69, 2),
2140
+ typedArrayEncoder(70, 4),
2141
+ typedArrayEncoder(71, 8),
2142
+ typedArrayEncoder(72, 1),
2143
+ typedArrayEncoder(77, 2),
2144
+ typedArrayEncoder(78, 4),
2145
+ typedArrayEncoder(79, 8),
2146
+ typedArrayEncoder(85, 4),
2147
+ typedArrayEncoder(86, 8),
2148
+ {
2149
+ encode(sharedData, encode2) {
2150
+ let packedValues2 = sharedData.packedValues || [];
2151
+ let sharedStructures = sharedData.structures || [];
2152
+ if (packedValues2.values.length > 0) {
2153
+ target[position++] = 216;
2154
+ target[position++] = 51;
2155
+ writeArrayHeader(4);
2156
+ let valuesArray = packedValues2.values;
2157
+ encode2(valuesArray);
2158
+ writeArrayHeader(0);
2159
+ writeArrayHeader(0);
2160
+ packedObjectMap = Object.create(sharedPackedObjectMap || null);
2161
+ for (let i = 0, l = valuesArray.length; i < l; i++) {
2162
+ packedObjectMap[valuesArray[i]] = i;
2163
+ }
2164
+ }
2165
+ if (sharedStructures) {
2166
+ targetView.setUint32(position, 3655335424);
2167
+ position += 3;
2168
+ let definitions = sharedStructures.slice(0);
2169
+ definitions.unshift(57344);
2170
+ definitions.push(new Tag(sharedData.version, 1399353956));
2171
+ encode2(definitions);
2172
+ } else
2173
+ encode2(new Tag(sharedData.version, 1399353956));
2174
+ }
2175
+ }
2176
+ ];
2177
+ function typedArrayEncoder(tag, size) {
2178
+ if (!isLittleEndianMachine && size > 1)
2179
+ tag -= 4;
2180
+ return {
2181
+ tag,
2182
+ encode: function writeExtBuffer(typedArray, encode2) {
2183
+ let length = typedArray.byteLength;
2184
+ let offset = typedArray.byteOffset || 0;
2185
+ let buffer = typedArray.buffer || typedArray;
2186
+ encode2(hasNodeBuffer ? Buffer$1.from(buffer, offset, length) : new Uint8Array(buffer, offset, length));
2187
+ }
2188
+ };
2189
+ }
2190
+ function writeBuffer(buffer, makeRoom) {
2191
+ let length = buffer.byteLength;
2192
+ if (length < 24) {
2193
+ target[position++] = 64 + length;
2194
+ } else if (length < 256) {
2195
+ target[position++] = 88;
2196
+ target[position++] = length;
2197
+ } else if (length < 65536) {
2198
+ target[position++] = 89;
2199
+ target[position++] = length >> 8;
2200
+ target[position++] = length & 255;
2201
+ } else {
2202
+ target[position++] = 90;
2203
+ targetView.setUint32(position, length);
2204
+ position += 4;
2205
+ }
2206
+ if (position + length >= target.length) {
2207
+ makeRoom(position + length);
2208
+ }
2209
+ target.set(buffer.buffer ? buffer : new Uint8Array(buffer), position);
2210
+ position += length;
2211
+ }
2212
+ function insertIds(serialized, idsToInsert) {
2213
+ let nextId;
2214
+ let distanceToMove = idsToInsert.length * 2;
2215
+ let lastEnd = serialized.length - distanceToMove;
2216
+ idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
2217
+ for (let id = 0; id < idsToInsert.length; id++) {
2218
+ let referee = idsToInsert[id];
2219
+ referee.id = id;
2220
+ for (let position2 of referee.references) {
2221
+ serialized[position2++] = id >> 8;
2222
+ serialized[position2] = id & 255;
2223
+ }
2224
+ }
2225
+ while (nextId = idsToInsert.pop()) {
2226
+ let offset = nextId.offset;
2227
+ serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
2228
+ distanceToMove -= 2;
2229
+ let position2 = offset + distanceToMove;
2230
+ serialized[position2++] = 216;
2231
+ serialized[position2++] = 28;
2232
+ lastEnd = offset;
2233
+ }
2234
+ return serialized;
2235
+ }
2236
+ function writeBundles(start, encode2) {
2237
+ targetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1);
2238
+ let writeStrings = bundledStrings;
2239
+ bundledStrings = null;
2240
+ encode2(writeStrings[0]);
2241
+ encode2(writeStrings[1]);
2242
+ }
2243
+ let defaultEncoder = new Encoder({ useRecords: false });
2244
+ const encode = defaultEncoder.encode;
2245
+ defaultEncoder.encodeAsIterable;
2246
+ defaultEncoder.encodeAsAsyncIterable;
2247
+ const REUSE_BUFFER_MODE = 512;
2248
+ const RESET_BUFFER_MODE = 1024;
2249
+ const THROW_ON_ITERABLE = 2048;
2250
+ function b64ToBytes(b64) {
2251
+ const binary = atob(b64);
2252
+ const out = new Uint8Array(binary.length);
2253
+ for (let i = 0; i < binary.length; i += 1)
2254
+ out[i] = binary.charCodeAt(i);
2255
+ return out;
2256
+ }
2257
+ class ServerPublicKeyCache {
2258
+ constructor(collectorUrl, opts = {}, fetchImpl = (...args) => fetch(...args)) {
2259
+ __publicField(this, "collectorUrl");
2260
+ __publicField(this, "opts");
2261
+ __publicField(this, "fetchImpl");
2262
+ __publicField(this, "cached", null);
2263
+ this.collectorUrl = collectorUrl;
2264
+ this.opts = opts;
2265
+ this.fetchImpl = fetchImpl;
2266
+ }
2267
+ async get() {
2268
+ return (await this.getBundle()).key;
2269
+ }
2270
+ /** Back-compat: returns the X25519 key + alias only. */
2271
+ async getWithAlias() {
2272
+ const bundle = await this.getBundle();
2273
+ return { key: bundle.key, aliasPath: bundle.aliasPath };
2274
+ }
2275
+ /**
2276
+ * Fetch (or return cached) the full PK bundle: X25519 ingest key, the
2277
+ * obfuscated alias path, and the optional Ed25519 result-signing public
2278
+ * key. Integrators that verify sealed results should hold onto the
2279
+ * `resultSigningKey` and pass it to `verifySealedResult()`.
2280
+ */
2281
+ async getBundle() {
2282
+ const maxAge = this.opts.maxAgeMs ?? 6e4;
2283
+ if (this.cached && Date.now() - this.cached.at < maxAge) {
2284
+ return this.cached.bundle;
2285
+ }
2286
+ const res = await this.fetchImpl(`${this.collectorUrl.replace(/\/$/, "")}/v1/pk`, {
2287
+ method: "GET",
2288
+ credentials: "omit"
2289
+ });
2290
+ if (!res.ok) {
2291
+ throw new Error(`fetch /v1/pk failed: ${res.status}`);
2292
+ }
2293
+ const body = await res.json();
2294
+ const primary = body.keys.find((k) => k.id === body.primary) ?? body.keys[0];
2295
+ if (!primary || primary.alg !== "x25519") {
2296
+ throw new Error("no x25519 key advertised by collector");
2297
+ }
2298
+ const bundle = {
2299
+ key: { id: primary.id, alg: "x25519", key: b64ToBytes(primary.key) },
2300
+ aliasPath: body.aliasPath ?? null,
2301
+ resultSigningKey: body.resultSigning && body.resultSigning.alg === "ed25519" ? b64ToBytes(body.resultSigning.key) : null
2302
+ };
2303
+ this.cached = { at: Date.now(), bundle };
2304
+ return bundle;
2305
+ }
2306
+ clear() {
2307
+ this.cached = null;
2308
+ }
2309
+ }
2310
+ async function sendIngest(params) {
2311
+ const base = params.collectorUrl.replace(/\/$/, "");
2312
+ const url = params.aliasPath ? `${base}${params.aliasPath}?q=ingest` : `${base}/v1/ingest`;
2313
+ if (params.preferBeacon && typeof navigator !== "undefined" && navigator.sendBeacon) {
2314
+ const blob = new Blob([params.wire], {
2315
+ type: "application/octet-stream"
2316
+ });
2317
+ const queued = navigator.sendBeacon(url, blob);
2318
+ if (queued)
2319
+ return null;
2320
+ }
2321
+ const fetchImpl = params.fetchImpl ?? ((...args) => fetch(...args));
2322
+ const headers = {
2323
+ "content-type": "application/octet-stream",
2324
+ "x-k": params.serverKeyId,
2325
+ "x-v": params.sdkVersion
2326
+ };
2327
+ if (params.projectKey)
2328
+ headers["x-project-key"] = params.projectKey;
2329
+ const res = await fetchImpl(url, {
2330
+ method: "POST",
2331
+ headers,
2332
+ body: params.wire,
2333
+ credentials: "include",
2334
+ keepalive: true
2335
+ });
2336
+ const text = await res.text();
2337
+ if (!res.ok) {
2338
+ const result = { status: res.status, body: text };
2339
+ throw Object.assign(new Error(`/v1/ingest failed: ${res.status}`), { result });
2340
+ }
2341
+ return JSON.parse(text);
2342
+ }
2343
+ const WIRE_VERSION = 1;
2344
+ const EPH_PUB_LEN = 32;
2345
+ const NONCE_LEN = 12;
2346
+ const AES_KEY_LEN = 32;
2347
+ const HKDF_INFO = "fp-v1-ingest";
2348
+ const crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
2349
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2350
+ function isBytes(a) {
2351
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2352
+ }
2353
+ function anumber(n) {
2354
+ if (!Number.isSafeInteger(n) || n < 0)
2355
+ throw new Error("positive integer expected, got " + n);
2356
+ }
2357
+ function abytes(b, ...lengths) {
2358
+ if (!isBytes(b))
2359
+ throw new Error("Uint8Array expected");
2360
+ if (lengths.length > 0 && !lengths.includes(b.length))
2361
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
2362
+ }
2363
+ function ahash(h) {
2364
+ if (typeof h !== "function" || typeof h.create !== "function")
2365
+ throw new Error("Hash should be wrapped by utils.createHasher");
2366
+ anumber(h.outputLen);
2367
+ anumber(h.blockLen);
2368
+ }
2369
+ function aexists(instance, checkFinished = true) {
2370
+ if (instance.destroyed)
2371
+ throw new Error("Hash instance has been destroyed");
2372
+ if (checkFinished && instance.finished)
2373
+ throw new Error("Hash#digest() has already been called");
2374
+ }
2375
+ function aoutput(out, instance) {
2376
+ abytes(out);
2377
+ const min = instance.outputLen;
2378
+ if (out.length < min) {
2379
+ throw new Error("digestInto() expects output buffer of length at least " + min);
2380
+ }
2381
+ }
2382
+ function clean(...arrays) {
2383
+ for (let i = 0; i < arrays.length; i++) {
2384
+ arrays[i].fill(0);
2385
+ }
2386
+ }
2387
+ function createView(arr) {
2388
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2389
+ }
2390
+ function rotr(word, shift) {
2391
+ return word << 32 - shift | word >>> shift;
2392
+ }
2393
+ const hasHexBuiltin = /* @__PURE__ */ (() => (
2394
+ // @ts-ignore
2395
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
2396
+ ))();
2397
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
2398
+ function bytesToHex(bytes) {
2399
+ abytes(bytes);
2400
+ if (hasHexBuiltin)
2401
+ return bytes.toHex();
2402
+ let hex = "";
2403
+ for (let i = 0; i < bytes.length; i++) {
2404
+ hex += hexes[bytes[i]];
2405
+ }
2406
+ return hex;
2407
+ }
2408
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
2409
+ function asciiToBase16(ch) {
2410
+ if (ch >= asciis._0 && ch <= asciis._9)
2411
+ return ch - asciis._0;
2412
+ if (ch >= asciis.A && ch <= asciis.F)
2413
+ return ch - (asciis.A - 10);
2414
+ if (ch >= asciis.a && ch <= asciis.f)
2415
+ return ch - (asciis.a - 10);
2416
+ return;
2417
+ }
2418
+ function hexToBytes(hex) {
2419
+ if (typeof hex !== "string")
2420
+ throw new Error("hex string expected, got " + typeof hex);
2421
+ if (hasHexBuiltin)
2422
+ return Uint8Array.fromHex(hex);
2423
+ const hl = hex.length;
2424
+ const al = hl / 2;
2425
+ if (hl % 2)
2426
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
2427
+ const array = new Uint8Array(al);
2428
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
2429
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
2430
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
2431
+ if (n1 === void 0 || n2 === void 0) {
2432
+ const char = hex[hi] + hex[hi + 1];
2433
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
2434
+ }
2435
+ array[ai] = n1 * 16 + n2;
2436
+ }
2437
+ return array;
2438
+ }
2439
+ function utf8ToBytes(str) {
2440
+ if (typeof str !== "string")
2441
+ throw new Error("string expected");
2442
+ return new Uint8Array(new TextEncoder().encode(str));
2443
+ }
2444
+ function toBytes(data) {
2445
+ if (typeof data === "string")
2446
+ data = utf8ToBytes(data);
2447
+ abytes(data);
2448
+ return data;
2449
+ }
2450
+ class Hash {
2451
+ }
2452
+ function createHasher(hashCons) {
2453
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
2454
+ const tmp = hashCons();
2455
+ hashC.outputLen = tmp.outputLen;
2456
+ hashC.blockLen = tmp.blockLen;
2457
+ hashC.create = () => hashCons();
2458
+ return hashC;
2459
+ }
2460
+ function randomBytes$1(bytesLength = 32) {
2461
+ if (crypto && typeof crypto.getRandomValues === "function") {
2462
+ return crypto.getRandomValues(new Uint8Array(bytesLength));
2463
+ }
2464
+ if (crypto && typeof crypto.randomBytes === "function") {
2465
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
2466
+ }
2467
+ throw new Error("crypto.getRandomValues must be defined");
2468
+ }
2469
+ function setBigUint64(view, byteOffset, value, isLE) {
2470
+ if (typeof view.setBigUint64 === "function")
2471
+ return view.setBigUint64(byteOffset, value, isLE);
2472
+ const _32n = BigInt(32);
2473
+ const _u32_max = BigInt(4294967295);
2474
+ const wh = Number(value >> _32n & _u32_max);
2475
+ const wl = Number(value & _u32_max);
2476
+ const h = isLE ? 4 : 0;
2477
+ const l = isLE ? 0 : 4;
2478
+ view.setUint32(byteOffset + h, wh, isLE);
2479
+ view.setUint32(byteOffset + l, wl, isLE);
2480
+ }
2481
+ function Chi(a, b, c) {
2482
+ return a & b ^ ~a & c;
2483
+ }
2484
+ function Maj(a, b, c) {
2485
+ return a & b ^ a & c ^ b & c;
2486
+ }
2487
+ class HashMD extends Hash {
2488
+ constructor(blockLen, outputLen, padOffset, isLE) {
2489
+ super();
2490
+ this.finished = false;
2491
+ this.length = 0;
2492
+ this.pos = 0;
2493
+ this.destroyed = false;
2494
+ this.blockLen = blockLen;
2495
+ this.outputLen = outputLen;
2496
+ this.padOffset = padOffset;
2497
+ this.isLE = isLE;
2498
+ this.buffer = new Uint8Array(blockLen);
2499
+ this.view = createView(this.buffer);
2500
+ }
2501
+ update(data) {
2502
+ aexists(this);
2503
+ data = toBytes(data);
2504
+ abytes(data);
2505
+ const { view, buffer, blockLen } = this;
2506
+ const len = data.length;
2507
+ for (let pos = 0; pos < len; ) {
2508
+ const take = Math.min(blockLen - this.pos, len - pos);
2509
+ if (take === blockLen) {
2510
+ const dataView2 = createView(data);
2511
+ for (; blockLen <= len - pos; pos += blockLen)
2512
+ this.process(dataView2, pos);
2513
+ continue;
2514
+ }
2515
+ buffer.set(data.subarray(pos, pos + take), this.pos);
2516
+ this.pos += take;
2517
+ pos += take;
2518
+ if (this.pos === blockLen) {
2519
+ this.process(view, 0);
2520
+ this.pos = 0;
2521
+ }
2522
+ }
2523
+ this.length += data.length;
2524
+ this.roundClean();
2525
+ return this;
2526
+ }
2527
+ digestInto(out) {
2528
+ aexists(this);
2529
+ aoutput(out, this);
2530
+ this.finished = true;
2531
+ const { buffer, view, blockLen, isLE } = this;
2532
+ let { pos } = this;
2533
+ buffer[pos++] = 128;
2534
+ clean(this.buffer.subarray(pos));
2535
+ if (this.padOffset > blockLen - pos) {
2536
+ this.process(view, 0);
2537
+ pos = 0;
2538
+ }
2539
+ for (let i = pos; i < blockLen; i++)
2540
+ buffer[i] = 0;
2541
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
2542
+ this.process(view, 0);
2543
+ const oview = createView(out);
2544
+ const len = this.outputLen;
2545
+ if (len % 4)
2546
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
2547
+ const outLen = len / 4;
2548
+ const state = this.get();
2549
+ if (outLen > state.length)
2550
+ throw new Error("_sha2: outputLen bigger than state");
2551
+ for (let i = 0; i < outLen; i++)
2552
+ oview.setUint32(4 * i, state[i], isLE);
2553
+ }
2554
+ digest() {
2555
+ const { buffer, outputLen } = this;
2556
+ this.digestInto(buffer);
2557
+ const res = buffer.slice(0, outputLen);
2558
+ this.destroy();
2559
+ return res;
2560
+ }
2561
+ _cloneInto(to) {
2562
+ to || (to = new this.constructor());
2563
+ to.set(...this.get());
2564
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
2565
+ to.destroyed = destroyed;
2566
+ to.finished = finished;
2567
+ to.length = length;
2568
+ to.pos = pos;
2569
+ if (length % blockLen)
2570
+ to.buffer.set(buffer);
2571
+ return to;
2572
+ }
2573
+ clone() {
2574
+ return this._cloneInto();
2575
+ }
2576
+ }
2577
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
2578
+ 1779033703,
2579
+ 3144134277,
2580
+ 1013904242,
2581
+ 2773480762,
2582
+ 1359893119,
2583
+ 2600822924,
2584
+ 528734635,
2585
+ 1541459225
2586
+ ]);
2587
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
2588
+ 1116352408,
2589
+ 1899447441,
2590
+ 3049323471,
2591
+ 3921009573,
2592
+ 961987163,
2593
+ 1508970993,
2594
+ 2453635748,
2595
+ 2870763221,
2596
+ 3624381080,
2597
+ 310598401,
2598
+ 607225278,
2599
+ 1426881987,
2600
+ 1925078388,
2601
+ 2162078206,
2602
+ 2614888103,
2603
+ 3248222580,
2604
+ 3835390401,
2605
+ 4022224774,
2606
+ 264347078,
2607
+ 604807628,
2608
+ 770255983,
2609
+ 1249150122,
2610
+ 1555081692,
2611
+ 1996064986,
2612
+ 2554220882,
2613
+ 2821834349,
2614
+ 2952996808,
2615
+ 3210313671,
2616
+ 3336571891,
2617
+ 3584528711,
2618
+ 113926993,
2619
+ 338241895,
2620
+ 666307205,
2621
+ 773529912,
2622
+ 1294757372,
2623
+ 1396182291,
2624
+ 1695183700,
2625
+ 1986661051,
2626
+ 2177026350,
2627
+ 2456956037,
2628
+ 2730485921,
2629
+ 2820302411,
2630
+ 3259730800,
2631
+ 3345764771,
2632
+ 3516065817,
2633
+ 3600352804,
2634
+ 4094571909,
2635
+ 275423344,
2636
+ 430227734,
2637
+ 506948616,
2638
+ 659060556,
2639
+ 883997877,
2640
+ 958139571,
2641
+ 1322822218,
2642
+ 1537002063,
2643
+ 1747873779,
2644
+ 1955562222,
2645
+ 2024104815,
2646
+ 2227730452,
2647
+ 2361852424,
2648
+ 2428436474,
2649
+ 2756734187,
2650
+ 3204031479,
2651
+ 3329325298
2652
+ ]);
2653
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
2654
+ class SHA256 extends HashMD {
2655
+ constructor(outputLen = 32) {
2656
+ super(64, outputLen, 8, false);
2657
+ this.A = SHA256_IV[0] | 0;
2658
+ this.B = SHA256_IV[1] | 0;
2659
+ this.C = SHA256_IV[2] | 0;
2660
+ this.D = SHA256_IV[3] | 0;
2661
+ this.E = SHA256_IV[4] | 0;
2662
+ this.F = SHA256_IV[5] | 0;
2663
+ this.G = SHA256_IV[6] | 0;
2664
+ this.H = SHA256_IV[7] | 0;
2665
+ }
2666
+ get() {
2667
+ const { A, B, C, D, E, F, G, H } = this;
2668
+ return [A, B, C, D, E, F, G, H];
2669
+ }
2670
+ // prettier-ignore
2671
+ set(A, B, C, D, E, F, G, H) {
2672
+ this.A = A | 0;
2673
+ this.B = B | 0;
2674
+ this.C = C | 0;
2675
+ this.D = D | 0;
2676
+ this.E = E | 0;
2677
+ this.F = F | 0;
2678
+ this.G = G | 0;
2679
+ this.H = H | 0;
2680
+ }
2681
+ process(view, offset) {
2682
+ for (let i = 0; i < 16; i++, offset += 4)
2683
+ SHA256_W[i] = view.getUint32(offset, false);
2684
+ for (let i = 16; i < 64; i++) {
2685
+ const W15 = SHA256_W[i - 15];
2686
+ const W2 = SHA256_W[i - 2];
2687
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
2688
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
2689
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
2690
+ }
2691
+ let { A, B, C, D, E, F, G, H } = this;
2692
+ for (let i = 0; i < 64; i++) {
2693
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
2694
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
2695
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
2696
+ const T2 = sigma0 + Maj(A, B, C) | 0;
2697
+ H = G;
2698
+ G = F;
2699
+ F = E;
2700
+ E = D + T1 | 0;
2701
+ D = C;
2702
+ C = B;
2703
+ B = A;
2704
+ A = T1 + T2 | 0;
2705
+ }
2706
+ A = A + this.A | 0;
2707
+ B = B + this.B | 0;
2708
+ C = C + this.C | 0;
2709
+ D = D + this.D | 0;
2710
+ E = E + this.E | 0;
2711
+ F = F + this.F | 0;
2712
+ G = G + this.G | 0;
2713
+ H = H + this.H | 0;
2714
+ this.set(A, B, C, D, E, F, G, H);
2715
+ }
2716
+ roundClean() {
2717
+ clean(SHA256_W);
2718
+ }
2719
+ destroy() {
2720
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
2721
+ clean(this.buffer);
2722
+ }
2723
+ }
2724
+ const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
2725
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2726
+ const _0n$2 = /* @__PURE__ */ BigInt(0);
2727
+ const _1n$3 = /* @__PURE__ */ BigInt(1);
2728
+ function hexToNumber(hex) {
2729
+ if (typeof hex !== "string")
2730
+ throw new Error("hex string expected, got " + typeof hex);
2731
+ return hex === "" ? _0n$2 : BigInt("0x" + hex);
2732
+ }
2733
+ function bytesToNumberBE(bytes) {
2734
+ return hexToNumber(bytesToHex(bytes));
2735
+ }
2736
+ function bytesToNumberLE(bytes) {
2737
+ abytes(bytes);
2738
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
2739
+ }
2740
+ function numberToBytesBE(n, len) {
2741
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
2742
+ }
2743
+ function numberToBytesLE(n, len) {
2744
+ return numberToBytesBE(n, len).reverse();
2745
+ }
2746
+ function ensureBytes(title, hex, expectedLength) {
2747
+ let res;
2748
+ if (typeof hex === "string") {
2749
+ try {
2750
+ res = hexToBytes(hex);
2751
+ } catch (e) {
2752
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
2753
+ }
2754
+ } else if (isBytes(hex)) {
2755
+ res = Uint8Array.from(hex);
2756
+ } else {
2757
+ throw new Error(title + " must be hex string or Uint8Array");
2758
+ }
2759
+ const len = res.length;
2760
+ if (typeof expectedLength === "number" && len !== expectedLength)
2761
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
2762
+ return res;
2763
+ }
2764
+ const isPosBig = (n) => typeof n === "bigint" && _0n$2 <= n;
2765
+ function inRange(n, min, max) {
2766
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
2767
+ }
2768
+ function aInRange(title, n, min, max) {
2769
+ if (!inRange(n, min, max))
2770
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
2771
+ }
2772
+ const bitMask = (n) => (_1n$3 << BigInt(n)) - _1n$3;
2773
+ function _validateObject(object, fields, optFields = {}) {
2774
+ if (!object || typeof object !== "object")
2775
+ throw new Error("expected valid options object");
2776
+ function checkField(fieldName, expectedType, isOpt) {
2777
+ const val = object[fieldName];
2778
+ if (isOpt && val === void 0)
2779
+ return;
2780
+ const current = typeof val;
2781
+ if (current !== expectedType || val === null)
2782
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
2783
+ }
2784
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
2785
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
2786
+ }
2787
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2788
+ const _0n$1 = BigInt(0), _1n$2 = BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
2789
+ const _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
2790
+ const _8n$1 = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
2791
+ function mod(a, b) {
2792
+ const result = a % b;
2793
+ return result >= _0n$1 ? result : b + result;
2794
+ }
2795
+ function pow2(x, power, modulo) {
2796
+ let res = x;
2797
+ while (power-- > _0n$1) {
2798
+ res *= res;
2799
+ res %= modulo;
2800
+ }
2801
+ return res;
2802
+ }
2803
+ function invert(number, modulo) {
2804
+ if (number === _0n$1)
2805
+ throw new Error("invert: expected non-zero number");
2806
+ if (modulo <= _0n$1)
2807
+ throw new Error("invert: expected positive modulus, got " + modulo);
2808
+ let a = mod(number, modulo);
2809
+ let b = modulo;
2810
+ let x = _0n$1, u = _1n$2;
2811
+ while (a !== _0n$1) {
2812
+ const q = b / a;
2813
+ const r = b % a;
2814
+ const m = x - u * q;
2815
+ b = a, a = r, x = u, u = m;
2816
+ }
2817
+ const gcd = b;
2818
+ if (gcd !== _1n$2)
2819
+ throw new Error("invert: does not exist");
2820
+ return mod(x, modulo);
2821
+ }
2822
+ function assertIsSquare(Fp2, root, n) {
2823
+ if (!Fp2.eql(Fp2.sqr(root), n))
2824
+ throw new Error("Cannot find square root");
2825
+ }
2826
+ function sqrt3mod4(Fp2, n) {
2827
+ const p1div4 = (Fp2.ORDER + _1n$2) / _4n;
2828
+ const root = Fp2.pow(n, p1div4);
2829
+ assertIsSquare(Fp2, root, n);
2830
+ return root;
2831
+ }
2832
+ function sqrt5mod8(Fp2, n) {
2833
+ const p5div8 = (Fp2.ORDER - _5n$1) / _8n$1;
2834
+ const n2 = Fp2.mul(n, _2n$2);
2835
+ const v = Fp2.pow(n2, p5div8);
2836
+ const nv = Fp2.mul(n, v);
2837
+ const i = Fp2.mul(Fp2.mul(nv, _2n$2), v);
2838
+ const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
2839
+ assertIsSquare(Fp2, root, n);
2840
+ return root;
2841
+ }
2842
+ function sqrt9mod16(P) {
2843
+ const Fp_ = Field(P);
2844
+ const tn = tonelliShanks(P);
2845
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
2846
+ const c2 = tn(Fp_, c1);
2847
+ const c3 = tn(Fp_, Fp_.neg(c1));
2848
+ const c4 = (P + _7n) / _16n;
2849
+ return (Fp2, n) => {
2850
+ let tv1 = Fp2.pow(n, c4);
2851
+ let tv2 = Fp2.mul(tv1, c1);
2852
+ const tv3 = Fp2.mul(tv1, c2);
2853
+ const tv4 = Fp2.mul(tv1, c3);
2854
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
2855
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
2856
+ tv1 = Fp2.cmov(tv1, tv2, e1);
2857
+ tv2 = Fp2.cmov(tv4, tv3, e2);
2858
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
2859
+ const root = Fp2.cmov(tv1, tv2, e3);
2860
+ assertIsSquare(Fp2, root, n);
2861
+ return root;
2862
+ };
2863
+ }
2864
+ function tonelliShanks(P) {
2865
+ if (P < _3n$1)
2866
+ throw new Error("sqrt is not defined for small field");
2867
+ let Q = P - _1n$2;
2868
+ let S = 0;
2869
+ while (Q % _2n$2 === _0n$1) {
2870
+ Q /= _2n$2;
2871
+ S++;
2872
+ }
2873
+ let Z = _2n$2;
2874
+ const _Fp = Field(P);
2875
+ while (FpLegendre(_Fp, Z) === 1) {
2876
+ if (Z++ > 1e3)
2877
+ throw new Error("Cannot find square root: probably non-prime P");
2878
+ }
2879
+ if (S === 1)
2880
+ return sqrt3mod4;
2881
+ let cc = _Fp.pow(Z, Q);
2882
+ const Q1div2 = (Q + _1n$2) / _2n$2;
2883
+ return function tonelliSlow(Fp2, n) {
2884
+ if (Fp2.is0(n))
2885
+ return n;
2886
+ if (FpLegendre(Fp2, n) !== 1)
2887
+ throw new Error("Cannot find square root");
2888
+ let M = S;
2889
+ let c = Fp2.mul(Fp2.ONE, cc);
2890
+ let t = Fp2.pow(n, Q);
2891
+ let R = Fp2.pow(n, Q1div2);
2892
+ while (!Fp2.eql(t, Fp2.ONE)) {
2893
+ if (Fp2.is0(t))
2894
+ return Fp2.ZERO;
2895
+ let i = 1;
2896
+ let t_tmp = Fp2.sqr(t);
2897
+ while (!Fp2.eql(t_tmp, Fp2.ONE)) {
2898
+ i++;
2899
+ t_tmp = Fp2.sqr(t_tmp);
2900
+ if (i === M)
2901
+ throw new Error("Cannot find square root");
2902
+ }
2903
+ const exponent = _1n$2 << BigInt(M - i - 1);
2904
+ const b = Fp2.pow(c, exponent);
2905
+ M = i;
2906
+ c = Fp2.sqr(b);
2907
+ t = Fp2.mul(t, c);
2908
+ R = Fp2.mul(R, b);
2909
+ }
2910
+ return R;
2911
+ };
2912
+ }
2913
+ function FpSqrt(P) {
2914
+ if (P % _4n === _3n$1)
2915
+ return sqrt3mod4;
2916
+ if (P % _8n$1 === _5n$1)
2917
+ return sqrt5mod8;
2918
+ if (P % _16n === _9n)
2919
+ return sqrt9mod16(P);
2920
+ return tonelliShanks(P);
2921
+ }
2922
+ function FpPow(Fp2, num, power) {
2923
+ if (power < _0n$1)
2924
+ throw new Error("invalid exponent, negatives unsupported");
2925
+ if (power === _0n$1)
2926
+ return Fp2.ONE;
2927
+ if (power === _1n$2)
2928
+ return num;
2929
+ let p = Fp2.ONE;
2930
+ let d = num;
2931
+ while (power > _0n$1) {
2932
+ if (power & _1n$2)
2933
+ p = Fp2.mul(p, d);
2934
+ d = Fp2.sqr(d);
2935
+ power >>= _1n$2;
2936
+ }
2937
+ return p;
2938
+ }
2939
+ function FpInvertBatch(Fp2, nums, passZero = false) {
2940
+ const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
2941
+ const multipliedAcc = nums.reduce((acc, num, i) => {
2942
+ if (Fp2.is0(num))
2943
+ return acc;
2944
+ inverted[i] = acc;
2945
+ return Fp2.mul(acc, num);
2946
+ }, Fp2.ONE);
2947
+ const invertedAcc = Fp2.inv(multipliedAcc);
2948
+ nums.reduceRight((acc, num, i) => {
2949
+ if (Fp2.is0(num))
2950
+ return acc;
2951
+ inverted[i] = Fp2.mul(acc, inverted[i]);
2952
+ return Fp2.mul(acc, num);
2953
+ }, invertedAcc);
2954
+ return inverted;
2955
+ }
2956
+ function FpLegendre(Fp2, n) {
2957
+ const p1mod2 = (Fp2.ORDER - _1n$2) / _2n$2;
2958
+ const powered = Fp2.pow(n, p1mod2);
2959
+ const yes = Fp2.eql(powered, Fp2.ONE);
2960
+ const zero = Fp2.eql(powered, Fp2.ZERO);
2961
+ const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
2962
+ if (!yes && !zero && !no)
2963
+ throw new Error("invalid Legendre symbol result");
2964
+ return yes ? 1 : zero ? 0 : -1;
2965
+ }
2966
+ function nLength(n, nBitLength) {
2967
+ if (nBitLength !== void 0)
2968
+ anumber(nBitLength);
2969
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
2970
+ const nByteLength = Math.ceil(_nBitLength / 8);
2971
+ return { nBitLength: _nBitLength, nByteLength };
2972
+ }
2973
+ function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
2974
+ if (ORDER <= _0n$1)
2975
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
2976
+ let _nbitLength = void 0;
2977
+ let _sqrt = void 0;
2978
+ let modFromBytes = false;
2979
+ let allowedLengths = void 0;
2980
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
2981
+ if (opts.sqrt || isLE)
2982
+ throw new Error("cannot specify opts in two arguments");
2983
+ const _opts = bitLenOrOpts;
2984
+ if (_opts.BITS)
2985
+ _nbitLength = _opts.BITS;
2986
+ if (_opts.sqrt)
2987
+ _sqrt = _opts.sqrt;
2988
+ if (typeof _opts.isLE === "boolean")
2989
+ isLE = _opts.isLE;
2990
+ if (typeof _opts.modFromBytes === "boolean")
2991
+ modFromBytes = _opts.modFromBytes;
2992
+ allowedLengths = _opts.allowedLengths;
2993
+ } else {
2994
+ if (typeof bitLenOrOpts === "number")
2995
+ _nbitLength = bitLenOrOpts;
2996
+ if (opts.sqrt)
2997
+ _sqrt = opts.sqrt;
2998
+ }
2999
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
3000
+ if (BYTES > 2048)
3001
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
3002
+ let sqrtP;
3003
+ const f = Object.freeze({
3004
+ ORDER,
3005
+ isLE,
3006
+ BITS,
3007
+ BYTES,
3008
+ MASK: bitMask(BITS),
3009
+ ZERO: _0n$1,
3010
+ ONE: _1n$2,
3011
+ allowedLengths,
3012
+ create: (num) => mod(num, ORDER),
3013
+ isValid: (num) => {
3014
+ if (typeof num !== "bigint")
3015
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
3016
+ return _0n$1 <= num && num < ORDER;
3017
+ },
3018
+ is0: (num) => num === _0n$1,
3019
+ // is valid and invertible
3020
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
3021
+ isOdd: (num) => (num & _1n$2) === _1n$2,
3022
+ neg: (num) => mod(-num, ORDER),
3023
+ eql: (lhs, rhs) => lhs === rhs,
3024
+ sqr: (num) => mod(num * num, ORDER),
3025
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
3026
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
3027
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
3028
+ pow: (num, power) => FpPow(f, num, power),
3029
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
3030
+ // Same as above, but doesn't normalize
3031
+ sqrN: (num) => num * num,
3032
+ addN: (lhs, rhs) => lhs + rhs,
3033
+ subN: (lhs, rhs) => lhs - rhs,
3034
+ mulN: (lhs, rhs) => lhs * rhs,
3035
+ inv: (num) => invert(num, ORDER),
3036
+ sqrt: _sqrt || ((n) => {
3037
+ if (!sqrtP)
3038
+ sqrtP = FpSqrt(ORDER);
3039
+ return sqrtP(f, n);
3040
+ }),
3041
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
3042
+ fromBytes: (bytes, skipValidation = true) => {
3043
+ if (allowedLengths) {
3044
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
3045
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
3046
+ }
3047
+ const padded = new Uint8Array(BYTES);
3048
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
3049
+ bytes = padded;
3050
+ }
3051
+ if (bytes.length !== BYTES)
3052
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
3053
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
3054
+ if (modFromBytes)
3055
+ scalar = mod(scalar, ORDER);
3056
+ if (!skipValidation) {
3057
+ if (!f.isValid(scalar))
3058
+ throw new Error("invalid field element: outside of range 0..ORDER");
3059
+ }
3060
+ return scalar;
3061
+ },
3062
+ // TODO: we don't need it here, move out to separate fn
3063
+ invertBatch: (lst) => FpInvertBatch(f, lst),
3064
+ // We can't move this out because Fp6, Fp12 implement it
3065
+ // and it's unclear what to return in there.
3066
+ cmov: (a, b, c) => c ? b : a
3067
+ });
3068
+ return Object.freeze(f);
3069
+ }
3070
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3071
+ BigInt(0);
3072
+ BigInt(1);
3073
+ BigInt(2);
3074
+ BigInt(8);
3075
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3076
+ const _0n = BigInt(0);
3077
+ const _1n$1 = BigInt(1);
3078
+ const _2n$1 = BigInt(2);
3079
+ function validateOpts(curve) {
3080
+ _validateObject(curve, {
3081
+ adjustScalarBytes: "function",
3082
+ powPminus2: "function"
3083
+ });
3084
+ return Object.freeze({ ...curve });
3085
+ }
3086
+ function montgomery(curveDef) {
3087
+ const CURVE = validateOpts(curveDef);
3088
+ const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
3089
+ const is25519 = type === "x25519";
3090
+ if (!is25519 && type !== "x448")
3091
+ throw new Error("invalid type");
3092
+ const randomBytes_ = rand || randomBytes$1;
3093
+ const montgomeryBits = is25519 ? 255 : 448;
3094
+ const fieldLen = is25519 ? 32 : 56;
3095
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
3096
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
3097
+ const minScalar = is25519 ? _2n$1 ** BigInt(254) : _2n$1 ** BigInt(447);
3098
+ const maxAdded = is25519 ? BigInt(8) * _2n$1 ** BigInt(251) - _1n$1 : BigInt(4) * _2n$1 ** BigInt(445) - _1n$1;
3099
+ const maxScalar = minScalar + maxAdded + _1n$1;
3100
+ const modP = (n) => mod(n, P);
3101
+ const GuBytes = encodeU(Gu);
3102
+ function encodeU(u) {
3103
+ return numberToBytesLE(modP(u), fieldLen);
3104
+ }
3105
+ function decodeU(u) {
3106
+ const _u = ensureBytes("u coordinate", u, fieldLen);
3107
+ if (is25519)
3108
+ _u[31] &= 127;
3109
+ return modP(bytesToNumberLE(_u));
3110
+ }
3111
+ function decodeScalar(scalar) {
3112
+ return bytesToNumberLE(adjustScalarBytes2(ensureBytes("scalar", scalar, fieldLen)));
3113
+ }
3114
+ function scalarMult(scalar, u) {
3115
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
3116
+ if (pu === _0n)
3117
+ throw new Error("invalid private or public key received");
3118
+ return encodeU(pu);
3119
+ }
3120
+ function scalarMultBase(scalar) {
3121
+ return scalarMult(scalar, GuBytes);
3122
+ }
3123
+ function cswap(swap, x_2, x_3) {
3124
+ const dummy = modP(swap * (x_2 - x_3));
3125
+ x_2 = modP(x_2 - dummy);
3126
+ x_3 = modP(x_3 + dummy);
3127
+ return { x_2, x_3 };
3128
+ }
3129
+ function montgomeryLadder(u, scalar) {
3130
+ aInRange("u", u, _0n, P);
3131
+ aInRange("scalar", scalar, minScalar, maxScalar);
3132
+ const k = scalar;
3133
+ const x_1 = u;
3134
+ let x_2 = _1n$1;
3135
+ let z_2 = _0n;
3136
+ let x_3 = u;
3137
+ let z_3 = _1n$1;
3138
+ let swap = _0n;
3139
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
3140
+ const k_t = k >> t & _1n$1;
3141
+ swap ^= k_t;
3142
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
3143
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
3144
+ swap = k_t;
3145
+ const A = x_2 + z_2;
3146
+ const AA = modP(A * A);
3147
+ const B = x_2 - z_2;
3148
+ const BB = modP(B * B);
3149
+ const E = AA - BB;
3150
+ const C = x_3 + z_3;
3151
+ const D = x_3 - z_3;
3152
+ const DA = modP(D * A);
3153
+ const CB = modP(C * B);
3154
+ const dacb = DA + CB;
3155
+ const da_cb = DA - CB;
3156
+ x_3 = modP(dacb * dacb);
3157
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
3158
+ x_2 = modP(AA * BB);
3159
+ z_2 = modP(E * (AA + modP(a24 * E)));
3160
+ }
3161
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
3162
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
3163
+ const z2 = powPminus2(z_2);
3164
+ return modP(x_2 * z2);
3165
+ }
3166
+ const lengths = {
3167
+ secretKey: fieldLen,
3168
+ publicKey: fieldLen,
3169
+ seed: fieldLen
3170
+ };
3171
+ const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
3172
+ abytes(seed, lengths.seed);
3173
+ return seed;
3174
+ };
3175
+ function keygen(seed) {
3176
+ const secretKey = randomSecretKey(seed);
3177
+ return { secretKey, publicKey: scalarMultBase(secretKey) };
3178
+ }
3179
+ const utils = {
3180
+ randomSecretKey,
3181
+ randomPrivateKey: randomSecretKey
3182
+ };
3183
+ return {
3184
+ keygen,
3185
+ getSharedSecret: (secretKey, publicKey) => scalarMult(secretKey, publicKey),
3186
+ getPublicKey: (secretKey) => scalarMultBase(secretKey),
3187
+ scalarMult,
3188
+ scalarMultBase,
3189
+ utils,
3190
+ GuBytes: GuBytes.slice(),
3191
+ lengths
3192
+ };
3193
+ }
3194
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3195
+ const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
3196
+ const _5n = BigInt(5), _8n = BigInt(8);
3197
+ const ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
3198
+ const ed25519_CURVE = /* @__PURE__ */ (() => ({
3199
+ p: ed25519_CURVE_p,
3200
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
3201
+ h: _8n,
3202
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
3203
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
3204
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
3205
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
3206
+ }))();
3207
+ function ed25519_pow_2_252_3(x) {
3208
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
3209
+ const P = ed25519_CURVE_p;
3210
+ const x2 = x * x % P;
3211
+ const b2 = x2 * x % P;
3212
+ const b4 = pow2(b2, _2n, P) * b2 % P;
3213
+ const b5 = pow2(b4, _1n, P) * x % P;
3214
+ const b10 = pow2(b5, _5n, P) * b5 % P;
3215
+ const b20 = pow2(b10, _10n, P) * b10 % P;
3216
+ const b40 = pow2(b20, _20n, P) * b20 % P;
3217
+ const b80 = pow2(b40, _40n, P) * b40 % P;
3218
+ const b160 = pow2(b80, _80n, P) * b80 % P;
3219
+ const b240 = pow2(b160, _80n, P) * b80 % P;
3220
+ const b250 = pow2(b240, _10n, P) * b10 % P;
3221
+ const pow_p_5_8 = pow2(b250, _2n, P) * x % P;
3222
+ return { pow_p_5_8, b2 };
3223
+ }
3224
+ function adjustScalarBytes(bytes) {
3225
+ bytes[0] &= 248;
3226
+ bytes[31] &= 127;
3227
+ bytes[31] |= 64;
3228
+ return bytes;
3229
+ }
3230
+ const Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
3231
+ const x25519 = /* @__PURE__ */ (() => {
3232
+ const P = Fp.ORDER;
3233
+ return montgomery({
3234
+ P,
3235
+ type: "x25519",
3236
+ powPminus2: (x) => {
3237
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
3238
+ return mod(pow2(pow_p_5_8, _3n, P) * b2, P);
3239
+ },
3240
+ adjustScalarBytes
3241
+ });
3242
+ })();
3243
+ function generateKeypair() {
3244
+ const privateKey = x25519.utils.randomPrivateKey();
3245
+ const publicKey = x25519.getPublicKey(privateKey);
3246
+ return { publicKey, privateKey };
3247
+ }
3248
+ function deriveSharedSecret(privateKey, peerPublicKey) {
3249
+ return x25519.getSharedSecret(privateKey, peerPublicKey);
3250
+ }
3251
+ class HMAC extends Hash {
3252
+ constructor(hash, _key) {
3253
+ super();
3254
+ this.finished = false;
3255
+ this.destroyed = false;
3256
+ ahash(hash);
3257
+ const key = toBytes(_key);
3258
+ this.iHash = hash.create();
3259
+ if (typeof this.iHash.update !== "function")
3260
+ throw new Error("Expected instance of class which extends utils.Hash");
3261
+ this.blockLen = this.iHash.blockLen;
3262
+ this.outputLen = this.iHash.outputLen;
3263
+ const blockLen = this.blockLen;
3264
+ const pad = new Uint8Array(blockLen);
3265
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
3266
+ for (let i = 0; i < pad.length; i++)
3267
+ pad[i] ^= 54;
3268
+ this.iHash.update(pad);
3269
+ this.oHash = hash.create();
3270
+ for (let i = 0; i < pad.length; i++)
3271
+ pad[i] ^= 54 ^ 92;
3272
+ this.oHash.update(pad);
3273
+ clean(pad);
3274
+ }
3275
+ update(buf2) {
3276
+ aexists(this);
3277
+ this.iHash.update(buf2);
3278
+ return this;
3279
+ }
3280
+ digestInto(out) {
3281
+ aexists(this);
3282
+ abytes(out, this.outputLen);
3283
+ this.finished = true;
3284
+ this.iHash.digestInto(out);
3285
+ this.oHash.update(out);
3286
+ this.oHash.digestInto(out);
3287
+ this.destroy();
3288
+ }
3289
+ digest() {
3290
+ const out = new Uint8Array(this.oHash.outputLen);
3291
+ this.digestInto(out);
3292
+ return out;
3293
+ }
3294
+ _cloneInto(to) {
3295
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
3296
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
3297
+ to = to;
3298
+ to.finished = finished;
3299
+ to.destroyed = destroyed;
3300
+ to.blockLen = blockLen;
3301
+ to.outputLen = outputLen;
3302
+ to.oHash = oHash._cloneInto(to.oHash);
3303
+ to.iHash = iHash._cloneInto(to.iHash);
3304
+ return to;
3305
+ }
3306
+ clone() {
3307
+ return this._cloneInto();
3308
+ }
3309
+ destroy() {
3310
+ this.destroyed = true;
3311
+ this.oHash.destroy();
3312
+ this.iHash.destroy();
3313
+ }
3314
+ }
3315
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
3316
+ hmac.create = (hash, key) => new HMAC(hash, key);
3317
+ function extract(hash, ikm, salt) {
3318
+ ahash(hash);
3319
+ if (salt === void 0)
3320
+ salt = new Uint8Array(hash.outputLen);
3321
+ return hmac(hash, toBytes(salt), toBytes(ikm));
3322
+ }
3323
+ const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
3324
+ const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
3325
+ function expand(hash, prk, info, length = 32) {
3326
+ ahash(hash);
3327
+ anumber(length);
3328
+ const olen = hash.outputLen;
3329
+ if (length > 255 * olen)
3330
+ throw new Error("Length should be <= 255*HashLen");
3331
+ const blocks = Math.ceil(length / olen);
3332
+ if (info === void 0)
3333
+ info = EMPTY_BUFFER;
3334
+ const okm = new Uint8Array(blocks * olen);
3335
+ const HMAC2 = hmac.create(hash, prk);
3336
+ const HMACTmp = HMAC2._cloneInto();
3337
+ const T = new Uint8Array(HMAC2.outputLen);
3338
+ for (let counter = 0; counter < blocks; counter++) {
3339
+ HKDF_COUNTER[0] = counter + 1;
3340
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
3341
+ okm.set(T, olen * counter);
3342
+ HMAC2._cloneInto(HMACTmp);
3343
+ }
3344
+ HMAC2.destroy();
3345
+ HMACTmp.destroy();
3346
+ clean(T, HKDF_COUNTER);
3347
+ return okm.slice(0, length);
3348
+ }
3349
+ const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
3350
+ const INFO_BYTES = new TextEncoder().encode(HKDF_INFO);
3351
+ const EMPTY_SALT = new Uint8Array(0);
3352
+ function deriveAesKey(sharedSecret, salt) {
3353
+ return hkdf(sha256, sharedSecret, EMPTY_SALT, INFO_BYTES, AES_KEY_LEN);
3354
+ }
3355
+ function requireSubtle() {
3356
+ const c = globalThis.crypto;
3357
+ if (!c?.subtle) {
3358
+ throw new Error("globalThis.crypto.subtle is unavailable in this runtime");
3359
+ }
3360
+ return c.subtle;
3361
+ }
3362
+ function buf(bytes) {
3363
+ return bytes;
3364
+ }
3365
+ async function importKey(raw, usages) {
3366
+ return requireSubtle().importKey("raw", buf(raw), { name: "AES-GCM" }, false, usages);
3367
+ }
3368
+ async function encryptGcm(key, nonce, plaintext) {
3369
+ const ck = await importKey(key, ["encrypt"]);
3370
+ const ct = await requireSubtle().encrypt({ name: "AES-GCM", iv: buf(nonce) }, ck, buf(plaintext));
3371
+ return new Uint8Array(ct);
3372
+ }
3373
+ function randomBytes(length) {
3374
+ const c = globalThis.crypto;
3375
+ if (!c?.getRandomValues) {
3376
+ throw new Error("globalThis.crypto.getRandomValues is unavailable");
3377
+ }
3378
+ return c.getRandomValues(new Uint8Array(length));
3379
+ }
3380
+ async function seal(serverPublicKey, plaintext) {
3381
+ const eph = generateKeypair();
3382
+ const shared = deriveSharedSecret(eph.privateKey, serverPublicKey);
3383
+ const aesKey = deriveAesKey(shared);
3384
+ const nonce = randomBytes(NONCE_LEN);
3385
+ const ct = await encryptGcm(aesKey, nonce, plaintext);
3386
+ const wire = new Uint8Array(1 + EPH_PUB_LEN + NONCE_LEN + ct.length);
3387
+ wire[0] = WIRE_VERSION;
3388
+ wire.set(eph.publicKey, 1);
3389
+ wire.set(nonce, 1 + EPH_PUB_LEN);
3390
+ wire.set(ct, 1 + EPH_PUB_LEN + NONCE_LEN);
3391
+ return { wire, ephemeralPublicKey: eph.publicKey };
3392
+ }
3393
+ function collectHardware() {
3394
+ const screen = Dimensions.get("screen");
3395
+ const ratio = PixelRatio.get();
3396
+ const osLabel = Platform.OS === "ios" ? "iOS" : Platform.OS === "android" ? "Android" : Platform.OS;
3397
+ const userAgent = `${osLabel}/${Platform.Version}; RN`;
3398
+ return {
3399
+ userAgent,
3400
+ platform: Platform.OS,
3401
+ screen: {
3402
+ width: Math.round(screen.width * ratio),
3403
+ height: Math.round(screen.height * ratio)
3404
+ },
3405
+ devicePixelRatio: ratio
3406
+ };
3407
+ }
3408
+ let localize = null;
3409
+ try {
3410
+ localize = require("react-native-localize");
3411
+ } catch {
3412
+ localize = null;
3413
+ }
3414
+ function collectIntl() {
3415
+ const timezone = localize?.getTimeZone() ?? jsTimezone();
3416
+ const languages = localize?.getLocales().map((l) => l.languageTag) ?? rnLanguages();
3417
+ const language = languages[0];
3418
+ return {
3419
+ ...timezone !== void 0 ? { timezone } : {},
3420
+ ...language !== void 0 ? { language } : {},
3421
+ ...languages.length > 0 ? { languages } : {}
3422
+ };
3423
+ }
3424
+ function jsTimezone() {
3425
+ try {
3426
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
3427
+ } catch {
3428
+ return void 0;
3429
+ }
3430
+ }
3431
+ function rnLanguages() {
3432
+ if (Platform.OS === "ios") {
3433
+ const settings = NativeModules.SettingsManager?.settings;
3434
+ if (settings?.AppleLanguages?.length) return settings.AppleLanguages;
3435
+ if (settings?.AppleLocale) return [settings.AppleLocale];
3436
+ } else if (Platform.OS === "android") {
3437
+ const locale = NativeModules.I18nManager?.localeIdentifier;
3438
+ if (locale) return [locale];
3439
+ }
3440
+ return I18nManager.isRTL ? ["ar"] : [];
3441
+ }
3442
+ let netinfo = null;
3443
+ try {
3444
+ netinfo = require("@react-native-community/netinfo");
3445
+ } catch {
3446
+ netinfo = null;
3447
+ }
3448
+ async function collectNetwork() {
3449
+ if (!netinfo) return void 0;
3450
+ try {
3451
+ const state = await netinfo.fetch();
3452
+ const details = state.details ?? {};
3453
+ const gen = typeof details.cellularGeneration === "string" ? details.cellularGeneration : void 0;
3454
+ const effectiveType = gen ?? state.type;
3455
+ const block = {};
3456
+ if (effectiveType) block.effectiveType = effectiveType;
3457
+ if (typeof details.isConnectionExpensive === "boolean") {
3458
+ block.saveData = details.isConnectionExpensive;
3459
+ }
3460
+ return Object.keys(block).length ? block : void 0;
3461
+ } catch {
3462
+ return void 0;
3463
+ }
3464
+ }
3465
+ const FP_RN_BRIDGE = NativeModules.FpRnModule;
3466
+ function isNativeLinked() {
3467
+ return FP_RN_BRIDGE !== void 0;
3468
+ }
3469
+ async function collectNativeMobile() {
3470
+ if (!FP_RN_BRIDGE) {
3471
+ return {};
3472
+ }
3473
+ try {
3474
+ return await FP_RN_BRIDGE.collect();
3475
+ } catch {
3476
+ return {};
3477
+ }
3478
+ }
3479
+ async function collectSignals() {
3480
+ const [network, native] = await Promise.all([collectNetwork(), collectNativeMobile()]);
3481
+ const signals = {
3482
+ hardware: collectHardware(),
3483
+ intl: collectIntl()
3484
+ };
3485
+ if (network) signals.network = network;
3486
+ const mobile = pickMobile(native);
3487
+ if (mobile) signals.mobile = mobile;
3488
+ return signals;
3489
+ }
3490
+ function pickMobile(p) {
3491
+ const out = {};
3492
+ if (p.os === "ios" || p.os === "android") out.os = p.os;
3493
+ if (typeof p.osVersion === "string") out.osVersion = p.osVersion;
3494
+ if (typeof p.model === "string") out.model = p.model;
3495
+ if (typeof p.manufacturer === "string") out.manufacturer = p.manufacturer;
3496
+ if (typeof p.idfv === "string") out.idfv = p.idfv;
3497
+ if (typeof p.androidId === "string") out.androidId = p.androidId;
3498
+ if (typeof p.installId === "string") out.installId = p.installId;
3499
+ if (typeof p.totalMemoryMb === "number") out.totalMemoryMb = p.totalMemoryMb;
3500
+ if (typeof p.isTablet === "boolean") out.isTablet = p.isTablet;
3501
+ if (typeof p.bundleId === "string") out.bundleId = p.bundleId;
3502
+ if (typeof p.appVersion === "string") out.appVersion = p.appVersion;
3503
+ return Object.keys(out).length ? out : void 0;
3504
+ }
3505
+ let asyncStorage = null;
3506
+ try {
3507
+ asyncStorage = require("@react-native-async-storage/async-storage").default;
3508
+ } catch {
3509
+ asyncStorage = null;
3510
+ }
3511
+ const SESSION_KEY = "fp79.sessionId";
3512
+ function freshSessionId() {
3513
+ const bytes = randomBytes(12);
3514
+ let out = "sess-";
3515
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
3516
+ return out;
3517
+ }
3518
+ let cached = null;
3519
+ let restoring = null;
3520
+ function getOrCreateSessionId() {
3521
+ if (cached) return cached;
3522
+ cached = freshSessionId();
3523
+ if (asyncStorage) {
3524
+ void asyncStorage.setItem(SESSION_KEY, cached);
3525
+ }
3526
+ return cached;
3527
+ }
3528
+ function restoreSessionId() {
3529
+ if (!asyncStorage) return Promise.resolve();
3530
+ if (!restoring) {
3531
+ restoring = asyncStorage.getItem(SESSION_KEY).then((stored) => {
3532
+ if (stored && !cached) cached = stored;
3533
+ }).catch(() => {
3534
+ });
3535
+ }
3536
+ return restoring;
3537
+ }
3538
+ const SDK_VERSION = "0.0.1";
3539
+ class FpRnClient {
3540
+ constructor(config) {
3541
+ __publicField(this, "pkCache");
3542
+ __publicField(this, "config");
3543
+ this.config = config;
3544
+ this.pkCache = new ServerPublicKeyCache(config.collectorUrl);
3545
+ void restoreSessionId();
3546
+ }
3547
+ /** Warm-up the public-key cache. FpProvider awaits this in useEffect
3548
+ * so the very first identify() call doesn't pay the /v1/pk hop and
3549
+ * so auth misconfig surfaces as ready=false up-front. */
3550
+ async warmUp() {
3551
+ await this.pkCache.getWithAlias();
3552
+ }
3553
+ async identify(opts = {}) {
3554
+ const signals = await collectSignals();
3555
+ const sessionId = getOrCreateSessionId();
3556
+ const event = opts.event ?? "pageview";
3557
+ const syncMode = opts.sync ?? true;
3558
+ const payload = {
3559
+ sdkVersion: SDK_VERSION,
3560
+ ts: Date.now(),
3561
+ sessionId,
3562
+ // Mobile apps have no URL but the wire schema requires a string —
3563
+ // use the bundle id (if collected via native) as a stable
3564
+ // "namespace" so dashboard filters don't choke on every event
3565
+ // sharing the same placeholder. Fall back to a sentinel scheme.
3566
+ pageUrl: bundleAsUrl(signals.mobile?.bundleId) ?? "rn://app",
3567
+ referrer: "",
3568
+ event,
3569
+ signals
3570
+ };
3571
+ if (opts.userId !== void 0) {
3572
+ payload.accountHint = { userId: opts.userId };
3573
+ }
3574
+ if (syncMode) payload.sync = true;
3575
+ const { key: serverKey, aliasPath } = await this.pkCache.getWithAlias();
3576
+ const plaintext = new Uint8Array(encode(payload));
3577
+ const { wire } = await seal(serverKey.key, plaintext);
3578
+ return await sendIngest({
3579
+ collectorUrl: this.config.collectorUrl,
3580
+ wire,
3581
+ serverKeyId: serverKey.id,
3582
+ sdkVersion: SDK_VERSION,
3583
+ preferBeacon: false,
3584
+ ...aliasPath ? { aliasPath } : {},
3585
+ projectKey: this.config.projectKey
3586
+ });
3587
+ }
3588
+ }
3589
+ function bundleAsUrl(bundleId) {
3590
+ if (!bundleId) return void 0;
3591
+ return `rn://${bundleId}`;
3592
+ }
3593
+ const FpContext = createContext({
3594
+ instance: null,
3595
+ ready: false,
3596
+ error: null
3597
+ });
3598
+ function FpProvider({ config, children }) {
3599
+ const instance = useMemo(() => new FpRnClient(config), [config.collectorUrl, config.projectKey]);
3600
+ const [state, setState] = useState({
3601
+ instance: null,
3602
+ ready: false,
3603
+ error: null
3604
+ });
3605
+ useEffect(() => {
3606
+ let cancelled = false;
3607
+ if (!isNativeLinked() && __DEV__) {
3608
+ console.warn(
3609
+ "[@fingerprint79/react-native] Native module not linked. Mobile signals (idfv / installId / hardware) will be absent. Did you run `pod install` (iOS) and rebuild (Android)?"
3610
+ );
3611
+ }
3612
+ instance.warmUp().then(() => {
3613
+ if (cancelled) return;
3614
+ setState({ instance, ready: true, error: null });
3615
+ }).catch((e) => {
3616
+ if (cancelled) return;
3617
+ setState({
3618
+ instance: null,
3619
+ ready: false,
3620
+ error: e instanceof Error ? e : new Error(String(e))
3621
+ });
3622
+ });
3623
+ return () => {
3624
+ cancelled = true;
3625
+ };
3626
+ }, [instance]);
3627
+ return /* @__PURE__ */ jsx(FpContext.Provider, { value: state, children });
3628
+ }
3629
+ function useFpContext() {
3630
+ return useContext(FpContext);
3631
+ }
3632
+ function useFpStatus() {
3633
+ const ctx = useFpContext();
3634
+ return { ready: ctx.ready, error: ctx.error };
3635
+ }
3636
+ function useIdentify(defaults = {}) {
3637
+ const ctx = useFpContext();
3638
+ const [data, setData] = useState(null);
3639
+ const [loading, setLoading] = useState(false);
3640
+ const [error, setError] = useState(null);
3641
+ const defaultEvent = defaults.event;
3642
+ const defaultUserId = defaults.userId;
3643
+ const defaultSync = defaults.sync;
3644
+ const identify = useCallback(
3645
+ async (opts) => {
3646
+ if (!ctx.instance) {
3647
+ const err = ctx.error ?? new Error("FpProvider not ready");
3648
+ setError(err);
3649
+ throw err;
3650
+ }
3651
+ const merged = {
3652
+ ...defaultEvent !== void 0 ? { event: defaultEvent } : {},
3653
+ ...defaultUserId !== void 0 ? { userId: defaultUserId } : {},
3654
+ ...defaultSync !== void 0 ? { sync: defaultSync } : {},
3655
+ ...opts ?? {}
3656
+ };
3657
+ setLoading(true);
3658
+ setError(null);
3659
+ try {
3660
+ const r = await ctx.instance.identify(merged);
3661
+ setData(r);
3662
+ return r;
3663
+ } catch (e) {
3664
+ const err = e instanceof Error ? e : new Error(String(e));
3665
+ setError(err);
3666
+ throw err;
3667
+ } finally {
3668
+ setLoading(false);
3669
+ }
3670
+ },
3671
+ [ctx.instance, ctx.error, defaultEvent, defaultUserId, defaultSync]
3672
+ );
3673
+ return { identify, data, loading, error };
3674
+ }
3675
+ function useAutoIdentify(opts = {}) {
3676
+ const ctx = useFpContext();
3677
+ const [data, setData] = useState(null);
3678
+ const [loading, setLoading] = useState(false);
3679
+ const [error, setError] = useState(null);
3680
+ const event = opts.event ?? "pageview";
3681
+ const userId = opts.userId;
3682
+ const sync = opts.sync;
3683
+ useEffect(() => {
3684
+ if (!ctx.instance) return;
3685
+ let cancelled = false;
3686
+ setLoading(true);
3687
+ setError(null);
3688
+ void ctx.instance.identify({
3689
+ event,
3690
+ ...userId !== void 0 ? { userId } : {},
3691
+ ...sync !== void 0 ? { sync } : {}
3692
+ }).then(
3693
+ (r) => {
3694
+ if (cancelled) return;
3695
+ setData(r);
3696
+ setLoading(false);
3697
+ },
3698
+ (e) => {
3699
+ if (cancelled) return;
3700
+ setError(e instanceof Error ? e : new Error(String(e)));
3701
+ setLoading(false);
3702
+ }
3703
+ );
3704
+ return () => {
3705
+ cancelled = true;
3706
+ };
3707
+ }, [ctx.instance, event, userId, sync]);
3708
+ return { data, loading, error };
3709
+ }
3710
+ export {
3711
+ FpProvider,
3712
+ FpRnClient,
3713
+ useAutoIdentify,
3714
+ useFpStatus,
3715
+ useIdentify
3716
+ };
3717
+ //# sourceMappingURL=index.mjs.map