@flickfyi/flkr 0.0.0 → 0.0.118

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 (34) hide show
  1. package/node_modules/@flickfyi/core/dist/index.js +2 -2
  2. package/node_modules/@flickfyi/core/package.json +2 -2
  3. package/node_modules/@flickfyi/core/src/generated-types.d.ts +1 -1
  4. package/node_modules/@flickfyi/core/tsgo.bun.lock +9 -9
  5. package/node_modules/@flickfyi/core/tsgo.package.json +2 -2
  6. package/node_modules/@flickfyi/http-message-sig/dist/index.js +11 -11
  7. package/node_modules/@flickfyi/identity/dist/{base-B-urclbM.js → base-B1Vicu5t.js} +1 -1
  8. package/node_modules/@flickfyi/identity/dist/biscuit.js +1 -1
  9. package/node_modules/@flickfyi/identity/dist/{curve-CpcHwjN8.js → curve-BVH9bh0Y.js} +7 -7
  10. package/node_modules/@flickfyi/identity/dist/{cwt-DySP8lzM.js → cwt-CfubTfiF.js} +25 -25
  11. package/node_modules/@flickfyi/identity/dist/cwt.js +1 -1
  12. package/node_modules/@flickfyi/identity/dist/index.js +3 -3
  13. package/node_modules/@flickfyi/identity/dist/{nist-DAZq4YJ7.js → nist-C8Poq91M.js} +4 -4
  14. package/node_modules/@flickfyi/identity/dist/signing.js +2 -2
  15. package/node_modules/@flickfyi/lens/dist/index.js +1 -1
  16. package/node_modules/@flickfyi/photon/dist/version.cjs +1 -1
  17. package/node_modules/@flickfyi/photon/dist/version.js +1 -1
  18. package/node_modules/@flickfyi/photon/generated/react-swiftui.d.ts +1 -1
  19. package/node_modules/@flickfyi/photon/generated/react-swiftui.json +2 -1
  20. package/node_modules/@flickfyi/photon/package.json +1 -1
  21. package/node_modules/@msgpackr-extract/msgpackr-extract-linux-x64/README.md +1 -0
  22. package/node_modules/@msgpackr-extract/msgpackr-extract-linux-x64/node.abi115.glibc.node +0 -0
  23. package/node_modules/@msgpackr-extract/msgpackr-extract-linux-x64/node.abi115.musl.node +0 -0
  24. package/node_modules/@msgpackr-extract/msgpackr-extract-linux-x64/node.napi.glibc.node +0 -0
  25. package/node_modules/@msgpackr-extract/msgpackr-extract-linux-x64/node.napi.musl.node +0 -0
  26. package/node_modules/@msgpackr-extract/{msgpackr-extract-darwin-arm64 → msgpackr-extract-linux-x64}/package.json +4 -4
  27. package/package.json +3 -3
  28. package/node_modules/@flickfyi/identity/dist/base-ClGB6hXM.js +0 -354
  29. package/node_modules/@flickfyi/identity/dist/curve-DALK-Fi3.js +0 -2768
  30. package/node_modules/@flickfyi/identity/dist/cwt-tfd4xMR_.js +0 -3397
  31. package/node_modules/@flickfyi/identity/dist/nist-luaoKQ1s.js +0 -1194
  32. package/node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64/README.md +0 -1
  33. package/node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64/node.napi.glibc.node +0 -0
  34. /package/node_modules/@msgpackr-extract/{msgpackr-extract-darwin-arm64 → msgpackr-extract-linux-x64}/index.js +0 -0
@@ -1,3397 +0,0 @@
1
- import { A as isBytes, C as bytesToHex, D as copyBytes, E as concatBytes$1, F as sha512, H as randomBytes$1, I as abytes$1, M as randomBytes, N as validateObject, T as bytesToNumberLE, V as concatBytes, _ as abool, a as normalizeZ, c as FpLegendre, d as isNegativeLE, h as aInRange, k as hexToBytes, m as pow2, n as createCurveFields, p as mod, r as createKeygen, s as validatePointCons, t as ScalarMultiplier, v as abytes, y as asafenumber } from "./curve-CpcHwjN8.js";
2
- import { i as base64urlnopad, r as base64url } from "./base-ClGB6hXM.js";
3
- import { z } from "zod";
4
- import { traceOperationSync } from "@flickfyi/rwsdk-extensions/otel";
5
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/is.js
6
- var objectTypeNames = [
7
- "Object",
8
- "RegExp",
9
- "Date",
10
- "Error",
11
- "Map",
12
- "Set",
13
- "WeakMap",
14
- "WeakSet",
15
- "ArrayBuffer",
16
- "SharedArrayBuffer",
17
- "DataView",
18
- "Promise",
19
- "URL",
20
- "HTMLElement",
21
- "Int8Array",
22
- "Uint8ClampedArray",
23
- "Int16Array",
24
- "Uint16Array",
25
- "Int32Array",
26
- "Uint32Array",
27
- "Float32Array",
28
- "Float64Array",
29
- "BigInt64Array",
30
- "BigUint64Array",
31
- "Tagged"
32
- ];
33
- /**
34
- * @param {any} value
35
- * @returns {string}
36
- */
37
- function is(value) {
38
- if (value === null) return "null";
39
- if (value === void 0) return "undefined";
40
- if (value === true || value === false) return "boolean";
41
- const typeOf = typeof value;
42
- if (typeOf === "string" || typeOf === "number" || typeOf === "bigint" || typeOf === "symbol") return typeOf;
43
- if (typeOf === "function") return "Function";
44
- if (Array.isArray(value)) return "Array";
45
- if (value instanceof Uint8Array) return "Uint8Array";
46
- if (value.constructor === Object) return "Object";
47
- const objectType = getObjectType(value);
48
- if (objectType) return objectType;
49
- return "Object";
50
- }
51
- /**
52
- * @param {any} value
53
- * @returns {string|undefined}
54
- */
55
- function getObjectType(value) {
56
- const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
57
- if (objectTypeNames.includes(objectTypeName)) return objectTypeName;
58
- }
59
- //#endregion
60
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/token.js
61
- var Type = class {
62
- /**
63
- * @param {number} major
64
- * @param {string} name
65
- * @param {boolean} terminal
66
- */
67
- constructor(major, name, terminal) {
68
- this.major = major;
69
- this.majorEncoded = major << 5;
70
- this.name = name;
71
- this.terminal = terminal;
72
- }
73
- toString() {
74
- return `Type[${this.major}].${this.name}`;
75
- }
76
- /**
77
- * @param {Type} typ
78
- * @returns {number}
79
- */
80
- compare(typ) {
81
- return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
82
- }
83
- /**
84
- * Check equality between two Type instances. Safe to use across different
85
- * copies of the Type class (e.g., when bundlers duplicate the module).
86
- * (major, name) uniquely identifies a Type; terminal is implied by these.
87
- * @param {Type} a
88
- * @param {Type} b
89
- * @returns {boolean}
90
- */
91
- static equals(a, b) {
92
- return a === b || a.major === b.major && a.name === b.name;
93
- }
94
- };
95
- Type.uint = new Type(0, "uint", true);
96
- Type.negint = new Type(1, "negint", true);
97
- Type.bytes = new Type(2, "bytes", true);
98
- Type.string = new Type(3, "string", true);
99
- Type.array = new Type(4, "array", false);
100
- Type.map = new Type(5, "map", false);
101
- Type.tag = new Type(6, "tag", false);
102
- Type.float = new Type(7, "float", true);
103
- Type.false = new Type(7, "false", true);
104
- Type.true = new Type(7, "true", true);
105
- Type.null = new Type(7, "null", true);
106
- Type.undefined = new Type(7, "undefined", true);
107
- Type.break = new Type(7, "break", true);
108
- var Token = class {
109
- /**
110
- * @param {Type} type
111
- * @param {any} [value]
112
- * @param {number} [encodedLength]
113
- */
114
- constructor(type, value, encodedLength) {
115
- this.type = type;
116
- this.value = value;
117
- this.encodedLength = encodedLength;
118
- /** @type {Uint8Array|undefined} */
119
- this.encodedBytes = void 0;
120
- /** @type {Uint8Array|undefined} */
121
- this.byteValue = void 0;
122
- }
123
- toString() {
124
- return `Token[${this.type}].${this.value}`;
125
- }
126
- };
127
- //#endregion
128
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/byte-utils.js
129
- var useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === "function";
130
- var textEncoder = new TextEncoder();
131
- /**
132
- * @typedef {import('../interface.js').ByteView} ByteView
133
- * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
134
- */
135
- /**
136
- * @param {Uint8Array} buf
137
- * @returns {boolean}
138
- */
139
- function isBuffer(buf) {
140
- return useBuffer && globalThis.Buffer.isBuffer(buf);
141
- }
142
- /**
143
- * @param {ByteView|number[]} buf
144
- * @returns {ByteView}
145
- */
146
- function asU8A(buf) {
147
- if (!(buf instanceof Uint8Array)) return Uint8Array.from(buf);
148
- return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;
149
- }
150
- var FROM_STRING_THRESHOLD_BUFFER = 24;
151
- var FROM_STRING_THRESHOLD_TEXTENCODER = 200;
152
- var fromString = useBuffer ? (string) => {
153
- return string.length >= FROM_STRING_THRESHOLD_BUFFER ? globalThis.Buffer.from(string) : utf8ToBytes(string);
154
- } :
155
- /**
156
- * @param {string} string
157
- */
158
- (string) => {
159
- return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string);
160
- };
161
- /**
162
- * Buffer variant not fast enough for what we need
163
- * @param {number[]} arr
164
- * @returns {AllocatedByteView}
165
- */
166
- var fromArray = (arr) => {
167
- return Uint8Array.from(arr);
168
- };
169
- var slice = useBuffer ? (bytes, start, end) => {
170
- if (isBuffer(bytes)) return new Uint8Array(bytes.subarray(start, end));
171
- return bytes.slice(start, end);
172
- } :
173
- /**
174
- * @param {Uint8Array} bytes
175
- * @param {number} start
176
- * @param {number} end
177
- */
178
- (bytes, start, end) => {
179
- return bytes.slice(start, end);
180
- };
181
- var concat = useBuffer ? (chunks, length) => {
182
- chunks = chunks.map((c) => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));
183
- return asU8A(globalThis.Buffer.concat(chunks, length));
184
- } :
185
- /**
186
- * @param {ByteView[]} chunks
187
- * @param {number} length
188
- * @returns {AllocatedByteView}
189
- */
190
- (chunks, length) => {
191
- const out = new Uint8Array(length);
192
- let off = 0;
193
- for (let b of chunks) {
194
- if (off + b.length > out.length) b = b.subarray(0, out.length - off);
195
- out.set(b, off);
196
- off += b.length;
197
- }
198
- return out;
199
- };
200
- var alloc = useBuffer ? (size) => {
201
- return globalThis.Buffer.allocUnsafe(size);
202
- } :
203
- /**
204
- * @param {number} size
205
- * @returns {AllocatedByteView}
206
- */
207
- (size) => {
208
- return new Uint8Array(size);
209
- };
210
- /**
211
- * @param {Uint8Array} b1
212
- * @param {Uint8Array} b2
213
- * @returns {number}
214
- */
215
- function compare(b1, b2) {
216
- if (isBuffer(b1) && isBuffer(b2)) return b1.compare(b2);
217
- for (let i = 0; i < b1.length; i++) {
218
- if (b1[i] === b2[i]) continue;
219
- return b1[i] < b2[i] ? -1 : 1;
220
- }
221
- return 0;
222
- }
223
- /**
224
- * @param {string} str
225
- * @returns {number[]}
226
- */
227
- function utf8ToBytes(str) {
228
- const out = [];
229
- let p = 0;
230
- for (let i = 0; i < str.length; i++) {
231
- let c = str.charCodeAt(i);
232
- if (c < 128) out[p++] = c;
233
- else if (c < 2048) {
234
- out[p++] = c >> 6 | 192;
235
- out[p++] = c & 63 | 128;
236
- } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
237
- c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
238
- out[p++] = c >> 18 | 240;
239
- out[p++] = c >> 12 & 63 | 128;
240
- out[p++] = c >> 6 & 63 | 128;
241
- out[p++] = c & 63 | 128;
242
- } else {
243
- if (c >= 55296 && c <= 57343) c = 65533;
244
- out[p++] = c >> 12 | 224;
245
- out[p++] = c >> 6 & 63 | 128;
246
- out[p++] = c & 63 | 128;
247
- }
248
- }
249
- return out;
250
- }
251
- //#endregion
252
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/bl.js
253
- /**
254
- * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
255
- * writing rather than reading.
256
- * A Bl object accepts set() operations for individual bytes and copyTo() for
257
- * inserting byte arrays. These write operations don't automatically increment
258
- * the internal cursor so its "length" won't be changed. Instead, increment()
259
- * must be called to extend its length to cover the inserted data.
260
- * The toBytes() call will convert all internal memory to a single Uint8Array of
261
- * the correct length, truncating any data that is stored but hasn't been
262
- * included by an increment().
263
- * get() can retrieve a single byte.
264
- * All operations (except toBytes()) take an "offset" argument that will perform
265
- * the write at the offset _from the current cursor_. For most operations this
266
- * will be `0` to write at the current cursor position but it can be ahead of
267
- * the current cursor. Negative offsets probably work but are untested.
268
- */
269
- /**
270
- * @typedef {import('../interface.js').ByteView} ByteView
271
- * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
272
- */
273
- var defaultChunkSize = 256;
274
- var Bl = class {
275
- /**
276
- * @param {number} [chunkSize]
277
- */
278
- constructor(chunkSize = defaultChunkSize) {
279
- this.chunkSize = chunkSize;
280
- /** @type {number} */
281
- this.cursor = 0;
282
- /** @type {number} */
283
- this.maxCursor = -1;
284
- /** @type {(ByteView|number[])[]} */
285
- this.chunks = [];
286
- /** @type {ByteView|number[]|null} */
287
- this._initReuseChunk = null;
288
- }
289
- reset() {
290
- this.cursor = 0;
291
- this.maxCursor = -1;
292
- if (this.chunks.length) this.chunks = [];
293
- if (this._initReuseChunk !== null) {
294
- this.chunks.push(this._initReuseChunk);
295
- this.maxCursor = this._initReuseChunk.length - 1;
296
- }
297
- }
298
- /**
299
- * @param {ByteView|number[]} bytes
300
- */
301
- push(bytes) {
302
- let topChunk = this.chunks[this.chunks.length - 1];
303
- if (this.cursor + bytes.length <= this.maxCursor + 1) {
304
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
305
- topChunk.set(bytes, chunkPos);
306
- } else {
307
- if (topChunk) {
308
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
309
- if (chunkPos < topChunk.length) {
310
- this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
311
- this.maxCursor = this.cursor - 1;
312
- }
313
- }
314
- if (bytes.length < 64 && bytes.length < this.chunkSize) {
315
- topChunk = alloc(this.chunkSize);
316
- this.chunks.push(topChunk);
317
- this.maxCursor += topChunk.length;
318
- if (this._initReuseChunk === null) this._initReuseChunk = topChunk;
319
- topChunk.set(bytes, 0);
320
- } else {
321
- this.chunks.push(bytes);
322
- this.maxCursor += bytes.length;
323
- }
324
- }
325
- this.cursor += bytes.length;
326
- }
327
- /**
328
- * @param {boolean} [reset]
329
- * @returns {AllocatedByteView}
330
- */
331
- toBytes(reset = false) {
332
- let byts;
333
- if (this.chunks.length === 1) {
334
- const chunk = this.chunks[0];
335
- if (reset && this.cursor > chunk.length / 2) {
336
- byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
337
- this._initReuseChunk = null;
338
- this.chunks = [];
339
- } else byts = slice(chunk, 0, this.cursor);
340
- } else byts = concat(this.chunks, this.cursor);
341
- if (reset) this.reset();
342
- return byts;
343
- }
344
- };
345
- /**
346
- * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
347
- * It provides the same interface as Bl but writes to a fixed destination.
348
- * @template {ArrayBufferLike} T
349
- */
350
- var U8Bl = class {
351
- /**
352
- * @param {Uint8Array<T>} dest
353
- */
354
- constructor(dest) {
355
- this.dest = dest;
356
- /** @type {number} */
357
- this.cursor = 0;
358
- /** @type {Array<Uint8Array<T>>} */
359
- this.chunks = [dest];
360
- }
361
- reset() {
362
- this.cursor = 0;
363
- }
364
- /**
365
- * @param {ByteView|number[]} bytes
366
- */
367
- push(bytes) {
368
- if (this.cursor + bytes.length > this.dest.length) throw new Error("write out of bounds, destination buffer is too small");
369
- this.dest.set(bytes, this.cursor);
370
- this.cursor += bytes.length;
371
- }
372
- /**
373
- * @param {boolean} [reset]
374
- * @returns {Uint8Array<T>}
375
- */
376
- toBytes(reset = false) {
377
- const byts = this.dest.subarray(0, this.cursor);
378
- if (reset) this.reset();
379
- return byts;
380
- }
381
- };
382
- //#endregion
383
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/common.js
384
- var decodeErrPrefix = "CBOR decode error:";
385
- var encodeErrPrefix = "CBOR encode error:";
386
- var uintMinorPrefixBytes = [];
387
- uintMinorPrefixBytes[23] = 1;
388
- uintMinorPrefixBytes[24] = 2;
389
- uintMinorPrefixBytes[25] = 3;
390
- uintMinorPrefixBytes[26] = 5;
391
- uintMinorPrefixBytes[27] = 9;
392
- /**
393
- * @param {Uint8Array} data
394
- * @param {number} pos
395
- * @param {number} need
396
- */
397
- function assertEnoughData(data, pos, need) {
398
- if (data.length - pos < need) throw new Error(`${decodeErrPrefix} not enough data for type`);
399
- }
400
- //#endregion
401
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/0uint.js
402
- var uintBoundaries = [
403
- 24,
404
- 256,
405
- 65536,
406
- 4294967296,
407
- BigInt("18446744073709551616")
408
- ];
409
- /**
410
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
411
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
412
- */
413
- /**
414
- * @param {Uint8Array} data
415
- * @param {number} offset
416
- * @param {DecodeOptions} options
417
- * @returns {number}
418
- */
419
- function readUint8(data, offset, options) {
420
- assertEnoughData(data, offset, 1);
421
- const value = data[offset];
422
- if (options.strict === true && value < uintBoundaries[0]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
423
- return value;
424
- }
425
- /**
426
- * @param {Uint8Array} data
427
- * @param {number} offset
428
- * @param {DecodeOptions} options
429
- * @returns {number}
430
- */
431
- function readUint16(data, offset, options) {
432
- assertEnoughData(data, offset, 2);
433
- const value = data[offset] << 8 | data[offset + 1];
434
- if (options.strict === true && value < uintBoundaries[1]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
435
- return value;
436
- }
437
- /**
438
- * @param {Uint8Array} data
439
- * @param {number} offset
440
- * @param {DecodeOptions} options
441
- * @returns {number}
442
- */
443
- function readUint32(data, offset, options) {
444
- assertEnoughData(data, offset, 4);
445
- const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
446
- if (options.strict === true && value < uintBoundaries[2]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
447
- return value;
448
- }
449
- /**
450
- * @param {Uint8Array} data
451
- * @param {number} offset
452
- * @param {DecodeOptions} options
453
- * @returns {number|bigint}
454
- */
455
- function readUint64(data, offset, options) {
456
- assertEnoughData(data, offset, 8);
457
- const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
458
- const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
459
- const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
460
- if (options.strict === true && value < uintBoundaries[3]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
461
- if (value <= Number.MAX_SAFE_INTEGER) return Number(value);
462
- if (options.allowBigInt === true) return value;
463
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
464
- }
465
- /**
466
- * @param {Uint8Array} data
467
- * @param {number} pos
468
- * @param {number} _minor
469
- * @param {DecodeOptions} options
470
- * @returns {Token}
471
- */
472
- function decodeUint8(data, pos, _minor, options) {
473
- return new Token(Type.uint, readUint8(data, pos + 1, options), 2);
474
- }
475
- /**
476
- * @param {Uint8Array} data
477
- * @param {number} pos
478
- * @param {number} _minor
479
- * @param {DecodeOptions} options
480
- * @returns {Token}
481
- */
482
- function decodeUint16(data, pos, _minor, options) {
483
- return new Token(Type.uint, readUint16(data, pos + 1, options), 3);
484
- }
485
- /**
486
- * @param {Uint8Array} data
487
- * @param {number} pos
488
- * @param {number} _minor
489
- * @param {DecodeOptions} options
490
- * @returns {Token}
491
- */
492
- function decodeUint32(data, pos, _minor, options) {
493
- return new Token(Type.uint, readUint32(data, pos + 1, options), 5);
494
- }
495
- /**
496
- * @param {Uint8Array} data
497
- * @param {number} pos
498
- * @param {number} _minor
499
- * @param {DecodeOptions} options
500
- * @returns {Token}
501
- */
502
- function decodeUint64(data, pos, _minor, options) {
503
- return new Token(Type.uint, readUint64(data, pos + 1, options), 9);
504
- }
505
- /**
506
- * @param {ByteWriter} writer
507
- * @param {Token} token
508
- */
509
- function encodeUint(writer, token) {
510
- return encodeUintValue(writer, 0, token.value);
511
- }
512
- /**
513
- * @param {ByteWriter} writer
514
- * @param {number} major
515
- * @param {number|bigint} uint
516
- */
517
- function encodeUintValue(writer, major, uint) {
518
- if (uint < uintBoundaries[0]) {
519
- const nuint = Number(uint);
520
- writer.push([major | nuint]);
521
- } else if (uint < uintBoundaries[1]) {
522
- const nuint = Number(uint);
523
- writer.push([major | 24, nuint]);
524
- } else if (uint < uintBoundaries[2]) {
525
- const nuint = Number(uint);
526
- writer.push([
527
- major | 25,
528
- nuint >>> 8,
529
- nuint & 255
530
- ]);
531
- } else if (uint < uintBoundaries[3]) {
532
- const nuint = Number(uint);
533
- writer.push([
534
- major | 26,
535
- nuint >>> 24 & 255,
536
- nuint >>> 16 & 255,
537
- nuint >>> 8 & 255,
538
- nuint & 255
539
- ]);
540
- } else {
541
- const buint = BigInt(uint);
542
- if (buint < uintBoundaries[4]) {
543
- const set = [
544
- major | 27,
545
- 0,
546
- 0,
547
- 0,
548
- 0,
549
- 0,
550
- 0,
551
- 0
552
- ];
553
- let lo = Number(buint & BigInt(4294967295));
554
- let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
555
- set[8] = lo & 255;
556
- lo = lo >> 8;
557
- set[7] = lo & 255;
558
- lo = lo >> 8;
559
- set[6] = lo & 255;
560
- lo = lo >> 8;
561
- set[5] = lo & 255;
562
- set[4] = hi & 255;
563
- hi = hi >> 8;
564
- set[3] = hi & 255;
565
- hi = hi >> 8;
566
- set[2] = hi & 255;
567
- hi = hi >> 8;
568
- set[1] = hi & 255;
569
- writer.push(set);
570
- } else throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
571
- }
572
- }
573
- /**
574
- * @param {Token} token
575
- * @returns {number}
576
- */
577
- encodeUint.encodedSize = function encodedSize(token) {
578
- return encodeUintValue.encodedSize(token.value);
579
- };
580
- /**
581
- * @param {number} uint
582
- * @returns {number}
583
- */
584
- encodeUintValue.encodedSize = function encodedSize(uint) {
585
- if (uint < uintBoundaries[0]) return 1;
586
- if (uint < uintBoundaries[1]) return 2;
587
- if (uint < uintBoundaries[2]) return 3;
588
- if (uint < uintBoundaries[3]) return 5;
589
- return 9;
590
- };
591
- /**
592
- * @param {Token} tok1
593
- * @param {Token} tok2
594
- * @returns {number}
595
- */
596
- encodeUint.compareTokens = function compareTokens(tok1, tok2) {
597
- return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;
598
- };
599
- //#endregion
600
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/1negint.js
601
- /**
602
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
603
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
604
- */
605
- /**
606
- * @param {Uint8Array} data
607
- * @param {number} pos
608
- * @param {number} _minor
609
- * @param {DecodeOptions} options
610
- * @returns {Token}
611
- */
612
- function decodeNegint8(data, pos, _minor, options) {
613
- return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
614
- }
615
- /**
616
- * @param {Uint8Array} data
617
- * @param {number} pos
618
- * @param {number} _minor
619
- * @param {DecodeOptions} options
620
- * @returns {Token}
621
- */
622
- function decodeNegint16(data, pos, _minor, options) {
623
- return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3);
624
- }
625
- /**
626
- * @param {Uint8Array} data
627
- * @param {number} pos
628
- * @param {number} _minor
629
- * @param {DecodeOptions} options
630
- * @returns {Token}
631
- */
632
- function decodeNegint32(data, pos, _minor, options) {
633
- return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5);
634
- }
635
- var neg1b$1 = BigInt(-1);
636
- var pos1b$1 = BigInt(1);
637
- /**
638
- * @param {Uint8Array} data
639
- * @param {number} pos
640
- * @param {number} _minor
641
- * @param {DecodeOptions} options
642
- * @returns {Token}
643
- */
644
- function decodeNegint64(data, pos, _minor, options) {
645
- const int = readUint64(data, pos + 1, options);
646
- if (typeof int !== "bigint") {
647
- const value = -1 - int;
648
- if (value >= Number.MIN_SAFE_INTEGER) return new Token(Type.negint, value, 9);
649
- }
650
- if (options.allowBigInt !== true) throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
651
- return new Token(Type.negint, neg1b$1 - BigInt(int), 9);
652
- }
653
- /**
654
- * @param {ByteWriter} writer
655
- * @param {Token} token
656
- */
657
- function encodeNegint(writer, token) {
658
- const negint = token.value;
659
- const unsigned = typeof negint === "bigint" ? negint * neg1b$1 - pos1b$1 : negint * -1 - 1;
660
- encodeUintValue(writer, token.type.majorEncoded, unsigned);
661
- }
662
- /**
663
- * @param {Token} token
664
- * @returns {number}
665
- */
666
- encodeNegint.encodedSize = function encodedSize(token) {
667
- const negint = token.value;
668
- const unsigned = typeof negint === "bigint" ? negint * neg1b$1 - pos1b$1 : negint * -1 - 1;
669
- if (unsigned < uintBoundaries[0]) return 1;
670
- if (unsigned < uintBoundaries[1]) return 2;
671
- if (unsigned < uintBoundaries[2]) return 3;
672
- if (unsigned < uintBoundaries[3]) return 5;
673
- return 9;
674
- };
675
- /**
676
- * @param {Token} tok1
677
- * @param {Token} tok2
678
- * @returns {number}
679
- */
680
- encodeNegint.compareTokens = function compareTokens(tok1, tok2) {
681
- return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;
682
- };
683
- //#endregion
684
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/2bytes.js
685
- /**
686
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
687
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
688
- */
689
- /**
690
- * @param {Uint8Array} data
691
- * @param {number} pos
692
- * @param {number} prefix
693
- * @param {number} length
694
- * @returns {Token}
695
- */
696
- function toToken$3(data, pos, prefix, length) {
697
- assertEnoughData(data, pos, prefix + length);
698
- const buf = data.slice(pos + prefix, pos + prefix + length);
699
- return new Token(Type.bytes, buf, prefix + length);
700
- }
701
- /**
702
- * @param {Uint8Array} data
703
- * @param {number} pos
704
- * @param {number} minor
705
- * @param {DecodeOptions} _options
706
- * @returns {Token}
707
- */
708
- function decodeBytesCompact(data, pos, minor, _options) {
709
- return toToken$3(data, pos, 1, minor);
710
- }
711
- /**
712
- * @param {Uint8Array} data
713
- * @param {number} pos
714
- * @param {number} _minor
715
- * @param {DecodeOptions} options
716
- * @returns {Token}
717
- */
718
- function decodeBytes8(data, pos, _minor, options) {
719
- return toToken$3(data, pos, 2, readUint8(data, pos + 1, options));
720
- }
721
- /**
722
- * @param {Uint8Array} data
723
- * @param {number} pos
724
- * @param {number} _minor
725
- * @param {DecodeOptions} options
726
- * @returns {Token}
727
- */
728
- function decodeBytes16(data, pos, _minor, options) {
729
- return toToken$3(data, pos, 3, readUint16(data, pos + 1, options));
730
- }
731
- /**
732
- * @param {Uint8Array} data
733
- * @param {number} pos
734
- * @param {number} _minor
735
- * @param {DecodeOptions} options
736
- * @returns {Token}
737
- */
738
- function decodeBytes32(data, pos, _minor, options) {
739
- return toToken$3(data, pos, 5, readUint32(data, pos + 1, options));
740
- }
741
- /**
742
- * @param {Uint8Array} data
743
- * @param {number} pos
744
- * @param {number} _minor
745
- * @param {DecodeOptions} options
746
- * @returns {Token}
747
- */
748
- function decodeBytes64(data, pos, _minor, options) {
749
- const l = readUint64(data, pos + 1, options);
750
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
751
- return toToken$3(data, pos, 9, l);
752
- }
753
- /**
754
- * `encodedBytes` allows for caching when we do a byte version of a string
755
- * for key sorting purposes
756
- * @param {Token} token
757
- * @returns {Uint8Array}
758
- */
759
- function tokenBytes(token) {
760
- if (token.encodedBytes === void 0) token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value;
761
- return token.encodedBytes;
762
- }
763
- /**
764
- * @param {ByteWriter} writer
765
- * @param {Token} token
766
- */
767
- function encodeBytes(writer, token) {
768
- const bytes = tokenBytes(token);
769
- encodeUintValue(writer, token.type.majorEncoded, bytes.length);
770
- writer.push(bytes);
771
- }
772
- /**
773
- * @param {Token} token
774
- * @returns {number}
775
- */
776
- encodeBytes.encodedSize = function encodedSize(token) {
777
- const bytes = tokenBytes(token);
778
- return encodeUintValue.encodedSize(bytes.length) + bytes.length;
779
- };
780
- /**
781
- * @param {Token} tok1
782
- * @param {Token} tok2
783
- * @returns {number}
784
- */
785
- encodeBytes.compareTokens = function compareTokens(tok1, tok2) {
786
- return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
787
- };
788
- /**
789
- * @param {Uint8Array} b1
790
- * @param {Uint8Array} b2
791
- * @returns {number}
792
- */
793
- function compareBytes(b1, b2) {
794
- return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
795
- }
796
- //#endregion
797
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/3string.js
798
- var textDecoder = new TextDecoder();
799
- var ASCII_THRESHOLD = 32;
800
- /**
801
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
802
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
803
- */
804
- /**
805
- * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
806
- * a simple loop is faster than TextDecoder.
807
- * @param {Uint8Array} bytes
808
- * @param {number} start
809
- * @param {number} end
810
- * @returns {string}
811
- */
812
- function toStr(bytes, start, end) {
813
- if (end - start < ASCII_THRESHOLD) {
814
- let str = "";
815
- for (let i = start; i < end; i++) {
816
- const c = bytes[i];
817
- if (c & 128) return textDecoder.decode(bytes.subarray(start, end));
818
- str += String.fromCharCode(c);
819
- }
820
- return str;
821
- }
822
- return textDecoder.decode(bytes.subarray(start, end));
823
- }
824
- /**
825
- * @param {Uint8Array} data
826
- * @param {number} pos
827
- * @param {number} prefix
828
- * @param {number} length
829
- * @param {DecodeOptions} options
830
- * @returns {Token}
831
- */
832
- function toToken$2(data, pos, prefix, length, options) {
833
- const totLength = prefix + length;
834
- assertEnoughData(data, pos, totLength);
835
- const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength);
836
- if (options.retainStringBytes === true) tok.byteValue = data.slice(pos + prefix, pos + totLength);
837
- return tok;
838
- }
839
- /**
840
- * @param {Uint8Array} data
841
- * @param {number} pos
842
- * @param {number} minor
843
- * @param {DecodeOptions} options
844
- * @returns {Token}
845
- */
846
- function decodeStringCompact(data, pos, minor, options) {
847
- return toToken$2(data, pos, 1, minor, options);
848
- }
849
- /**
850
- * @param {Uint8Array} data
851
- * @param {number} pos
852
- * @param {number} _minor
853
- * @param {DecodeOptions} options
854
- * @returns {Token}
855
- */
856
- function decodeString8(data, pos, _minor, options) {
857
- return toToken$2(data, pos, 2, readUint8(data, pos + 1, options), options);
858
- }
859
- /**
860
- * @param {Uint8Array} data
861
- * @param {number} pos
862
- * @param {number} _minor
863
- * @param {DecodeOptions} options
864
- * @returns {Token}
865
- */
866
- function decodeString16(data, pos, _minor, options) {
867
- return toToken$2(data, pos, 3, readUint16(data, pos + 1, options), options);
868
- }
869
- /**
870
- * @param {Uint8Array} data
871
- * @param {number} pos
872
- * @param {number} _minor
873
- * @param {DecodeOptions} options
874
- * @returns {Token}
875
- */
876
- function decodeString32(data, pos, _minor, options) {
877
- return toToken$2(data, pos, 5, readUint32(data, pos + 1, options), options);
878
- }
879
- /**
880
- * @param {Uint8Array} data
881
- * @param {number} pos
882
- * @param {number} _minor
883
- * @param {DecodeOptions} options
884
- * @returns {Token}
885
- */
886
- function decodeString64(data, pos, _minor, options) {
887
- const l = readUint64(data, pos + 1, options);
888
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
889
- return toToken$2(data, pos, 9, l, options);
890
- }
891
- var encodeString = encodeBytes;
892
- //#endregion
893
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/4array.js
894
- /**
895
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
896
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
897
- */
898
- /**
899
- * @param {Uint8Array} _data
900
- * @param {number} _pos
901
- * @param {number} prefix
902
- * @param {number} length
903
- * @returns {Token}
904
- */
905
- function toToken$1(_data, _pos, prefix, length) {
906
- return new Token(Type.array, length, prefix);
907
- }
908
- /**
909
- * @param {Uint8Array} data
910
- * @param {number} pos
911
- * @param {number} minor
912
- * @param {DecodeOptions} _options
913
- * @returns {Token}
914
- */
915
- function decodeArrayCompact(data, pos, minor, _options) {
916
- return toToken$1(data, pos, 1, minor);
917
- }
918
- /**
919
- * @param {Uint8Array} data
920
- * @param {number} pos
921
- * @param {number} _minor
922
- * @param {DecodeOptions} options
923
- * @returns {Token}
924
- */
925
- function decodeArray8(data, pos, _minor, options) {
926
- return toToken$1(data, pos, 2, readUint8(data, pos + 1, options));
927
- }
928
- /**
929
- * @param {Uint8Array} data
930
- * @param {number} pos
931
- * @param {number} _minor
932
- * @param {DecodeOptions} options
933
- * @returns {Token}
934
- */
935
- function decodeArray16(data, pos, _minor, options) {
936
- return toToken$1(data, pos, 3, readUint16(data, pos + 1, options));
937
- }
938
- /**
939
- * @param {Uint8Array} data
940
- * @param {number} pos
941
- * @param {number} _minor
942
- * @param {DecodeOptions} options
943
- * @returns {Token}
944
- */
945
- function decodeArray32(data, pos, _minor, options) {
946
- return toToken$1(data, pos, 5, readUint32(data, pos + 1, options));
947
- }
948
- /**
949
- * @param {Uint8Array} data
950
- * @param {number} pos
951
- * @param {number} _minor
952
- * @param {DecodeOptions} options
953
- * @returns {Token}
954
- */
955
- function decodeArray64(data, pos, _minor, options) {
956
- const l = readUint64(data, pos + 1, options);
957
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
958
- return toToken$1(data, pos, 9, l);
959
- }
960
- /**
961
- * @param {Uint8Array} data
962
- * @param {number} pos
963
- * @param {number} _minor
964
- * @param {DecodeOptions} options
965
- * @returns {Token}
966
- */
967
- function decodeArrayIndefinite(data, pos, _minor, options) {
968
- if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
969
- return toToken$1(data, pos, 1, Infinity);
970
- }
971
- /**
972
- * @param {ByteWriter} writer
973
- * @param {Token} token
974
- */
975
- function encodeArray(writer, token) {
976
- encodeUintValue(writer, Type.array.majorEncoded, token.value);
977
- }
978
- encodeArray.compareTokens = encodeUint.compareTokens;
979
- /**
980
- * @param {Token} token
981
- * @returns {number}
982
- */
983
- encodeArray.encodedSize = function encodedSize(token) {
984
- return encodeUintValue.encodedSize(token.value);
985
- };
986
- //#endregion
987
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/5map.js
988
- /**
989
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
990
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
991
- */
992
- /**
993
- * @param {Uint8Array} _data
994
- * @param {number} _pos
995
- * @param {number} prefix
996
- * @param {number} length
997
- * @returns {Token}
998
- */
999
- function toToken(_data, _pos, prefix, length) {
1000
- return new Token(Type.map, length, prefix);
1001
- }
1002
- /**
1003
- * @param {Uint8Array} data
1004
- * @param {number} pos
1005
- * @param {number} minor
1006
- * @param {DecodeOptions} _options
1007
- * @returns {Token}
1008
- */
1009
- function decodeMapCompact(data, pos, minor, _options) {
1010
- return toToken(data, pos, 1, minor);
1011
- }
1012
- /**
1013
- * @param {Uint8Array} data
1014
- * @param {number} pos
1015
- * @param {number} _minor
1016
- * @param {DecodeOptions} options
1017
- * @returns {Token}
1018
- */
1019
- function decodeMap8(data, pos, _minor, options) {
1020
- return toToken(data, pos, 2, readUint8(data, pos + 1, options));
1021
- }
1022
- /**
1023
- * @param {Uint8Array} data
1024
- * @param {number} pos
1025
- * @param {number} _minor
1026
- * @param {DecodeOptions} options
1027
- * @returns {Token}
1028
- */
1029
- function decodeMap16(data, pos, _minor, options) {
1030
- return toToken(data, pos, 3, readUint16(data, pos + 1, options));
1031
- }
1032
- /**
1033
- * @param {Uint8Array} data
1034
- * @param {number} pos
1035
- * @param {number} _minor
1036
- * @param {DecodeOptions} options
1037
- * @returns {Token}
1038
- */
1039
- function decodeMap32(data, pos, _minor, options) {
1040
- return toToken(data, pos, 5, readUint32(data, pos + 1, options));
1041
- }
1042
- /**
1043
- * @param {Uint8Array} data
1044
- * @param {number} pos
1045
- * @param {number} _minor
1046
- * @param {DecodeOptions} options
1047
- * @returns {Token}
1048
- */
1049
- function decodeMap64(data, pos, _minor, options) {
1050
- const l = readUint64(data, pos + 1, options);
1051
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
1052
- return toToken(data, pos, 9, l);
1053
- }
1054
- /**
1055
- * @param {Uint8Array} data
1056
- * @param {number} pos
1057
- * @param {number} _minor
1058
- * @param {DecodeOptions} options
1059
- * @returns {Token}
1060
- */
1061
- function decodeMapIndefinite(data, pos, _minor, options) {
1062
- if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
1063
- return toToken(data, pos, 1, Infinity);
1064
- }
1065
- /**
1066
- * @param {ByteWriter} writer
1067
- * @param {Token} token
1068
- */
1069
- function encodeMap(writer, token) {
1070
- encodeUintValue(writer, Type.map.majorEncoded, token.value);
1071
- }
1072
- encodeMap.compareTokens = encodeUint.compareTokens;
1073
- /**
1074
- * @param {Token} token
1075
- * @returns {number}
1076
- */
1077
- encodeMap.encodedSize = function encodedSize(token) {
1078
- return encodeUintValue.encodedSize(token.value);
1079
- };
1080
- //#endregion
1081
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/6tag.js
1082
- /**
1083
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
1084
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
1085
- */
1086
- /**
1087
- * @param {Uint8Array} _data
1088
- * @param {number} _pos
1089
- * @param {number} minor
1090
- * @param {DecodeOptions} _options
1091
- * @returns {Token}
1092
- */
1093
- function decodeTagCompact(_data, _pos, minor, _options) {
1094
- return new Token(Type.tag, minor, 1);
1095
- }
1096
- /**
1097
- * @param {Uint8Array} data
1098
- * @param {number} pos
1099
- * @param {number} _minor
1100
- * @param {DecodeOptions} options
1101
- * @returns {Token}
1102
- */
1103
- function decodeTag8(data, pos, _minor, options) {
1104
- return new Token(Type.tag, readUint8(data, pos + 1, options), 2);
1105
- }
1106
- /**
1107
- * @param {Uint8Array} data
1108
- * @param {number} pos
1109
- * @param {number} _minor
1110
- * @param {DecodeOptions} options
1111
- * @returns {Token}
1112
- */
1113
- function decodeTag16(data, pos, _minor, options) {
1114
- return new Token(Type.tag, readUint16(data, pos + 1, options), 3);
1115
- }
1116
- /**
1117
- * @param {Uint8Array} data
1118
- * @param {number} pos
1119
- * @param {number} _minor
1120
- * @param {DecodeOptions} options
1121
- * @returns {Token}
1122
- */
1123
- function decodeTag32(data, pos, _minor, options) {
1124
- return new Token(Type.tag, readUint32(data, pos + 1, options), 5);
1125
- }
1126
- /**
1127
- * @param {Uint8Array} data
1128
- * @param {number} pos
1129
- * @param {number} _minor
1130
- * @param {DecodeOptions} options
1131
- * @returns {Token}
1132
- */
1133
- function decodeTag64(data, pos, _minor, options) {
1134
- return new Token(Type.tag, readUint64(data, pos + 1, options), 9);
1135
- }
1136
- /**
1137
- * @param {ByteWriter} writer
1138
- * @param {Token} token
1139
- */
1140
- function encodeTag(writer, token) {
1141
- encodeUintValue(writer, Type.tag.majorEncoded, token.value);
1142
- }
1143
- encodeTag.compareTokens = encodeUint.compareTokens;
1144
- /**
1145
- * @param {Token} token
1146
- * @returns {number}
1147
- */
1148
- encodeTag.encodedSize = function encodedSize(token) {
1149
- return encodeUintValue.encodedSize(token.value);
1150
- };
1151
- /**
1152
- * @param {Uint8Array} _data
1153
- * @param {number} _pos
1154
- * @param {number} _minor
1155
- * @param {DecodeOptions} options
1156
- * @returns {Token}
1157
- */
1158
- function decodeUndefined(_data, _pos, _minor, options) {
1159
- if (options.allowUndefined === false) throw new Error(`${decodeErrPrefix} undefined values are not supported`);
1160
- else if (options.coerceUndefinedToNull === true) return new Token(Type.null, null, 1);
1161
- return new Token(Type.undefined, void 0, 1);
1162
- }
1163
- /**
1164
- * @param {Uint8Array} _data
1165
- * @param {number} _pos
1166
- * @param {number} _minor
1167
- * @param {DecodeOptions} options
1168
- * @returns {Token}
1169
- */
1170
- function decodeBreak(_data, _pos, _minor, options) {
1171
- if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
1172
- return new Token(Type.break, void 0, 1);
1173
- }
1174
- /**
1175
- * @param {number} value
1176
- * @param {number} bytes
1177
- * @param {DecodeOptions} options
1178
- * @returns {Token}
1179
- */
1180
- function createToken(value, bytes, options) {
1181
- if (options) {
1182
- if (options.allowNaN === false && Number.isNaN(value)) throw new Error(`${decodeErrPrefix} NaN values are not supported`);
1183
- if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
1184
- }
1185
- return new Token(Type.float, value, bytes);
1186
- }
1187
- /**
1188
- * @param {Uint8Array} data
1189
- * @param {number} pos
1190
- * @param {number} _minor
1191
- * @param {DecodeOptions} options
1192
- * @returns {Token}
1193
- */
1194
- function decodeFloat16(data, pos, _minor, options) {
1195
- return createToken(readFloat16(data, pos + 1), 3, options);
1196
- }
1197
- /**
1198
- * @param {Uint8Array} data
1199
- * @param {number} pos
1200
- * @param {number} _minor
1201
- * @param {DecodeOptions} options
1202
- * @returns {Token}
1203
- */
1204
- function decodeFloat32(data, pos, _minor, options) {
1205
- return createToken(readFloat32(data, pos + 1), 5, options);
1206
- }
1207
- /**
1208
- * @param {Uint8Array} data
1209
- * @param {number} pos
1210
- * @param {number} _minor
1211
- * @param {DecodeOptions} options
1212
- * @returns {Token}
1213
- */
1214
- function decodeFloat64(data, pos, _minor, options) {
1215
- return createToken(readFloat64(data, pos + 1), 9, options);
1216
- }
1217
- /**
1218
- * @param {ByteWriter} writer
1219
- * @param {Token} token
1220
- * @param {EncodeOptions} options
1221
- */
1222
- function encodeFloat(writer, token, options) {
1223
- const float = token.value;
1224
- if (float === false) writer.push([Type.float.majorEncoded | 20]);
1225
- else if (float === true) writer.push([Type.float.majorEncoded | 21]);
1226
- else if (float === null) writer.push([Type.float.majorEncoded | 22]);
1227
- else if (float === void 0) writer.push([Type.float.majorEncoded | 23]);
1228
- else {
1229
- let decoded;
1230
- let success = false;
1231
- if (!options || options.float64 !== true) {
1232
- encodeFloat16(float);
1233
- decoded = readFloat16(ui8a, 1);
1234
- if (float === decoded || Number.isNaN(float)) {
1235
- ui8a[0] = 249;
1236
- writer.push(ui8a.slice(0, 3));
1237
- success = true;
1238
- } else {
1239
- encodeFloat32(float);
1240
- decoded = readFloat32(ui8a, 1);
1241
- if (float === decoded) {
1242
- ui8a[0] = 250;
1243
- writer.push(ui8a.slice(0, 5));
1244
- success = true;
1245
- }
1246
- }
1247
- }
1248
- if (!success) {
1249
- encodeFloat64(float);
1250
- decoded = readFloat64(ui8a, 1);
1251
- ui8a[0] = 251;
1252
- writer.push(ui8a.slice(0, 9));
1253
- }
1254
- }
1255
- }
1256
- /**
1257
- * @param {Token} token
1258
- * @param {EncodeOptions} options
1259
- * @returns {number}
1260
- */
1261
- encodeFloat.encodedSize = function encodedSize(token, options) {
1262
- const float = token.value;
1263
- if (float === false || float === true || float === null || float === void 0) return 1;
1264
- if (!options || options.float64 !== true) {
1265
- encodeFloat16(float);
1266
- let decoded = readFloat16(ui8a, 1);
1267
- if (float === decoded || Number.isNaN(float)) return 3;
1268
- encodeFloat32(float);
1269
- decoded = readFloat32(ui8a, 1);
1270
- if (float === decoded) return 5;
1271
- }
1272
- return 9;
1273
- };
1274
- var buffer = /* @__PURE__ */ new ArrayBuffer(9);
1275
- var dataView = new DataView(buffer, 1);
1276
- var ui8a = new Uint8Array(buffer, 0);
1277
- /**
1278
- * @param {number} inp
1279
- */
1280
- function encodeFloat16(inp) {
1281
- if (inp === Infinity) dataView.setUint16(0, 31744, false);
1282
- else if (inp === -Infinity) dataView.setUint16(0, 64512, false);
1283
- else if (Number.isNaN(inp)) dataView.setUint16(0, 32256, false);
1284
- else {
1285
- dataView.setFloat32(0, inp);
1286
- const valu32 = dataView.getUint32(0);
1287
- const exponent = (valu32 & 2139095040) >> 23;
1288
- const mantissa = valu32 & 8388607;
1289
- if (exponent === 255) dataView.setUint16(0, 31744, false);
1290
- else if (exponent === 0) dataView.setUint16(0, (valu32 & 2147483648) >> 16 | mantissa >> 13, false);
1291
- else {
1292
- const logicalExponent = exponent - 127;
1293
- if (logicalExponent < -24) dataView.setUint16(0, 0);
1294
- else if (logicalExponent < -14) dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false);
1295
- else dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);
1296
- }
1297
- }
1298
- }
1299
- /**
1300
- * @param {Uint8Array} ui8a
1301
- * @param {number} pos
1302
- * @returns {number}
1303
- */
1304
- function readFloat16(ui8a, pos) {
1305
- if (ui8a.length - pos < 2) throw new Error(`${decodeErrPrefix} not enough data for float16`);
1306
- const half = (ui8a[pos] << 8) + ui8a[pos + 1];
1307
- if (half === 31744) return Infinity;
1308
- if (half === 64512) return -Infinity;
1309
- if (half === 32256) return NaN;
1310
- const exp = half >> 10 & 31;
1311
- const mant = half & 1023;
1312
- let val;
1313
- if (exp === 0) val = mant * 2 ** -24;
1314
- else if (exp !== 31) val = (mant + 1024) * 2 ** (exp - 25);
1315
- else val = mant === 0 ? Infinity : NaN;
1316
- return half & 32768 ? -val : val;
1317
- }
1318
- /**
1319
- * @param {number} inp
1320
- */
1321
- function encodeFloat32(inp) {
1322
- dataView.setFloat32(0, inp, false);
1323
- }
1324
- /**
1325
- * @param {Uint8Array} ui8a
1326
- * @param {number} pos
1327
- * @returns {number}
1328
- */
1329
- function readFloat32(ui8a, pos) {
1330
- if (ui8a.length - pos < 4) throw new Error(`${decodeErrPrefix} not enough data for float32`);
1331
- const offset = (ui8a.byteOffset || 0) + pos;
1332
- return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false);
1333
- }
1334
- /**
1335
- * @param {number} inp
1336
- */
1337
- function encodeFloat64(inp) {
1338
- dataView.setFloat64(0, inp, false);
1339
- }
1340
- /**
1341
- * @param {Uint8Array} ui8a
1342
- * @param {number} pos
1343
- * @returns {number}
1344
- */
1345
- function readFloat64(ui8a, pos) {
1346
- if (ui8a.length - pos < 8) throw new Error(`${decodeErrPrefix} not enough data for float64`);
1347
- const offset = (ui8a.byteOffset || 0) + pos;
1348
- return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false);
1349
- }
1350
- /**
1351
- * @param {Token} _tok1
1352
- * @param {Token} _tok2
1353
- * @returns {number}
1354
- */
1355
- encodeFloat.compareTokens = encodeUint.compareTokens;
1356
- //#endregion
1357
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/jump.js
1358
- /**
1359
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
1360
- * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
1361
- */
1362
- /**
1363
- * @param {Uint8Array} data
1364
- * @param {number} pos
1365
- * @param {number} minor
1366
- */
1367
- function invalidMinor(data, pos, minor) {
1368
- throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
1369
- }
1370
- /**
1371
- * @param {string} msg
1372
- * @returns {()=>any}
1373
- */
1374
- function errorer(msg) {
1375
- return () => {
1376
- throw new Error(`${decodeErrPrefix} ${msg}`);
1377
- };
1378
- }
1379
- /** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
1380
- var jump = [];
1381
- for (let i = 0; i <= 23; i++) jump[i] = invalidMinor;
1382
- jump[24] = decodeUint8;
1383
- jump[25] = decodeUint16;
1384
- jump[26] = decodeUint32;
1385
- jump[27] = decodeUint64;
1386
- jump[28] = invalidMinor;
1387
- jump[29] = invalidMinor;
1388
- jump[30] = invalidMinor;
1389
- jump[31] = invalidMinor;
1390
- for (let i = 32; i <= 55; i++) jump[i] = invalidMinor;
1391
- jump[56] = decodeNegint8;
1392
- jump[57] = decodeNegint16;
1393
- jump[58] = decodeNegint32;
1394
- jump[59] = decodeNegint64;
1395
- jump[60] = invalidMinor;
1396
- jump[61] = invalidMinor;
1397
- jump[62] = invalidMinor;
1398
- jump[63] = invalidMinor;
1399
- for (let i = 64; i <= 87; i++) jump[i] = decodeBytesCompact;
1400
- jump[88] = decodeBytes8;
1401
- jump[89] = decodeBytes16;
1402
- jump[90] = decodeBytes32;
1403
- jump[91] = decodeBytes64;
1404
- jump[92] = invalidMinor;
1405
- jump[93] = invalidMinor;
1406
- jump[94] = invalidMinor;
1407
- jump[95] = errorer("indefinite length bytes/strings are not supported");
1408
- for (let i = 96; i <= 119; i++) jump[i] = decodeStringCompact;
1409
- jump[120] = decodeString8;
1410
- jump[121] = decodeString16;
1411
- jump[122] = decodeString32;
1412
- jump[123] = decodeString64;
1413
- jump[124] = invalidMinor;
1414
- jump[125] = invalidMinor;
1415
- jump[126] = invalidMinor;
1416
- jump[127] = errorer("indefinite length bytes/strings are not supported");
1417
- for (let i = 128; i <= 151; i++) jump[i] = decodeArrayCompact;
1418
- jump[152] = decodeArray8;
1419
- jump[153] = decodeArray16;
1420
- jump[154] = decodeArray32;
1421
- jump[155] = decodeArray64;
1422
- jump[156] = invalidMinor;
1423
- jump[157] = invalidMinor;
1424
- jump[158] = invalidMinor;
1425
- jump[159] = decodeArrayIndefinite;
1426
- for (let i = 160; i <= 183; i++) jump[i] = decodeMapCompact;
1427
- jump[184] = decodeMap8;
1428
- jump[185] = decodeMap16;
1429
- jump[186] = decodeMap32;
1430
- jump[187] = decodeMap64;
1431
- jump[188] = invalidMinor;
1432
- jump[189] = invalidMinor;
1433
- jump[190] = invalidMinor;
1434
- jump[191] = decodeMapIndefinite;
1435
- for (let i = 192; i <= 215; i++) jump[i] = decodeTagCompact;
1436
- jump[216] = decodeTag8;
1437
- jump[217] = decodeTag16;
1438
- jump[218] = decodeTag32;
1439
- jump[219] = decodeTag64;
1440
- jump[220] = invalidMinor;
1441
- jump[221] = invalidMinor;
1442
- jump[222] = invalidMinor;
1443
- jump[223] = invalidMinor;
1444
- for (let i = 224; i <= 243; i++) jump[i] = errorer("simple values are not supported");
1445
- jump[244] = invalidMinor;
1446
- jump[245] = invalidMinor;
1447
- jump[246] = invalidMinor;
1448
- jump[247] = decodeUndefined;
1449
- jump[248] = errorer("simple values are not supported");
1450
- jump[249] = decodeFloat16;
1451
- jump[250] = decodeFloat32;
1452
- jump[251] = decodeFloat64;
1453
- jump[252] = invalidMinor;
1454
- jump[253] = invalidMinor;
1455
- jump[254] = invalidMinor;
1456
- jump[255] = decodeBreak;
1457
- /** @type {Token[]} */
1458
- var quick = [];
1459
- for (let i = 0; i < 24; i++) quick[i] = new Token(Type.uint, i, 1);
1460
- for (let i = -1; i >= -24; i--) quick[31 - i] = new Token(Type.negint, i, 1);
1461
- quick[64] = new Token(Type.bytes, /* @__PURE__ */ new Uint8Array(0), 1);
1462
- quick[96] = new Token(Type.string, "", 1);
1463
- quick[128] = new Token(Type.array, 0, 1);
1464
- quick[160] = new Token(Type.map, 0, 1);
1465
- quick[244] = new Token(Type.false, false, 1);
1466
- quick[245] = new Token(Type.true, true, 1);
1467
- quick[246] = new Token(Type.null, null, 1);
1468
- /**
1469
- * @param {Token} token
1470
- * @returns {AllocatedByteView|undefined}
1471
- */
1472
- function quickEncodeToken(token) {
1473
- switch (token.type) {
1474
- case Type.false: return fromArray([244]);
1475
- case Type.true: return fromArray([245]);
1476
- case Type.null: return fromArray([246]);
1477
- case Type.bytes:
1478
- if (!token.value.length) return fromArray([64]);
1479
- return;
1480
- case Type.string:
1481
- if (token.value === "") return fromArray([96]);
1482
- return;
1483
- case Type.array:
1484
- if (token.value === 0) return fromArray([128]);
1485
- return;
1486
- case Type.map:
1487
- if (token.value === 0) return fromArray([160]);
1488
- return;
1489
- case Type.uint:
1490
- if (token.value < 24) return fromArray([Number(token.value)]);
1491
- return;
1492
- case Type.negint: if (token.value >= -24) return fromArray([31 - Number(token.value)]);
1493
- }
1494
- }
1495
- //#endregion
1496
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/encode.js
1497
- /**
1498
- * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
1499
- * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
1500
- * @typedef {import('../interface.js').Reference} Reference
1501
- * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
1502
- * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
1503
- * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
1504
- * @typedef {import('../interface.js').ByteWriter} ByteWriter
1505
- * @typedef {import('../interface.js').ByteView} ByteView
1506
- * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
1507
- */
1508
- /** @type {EncodeOptions} */
1509
- var defaultEncodeOptions = {
1510
- float64: false,
1511
- mapSorter,
1512
- quickEncodeToken
1513
- };
1514
- /** @type {EncodeOptions} */
1515
- var rfc8949EncodeOptions = Object.freeze({
1516
- mapSorter: rfc8949MapSorter,
1517
- quickEncodeToken
1518
- });
1519
- /** @returns {TokenTypeEncoder[]} */
1520
- function makeCborEncoders() {
1521
- const encoders = [];
1522
- encoders[Type.uint.major] = encodeUint;
1523
- encoders[Type.negint.major] = encodeNegint;
1524
- encoders[Type.bytes.major] = encodeBytes;
1525
- encoders[Type.string.major] = encodeString;
1526
- encoders[Type.array.major] = encodeArray;
1527
- encoders[Type.map.major] = encodeMap;
1528
- encoders[Type.tag.major] = encodeTag;
1529
- encoders[Type.float.major] = encodeFloat;
1530
- return encoders;
1531
- }
1532
- var cborEncoders = makeCborEncoders();
1533
- var defaultWriter = new Bl();
1534
- /** @implements {Reference} */
1535
- var Ref = class Ref {
1536
- /**
1537
- * @param {object|any[]} obj
1538
- * @param {Reference|undefined} parent
1539
- */
1540
- constructor(obj, parent) {
1541
- this.obj = obj;
1542
- this.parent = parent;
1543
- }
1544
- /**
1545
- * @param {object|any[]} obj
1546
- * @returns {boolean}
1547
- */
1548
- includes(obj) {
1549
- /** @type {Reference|undefined} */
1550
- let p = this;
1551
- do
1552
- if (p.obj === obj) return true;
1553
- while (p = p.parent);
1554
- return false;
1555
- }
1556
- /**
1557
- * @param {Reference|undefined} stack
1558
- * @param {object|any[]} obj
1559
- * @returns {Reference}
1560
- */
1561
- static createCheck(stack, obj) {
1562
- if (stack && stack.includes(obj)) throw new Error(`${encodeErrPrefix} object contains circular references`);
1563
- return new Ref(obj, stack);
1564
- }
1565
- };
1566
- var simpleTokens = {
1567
- null: new Token(Type.null, null),
1568
- undefined: new Token(Type.undefined, void 0),
1569
- true: new Token(Type.true, true),
1570
- false: new Token(Type.false, false),
1571
- emptyArray: new Token(Type.array, 0),
1572
- emptyMap: new Token(Type.map, 0)
1573
- };
1574
- /** @type {{[typeName: string]: StrictTypeEncoder}} */
1575
- var typeEncoders = {
1576
- /**
1577
- * @param {any} obj
1578
- * @param {string} _typ
1579
- * @param {EncodeOptions} _options
1580
- * @param {Reference} [_refStack]
1581
- * @returns {TokenOrNestedTokens}
1582
- */
1583
- number(obj, _typ, _options, _refStack) {
1584
- if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) return new Token(Type.float, obj);
1585
- else if (obj >= 0) return new Token(Type.uint, obj);
1586
- else return new Token(Type.negint, obj);
1587
- },
1588
- /**
1589
- * @param {any} obj
1590
- * @param {string} _typ
1591
- * @param {EncodeOptions} _options
1592
- * @param {Reference} [_refStack]
1593
- * @returns {TokenOrNestedTokens}
1594
- */
1595
- bigint(obj, _typ, _options, _refStack) {
1596
- if (obj >= BigInt(0)) return new Token(Type.uint, obj);
1597
- else return new Token(Type.negint, obj);
1598
- },
1599
- /**
1600
- * @param {any} obj
1601
- * @param {string} _typ
1602
- * @param {EncodeOptions} _options
1603
- * @param {Reference} [_refStack]
1604
- * @returns {TokenOrNestedTokens}
1605
- */
1606
- Uint8Array(obj, _typ, _options, _refStack) {
1607
- return new Token(Type.bytes, obj);
1608
- },
1609
- /**
1610
- * @param {any} obj
1611
- * @param {string} _typ
1612
- * @param {EncodeOptions} _options
1613
- * @param {Reference} [_refStack]
1614
- * @returns {TokenOrNestedTokens}
1615
- */
1616
- string(obj, _typ, _options, _refStack) {
1617
- return new Token(Type.string, obj);
1618
- },
1619
- /**
1620
- * @param {any} obj
1621
- * @param {string} _typ
1622
- * @param {EncodeOptions} _options
1623
- * @param {Reference} [_refStack]
1624
- * @returns {TokenOrNestedTokens}
1625
- */
1626
- boolean(obj, _typ, _options, _refStack) {
1627
- return obj ? simpleTokens.true : simpleTokens.false;
1628
- },
1629
- /**
1630
- * @param {any} _obj
1631
- * @param {string} _typ
1632
- * @param {EncodeOptions} _options
1633
- * @param {Reference} [_refStack]
1634
- * @returns {TokenOrNestedTokens}
1635
- */
1636
- null(_obj, _typ, _options, _refStack) {
1637
- return simpleTokens.null;
1638
- },
1639
- /**
1640
- * @param {any} _obj
1641
- * @param {string} _typ
1642
- * @param {EncodeOptions} _options
1643
- * @param {Reference} [_refStack]
1644
- * @returns {TokenOrNestedTokens}
1645
- */
1646
- undefined(_obj, _typ, _options, _refStack) {
1647
- return simpleTokens.undefined;
1648
- },
1649
- /**
1650
- * @param {any} obj
1651
- * @param {string} _typ
1652
- * @param {EncodeOptions} _options
1653
- * @param {Reference} [_refStack]
1654
- * @returns {TokenOrNestedTokens}
1655
- */
1656
- ArrayBuffer(obj, _typ, _options, _refStack) {
1657
- return new Token(Type.bytes, new Uint8Array(obj));
1658
- },
1659
- /**
1660
- * @param {any} obj
1661
- * @param {string} _typ
1662
- * @param {EncodeOptions} _options
1663
- * @param {Reference} [_refStack]
1664
- * @returns {TokenOrNestedTokens}
1665
- */
1666
- DataView(obj, _typ, _options, _refStack) {
1667
- return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
1668
- },
1669
- /**
1670
- * @param {any} obj
1671
- * @param {string} _typ
1672
- * @param {EncodeOptions} options
1673
- * @param {Reference} [refStack]
1674
- * @returns {TokenOrNestedTokens}
1675
- */
1676
- Array(obj, _typ, options, refStack) {
1677
- if (!obj.length) {
1678
- if (options.addBreakTokens === true) return [simpleTokens.emptyArray, new Token(Type.break)];
1679
- return simpleTokens.emptyArray;
1680
- }
1681
- refStack = Ref.createCheck(refStack, obj);
1682
- const entries = [];
1683
- let i = 0;
1684
- for (const e of obj) entries[i++] = objectToTokens(e, options, refStack);
1685
- if (options.addBreakTokens) return [
1686
- new Token(Type.array, obj.length),
1687
- entries,
1688
- new Token(Type.break)
1689
- ];
1690
- return [new Token(Type.array, obj.length), entries];
1691
- },
1692
- /**
1693
- * @param {any} obj
1694
- * @param {string} typ
1695
- * @param {EncodeOptions} options
1696
- * @param {Reference} [refStack]
1697
- * @returns {TokenOrNestedTokens}
1698
- */
1699
- Object(obj, typ, options, refStack) {
1700
- const isMap = typ !== "Object";
1701
- const keys = isMap ? obj.keys() : Object.keys(obj);
1702
- const maxLength = isMap ? obj.size : keys.length;
1703
- /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
1704
- let entries;
1705
- if (maxLength) {
1706
- entries = new Array(maxLength);
1707
- refStack = Ref.createCheck(refStack, obj);
1708
- const skipUndefined = !isMap && options.ignoreUndefinedProperties;
1709
- let i = 0;
1710
- for (const key of keys) {
1711
- const value = isMap ? obj.get(key) : obj[key];
1712
- if (skipUndefined && value === void 0) continue;
1713
- entries[i++] = [objectToTokens(key, options, refStack), objectToTokens(value, options, refStack)];
1714
- }
1715
- if (i < maxLength) entries.length = i;
1716
- }
1717
- if (!entries?.length) {
1718
- if (options.addBreakTokens === true) return [simpleTokens.emptyMap, new Token(Type.break)];
1719
- return simpleTokens.emptyMap;
1720
- }
1721
- sortMapEntries(entries, options);
1722
- if (options.addBreakTokens) return [
1723
- new Token(Type.map, entries.length),
1724
- entries,
1725
- new Token(Type.break)
1726
- ];
1727
- return [new Token(Type.map, entries.length), entries];
1728
- },
1729
- /**
1730
- * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
1731
- * form of the wrapped value. The value is recursively tokenised through
1732
- * `objectToTokens()` so any registered `typeEncoders` apply to it.
1733
- *
1734
- * @param {any} obj
1735
- * @param {string} _typ
1736
- * @param {EncodeOptions} options
1737
- * @param {Reference} [refStack]
1738
- * @returns {TokenOrNestedTokens}
1739
- */
1740
- Tagged(obj, _typ, options, refStack) {
1741
- return [new Token(Type.tag, obj.tag), objectToTokens(obj.value, options, refStack)];
1742
- }
1743
- };
1744
- typeEncoders.Map = typeEncoders.Object;
1745
- typeEncoders.Buffer = typeEncoders.Uint8Array;
1746
- for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) typeEncoders[`${typ}Array`] = typeEncoders.DataView;
1747
- /**
1748
- * @param {any} obj
1749
- * @param {EncodeOptions} [options]
1750
- * @param {Reference} [refStack]
1751
- * @returns {TokenOrNestedTokens}
1752
- */
1753
- function objectToTokens(obj, options = {}, refStack) {
1754
- const typ = is(obj);
1755
- const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];
1756
- if (typeof customTypeEncoder === "function") {
1757
- const tokens = customTypeEncoder(obj, typ, options, refStack);
1758
- if (tokens != null) return tokens;
1759
- }
1760
- const typeEncoder = typeEncoders[typ];
1761
- if (!typeEncoder) throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1762
- return typeEncoder(obj, typ, options, refStack);
1763
- }
1764
- /**
1765
- * @param {TokenOrNestedTokens[]} entries
1766
- * @param {EncodeOptions} options
1767
- */
1768
- function sortMapEntries(entries, options) {
1769
- if (options.mapSorter) entries.sort(options.mapSorter);
1770
- }
1771
- /**
1772
- * @param {(Token|Token[])[]} e1
1773
- * @param {(Token|Token[])[]} e2
1774
- * @returns {number}
1775
- */
1776
- function mapSorter(e1, e2) {
1777
- const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];
1778
- const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];
1779
- if (keyToken1.type !== keyToken2.type) return keyToken1.type.compare(keyToken2.type);
1780
- const tcmp = cborEncoders[keyToken1.type.major].compareTokens(keyToken1, keyToken2);
1781
- if (tcmp === 0) console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone");
1782
- return tcmp;
1783
- }
1784
- /**
1785
- * @typedef {Token & { _keyBytes?: AllocatedByteView }} TokenEx
1786
- *
1787
- * @param {(Token|Token[])[]} e1
1788
- * @param {(Token|Token[])[]} e2
1789
- * @returns {number}
1790
- */
1791
- function rfc8949MapSorter(e1, e2) {
1792
- if (e1[0] instanceof Token && e2[0] instanceof Token) {
1793
- const t1 = e1[0];
1794
- const t2 = e2[0];
1795
- if (!t1._keyBytes) t1._keyBytes = encodeRfc8949(t1.value);
1796
- if (!t2._keyBytes) t2._keyBytes = encodeRfc8949(t2.value);
1797
- return compare(t1._keyBytes, t2._keyBytes);
1798
- }
1799
- throw new Error("rfc8949MapSorter: complex key types are not supported yet");
1800
- }
1801
- /**
1802
- * @param {any} data
1803
- * @returns {AllocatedByteView}
1804
- */
1805
- function encodeRfc8949(data) {
1806
- return encodeCustom(data, cborEncoders, rfc8949EncodeOptions);
1807
- }
1808
- /**
1809
- * @param {ByteWriter} writer
1810
- * @param {TokenOrNestedTokens} tokens
1811
- * @param {TokenTypeEncoder[]} encoders
1812
- * @param {EncodeOptions} options
1813
- */
1814
- function tokensToEncoded(writer, tokens, encoders, options) {
1815
- if (Array.isArray(tokens)) for (const token of tokens) tokensToEncoded(writer, token, encoders, options);
1816
- else encoders[tokens.type.major](writer, tokens, options);
1817
- }
1818
- var MAJOR_UINT = Type.uint.majorEncoded;
1819
- var MAJOR_NEGINT = Type.negint.majorEncoded;
1820
- var MAJOR_BYTES = Type.bytes.majorEncoded;
1821
- var MAJOR_STRING = Type.string.majorEncoded;
1822
- var MAJOR_ARRAY = Type.array.majorEncoded;
1823
- var SIMPLE_FALSE = Type.float.majorEncoded | 20;
1824
- var SIMPLE_TRUE = Type.float.majorEncoded | 21;
1825
- var SIMPLE_NULL = Type.float.majorEncoded | 22;
1826
- var SIMPLE_UNDEFINED = Type.float.majorEncoded | 23;
1827
- var neg1b = BigInt(-1);
1828
- var pos1b = BigInt(1);
1829
- /**
1830
- * Check if direct encoding can be used for the given options.
1831
- * Direct encoding bypasses token creation for most values.
1832
- * @param {EncodeOptions} options
1833
- * @returns {boolean}
1834
- */
1835
- function canDirectEncode(options) {
1836
- return options.addBreakTokens !== true;
1837
- }
1838
- /**
1839
- * Direct encode a value to the writer, bypassing token creation for most types.
1840
- * Falls back to token-based encoding for custom type encoders.
1841
- * @param {ByteWriter} writer
1842
- * @param {any} data
1843
- * @param {EncodeOptions} options
1844
- * @param {Reference|undefined} refStack
1845
- */
1846
- function directEncode(writer, data, options, refStack) {
1847
- const typ = is(data);
1848
- const customEncoder = options.typeEncoders && options.typeEncoders[typ];
1849
- if (customEncoder) {
1850
- const tokens = customEncoder(data, typ, options, refStack);
1851
- if (tokens != null) {
1852
- tokensToEncoded(writer, tokens, cborEncoders, options);
1853
- return;
1854
- }
1855
- }
1856
- switch (typ) {
1857
- case "null":
1858
- writer.push([SIMPLE_NULL]);
1859
- return;
1860
- case "undefined":
1861
- writer.push([SIMPLE_UNDEFINED]);
1862
- return;
1863
- case "boolean":
1864
- writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE]);
1865
- return;
1866
- case "number":
1867
- if (!Number.isInteger(data) || !Number.isSafeInteger(data)) encodeFloat(writer, new Token(Type.float, data), options);
1868
- else if (data >= 0) encodeUintValue(writer, MAJOR_UINT, data);
1869
- else encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1);
1870
- return;
1871
- case "bigint":
1872
- if (data >= BigInt(0)) encodeUintValue(writer, MAJOR_UINT, data);
1873
- else encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b);
1874
- return;
1875
- case "string": {
1876
- const bytes = fromString(data);
1877
- encodeUintValue(writer, MAJOR_STRING, bytes.length);
1878
- writer.push(bytes);
1879
- return;
1880
- }
1881
- case "Uint8Array":
1882
- encodeUintValue(writer, MAJOR_BYTES, data.length);
1883
- writer.push(data);
1884
- return;
1885
- case "Array":
1886
- if (!data.length) {
1887
- writer.push([MAJOR_ARRAY]);
1888
- return;
1889
- }
1890
- refStack = Ref.createCheck(refStack, data);
1891
- encodeUintValue(writer, MAJOR_ARRAY, data.length);
1892
- for (const elem of data) directEncode(writer, elem, options, refStack);
1893
- return;
1894
- case "Object":
1895
- case "Map":
1896
- tokensToEncoded(writer, typeEncoders.Object(data, typ, options, refStack), cborEncoders, options);
1897
- return;
1898
- default: {
1899
- const typeEncoder = typeEncoders[typ];
1900
- if (!typeEncoder) throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1901
- tokensToEncoded(writer, typeEncoder(data, typ, options, refStack), cborEncoders, options);
1902
- }
1903
- }
1904
- }
1905
- /**
1906
- * @template {ArrayBufferLike} T
1907
- * @overload
1908
- * @param {any} data
1909
- * @param {TokenTypeEncoder[]} encoders
1910
- * @param {EncodeOptions} options
1911
- * @param {Uint8Array<T>} destination
1912
- * @returns {Uint8Array<T>}
1913
- */
1914
- /**
1915
- * @overload
1916
- * @param {any} data
1917
- * @param {TokenTypeEncoder[]} encoders
1918
- * @param {EncodeOptions} options
1919
- * @returns {AllocatedByteView}
1920
- */
1921
- /**
1922
- * @param {any} data
1923
- * @param {TokenTypeEncoder[]} encoders
1924
- * @param {EncodeOptions} options
1925
- * @param {ByteView} [destination]
1926
- * @returns {ByteView}
1927
- */
1928
- function encodeCustom(data, encoders, options, destination) {
1929
- const hasDest = destination instanceof Uint8Array;
1930
- let writeTo = hasDest ? new U8Bl(destination) : defaultWriter;
1931
- const tokens = objectToTokens(data, options);
1932
- if (!Array.isArray(tokens) && options.quickEncodeToken) {
1933
- const quickBytes = options.quickEncodeToken(tokens);
1934
- if (quickBytes) {
1935
- if (hasDest) {
1936
- writeTo.push(quickBytes);
1937
- return writeTo.toBytes();
1938
- }
1939
- return quickBytes;
1940
- }
1941
- const encoder = encoders[tokens.type.major];
1942
- if (encoder.encodedSize) {
1943
- const size = encoder.encodedSize(tokens, options);
1944
- if (!hasDest) writeTo = new Bl(size);
1945
- encoder(writeTo, tokens, options);
1946
- if (writeTo.chunks.length !== 1) throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
1947
- return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0]);
1948
- }
1949
- }
1950
- writeTo.reset();
1951
- tokensToEncoded(writeTo, tokens, encoders, options);
1952
- return writeTo.toBytes(true);
1953
- }
1954
- /**
1955
- * @param {any} data
1956
- * @param {EncodeOptions} [options]
1957
- * @returns {AllocatedByteView}
1958
- */
1959
- function encode(data, options) {
1960
- options = Object.assign({}, defaultEncodeOptions, options);
1961
- if (canDirectEncode(options)) {
1962
- defaultWriter.reset();
1963
- directEncode(defaultWriter, data, options, void 0);
1964
- return defaultWriter.toBytes(true);
1965
- }
1966
- return encodeCustom(data, cborEncoders, options);
1967
- }
1968
- //#endregion
1969
- //#region ../../../../../../.pnpm-store/v11/links/@/cborg/5.1.11/e24c650a80e15c1eaf2be19ad9eb588e573106ba2ecb18c14c15852be6303448/node_modules/cborg/lib/decode.js
1970
- /**
1971
- * @typedef {import('./token.js').Token} Token
1972
- * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
1973
- * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
1974
- * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
1975
- */
1976
- var defaultDecodeOptions = {
1977
- strict: false,
1978
- allowIndefinite: true,
1979
- allowUndefined: true,
1980
- allowBigInt: true
1981
- };
1982
- /**
1983
- * @implements {DecodeTokenizer}
1984
- */
1985
- var Tokeniser = class {
1986
- /**
1987
- * @param {Uint8Array} data
1988
- * @param {DecodeOptions} options
1989
- */
1990
- constructor(data, options = {}) {
1991
- this._pos = 0;
1992
- this.data = data;
1993
- this.options = options;
1994
- }
1995
- pos() {
1996
- return this._pos;
1997
- }
1998
- done() {
1999
- return this._pos >= this.data.length;
2000
- }
2001
- next() {
2002
- const byt = this.data[this._pos];
2003
- let token = quick[byt];
2004
- if (token === void 0) {
2005
- const decoder = jump[byt];
2006
- if (!decoder) throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`);
2007
- const minor = byt & 31;
2008
- token = decoder(this.data, this._pos, minor, this.options);
2009
- }
2010
- this._pos += token.encodedLength;
2011
- return token;
2012
- }
2013
- };
2014
- var DONE = Symbol.for("DONE");
2015
- var BREAK = Symbol.for("BREAK");
2016
- /**
2017
- * @param {Token} token
2018
- * @param {DecodeTokenizer} tokeniser
2019
- * @param {DecodeOptions} options
2020
- * @returns {any|typeof BREAK|typeof DONE}
2021
- */
2022
- function tokenToArray(token, tokeniser, options) {
2023
- const arr = [];
2024
- for (let i = 0; i < token.value; i++) {
2025
- const value = tokensToObject(tokeniser, options);
2026
- if (value === BREAK) {
2027
- if (token.value === Infinity) break;
2028
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`);
2029
- }
2030
- if (value === DONE) throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`);
2031
- arr[i] = value;
2032
- }
2033
- return arr;
2034
- }
2035
- /**
2036
- * @param {Token} token
2037
- * @param {DecodeTokenizer} tokeniser
2038
- * @param {DecodeOptions} options
2039
- * @returns {any|typeof BREAK|typeof DONE}
2040
- */
2041
- function tokenToMap(token, tokeniser, options) {
2042
- const useMaps = options.useMaps === true;
2043
- const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true;
2044
- const obj = useMaps ? void 0 : {};
2045
- const m = useMaps ? /* @__PURE__ */ new Map() : void 0;
2046
- for (let i = 0; i < token.value; i++) {
2047
- const key = tokensToObject(tokeniser, options);
2048
- if (key === BREAK) {
2049
- if (token.value === Infinity) break;
2050
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`);
2051
- }
2052
- if (key === DONE) throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`);
2053
- if (!useMaps && typeof key !== "string") throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`);
2054
- if (rejectDuplicateMapKeys) {
2055
- if (useMaps && m.has(key) || !useMaps && Object.hasOwn(obj, key)) throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`);
2056
- }
2057
- const value = tokensToObject(tokeniser, options);
2058
- if (value === DONE) throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`);
2059
- if (useMaps) m.set(key, value);
2060
- else obj[key] = value;
2061
- }
2062
- return useMaps ? m : obj;
2063
- }
2064
- /**
2065
- * Generator that yields [key, value] entries from a CBOR map token.
2066
- * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
2067
- * @param {Token} token - The map token
2068
- * @param {DecodeTokenizer} tokeniser
2069
- * @param {DecodeOptions} options
2070
- * @returns {Generator<[any, any], void, unknown>}
2071
- */
2072
- function* tokenToMapEntries(token, tokeniser, options) {
2073
- for (let i = 0; i < token.value; i++) {
2074
- const key = tokensToObject(tokeniser, options);
2075
- if (key === BREAK) {
2076
- if (token.value === Infinity) break;
2077
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`);
2078
- }
2079
- if (key === DONE) throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`);
2080
- const value = tokensToObject(tokeniser, options);
2081
- if (value === DONE) throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`);
2082
- yield [key, value];
2083
- }
2084
- }
2085
- /**
2086
- * Creates a TagDecodeControl object for tag decoders.
2087
- * @param {DecodeTokenizer} tokeniser
2088
- * @param {DecodeOptions} options
2089
- * @returns {TagDecodeControl}
2090
- */
2091
- function createTagDecodeControl(tokeniser, options) {
2092
- let called = false;
2093
- /**
2094
- * @type {TagDecodeControl}
2095
- */
2096
- const decode = function() {
2097
- if (called) throw new Error(`${decodeErrPrefix} tag decode() may only be called once`);
2098
- called = true;
2099
- const value = tokensToObject(tokeniser, options);
2100
- if (value === DONE) throw new Error(`${decodeErrPrefix} tag content missing`);
2101
- if (value === BREAK) throw new Error(`${decodeErrPrefix} got unexpected break in tag content`);
2102
- return value;
2103
- };
2104
- decode.entries = function() {
2105
- if (called) throw new Error(`${decodeErrPrefix} tag decode() may only be called once`);
2106
- called = true;
2107
- const token = tokeniser.next();
2108
- if (!Type.equals(token.type, Type.map)) throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`);
2109
- const entries = [];
2110
- for (const entry of tokenToMapEntries(token, tokeniser, options)) entries.push(entry);
2111
- return entries;
2112
- };
2113
- Object.defineProperty(decode, "_called", {
2114
- get() {
2115
- return called;
2116
- },
2117
- enumerable: false
2118
- });
2119
- return decode;
2120
- }
2121
- /**
2122
- * @param {DecodeTokenizer} tokeniser
2123
- * @param {DecodeOptions} options
2124
- * @returns {any|typeof BREAK|typeof DONE}
2125
- */
2126
- function tokensToObject(tokeniser, options) {
2127
- if (tokeniser.done()) return DONE;
2128
- const token = tokeniser.next();
2129
- if (Type.equals(token.type, Type.break)) return BREAK;
2130
- if (token.type.terminal) return token.value;
2131
- if (Type.equals(token.type, Type.array)) return tokenToArray(token, tokeniser, options);
2132
- if (Type.equals(token.type, Type.map)) return tokenToMap(token, tokeniser, options);
2133
- if (Type.equals(token.type, Type.tag)) {
2134
- if (options.tags && typeof options.tags[token.value] === "function") {
2135
- const decodeControl = createTagDecodeControl(tokeniser, options);
2136
- const result = options.tags[token.value](decodeControl);
2137
- if (!decodeControl._called) throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`);
2138
- return result;
2139
- }
2140
- throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`);
2141
- }
2142
- throw new Error("unsupported");
2143
- }
2144
- /**
2145
- * @param {Uint8Array} data
2146
- * @param {DecodeOptions} [options]
2147
- * @returns {[any, Uint8Array]}
2148
- */
2149
- function decodeFirst(data, options) {
2150
- if (!(data instanceof Uint8Array)) throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`);
2151
- options = Object.assign({}, defaultDecodeOptions, options);
2152
- const u8aData = asU8A(data);
2153
- const tokeniser = options.tokenizer || new Tokeniser(u8aData, options);
2154
- const decoded = tokensToObject(tokeniser, options);
2155
- if (decoded === DONE) throw new Error(`${decodeErrPrefix} did not find any content to decode`);
2156
- if (decoded === BREAK) throw new Error(`${decodeErrPrefix} got unexpected break`);
2157
- return [decoded, data.subarray(tokeniser.pos())];
2158
- }
2159
- /**
2160
- * @param {Uint8Array} data
2161
- * @param {DecodeOptions} [options]
2162
- * @returns {any}
2163
- */
2164
- function decode(data, options) {
2165
- const [decoded, remainder] = decodeFirst(data, options);
2166
- if (remainder.length > 0) throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`);
2167
- return decoded;
2168
- }
2169
- Object.defineProperty(class Tagged {
2170
- /**
2171
- * @param {number} tag - CBOR tag number, a non-negative integer
2172
- * @param {any} value - The value to be tagged; encoded recursively
2173
- */
2174
- constructor(tag, value) {
2175
- if (typeof tag !== "number" || !Number.isInteger(tag) || tag < 0) throw new TypeError("Tagged: tag must be a non-negative integer");
2176
- this.tag = tag;
2177
- this.value = value;
2178
- }
2179
- /**
2180
- * Build a tag decoder for use in `decode()`'s `tags` option that returns the
2181
- * decoded content wrapped in a `Tagged` instance, preserving the tag number
2182
- * for the caller to inspect.
2183
- *
2184
- * @param {number} tag - The CBOR tag number this decoder will be registered for
2185
- * @returns {TaggedTagDecoder}
2186
- *
2187
- * @example
2188
- * import { decode, Tagged } from 'cborg'
2189
- * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
2190
- * // value instanceof Tagged; value.tag === 16
2191
- */
2192
- static decoder(tag) {
2193
- return (decode) => new Tagged(tag, decode());
2194
- }
2195
- /**
2196
- * Build a `tags` option for `decode()` that wraps each listed tag number in
2197
- * a `Tagged` instance, preserving those tags through decode without
2198
- * registering a dedicated decoder per tag.
2199
- *
2200
- * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
2201
- * @returns {{[tagNumber: number]: TaggedTagDecoder}}
2202
- *
2203
- * @example
2204
- * import { decode, Tagged } from 'cborg'
2205
- * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
2206
- */
2207
- static preserve(...tagNumbers) {
2208
- /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
2209
- const tags = {};
2210
- for (const tag of tagNumbers) tags[tag] = Tagged.decoder(tag);
2211
- return tags;
2212
- }
2213
- }.prototype, Symbol.toStringTag, { value: "Tagged" });
2214
- Uint8Array.prototype.toBase64;
2215
- Uint8Array.fromBase64;
2216
- function decodeCBOR(data) {
2217
- return decode(data, {
2218
- useMaps: true,
2219
- rejectDuplicateMapKeys: true
2220
- });
2221
- }
2222
- function encodeCBOR(data) {
2223
- return encode(data, rfc8949EncodeOptions);
2224
- }
2225
- //#endregion
2226
- //#region ../../../../../../.pnpm-store/v11/links/@ldclabs/cose-ts/1.7.0/a470182239a6259287f50f513c384f2f3f3a1550025b6307427708908f279082/node_modules/@ldclabs/cose-ts/dist/map.js
2227
- function assertText(value, name) {
2228
- if (typeof value === "string") return value;
2229
- throw new TypeError(`${name} must be a string, but got ${String(value)}`);
2230
- }
2231
- function assertInt(value, name) {
2232
- if (Number.isSafeInteger(value)) return value;
2233
- throw new TypeError(`${name} must be a integer, but got ${String(value)}`);
2234
- }
2235
- function assertIntOrText(value, name) {
2236
- if (typeof value === "string") return value;
2237
- if (Number.isSafeInteger(value)) return value;
2238
- throw new TypeError(`${name} must be a integer or string, but got ${String(value)}`);
2239
- }
2240
- function assertBytes(value, name) {
2241
- if (value instanceof Uint8Array) return value;
2242
- throw new TypeError(`${name} must be a Uint8Array, but got ${String(value)}`);
2243
- }
2244
- function assertBool(value, name) {
2245
- if (typeof value === "boolean") return value;
2246
- throw new TypeError(`${name} must be a Boolean, but got ${String(value)}`);
2247
- }
2248
- function assertMap(value, name) {
2249
- if (value instanceof Map) return value;
2250
- throw new TypeError(`${name} must be a Map, but got ${String(value)}`);
2251
- }
2252
- var KVMap = class KVMap {
2253
- _raw;
2254
- static fromBytes(data) {
2255
- return new KVMap(decodeCBOR(data));
2256
- }
2257
- constructor(kv = /* @__PURE__ */ new Map()) {
2258
- if (!(kv instanceof Map)) throw new TypeError("key/value must be a Map");
2259
- this._raw = kv;
2260
- }
2261
- has(key) {
2262
- return this._raw.has(key);
2263
- }
2264
- delete(key) {
2265
- return this._raw.delete(key);
2266
- }
2267
- getInt(key, name) {
2268
- return assertInt(this._raw.get(key), name ?? String(key));
2269
- }
2270
- getText(key, name) {
2271
- return assertText(this._raw.get(key), name ?? String(key));
2272
- }
2273
- getBytes(key, name) {
2274
- return assertBytes(this._raw.get(key), name ?? String(key));
2275
- }
2276
- getBool(key, name) {
2277
- return assertBool(this._raw.get(key), name ?? String(key));
2278
- }
2279
- getType(key, assertFn, name) {
2280
- return assertFn(this._raw.get(key), name ?? String(key));
2281
- }
2282
- getArray(key, assertFn, name) {
2283
- const na = name ? name : String(key);
2284
- const arr = this._raw.get(key);
2285
- if (!Array.isArray(arr)) throw new TypeError(`${na} must be an array, but got ${String(arr)}`);
2286
- for (const item of arr) assertFn(item, na);
2287
- return arr;
2288
- }
2289
- getParam(key) {
2290
- return this._raw.get(key);
2291
- }
2292
- setParam(key, value) {
2293
- this._raw.set(key, value);
2294
- return this;
2295
- }
2296
- getCBORParam(key) {
2297
- return this._raw.has(key) ? decodeCBOR(assertBytes(this._raw.get(key), String(key))) : void 0;
2298
- }
2299
- setCBORParam(key, value) {
2300
- this._raw.set(key, encodeCBOR(value));
2301
- return this;
2302
- }
2303
- clone() {
2304
- return new Map(this._raw);
2305
- }
2306
- toRaw() {
2307
- return this._raw;
2308
- }
2309
- toBytes() {
2310
- return encodeCBOR(this._raw);
2311
- }
2312
- };
2313
- new Uint8Array([208]);
2314
- new Uint8Array([209]);
2315
- var Sign1MessagePrefix = new Uint8Array([210]);
2316
- var CwtPrefix = new Uint8Array([216, 61]);
2317
- new Uint8Array([216, 96]);
2318
- new Uint8Array([216, 97]);
2319
- new Uint8Array([216, 98]);
2320
- var CBORSelfPrefix = new Uint8Array([
2321
- 217,
2322
- 217,
2323
- 247
2324
- ]);
2325
- function withTag(tag, data) {
2326
- return concatBytes(tag, data);
2327
- }
2328
- function skipTag(tag, data) {
2329
- if (data.length < tag.length) return data;
2330
- for (let i = 0; i < tag.length; i++) if (data[i] !== tag[i]) return data;
2331
- return data.subarray(tag.length);
2332
- }
2333
- //#endregion
2334
- //#region ../../../../../../.pnpm-store/v11/links/@ldclabs/cose-ts/1.7.0/a470182239a6259287f50f513c384f2f3f3a1550025b6307427708908f279082/node_modules/@ldclabs/cose-ts/dist/cwt.js
2335
- /**
2336
- * Claims represents a set of common claims for CWT.
2337
- *
2338
- * Encode claims as the payload of a COSE message, commonly COSE_Sign1, then
2339
- * apply withCWTTag() when the surrounding protocol expects the CWT tag.
2340
- *
2341
- * @example
2342
- * ```ts
2343
- * const claims = new Claims()
2344
- * claims.iss = 'issuer'
2345
- * claims.aud = 'service'
2346
- * claims.exp = Math.floor(Date.now() / 1000) + 3600
2347
- * const token = withCWTTag(new Sign1Message(claims.toBytes()).toBytes(key))
2348
- * ```
2349
- *
2350
- * Reference https://www.iana.org/assignments/cwt/cwt.xhtml
2351
- */
2352
- var Claims = class Claims extends KVMap {
2353
- static fromBytes(data) {
2354
- return new Claims(decodeCBOR(data));
2355
- }
2356
- constructor(kv = /* @__PURE__ */ new Map()) {
2357
- super(kv);
2358
- }
2359
- get iss() {
2360
- return this.getText(1, "iss");
2361
- }
2362
- set iss(iss) {
2363
- this.setParam(1, assertText(iss, "iss"));
2364
- }
2365
- get sub() {
2366
- return this.getText(2, "sub");
2367
- }
2368
- set sub(sub) {
2369
- this.setParam(2, assertText(sub, "sub"));
2370
- }
2371
- get aud() {
2372
- return this.getText(3, "aud");
2373
- }
2374
- set aud(aud) {
2375
- this.setParam(3, assertText(aud, "aud"));
2376
- }
2377
- get exp() {
2378
- return this.getInt(4, "exp");
2379
- }
2380
- set exp(exp) {
2381
- this.setParam(4, assertInt(exp, "exp"));
2382
- }
2383
- get nbf() {
2384
- return this.getInt(5, "nbf");
2385
- }
2386
- set nbf(nbf) {
2387
- this.setParam(5, assertInt(nbf, "nbf"));
2388
- }
2389
- get iat() {
2390
- return this.getInt(6, "iat");
2391
- }
2392
- set iat(iat) {
2393
- this.setParam(6, assertInt(iat, "iat"));
2394
- }
2395
- get cti() {
2396
- return this.getBytes(7, "cti");
2397
- }
2398
- set cti(cti) {
2399
- this.setParam(7, assertBytes(cti, "cti"));
2400
- }
2401
- get cnf() {
2402
- return this.getType(8, assertMap, "cnf");
2403
- }
2404
- set cnf(cnf) {
2405
- this.setParam(8, assertMap(cnf, "cnf"));
2406
- }
2407
- get scope() {
2408
- return this.getText(9, "scope");
2409
- }
2410
- set scope(scope) {
2411
- this.setParam(9, assertText(scope, "scope"));
2412
- }
2413
- get nonce() {
2414
- return this.getBytes(10, "nonce");
2415
- }
2416
- set nonce(nonce) {
2417
- this.setParam(10, assertBytes(nonce, "nonce"));
2418
- }
2419
- };
2420
- function withCWTTag(coseData) {
2421
- return withTag(CwtPrefix, coseData);
2422
- }
2423
- //#endregion
2424
- //#region ../../../../../../.pnpm-store/v11/links/@noble/curves/2.4.0/766129a921e8dfd2ef1de557b88b41133e3334d958e354fac1f5d17f98661627/node_modules/@noble/curves/abstract/edwards.js
2425
- /**
2426
- * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
2427
- * For design rationale of types / exports, see weierstrass module documentation.
2428
- * Untwisted Edwards curves exist, but they aren't used in real-world protocols.
2429
- * @module
2430
- */
2431
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2432
- var _0n = /* @__PURE__ */ BigInt(0);
2433
- var _1n$1 = /* @__PURE__ */ BigInt(1);
2434
- var _2n$1 = /* @__PURE__ */ BigInt(2);
2435
- var _4n = /* @__PURE__ */ BigInt(4);
2436
- var _8n$1 = /* @__PURE__ */ BigInt(8);
2437
- function isEdValidXY(Fp, CURVE, x, y) {
2438
- const x2 = Fp.sqr(x);
2439
- const y2 = Fp.sqr(y);
2440
- const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
2441
- const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
2442
- return Fp.eql(left, right);
2443
- }
2444
- /**
2445
- * @param params - Curve parameters. See {@link EdwardsOpts}.
2446
- * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.
2447
- * @returns Edwards point constructor. Generator validation here only checks
2448
- * that `(Gx, Gy)` satisfies the affine Edwards equation.
2449
- * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`
2450
- * are left to the caller's chosen parameters, since eager subgroup
2451
- * validation here adds about 10-15ms to heavyweight imports like ed448.
2452
- * The returned constructor also eagerly marks `Point.BASE` for W=6
2453
- * precompute caching. Some code paths still assume
2454
- * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.
2455
- * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}
2456
- * @example
2457
- * ```ts
2458
- * import { edwards } from '@noble/curves/abstract/edwards.js';
2459
- * import { jubjub } from '@noble/curves/misc.js';
2460
- * // Build a point constructor from explicit curve parameters, then use its base point.
2461
- * const Point = edwards(jubjub.Point.CURVE());
2462
- * Point.BASE.toHex();
2463
- * ```
2464
- */
2465
- function edwards(params, extraOpts = {}) {
2466
- validateObject(extraOpts, {}, {}, "extraOpts");
2467
- const opts = extraOpts;
2468
- const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
2469
- const { Fp, Fn } = validated;
2470
- let CURVE = validated.CURVE;
2471
- const { h: cofactor } = CURVE;
2472
- if (FpLegendre(Fp, CURVE.a) !== 1) throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
2473
- if (FpLegendre(Fp, CURVE.d) !== -1) throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
2474
- validateObject(opts, {}, {
2475
- uvRatio: "function",
2476
- randomBytes: "function"
2477
- });
2478
- const randomBytes$2 = opts.randomBytes === void 0 ? randomBytes : opts.randomBytes;
2479
- const MASK = _2n$1 << BigInt(Fp.BYTES * 8) - _1n$1;
2480
- function isOdd(n) {
2481
- if (!Fp.isOdd) throw new Error("Field does not have .isOdd()");
2482
- return Fp.isOdd(n);
2483
- }
2484
- const uvRatio = opts.uvRatio === void 0 ? (u, v) => {
2485
- try {
2486
- return {
2487
- isValid: true,
2488
- value: Fp.sqrt(Fp.div(u, v))
2489
- };
2490
- } catch (e) {
2491
- return {
2492
- isValid: false,
2493
- value: _0n
2494
- };
2495
- }
2496
- } : opts.uvRatio;
2497
- if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
2498
- const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x) : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x : (x) => Fp.mul(CURVE.a, x);
2499
- /**
2500
- * Asserts coordinate is valid: 0 <= n < MASK.
2501
- * Coordinates >= Fp.ORDER are allowed for zip215.
2502
- */
2503
- function acoord(title, n, banZero = false) {
2504
- const min = banZero ? _1n$1 : _0n;
2505
- aInRange("coordinate " + title, n, min, MASK);
2506
- return n;
2507
- }
2508
- function aedpoint(other) {
2509
- if (!(other instanceof Point)) throw new Error("EdwardsPoint expected");
2510
- }
2511
- class Point {
2512
- static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy));
2513
- static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO);
2514
- static Fp = Fp;
2515
- static Fn = Fn;
2516
- X;
2517
- Y;
2518
- Z;
2519
- T;
2520
- constructor(X, Y, Z, T) {
2521
- this.X = acoord("x", X);
2522
- this.Y = acoord("y", Y);
2523
- this.Z = acoord("z", Z, true);
2524
- this.T = acoord("t", T);
2525
- Object.freeze(this);
2526
- }
2527
- static CURVE() {
2528
- return CURVE;
2529
- }
2530
- /**
2531
- * Create one extended Edwards point from affine coordinates.
2532
- * Does NOT validate that the point is on-curve or torsion-free.
2533
- * Use `.assertValidity()` on adversarial inputs.
2534
- */
2535
- static fromAffine(p) {
2536
- if (p instanceof Point) throw new Error("extended point not allowed");
2537
- const { x, y } = p || {};
2538
- acoord("x", x);
2539
- acoord("y", y);
2540
- return new Point(x, y, Fp.ONE, Fp.mul(x, y));
2541
- }
2542
- static fromBytes(bytes, zip215 = false) {
2543
- const len = Fp.BYTES;
2544
- const { a, d } = CURVE;
2545
- bytes = copyBytes(abytes(bytes, len, "point"));
2546
- abool(zip215, "zip215");
2547
- const normed = copyBytes(bytes);
2548
- const lastByte = bytes[len - 1];
2549
- normed[len - 1] = lastByte & -129;
2550
- const y = bytesToNumberLE(normed);
2551
- const max = zip215 ? MASK : Fp.ORDER;
2552
- aInRange("point.y", y, _0n, max);
2553
- const y2 = Fp.sqr(y);
2554
- const u = Fp.sub(y2, Fp.ONE);
2555
- const v = Fp.sub(Fp.mulN(d, y2), a);
2556
- let { isValid, value: x } = uvRatio(u, v);
2557
- if (!isValid) throw new Error("bad point: invalid y coordinate");
2558
- const isXOdd = isOdd(x);
2559
- const isLastByteOdd = (lastByte & 128) !== 0;
2560
- if (!zip215 && Fp.is0(x) && isLastByteOdd) throw new Error("bad point: x=0 and x_0=1");
2561
- if (isLastByteOdd !== isXOdd) x = Fp.neg(x);
2562
- return Point.fromAffine({
2563
- x,
2564
- y
2565
- });
2566
- }
2567
- static fromHex(hex, zip215 = false) {
2568
- return Point.fromBytes(hexToBytes(hex), zip215);
2569
- }
2570
- get x() {
2571
- return this.toAffine().x;
2572
- }
2573
- get y() {
2574
- return this.toAffine().y;
2575
- }
2576
- precompute(windowSize = 6, isLazy = true) {
2577
- wnaf.setWindowSize(this, windowSize);
2578
- if (!isLazy) this.multiply(_2n$1);
2579
- return this;
2580
- }
2581
- assertValidity() {
2582
- const p = this;
2583
- const { a, d } = CURVE;
2584
- if (p.is0()) throw new Error("bad point: ZERO");
2585
- const { X, Y, Z, T } = p;
2586
- const X2 = Fp.sqr(X);
2587
- const Y2 = Fp.sqr(Y);
2588
- const Z2 = Fp.sqr(Z);
2589
- const Z4 = Fp.sqr(Z2);
2590
- const aX2 = Fp.mul(X2, a);
2591
- const left = Fp.mul(Fp.add(aX2, Y2), Z2);
2592
- const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2)));
2593
- if (!Fp.eql(left, right)) throw new Error("bad point: equation left != right (1)");
2594
- const XY = Fp.mul(X, Y);
2595
- const ZT = Fp.mul(Z, T);
2596
- if (!Fp.eql(XY, ZT)) throw new Error("bad point: equation left != right (2)");
2597
- }
2598
- equals(other) {
2599
- aedpoint(other);
2600
- const { X: X1, Y: Y1, Z: Z1 } = this;
2601
- const { X: X2, Y: Y2, Z: Z2 } = other;
2602
- const X1Z2 = Fp.mul(X1, Z2);
2603
- const X2Z1 = Fp.mul(X2, Z1);
2604
- const Y1Z2 = Fp.mul(Y1, Z2);
2605
- const Y2Z1 = Fp.mul(Y2, Z1);
2606
- return Fp.eql(X1Z2, X2Z1) && Fp.eql(Y1Z2, Y2Z1);
2607
- }
2608
- is0() {
2609
- return this.equals(Point.ZERO);
2610
- }
2611
- negate() {
2612
- return new Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));
2613
- }
2614
- double() {
2615
- const { X: X1, Y: Y1, Z: Z1 } = this;
2616
- const A = Fp.sqr(X1);
2617
- const B = Fp.sqr(Y1);
2618
- const C = Fp.mul(Fp.sqr(Z1), _2n$1);
2619
- const D = mulA(A);
2620
- const x1y1 = Fp.addN(X1, Y1);
2621
- const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B);
2622
- const G = Fp.addN(D, B);
2623
- const F = Fp.subN(G, C);
2624
- const H = Fp.subN(D, B);
2625
- const X3 = Fp.mul(E, F);
2626
- const Y3 = Fp.mul(G, H);
2627
- const T3 = Fp.mul(E, H);
2628
- const Z3 = Fp.mul(F, G);
2629
- return new Point(X3, Y3, Z3, T3);
2630
- }
2631
- add(other) {
2632
- aedpoint(other);
2633
- const { d } = CURVE;
2634
- const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
2635
- const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
2636
- const A = Fp.mul(X1, X2);
2637
- const B = Fp.mul(Y1, Y2);
2638
- const C = Fp.mul(Fp.mulN(T1, d), T2);
2639
- const D = Fp.mul(Z1, Z2);
2640
- const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B);
2641
- const F = Fp.subN(D, C);
2642
- const G = Fp.addN(D, C);
2643
- const H = Fp.sub(B, mulA(A));
2644
- const X3 = Fp.mul(E, F);
2645
- const Y3 = Fp.mul(G, H);
2646
- const T3 = Fp.mul(E, H);
2647
- const Z3 = Fp.mul(F, G);
2648
- return new Point(X3, Y3, Z3, T3);
2649
- }
2650
- subtract(other) {
2651
- aedpoint(other);
2652
- return this.add(other.negate());
2653
- }
2654
- multiply(scalar) {
2655
- if (!Fn.isValidNot0(scalar)) throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
2656
- const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
2657
- return normalize([p, f])[0];
2658
- }
2659
- multiplyUnsafe(scalar) {
2660
- if (!Fn.isValid(scalar)) throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
2661
- if (scalar === _0n) return Point.ZERO;
2662
- if (this.is0() || scalar === _1n$1) return this;
2663
- return wnaf.mulUnsafe(this, scalar, normalize);
2664
- }
2665
- isSmallOrder() {
2666
- return this.clearCofactor().is0();
2667
- }
2668
- isTorsionFree() {
2669
- return wnaf.mulUnsafe(this, CURVE.n).is0();
2670
- }
2671
- toAffine(invertedZ) {
2672
- const p = this;
2673
- let iz = invertedZ;
2674
- if (iz != null && typeof iz !== "bigint") throw new TypeError("\"invertedZ\" expected bigint, got type=" + typeof iz);
2675
- const { X, Y, Z } = p;
2676
- const is0 = p.is0();
2677
- if (iz == null) iz = is0 ? Fp.create(_8n$1) : Fp.inv(Z);
2678
- const x = Fp.mul(X, iz);
2679
- const y = Fp.mul(Y, iz);
2680
- const zz = Fp.mul(Z, iz);
2681
- if (is0) return {
2682
- x: Fp.ZERO,
2683
- y: Fp.ONE
2684
- };
2685
- if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
2686
- return {
2687
- x,
2688
- y
2689
- };
2690
- }
2691
- clearCofactor() {
2692
- if (cofactor === _1n$1) return this;
2693
- if (cofactor === _2n$1) return this.double();
2694
- if (cofactor === _4n) return this.double().double();
2695
- if (cofactor === _8n$1) return this.double().double().double();
2696
- return this.multiplyUnsafe(cofactor);
2697
- }
2698
- toBytes() {
2699
- const { x, y } = this.toAffine();
2700
- const bytes = Fp.toBytes(y);
2701
- bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
2702
- return bytes;
2703
- }
2704
- toHex() {
2705
- return bytesToHex(this.toBytes());
2706
- }
2707
- toString() {
2708
- return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2709
- }
2710
- }
2711
- const normalize = (points) => normalizeZ(Point, points);
2712
- const wnaf = new ScalarMultiplier(Point, randomBytes$2);
2713
- if (wnaf.bits >= 6) Point.BASE.precompute(6);
2714
- Object.freeze(Point.prototype);
2715
- Object.freeze(Point);
2716
- return Point;
2717
- }
2718
- /**
2719
- * Initializes EdDSA signatures over given Edwards curve.
2720
- * @param Point - Edwards point constructor.
2721
- * @param cHash - Hash function.
2722
- * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.
2723
- * @returns EdDSA helper namespace.
2724
- * @throws If the hash function, options, or derived point operations are invalid. {@link Error}
2725
- * @example
2726
- * Initializes EdDSA signatures over given Edwards curve.
2727
- *
2728
- * ```ts
2729
- * import { eddsa } from '@noble/curves/abstract/edwards.js';
2730
- * import { jubjub } from '@noble/curves/misc.js';
2731
- * import { sha512 } from '@noble/hashes/sha2.js';
2732
- * const sigs = eddsa(jubjub.Point, sha512);
2733
- * const { secretKey, publicKey } = sigs.keygen();
2734
- * const msg = new TextEncoder().encode('hello noble');
2735
- * const sig = sigs.sign(msg, secretKey);
2736
- * const isValid = sigs.verify(sig, msg, publicKey);
2737
- * ```
2738
- */
2739
- function eddsa(Point, cHash, eddsaOpts = {}) {
2740
- validatePointCons(Point);
2741
- if (typeof cHash !== "function") throw new Error("\"hash\" function param is required");
2742
- const hash = cHash;
2743
- const opts = eddsaOpts;
2744
- validateObject(opts, {}, {
2745
- adjustScalarBytes: "function",
2746
- randomBytes: "function",
2747
- domain: "function",
2748
- prehash: "function",
2749
- zip215: "boolean",
2750
- mapToCurve: "function",
2751
- toMontgomery: "function",
2752
- toMontgomerySecret: "function"
2753
- });
2754
- const { prehash } = opts;
2755
- const { BASE, Fp, Fn } = Point;
2756
- const outputLen = hash.outputLen;
2757
- const expectedLen = 2 * Fp.BYTES;
2758
- if (outputLen !== void 0) {
2759
- asafenumber(outputLen, "hash.outputLen");
2760
- if (outputLen !== expectedLen) throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
2761
- }
2762
- const randomBytes$3 = opts.randomBytes === void 0 ? randomBytes : opts.randomBytes;
2763
- const toMontgomery = opts.toMontgomery;
2764
- const toMontgomerySecret = opts.toMontgomerySecret;
2765
- const adjustScalarBytes = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
2766
- const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
2767
- abool(phflag, "phflag");
2768
- if (ctx.length || phflag) throw new Error("Contexts/pre-hash are not supported");
2769
- return data;
2770
- } : opts.domain;
2771
- function modN_LE(hash) {
2772
- return Fn.create(bytesToNumberLE(hash));
2773
- }
2774
- function getPrivateScalar(key) {
2775
- const len = lengths.secretKey;
2776
- abytes(key, lengths.secretKey, "secretKey");
2777
- const hashed = abytes(hash(key), 2 * len, "hashedSecretKey");
2778
- const head = adjustScalarBytes(hashed.slice(0, len));
2779
- return {
2780
- head,
2781
- prefix: hashed.slice(len, 2 * len),
2782
- scalar: modN_LE(head)
2783
- };
2784
- }
2785
- /** Convenience method that creates public key from scalar. RFC8032 5.1.5
2786
- * Also exposes the derived scalar/prefix tuple and point form reused by sign().
2787
- */
2788
- function getExtendedPublicKey(secretKey) {
2789
- const { head, prefix, scalar } = getPrivateScalar(secretKey);
2790
- const point = BASE.multiply(scalar);
2791
- return {
2792
- head,
2793
- prefix,
2794
- scalar,
2795
- point,
2796
- pointBytes: point.toBytes()
2797
- };
2798
- }
2799
- /** Calculates EdDSA pub key. RFC8032 5.1.5. */
2800
- function getPublicKey(secretKey) {
2801
- return getExtendedPublicKey(secretKey).pointBytes;
2802
- }
2803
- function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
2804
- const msg = concatBytes$1(...msgs);
2805
- return modN_LE(hash(domain(msg, abytes(context, void 0, "context"), !!prehash)));
2806
- }
2807
- /** Signs message with secret key. RFC8032 5.1.6 */
2808
- function sign(msg, secretKey, options = {}) {
2809
- validateObject(options, {}, {}, "options");
2810
- msg = copyBytes(abytes(msg, void 0, "message"));
2811
- if (prehash) msg = prehash(msg);
2812
- const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
2813
- const r = hashDomainToScalar(options.context, prefix, msg);
2814
- const R = BASE.multiply(r).toBytes();
2815
- const k = hashDomainToScalar(options.context, R, pointBytes, msg);
2816
- const s = Fn.create(r + k * scalar);
2817
- if (!Fn.isValid(s)) throw new Error("sign failed: invalid s");
2818
- const rs = concatBytes$1(R, Fn.toBytes(s));
2819
- return abytes(rs, lengths.signature, "result");
2820
- }
2821
- const verifyOpts = { zip215: opts.zip215 };
2822
- /**
2823
- * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.
2824
- * A cofactored verification equation is checked.
2825
- */
2826
- function verify(sig, msg, publicKey, options = verifyOpts) {
2827
- validateObject(options);
2828
- const { context } = options;
2829
- const zip215 = options.zip215 === void 0 ? !!verifyOpts.zip215 : options.zip215;
2830
- const len = lengths.signature;
2831
- sig = abytes(sig, len, "signature");
2832
- msg = abytes(msg, void 0, "message");
2833
- publicKey = abytes(publicKey, lengths.publicKey, "publicKey");
2834
- if (zip215 !== void 0) abool(zip215, "zip215");
2835
- if (prehash) msg = prehash(msg);
2836
- const mid = len / 2;
2837
- const r = sig.subarray(0, mid);
2838
- const s = bytesToNumberLE(sig.subarray(mid, len));
2839
- let A, R, SB;
2840
- try {
2841
- A = Point.fromBytes(publicKey, zip215);
2842
- R = Point.fromBytes(r, zip215);
2843
- SB = BASE.multiplyUnsafe(s);
2844
- } catch (error) {
2845
- return false;
2846
- }
2847
- if (!zip215 && A.isSmallOrder()) return false;
2848
- const k = hashDomainToScalar(context, r, publicKey, msg);
2849
- return R.add(A.multiplyUnsafe(k)).subtract(SB).clearCofactor().is0();
2850
- }
2851
- const _size = Fp.BYTES;
2852
- const lengths = {
2853
- secretKey: _size,
2854
- publicKey: _size,
2855
- signature: 2 * _size,
2856
- seed: _size
2857
- };
2858
- function randomSecretKey(seed) {
2859
- seed = seed === void 0 ? randomBytes$3(lengths.seed) : seed;
2860
- return abytes(seed, lengths.seed, "seed");
2861
- }
2862
- function isValidSecretKey(key) {
2863
- return isBytes(key) && key.length === lengths.secretKey;
2864
- }
2865
- function isValidPublicKey(key, zip215) {
2866
- try {
2867
- return !!Point.fromBytes(key, zip215 === void 0 ? verifyOpts.zip215 : zip215);
2868
- } catch (error) {
2869
- return false;
2870
- }
2871
- }
2872
- const utils = {
2873
- getExtendedPublicKey,
2874
- randomSecretKey,
2875
- isValidSecretKey,
2876
- isValidPublicKey,
2877
- /** Converts an Edwards public key to a companion Montgomery public key. */
2878
- toMontgomery(publicKey) {
2879
- if (toMontgomery === void 0) throw new Error("Montgomery conversion is not supported for this curve");
2880
- return toMontgomery(Point.fromBytes(publicKey));
2881
- },
2882
- toMontgomerySecret(secretKey) {
2883
- if (toMontgomerySecret === void 0) throw new Error("Montgomery conversion is not supported for this curve");
2884
- return toMontgomerySecret(secretKey);
2885
- }
2886
- };
2887
- Object.freeze(lengths);
2888
- Object.freeze(utils);
2889
- return Object.freeze({
2890
- keygen: createKeygen(randomSecretKey, getPublicKey),
2891
- getPublicKey,
2892
- sign,
2893
- verify,
2894
- utils,
2895
- Point,
2896
- lengths
2897
- });
2898
- }
2899
- //#endregion
2900
- //#region ../../../../../../.pnpm-store/v11/links/@noble/curves/2.4.0/766129a921e8dfd2ef1de557b88b41133e3334d958e354fac1f5d17f98661627/node_modules/@noble/curves/ed25519.js
2901
- /**
2902
- * ed25519 Twisted Edwards curve with following addons:
2903
- * - X25519 ECDH
2904
- * - Ristretto cofactor elimination
2905
- * - Elligator hash-to-group / point indistinguishability
2906
- * @module
2907
- */
2908
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2909
- var _1n = /* @__PURE__ */ BigInt(1);
2910
- var _2n = /* @__PURE__ */ BigInt(2);
2911
- var _5n = /* @__PURE__ */ BigInt(5);
2912
- var _8n = /* @__PURE__ */ BigInt(8);
2913
- var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2914
- var ed25519_CURVE = /* @__PURE__ */ (() => ({
2915
- p: ed25519_CURVE_p,
2916
- n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2917
- h: _8n,
2918
- a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2919
- d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2920
- Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2921
- Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2922
- }))();
2923
- function ed25519_pow_2_252_3(x) {
2924
- const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2925
- const P = ed25519_CURVE_p;
2926
- const b2 = x * x % P * x % P;
2927
- const b4 = pow2(b2, _2n, P) * b2 % P;
2928
- const b5 = pow2(b4, _1n, P) * x % P;
2929
- const b10 = pow2(b5, _5n, P) * b5 % P;
2930
- const b20 = pow2(b10, _10n, P) * b10 % P;
2931
- const b40 = pow2(b20, _20n, P) * b20 % P;
2932
- const b80 = pow2(b40, _40n, P) * b40 % P;
2933
- const b160 = pow2(b80, _80n, P) * b80 % P;
2934
- const b240 = pow2(b160, _80n, P) * b80 % P;
2935
- const b250 = pow2(b240, _10n, P) * b10 % P;
2936
- return {
2937
- pow_p_5_8: pow2(b250, _2n, P) * x % P,
2938
- b2
2939
- };
2940
- }
2941
- function adjustScalarBytes(bytes) {
2942
- bytes[0] &= 248;
2943
- bytes[31] &= 127;
2944
- bytes[31] |= 64;
2945
- return bytes;
2946
- }
2947
- var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2948
- function uvRatio(u, v) {
2949
- const P = ed25519_CURVE_p;
2950
- const v3 = mod(v * v * v, P);
2951
- const pow = ed25519_pow_2_252_3(u * mod(v3 * v3 * v, P)).pow_p_5_8;
2952
- let x = mod(u * v3 * pow, P);
2953
- const vx2 = mod(v * x * x, P);
2954
- const root1 = x;
2955
- const root2 = mod(x * ED25519_SQRT_M1, P);
2956
- const useRoot1 = vx2 === u;
2957
- const useRoot2 = vx2 === mod(-u, P);
2958
- const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2959
- if (useRoot1) x = root1;
2960
- if (useRoot2 || noRoot) x = root2;
2961
- if (isNegativeLE(x, P)) x = mod(-x, P);
2962
- return {
2963
- isValid: useRoot1 || useRoot2,
2964
- value: x
2965
- };
2966
- }
2967
- var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2968
- var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2969
- function toMontgomery(point) {
2970
- const { y } = point;
2971
- return Fp.toBytes(Fp.div(_1n + y, _1n - y));
2972
- }
2973
- function toMontgomerySecret(secretKey) {
2974
- const size = ed25519_Point.Fp.BYTES;
2975
- abytes$1(secretKey, size);
2976
- return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);
2977
- }
2978
- function ed(opts) {
2979
- return eddsa(ed25519_Point, sha512, Object.assign({
2980
- adjustScalarBytes,
2981
- toMontgomery,
2982
- toMontgomerySecret,
2983
- zip215: true
2984
- }, opts));
2985
- }
2986
- /**
2987
- * ed25519 curve with EdDSA signatures.
2988
- * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided
2989
- * 32-byte seed buffer instead of copying it.
2990
- * @example
2991
- * Generate one Ed25519 keypair, sign a message, and verify it.
2992
- *
2993
- * ```js
2994
- * import { ed25519 } from '@noble/curves/ed25519.js';
2995
- * const { secretKey, publicKey } = ed25519.keygen();
2996
- * // const publicKey = ed25519.getPublicKey(secretKey);
2997
- * const msg = new TextEncoder().encode('hello noble');
2998
- * const sig = ed25519.sign(msg, secretKey);
2999
- * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215
3000
- * // RFC8032 / FIPS 186-5
3001
- * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });
3002
- * ```
3003
- */
3004
- var ed25519 = /* @__PURE__ */ ed({});
3005
- //#endregion
3006
- //#region ../../../../../../.pnpm-store/v11/links/@ldclabs/cose-ts/1.7.0/a470182239a6259287f50f513c384f2f3f3a1550025b6307427708908f279082/node_modules/@ldclabs/cose-ts/dist/key.js
3007
- var Key = class Key extends KVMap {
3008
- static fromBytes(data) {
3009
- return new Key(decodeCBOR(data));
3010
- }
3011
- constructor(kv = /* @__PURE__ */ new Map()) {
3012
- super(kv);
3013
- }
3014
- get kty() {
3015
- return this.getType(1, assertIntOrText, "kty");
3016
- }
3017
- set kty(kty) {
3018
- this.setParam(1, assertIntOrText(kty, "kty"));
3019
- }
3020
- get kid() {
3021
- return this.getBytes(2, "kid");
3022
- }
3023
- set kid(kid) {
3024
- this.setParam(2, assertBytes(kid, "kid"));
3025
- }
3026
- get alg() {
3027
- return this.getType(3, assertIntOrText, "alg");
3028
- }
3029
- set alg(alg) {
3030
- this.setParam(3, assertIntOrText(alg, "alg"));
3031
- }
3032
- get ops() {
3033
- return this.getArray(4, assertIntOrText, "ops");
3034
- }
3035
- set ops(ops) {
3036
- if (!Array.isArray(ops)) throw new TypeError("ops must be an array");
3037
- ops.forEach((op) => assertIntOrText(op, "ops"));
3038
- this.setParam(4, ops);
3039
- }
3040
- get baseIV() {
3041
- return this.getBytes(5, "Base IV");
3042
- }
3043
- set baseIV(iv) {
3044
- this.setParam(5, assertBytes(iv, "Base IV"));
3045
- }
3046
- getKid() {
3047
- return decodeCBOR(this.getBytes(2, "kid"));
3048
- }
3049
- setKid(kid) {
3050
- this.setParam(2, encodeCBOR(kid));
3051
- return this;
3052
- }
3053
- getSecret() {
3054
- switch (this.kty) {
3055
- case 1: return this.getBytes(-4, "k");
3056
- case 2: return this.getBytes(-4, "d");
3057
- case 4: return this.getBytes(-1, "k");
3058
- default: throw new Error("unsupported key type");
3059
- }
3060
- }
3061
- verifyOps(...allowed) {
3062
- if (!this.has(4)) return;
3063
- const ops = this.ops;
3064
- for (const op of allowed) if (ops.includes(op)) return;
3065
- throw new Error(`cose-ts: key_ops ${JSON.stringify(ops)} does not permit operation ${allowed.join("/")}`);
3066
- }
3067
- };
3068
- //#endregion
3069
- //#region ../../../../../../.pnpm-store/v11/links/@ldclabs/cose-ts/1.7.0/a470182239a6259287f50f513c384f2f3f3a1550025b6307427708908f279082/node_modules/@ldclabs/cose-ts/dist/ed25519.js
3070
- /**
3071
- * Ed25519Key implements the Ed25519 signature algorithm (EdDSA) for COSE, as
3072
- * defined in RFC 9053. Use it with {@link Sign1Message} or {@link SignMessage}.
3073
- *
3074
- * Construction signature: `generate(kid?)` — the algorithm is fixed, so the
3075
- * first argument is the optional key id, not the algorithm.
3076
- *
3077
- * @example
3078
- * ```ts
3079
- * const key = Ed25519Key.generate('signing-key-1')
3080
- * const cose = new Sign1Message(payload).toBytes(key)
3081
- * Sign1Message.fromBytes(key.public(), cose)
3082
- * ```
3083
- *
3084
- * @see https://datatracker.ietf.org/doc/html/rfc9053#name-edwards-curve-digital-signa
3085
- */
3086
- var Ed25519Key = class Ed25519Key extends Key {
3087
- /** Decodes a COSE_Key from CBOR bytes into an Ed25519Key. */
3088
- static fromBytes(data) {
3089
- return new Ed25519Key(decodeCBOR(data));
3090
- }
3091
- /**
3092
- * Generates a new Ed25519 private key from a random 32-byte seed.
3093
- *
3094
- * @param kid - Optional key id; stored CBOR-encoded in the COSE_Key and
3095
- * copied into the unprotected header by message helpers.
3096
- */
3097
- static generate(kid) {
3098
- return Ed25519Key.fromSecret(randomBytes$1(32), kid);
3099
- }
3100
- /**
3101
- * Imports an Ed25519 private key from a raw 32-byte seed.
3102
- *
3103
- * @param secret - The 32-byte Ed25519 seed (private key).
3104
- * @param kid - Optional key id.
3105
- */
3106
- static fromSecret(secret, kid) {
3107
- assertBytes(secret, "secret");
3108
- if (secret.length !== 32) throw new Error(`cose-ts: Ed25519Key.fromSecret: secret size mismatch, expected 32, got ${secret.length}`);
3109
- const key = new Ed25519Key();
3110
- key.setParam(-4, secret);
3111
- if (kid != null) key.setKid(kid);
3112
- return key;
3113
- }
3114
- /**
3115
- * Imports an Ed25519 public (verify-only) key from a raw 32-byte point.
3116
- *
3117
- * @param pubkey - The 32-byte Ed25519 public key.
3118
- * @param kid - Optional key id.
3119
- */
3120
- static fromPublic(pubkey, kid) {
3121
- assertBytes(pubkey, "public key");
3122
- if (pubkey.length !== 32) throw new Error(`cose-ts: Ed25519Key.fromPublic: public key size mismatch, expected 32, got ${pubkey.length}`);
3123
- const key = new Ed25519Key();
3124
- key.setParam(-2, pubkey);
3125
- if (kid != null) key.setKid(kid);
3126
- return key;
3127
- }
3128
- constructor(kv) {
3129
- super(kv);
3130
- this.kty = 1;
3131
- this.alg = -8;
3132
- this.setParam(-1, 6);
3133
- }
3134
- getSecretKey() {
3135
- return this.getBytes(-4, "d");
3136
- }
3137
- getPublicKey() {
3138
- if (this.has(-2)) return this.getBytes(-2, "x");
3139
- return ed25519.getPublicKey(this.getSecretKey());
3140
- }
3141
- /**
3142
- * Returns a verify-only copy of this key: the private seed is removed and
3143
- * `key_ops` (if present) is narrowed to verify.
3144
- */
3145
- public() {
3146
- const key = new Ed25519Key(this.clone());
3147
- if (key.has(-4)) {
3148
- key.setParam(-2, key.getPublicKey());
3149
- key.delete(-4);
3150
- }
3151
- if (key.has(4)) key.ops = [2];
3152
- return key;
3153
- }
3154
- sign(message) {
3155
- this.verifyOps(1);
3156
- return ed25519.sign(message, this.getSecretKey());
3157
- }
3158
- verify(message, signature) {
3159
- this.verifyOps(2);
3160
- return ed25519.verify(signature, message, this.getPublicKey());
3161
- }
3162
- };
3163
- //#endregion
3164
- //#region ../../../../../../.pnpm-store/v11/links/@ldclabs/cose-ts/1.7.0/a470182239a6259287f50f513c384f2f3f3a1550025b6307427708908f279082/node_modules/@ldclabs/cose-ts/dist/header.js
3165
- var Header = class Header extends KVMap {
3166
- static fromBytes(data) {
3167
- if (data.length === 0) return new Header();
3168
- return new Header(decodeCBOR(data));
3169
- }
3170
- constructor(kv = /* @__PURE__ */ new Map()) {
3171
- super(kv);
3172
- }
3173
- toBytes() {
3174
- if (this.toRaw().size === 0) return /* @__PURE__ */ new Uint8Array();
3175
- return super.toBytes();
3176
- }
3177
- };
3178
- function verifyHeaders(protectedHeader, unprotectedHeader, understoodCriticalLabels) {
3179
- for (const label of unprotectedHeader.toRaw().keys()) assertIntOrText(label, "unprotected header label");
3180
- for (const label of protectedHeader.toRaw().keys()) {
3181
- assertIntOrText(label, "protected header label");
3182
- if (unprotectedHeader.has(label)) throw new Error(`cose-ts: header parameter ${String(label)} occurs in both the protected and unprotected buckets`);
3183
- }
3184
- verifyCommonHeaderParameters(protectedHeader, "protected");
3185
- verifyCommonHeaderParameters(unprotectedHeader, "unprotected");
3186
- const hasIV = protectedHeader.has(5) || unprotectedHeader.has(5);
3187
- const hasPartialIV = protectedHeader.has(6) || unprotectedHeader.has(6);
3188
- if (hasIV && hasPartialIV) throw new Error("cose-ts: IV and Partial IV must not both be present in the same header layer");
3189
- if (unprotectedHeader.has(2)) throw new Error("cose-ts: crit header parameter must be in the protected bucket");
3190
- if (!protectedHeader.has(2)) return [];
3191
- const crit = protectedHeader.getArray(2, assertIntOrText, "crit");
3192
- if (crit.length === 0) throw new Error("cose-ts: crit header parameter must have at least one value");
3193
- for (const label of crit) if (!protectedHeader.has(label)) throw new Error(`cose-ts: critical header parameter ${String(label)} is not present in the protected bucket`);
3194
- if (understoodCriticalLabels != null) {
3195
- const understood = new Set(understoodCriticalLabels);
3196
- for (const label of crit) if (!understood.has(label)) throw new Error(`cose-ts: critical header parameter ${String(label)} is not understood`);
3197
- }
3198
- return crit;
3199
- }
3200
- function verifyCommonHeaderParameters(header, bucket) {
3201
- if (header.has(1)) header.getType(1, assertIntOrText, `${bucket} alg`);
3202
- if (header.has(3)) header.getType(3, assertContentType, `${bucket} content type`);
3203
- if (header.has(4)) header.getType(4, assertBytes, `${bucket} kid`);
3204
- if (header.has(5)) header.getType(5, assertBytes, `${bucket} IV`);
3205
- if (header.has(6)) header.getType(6, assertBytes, `${bucket} Partial IV`);
3206
- }
3207
- function assertContentType(value, name) {
3208
- if (typeof value === "string") return value;
3209
- if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return value;
3210
- throw new TypeError(`${name} must be a non-negative integer or string, but got ${String(value)}`);
3211
- }
3212
- //#endregion
3213
- //#region ../../../../../../.pnpm-store/v11/links/@ldclabs/cose-ts/1.7.0/a470182239a6259287f50f513c384f2f3f3a1550025b6307427708908f279082/node_modules/@ldclabs/cose-ts/dist/sign1.js
3214
- /**
3215
- * Sign1Message represents a COSE_Sign1 object.
3216
- *
3217
- * The optional externalData argument on toBytes()/fromBytes() is included in
3218
- * the Sig_structure and must match exactly on signing and verification.
3219
- *
3220
- * @example
3221
- * ```ts
3222
- * const key = Ed25519Key.generate()
3223
- * const aad = utf8ToBytes('profile:v1')
3224
- * const cose = new Sign1Message(utf8ToBytes('hello')).toBytes(key, aad)
3225
- * const verified = Sign1Message.fromBytes(key.public(), cose, aad)
3226
- * ```
3227
- *
3228
- * Reference https://datatracker.ietf.org/doc/html/rfc9052#name-signing-with-one-signer
3229
- */
3230
- var Sign1Message = class Sign1Message {
3231
- payload;
3232
- protected = null;
3233
- unprotected = null;
3234
- static signBytes(payload, protectedHeader, externalData) {
3235
- return encodeCBOR([
3236
- "Signature1",
3237
- protectedHeader,
3238
- externalData ?? /* @__PURE__ */ new Uint8Array(),
3239
- payload
3240
- ]);
3241
- }
3242
- static fromBytes(key, coseData, externalData, understoodCriticalLabels) {
3243
- const [protectedBytes, unprotected, payload, signature] = decodeCBOR(skipTag(Sign1MessagePrefix, skipTag(CwtPrefix, skipTag(CBORSelfPrefix, coseData))));
3244
- const protectedHeader = Header.fromBytes(protectedBytes);
3245
- const unprotectedHeader = new Header(unprotected);
3246
- verifyHeaders(protectedHeader, unprotectedHeader, [1, ...understoodCriticalLabels ?? []]);
3247
- if (protectedHeader.has(1)) {
3248
- const alg = protectedHeader.getType(1, assertIntOrText, "alg");
3249
- if (alg !== key.alg) throw new Error(`cose-ts: Sign1Message.fromBytes: alg mismatch, expected ${alg}, got ${key.alg}`);
3250
- }
3251
- if (!key.verify(Sign1Message.signBytes(payload, protectedBytes, externalData), signature)) throw new Error("cose-ts: Sign1Message.fromBytes: signature mismatch");
3252
- return new Sign1Message(payload, protectedHeader, unprotectedHeader);
3253
- }
3254
- static withTag(coseData) {
3255
- return withTag(Sign1MessagePrefix, coseData);
3256
- }
3257
- /**
3258
- * @param payload - The payload bytes to sign.
3259
- * @param protectedHeader - Optional protected (authenticated) header. When
3260
- * omitted, `toBytes` creates one and sets `alg` from the signing key.
3261
- * @param unprotected - Optional unprotected header. When omitted, `toBytes`
3262
- * creates one and copies the key's `kid` if present.
3263
- */
3264
- constructor(payload, protectedHeader, unprotected) {
3265
- this.payload = payload;
3266
- this.protected = protectedHeader ? new Header(protectedHeader.clone()) : null;
3267
- this.unprotected = unprotected ? new Header(unprotected.clone()) : null;
3268
- }
3269
- toBytes(key, externalData) {
3270
- if (this.protected == null) {
3271
- this.protected = new Header();
3272
- if (key.has(3)) this.protected.setParam(1, key.alg);
3273
- } else if (this.protected.has(1)) {
3274
- const alg = this.protected.getType(1, assertIntOrText, "alg");
3275
- if (alg !== key.alg) throw new Error(`cose-ts: Sign1Message.toBytes: alg mismatch, expected ${alg}, got ${key.alg}`);
3276
- }
3277
- if (this.unprotected == null) {
3278
- this.unprotected = new Header();
3279
- if (key.has(2)) this.unprotected.setParam(4, key.kid);
3280
- }
3281
- verifyHeaders(this.protected, this.unprotected);
3282
- const protectedBytes = this.protected.toBytes();
3283
- const sig = key.sign(Sign1Message.signBytes(this.payload, protectedBytes, externalData));
3284
- return encodeCBOR([
3285
- protectedBytes,
3286
- this.unprotected.toRaw(),
3287
- this.payload,
3288
- sig
3289
- ]);
3290
- }
3291
- };
3292
- //#endregion
3293
- //#region src/cwt.ts
3294
- var CWT_APP_ID = -65537;
3295
- var CWT_ATTESTATION_PUBLIC_KEY = -65538;
3296
- var CWT_IDENTITY_PUBLIC_KEY = -65539;
3297
- var CWT_PROOF = -65540;
3298
- var IdentityTokenProof = {
3299
- AppAttest: "app-attest",
3300
- IdentityKey: "identity-key"
3301
- };
3302
- /**
3303
- * Mint a CWT (CBOR Web Token) with COSE Sign1 envelope, Ed25519 signature.
3304
- *
3305
- * @param privateKey - Ed25519 private key (32 bytes)
3306
- * @param claims - Token claims
3307
- * @returns base64url-encoded CWT
3308
- */
3309
- function mintIdentityToken(claims, privateKey) {
3310
- const now = Math.floor(Date.now() / 1e3);
3311
- const c = new Claims();
3312
- c.iss = "crayon";
3313
- c.sub = claims.userId;
3314
- c.iat = now;
3315
- c.setParam(CWT_IDENTITY_PUBLIC_KEY, claims.identityPublicKey);
3316
- c.setParam(CWT_PROOF, claims.proof ?? IdentityTokenProof.AppAttest);
3317
- if ("appId" in claims) {
3318
- c.setParam(CWT_APP_ID, claims.appId);
3319
- c.setParam(CWT_ATTESTATION_PUBLIC_KEY, claims.attestationPublicKey);
3320
- }
3321
- const payload = c.toBytes();
3322
- const key = Ed25519Key.fromSecret(privateKey);
3323
- const msg = new Sign1Message(payload, new Header().setParam(1, -8));
3324
- const signed = withCWTTag(Sign1Message.withTag(msg.toBytes(key)));
3325
- return base64urlnopad.encode(signed);
3326
- }
3327
- /**
3328
- * Verify a CWT and decode its claims.
3329
- *
3330
- * @param publicKey - Ed25519 public key (32 bytes)
3331
- * @param token - base64url-encoded CWT
3332
- * @returns Decoded and verified claims
3333
- * @throws If signature verification fails or token is malformed
3334
- */
3335
- function verifyIdentityToken(publicKey, token, { expectedClaims, tracer } = {}) {
3336
- if (!token) throw new Error("Empty token");
3337
- const encoded = decodeIdentityToken(token);
3338
- const key = Ed25519Key.fromPublic(publicKey);
3339
- const msg = traceOperationSync(tracer, "identity.cwt.signature.verify", () => Sign1Message.fromBytes(key, encoded));
3340
- const c = Claims.fromBytes(msg.payload);
3341
- let claims;
3342
- try {
3343
- claims = VerifiedIdentityTokenSchema.parse({
3344
- appId: optionalTextClaim(c, CWT_APP_ID),
3345
- attestationPublicKey: optionalTextClaim(c, CWT_ATTESTATION_PUBLIC_KEY),
3346
- iat: c.iat,
3347
- identityPublicKey: c.getText(CWT_IDENTITY_PUBLIC_KEY),
3348
- proof: optionalTextClaim(c, CWT_PROOF),
3349
- userId: c.sub
3350
- });
3351
- } catch {
3352
- throw new Error("Malformed CWT claims");
3353
- }
3354
- return expectedClaims ? expectedIdentityTokenSchema(expectedClaims).parse(claims) : claims;
3355
- }
3356
- var IdentityTokenProofSchema = z.enum([IdentityTokenProof.AppAttest, IdentityTokenProof.IdentityKey]);
3357
- var RawIdentityTokenSchema = z.object({
3358
- appId: z.string().optional(),
3359
- attestationPublicKey: z.string().optional(),
3360
- iat: z.number(),
3361
- identityPublicKey: z.string(),
3362
- proof: IdentityTokenProofSchema.default(IdentityTokenProof.AppAttest),
3363
- userId: z.string()
3364
- });
3365
- var AppAttestIdentityTokenSchema = z.object({
3366
- appId: z.string(),
3367
- attestationPublicKey: z.string(),
3368
- iat: z.number(),
3369
- identityPublicKey: z.string(),
3370
- proof: z.literal(IdentityTokenProof.AppAttest),
3371
- userId: z.string()
3372
- });
3373
- var IdentityKeyIdentityTokenSchema = z.object({
3374
- iat: z.number(),
3375
- identityPublicKey: z.string(),
3376
- proof: z.literal(IdentityTokenProof.IdentityKey),
3377
- userId: z.string()
3378
- });
3379
- var VerifiedIdentityTokenSchema = RawIdentityTokenSchema.pipe(z.discriminatedUnion("proof", [AppAttestIdentityTokenSchema, IdentityKeyIdentityTokenSchema]));
3380
- function expectedIdentityTokenSchema(expected) {
3381
- return expected.proof === IdentityTokenProof.AppAttest ? AppAttestIdentityTokenSchema.extend({
3382
- appId: z.literal(expected.appId),
3383
- identityPublicKey: z.literal(expected.identityPublicKey)
3384
- }) : IdentityKeyIdentityTokenSchema.extend({ identityPublicKey: z.literal(expected.identityPublicKey) });
3385
- }
3386
- function optionalTextClaim(claims, key) {
3387
- return claims.has(key) ? claims.getText(key) : void 0;
3388
- }
3389
- function decodeIdentityToken(token) {
3390
- try {
3391
- return base64urlnopad.decode(token);
3392
- } catch {
3393
- return base64url.decode(token);
3394
- }
3395
- }
3396
- //#endregion
3397
- export { mintIdentityToken as n, verifyIdentityToken as r, IdentityTokenProof as t };