@ai-matrx/vault 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,819 @@
1
+ // ../../node_modules/.pnpm/lossless-json@4.3.1/node_modules/lossless-json/lib/esm/utils.js
2
+ function isInteger(value) {
3
+ return INTEGER_REGEX.test(value);
4
+ }
5
+ var INTEGER_REGEX = /^-?[0-9]+$/;
6
+ function isNumber(value) {
7
+ return NUMBER_REGEX.test(value);
8
+ }
9
+ var NUMBER_REGEX = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
10
+ function isSafeNumber(value, config2) {
11
+ if (isInteger(value)) {
12
+ return Number.isSafeInteger(Number.parseInt(value, 10));
13
+ }
14
+ const num = Number.parseFloat(value);
15
+ const parsed = String(num);
16
+ if (value === parsed) {
17
+ return true;
18
+ }
19
+ const valueDigits = extractSignificantDigits(value);
20
+ const parsedDigits = extractSignificantDigits(parsed);
21
+ if (valueDigits === parsedDigits) {
22
+ return true;
23
+ }
24
+ if (config2?.approx === true) {
25
+ const requiredDigits = 14;
26
+ if (!isInteger(value) && parsedDigits.length >= requiredDigits && valueDigits.startsWith(parsedDigits.substring(0, requiredDigits))) {
27
+ return true;
28
+ }
29
+ }
30
+ return false;
31
+ }
32
+ var UnsafeNumberReason = /* @__PURE__ */ (function(UnsafeNumberReason2) {
33
+ UnsafeNumberReason2["underflow"] = "underflow";
34
+ UnsafeNumberReason2["overflow"] = "overflow";
35
+ UnsafeNumberReason2["truncate_integer"] = "truncate_integer";
36
+ UnsafeNumberReason2["truncate_float"] = "truncate_float";
37
+ return UnsafeNumberReason2;
38
+ })({});
39
+ function getUnsafeNumberReason(value) {
40
+ if (isSafeNumber(value, {
41
+ approx: false
42
+ })) {
43
+ return void 0;
44
+ }
45
+ if (isInteger(value)) {
46
+ return UnsafeNumberReason.truncate_integer;
47
+ }
48
+ const num = Number.parseFloat(value);
49
+ if (!Number.isFinite(num)) {
50
+ return UnsafeNumberReason.overflow;
51
+ }
52
+ if (num === 0) {
53
+ return UnsafeNumberReason.underflow;
54
+ }
55
+ return UnsafeNumberReason.truncate_float;
56
+ }
57
+ function extractSignificantDigits(value) {
58
+ const {
59
+ start,
60
+ end
61
+ } = getSignificantDigitRange(value);
62
+ const digits = value.substring(start, end);
63
+ const dot = digits.indexOf(".");
64
+ if (dot === -1) {
65
+ return digits;
66
+ }
67
+ return digits.substring(0, dot) + digits.substring(dot + 1);
68
+ }
69
+ function getSignificantDigitRange(value) {
70
+ let start = 0;
71
+ if (value[0] === "-") {
72
+ start++;
73
+ }
74
+ while (value[start] === "0" || value[start] === ".") {
75
+ start++;
76
+ }
77
+ let end = value.lastIndexOf("e");
78
+ if (end === -1) {
79
+ end = value.lastIndexOf("E");
80
+ }
81
+ if (end === -1) {
82
+ end = value.length;
83
+ }
84
+ while ((value[end - 1] === "0" || value[end - 1] === ".") && end > start) {
85
+ end--;
86
+ }
87
+ return {
88
+ start,
89
+ end
90
+ };
91
+ }
92
+
93
+ // ../../node_modules/.pnpm/lossless-json@4.3.1/node_modules/lossless-json/lib/esm/LosslessNumber.js
94
+ var LosslessNumber = class {
95
+ // numeric value as string
96
+ // type information
97
+ isLosslessNumber = true;
98
+ constructor(value) {
99
+ if (!isNumber(value)) {
100
+ throw new Error(`Invalid number (value: "${value}")`);
101
+ }
102
+ this.value = value;
103
+ }
104
+ /**
105
+ * Get the value of the LosslessNumber as number or bigint.
106
+ *
107
+ * - a number is returned for safe numbers and decimal values that only lose some insignificant digits
108
+ * - a bigint is returned for big integer numbers
109
+ * - an Error is thrown for values that will overflow or underflow
110
+ *
111
+ * Note that you can implement your own strategy for conversion by just getting the value as string
112
+ * via .toString(), and using util functions like isInteger, isSafeNumber, getUnsafeNumberReason,
113
+ * and toSafeNumberOrThrow to convert it to a numeric value.
114
+ */
115
+ valueOf() {
116
+ const unsafeReason = getUnsafeNumberReason(this.value);
117
+ if (unsafeReason === void 0 || unsafeReason === UnsafeNumberReason.truncate_float) {
118
+ return Number.parseFloat(this.value);
119
+ }
120
+ if (isInteger(this.value)) {
121
+ return BigInt(this.value);
122
+ }
123
+ throw new Error(`Cannot safely convert to number: the value '${this.value}' would ${unsafeReason} and become ${Number.parseFloat(this.value)}`);
124
+ }
125
+ /**
126
+ * Get the value of the LosslessNumber as string.
127
+ */
128
+ toString() {
129
+ return this.value;
130
+ }
131
+ // Note: we do NOT implement a .toJSON() method, and you should not implement
132
+ // or use that, it cannot safely turn the numeric value in the string into
133
+ // stringified JSON since it has to be parsed into a number first.
134
+ };
135
+ function isLosslessNumber(value) {
136
+ return value && typeof value === "object" && value.isLosslessNumber || false;
137
+ }
138
+
139
+ // ../../node_modules/.pnpm/lossless-json@4.3.1/node_modules/lossless-json/lib/esm/numberParsers.js
140
+ function parseLosslessNumber(value) {
141
+ return new LosslessNumber(value);
142
+ }
143
+
144
+ // ../../node_modules/.pnpm/lossless-json@4.3.1/node_modules/lossless-json/lib/esm/revive.js
145
+ function revive(json, reviver) {
146
+ return reviveValue({
147
+ "": json
148
+ }, "", json, reviver);
149
+ }
150
+ function reviveValue(context, key, value, reviver) {
151
+ if (Array.isArray(value)) {
152
+ return reviver.call(context, key, reviveArray(value, reviver));
153
+ }
154
+ if (value && typeof value === "object" && !isLosslessNumber(value)) {
155
+ return reviver.call(context, key, reviveObject(value, reviver));
156
+ }
157
+ return reviver.call(context, key, value);
158
+ }
159
+ function reviveObject(object2, reviver) {
160
+ for (const key of Object.keys(object2)) {
161
+ const value = reviveValue(object2, key, object2[key], reviver);
162
+ if (value !== void 0) {
163
+ object2[key] = value;
164
+ } else {
165
+ delete object2[key];
166
+ }
167
+ }
168
+ return object2;
169
+ }
170
+ function reviveArray(array, reviver) {
171
+ for (let i = 0; i < array.length; i++) {
172
+ array[i] = reviveValue(array, String(i), array[i], reviver);
173
+ }
174
+ return array;
175
+ }
176
+
177
+ // ../../node_modules/.pnpm/lossless-json@4.3.1/node_modules/lossless-json/lib/esm/parse.js
178
+ function parse(text, reviver, options) {
179
+ const optionsObj = typeof options === "function" ? {
180
+ parseNumber: options
181
+ } : options;
182
+ const parseNumber = optionsObj?.parseNumber ?? parseLosslessNumber;
183
+ const onDuplicateKey = optionsObj?.onDuplicateKey ?? throwDuplicateKey;
184
+ let i = 0;
185
+ const value = parseValue();
186
+ expectValue(value);
187
+ expectEndOfInput();
188
+ return reviver ? revive(value, reviver) : value;
189
+ function parseObject() {
190
+ if (text.charCodeAt(i) === codeOpeningBrace) {
191
+ i++;
192
+ skipWhitespace();
193
+ const object2 = {};
194
+ let initial = true;
195
+ while (i < text.length && text.charCodeAt(i) !== codeClosingBrace) {
196
+ if (!initial) {
197
+ eatComma();
198
+ skipWhitespace();
199
+ } else {
200
+ initial = false;
201
+ }
202
+ const start = i;
203
+ const key = parseString();
204
+ if (key === void 0) {
205
+ throwObjectKeyExpected();
206
+ return;
207
+ }
208
+ skipWhitespace();
209
+ eatColon();
210
+ const value2 = parseValue();
211
+ if (value2 === void 0) {
212
+ throwObjectValueExpected();
213
+ return;
214
+ }
215
+ if (Object.prototype.hasOwnProperty.call(object2, key) && !isDeepEqual(value2, object2[key])) {
216
+ const returnedValue = onDuplicateKey({
217
+ key,
218
+ position: start + 1,
219
+ oldValue: object2[key],
220
+ newValue: value2
221
+ });
222
+ if (returnedValue !== void 0) {
223
+ object2[key] = returnedValue;
224
+ }
225
+ } else {
226
+ object2[key] = value2;
227
+ }
228
+ }
229
+ if (text.charCodeAt(i) !== codeClosingBrace) {
230
+ throwObjectKeyOrEndExpected();
231
+ }
232
+ i++;
233
+ return object2;
234
+ }
235
+ }
236
+ function parseArray() {
237
+ if (text.charCodeAt(i) === codeOpeningBracket) {
238
+ i++;
239
+ skipWhitespace();
240
+ const array = [];
241
+ let initial = true;
242
+ while (i < text.length && text.charCodeAt(i) !== codeClosingBracket) {
243
+ if (!initial) {
244
+ eatComma();
245
+ } else {
246
+ initial = false;
247
+ }
248
+ const value2 = parseValue();
249
+ expectArrayItem(value2);
250
+ array.push(value2);
251
+ }
252
+ if (text.charCodeAt(i) !== codeClosingBracket) {
253
+ throwArrayItemOrEndExpected();
254
+ }
255
+ i++;
256
+ return array;
257
+ }
258
+ }
259
+ function parseValue() {
260
+ skipWhitespace();
261
+ const value2 = parseString() ?? parseNumeric() ?? parseObject() ?? parseArray() ?? parseKeyword("true", true) ?? parseKeyword("false", false) ?? parseKeyword("null", null);
262
+ skipWhitespace();
263
+ return value2;
264
+ }
265
+ function parseKeyword(name, value2) {
266
+ if (text.slice(i, i + name.length) === name) {
267
+ i += name.length;
268
+ return value2;
269
+ }
270
+ }
271
+ function skipWhitespace() {
272
+ while (isWhitespace(text.charCodeAt(i))) {
273
+ i++;
274
+ }
275
+ }
276
+ function parseString() {
277
+ if (text.charCodeAt(i) === codeDoubleQuote) {
278
+ i++;
279
+ let result = "";
280
+ while (i < text.length && text.charCodeAt(i) !== codeDoubleQuote) {
281
+ if (text.charCodeAt(i) === codeBackslash) {
282
+ const char = text[i + 1];
283
+ const escapeChar = escapeCharacters[char];
284
+ if (escapeChar !== void 0) {
285
+ result += escapeChar;
286
+ i++;
287
+ } else if (char === "u") {
288
+ if (isHex(text.charCodeAt(i + 2)) && isHex(text.charCodeAt(i + 3)) && isHex(text.charCodeAt(i + 4)) && isHex(text.charCodeAt(i + 5))) {
289
+ result += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
290
+ i += 5;
291
+ } else {
292
+ throwInvalidUnicodeCharacter(i);
293
+ }
294
+ } else {
295
+ throwInvalidEscapeCharacter(i);
296
+ }
297
+ } else {
298
+ if (isValidStringCharacter(text.charCodeAt(i))) {
299
+ result += text[i];
300
+ } else {
301
+ throwInvalidCharacter(text[i]);
302
+ }
303
+ }
304
+ i++;
305
+ }
306
+ expectEndOfString();
307
+ i++;
308
+ return result;
309
+ }
310
+ }
311
+ function parseNumeric() {
312
+ const start = i;
313
+ if (text.charCodeAt(i) === codeMinus) {
314
+ i++;
315
+ expectDigit(start);
316
+ }
317
+ if (text.charCodeAt(i) === codeZero) {
318
+ i++;
319
+ } else if (isNonZeroDigit(text.charCodeAt(i))) {
320
+ i++;
321
+ while (isDigit(text.charCodeAt(i))) {
322
+ i++;
323
+ }
324
+ }
325
+ if (text.charCodeAt(i) === codeDot) {
326
+ i++;
327
+ expectDigit(start);
328
+ while (isDigit(text.charCodeAt(i))) {
329
+ i++;
330
+ }
331
+ }
332
+ if (text.charCodeAt(i) === codeLowercaseE || text.charCodeAt(i) === codeUppercaseE) {
333
+ i++;
334
+ if (text.charCodeAt(i) === codeMinus || text.charCodeAt(i) === codePlus) {
335
+ i++;
336
+ }
337
+ expectDigit(start);
338
+ while (isDigit(text.charCodeAt(i))) {
339
+ i++;
340
+ }
341
+ }
342
+ if (i > start) {
343
+ return parseNumber(text.slice(start, i));
344
+ }
345
+ }
346
+ function eatComma() {
347
+ if (text.charCodeAt(i) !== codeComma) {
348
+ throw new SyntaxError(`Comma ',' expected after value ${gotAt()}`);
349
+ }
350
+ i++;
351
+ }
352
+ function eatColon() {
353
+ if (text.charCodeAt(i) !== codeColon) {
354
+ throw new SyntaxError(`Colon ':' expected after property name ${gotAt()}`);
355
+ }
356
+ i++;
357
+ }
358
+ function expectValue(value2) {
359
+ if (value2 === void 0) {
360
+ throw new SyntaxError(`JSON value expected ${gotAt()}`);
361
+ }
362
+ }
363
+ function expectArrayItem(value2) {
364
+ if (value2 === void 0) {
365
+ throw new SyntaxError(`Array item expected ${gotAt()}`);
366
+ }
367
+ }
368
+ function expectEndOfInput() {
369
+ if (i < text.length) {
370
+ throw new SyntaxError(`Expected end of input ${gotAt()}`);
371
+ }
372
+ }
373
+ function expectDigit(start) {
374
+ if (!isDigit(text.charCodeAt(i))) {
375
+ const numSoFar = text.slice(start, i);
376
+ throw new SyntaxError(`Invalid number '${numSoFar}', expecting a digit ${gotAt()}`);
377
+ }
378
+ }
379
+ function expectEndOfString() {
380
+ if (text.charCodeAt(i) !== codeDoubleQuote) {
381
+ throw new SyntaxError(`End of string '"' expected ${gotAt()}`);
382
+ }
383
+ }
384
+ function throwObjectKeyExpected() {
385
+ throw new SyntaxError(`Quoted object key expected ${gotAt()}`);
386
+ }
387
+ function throwDuplicateKey(_ref) {
388
+ let {
389
+ key,
390
+ position
391
+ } = _ref;
392
+ throw new SyntaxError(`Duplicate key '${key}' encountered at position ${position}`);
393
+ }
394
+ function throwObjectKeyOrEndExpected() {
395
+ throw new SyntaxError(`Quoted object key or end of object '}' expected ${gotAt()}`);
396
+ }
397
+ function throwArrayItemOrEndExpected() {
398
+ throw new SyntaxError(`Array item or end of array ']' expected ${gotAt()}`);
399
+ }
400
+ function throwInvalidCharacter(char) {
401
+ throw new SyntaxError(`Invalid character '${char}' ${pos()}`);
402
+ }
403
+ function throwInvalidEscapeCharacter(start) {
404
+ const chars = text.slice(start, start + 2);
405
+ throw new SyntaxError(`Invalid escape character '${chars}' ${pos()}`);
406
+ }
407
+ function throwObjectValueExpected() {
408
+ throw new SyntaxError(`Object value expected after ':' ${pos()}`);
409
+ }
410
+ function throwInvalidUnicodeCharacter(start) {
411
+ const chars = text.slice(start, start + 6);
412
+ throw new SyntaxError(`Invalid unicode character '${chars}' ${pos()}`);
413
+ }
414
+ function pos() {
415
+ return `at position ${i}`;
416
+ }
417
+ function got() {
418
+ return i < text.length ? `but got '${text[i]}'` : "but reached end of input";
419
+ }
420
+ function gotAt() {
421
+ return `${got()} ${pos()}`;
422
+ }
423
+ }
424
+ function isWhitespace(code) {
425
+ return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;
426
+ }
427
+ function isHex(code) {
428
+ return code >= codeZero && code <= codeNine || code >= codeUppercaseA && code <= codeUppercaseF || code >= codeLowercaseA && code <= codeLowercaseF;
429
+ }
430
+ function isDigit(code) {
431
+ return code >= codeZero && code <= codeNine;
432
+ }
433
+ function isNonZeroDigit(code) {
434
+ return code >= codeOne && code <= codeNine;
435
+ }
436
+ function isValidStringCharacter(code) {
437
+ return code >= 32 && code <= 1114111;
438
+ }
439
+ function isDeepEqual(a, b) {
440
+ if (a === b) {
441
+ return true;
442
+ }
443
+ if (Array.isArray(a) && Array.isArray(b)) {
444
+ return a.length === b.length && a.every((item, index) => isDeepEqual(item, b[index]));
445
+ }
446
+ if (isObject(a) && isObject(b)) {
447
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])];
448
+ return keys.every((key) => isDeepEqual(a[key], b[key]));
449
+ }
450
+ return false;
451
+ }
452
+ function isObject(value) {
453
+ return typeof value === "object" && value !== null;
454
+ }
455
+ var escapeCharacters = {
456
+ '"': '"',
457
+ "\\": "\\",
458
+ "/": "/",
459
+ b: "\b",
460
+ f: "\f",
461
+ n: "\n",
462
+ r: "\r",
463
+ t: " "
464
+ // note that \u is handled separately in parseString()
465
+ };
466
+ var codeBackslash = 92;
467
+ var codeOpeningBrace = 123;
468
+ var codeClosingBrace = 125;
469
+ var codeOpeningBracket = 91;
470
+ var codeClosingBracket = 93;
471
+ var codeSpace = 32;
472
+ var codeNewline = 10;
473
+ var codeTab = 9;
474
+ var codeReturn = 13;
475
+ var codeDoubleQuote = 34;
476
+ var codePlus = 43;
477
+ var codeMinus = 45;
478
+ var codeZero = 48;
479
+ var codeOne = 49;
480
+ var codeNine = 57;
481
+ var codeComma = 44;
482
+ var codeDot = 46;
483
+ var codeColon = 58;
484
+ var codeUppercaseA = 65;
485
+ var codeLowercaseA = 97;
486
+ var codeUppercaseE = 69;
487
+ var codeLowercaseE = 101;
488
+ var codeUppercaseF = 70;
489
+ var codeLowercaseF = 102;
490
+
491
+ // ../../node_modules/.pnpm/lossless-json@4.3.1/node_modules/lossless-json/lib/esm/stringify.js
492
+ function stringify(value, replacer, space, numberStringifiers) {
493
+ const resolvedSpace = resolveSpace(space);
494
+ const replacedValue = typeof replacer === "function" ? replacer.call({
495
+ "": value
496
+ }, "", value) : value;
497
+ return stringifyValue(replacedValue, "");
498
+ function stringifyValue(value2, indent) {
499
+ if (Array.isArray(numberStringifiers)) {
500
+ const stringifier = numberStringifiers.find((item) => item.test(value2));
501
+ if (stringifier) {
502
+ const str = stringifier.stringify(value2);
503
+ if (typeof str !== "string" || !isNumber(str)) {
504
+ throw new Error(`Invalid JSON number: output of a number stringifier must be a string containing a JSON number (output: ${str})`);
505
+ }
506
+ return str;
507
+ }
508
+ }
509
+ if (typeof value2 === "boolean" || typeof value2 === "number" || typeof value2 === "string" || value2 === null || value2 instanceof Date || value2 instanceof Boolean || value2 instanceof Number || value2 instanceof String) {
510
+ return JSON.stringify(value2);
511
+ }
512
+ if (value2?.isLosslessNumber) {
513
+ return value2.toString();
514
+ }
515
+ if (typeof value2 === "bigint") {
516
+ return value2.toString();
517
+ }
518
+ if (Array.isArray(value2)) {
519
+ return stringifyArray(value2, indent);
520
+ }
521
+ if (value2 && typeof value2 === "object") {
522
+ return stringifyObject(value2, indent);
523
+ }
524
+ return void 0;
525
+ }
526
+ function stringifyArray(array, indent) {
527
+ if (array.length === 0) {
528
+ return "[]";
529
+ }
530
+ const childIndent = resolvedSpace ? indent + resolvedSpace : void 0;
531
+ let str = resolvedSpace ? "[\n" : "[";
532
+ for (let i = 0; i < array.length; i++) {
533
+ const item = typeof replacer === "function" ? replacer.call(array, String(i), array[i]) : array[i];
534
+ if (resolvedSpace) {
535
+ str += childIndent;
536
+ }
537
+ if (typeof item !== "undefined" && typeof item !== "function") {
538
+ str += stringifyValue(item, childIndent);
539
+ } else {
540
+ str += "null";
541
+ }
542
+ if (i < array.length - 1) {
543
+ str += resolvedSpace ? ",\n" : ",";
544
+ }
545
+ }
546
+ str += resolvedSpace ? `
547
+ ${indent}]` : "]";
548
+ return str;
549
+ }
550
+ function stringifyObject(object2, indent) {
551
+ if (typeof object2.toJSON === "function") {
552
+ return stringify(object2.toJSON(), replacer, space, void 0);
553
+ }
554
+ const keys = Array.isArray(replacer) ? replacer.map(String) : Object.keys(object2);
555
+ if (keys.length === 0) {
556
+ return "{}";
557
+ }
558
+ const childIndent = resolvedSpace ? indent + resolvedSpace : void 0;
559
+ let first = true;
560
+ let str = resolvedSpace ? "{\n" : "{";
561
+ for (const key of keys) {
562
+ const value2 = typeof replacer === "function" ? replacer.call(object2, key, object2[key]) : object2[key];
563
+ if (includeProperty(key, value2)) {
564
+ if (first) {
565
+ first = false;
566
+ } else {
567
+ str += resolvedSpace ? ",\n" : ",";
568
+ }
569
+ const keyStr = JSON.stringify(key);
570
+ str += resolvedSpace ? `${childIndent + keyStr}: ` : `${keyStr}:`;
571
+ str += stringifyValue(value2, childIndent);
572
+ }
573
+ }
574
+ str += resolvedSpace ? `
575
+ ${indent}}` : "}";
576
+ return str;
577
+ }
578
+ function includeProperty(_key, value2) {
579
+ return typeof value2 !== "undefined" && typeof value2 !== "function" && typeof value2 !== "symbol";
580
+ }
581
+ }
582
+ function resolveSpace(space) {
583
+ if (typeof space === "number") {
584
+ return " ".repeat(space);
585
+ }
586
+ if (typeof space === "string" && space !== "") {
587
+ return space;
588
+ }
589
+ return void 0;
590
+ }
591
+
592
+ // src/io/strict-json.ts
593
+ function assertNoDuplicateKeys(text) {
594
+ const stack = [];
595
+ let i = 0;
596
+ while (i < text.length) {
597
+ const ch = text[i];
598
+ if (ch === '"') {
599
+ const start = i;
600
+ i++;
601
+ while (i < text.length && text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
602
+ const top = stack[stack.length - 1];
603
+ if (top?.keys && top.expectKey) {
604
+ const key = JSON.parse(text.slice(start, i + 1));
605
+ if (top.keys.has(key)) throw new SyntaxError(`Duplicate key '${key}' encountered at position ${start + 1}`);
606
+ top.keys.add(key);
607
+ top.expectKey = false;
608
+ }
609
+ } else if (ch === "{") stack.push({ keys: /* @__PURE__ */ new Set(), expectKey: true });
610
+ else if (ch === "[") stack.push({ keys: null, expectKey: false });
611
+ else if (ch === "}" || ch === "]") stack.pop();
612
+ else if (ch === ",") {
613
+ const top = stack[stack.length - 1];
614
+ if (top?.keys) top.expectKey = true;
615
+ }
616
+ i++;
617
+ }
618
+ }
619
+ var parse2 = (text, ...rest) => {
620
+ assertNoDuplicateKeys(text);
621
+ return parse(text, ...rest);
622
+ };
623
+
624
+ // src/io/csv-import.ts
625
+ function safeDestination(raw) {
626
+ try {
627
+ const parsed = new URL(raw);
628
+ if (!/^https?:$/.test(parsed.protocol))
629
+ return { metadata: null, host: null };
630
+ if (parsed.username || parsed.password)
631
+ return { metadata: null, host: null };
632
+ return { metadata: parsed.origin, host: parsed.host };
633
+ } catch {
634
+ return { metadata: null, host: null };
635
+ }
636
+ }
637
+
638
+ // ../kit/src/uuid.ts
639
+ var RFC_4122_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
640
+ function isRfc4122Uuid(value) {
641
+ return typeof value === "string" && RFC_4122_RE.test(value);
642
+ }
643
+
644
+ // src/io/bitwarden-json.ts
645
+ var rootKeys = /* @__PURE__ */ new Set(["encrypted", "folders", "items"]);
646
+ var folderKeys = /* @__PURE__ */ new Set(["id", "name"]);
647
+ var itemKeys = /* @__PURE__ */ new Set(["id", "name", "type", "folderId", "organizationId", "collectionIds", "notes", "login", "secureNote", "card", "identity", "sshKey", "favorite", "reprompt", "fields", "passwordHistory", "revisionDate", "creationDate", "deletedDate", "attachments"]);
648
+ var loginKeys = /* @__PURE__ */ new Set(["username", "password", "totp", "uris", "fido2Credentials"]);
649
+ var uriKeys = /* @__PURE__ */ new Set(["uri", "match"]);
650
+ var sshKeys = /* @__PURE__ */ new Set(["privateKey", "publicKey", "keyFingerprint"]);
651
+ var fieldKeys = /* @__PURE__ */ new Set(["name", "value", "type", "linkedId"]);
652
+ var noteKeys = /* @__PURE__ */ new Set(["type"]);
653
+ var cardKeys = /* @__PURE__ */ new Set(["cardholderName", "expMonth", "expYear", "code", "brand", "number"]);
654
+ var identityKeys = /* @__PURE__ */ new Set(["title", "firstName", "middleName", "lastName", "address1", "address2", "address3", "city", "state", "postalCode", "country", "company", "email", "phone", "ssn", "username", "passportNumber", "licenseNumber"]);
655
+ function object(value) {
656
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
657
+ }
658
+ function bytes(value) {
659
+ return typeof TextEncoder !== "undefined" ? new TextEncoder().encode(value).byteLength : unescape(encodeURIComponent(value)).length;
660
+ }
661
+ function only(value, allowed) {
662
+ return Object.keys(value).every((key) => allowed.has(key));
663
+ }
664
+ function stringOrNull(value) {
665
+ return value === null || typeof value === "string";
666
+ }
667
+ function exactInt(value, min, max) {
668
+ const text = value instanceof LosslessNumber ? value.value : "";
669
+ return /^(0|[1-9][0-9]*)$/.test(text) && Number(text) >= min && Number(text) <= max;
670
+ }
671
+ function timestamp(value) {
672
+ return typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value);
673
+ }
674
+ function jsonDepthOk(value, maxDepth) {
675
+ const stack = [[value, 1]];
676
+ while (stack.length) {
677
+ const [node, depth] = stack.pop();
678
+ if (depth > maxDepth) return false;
679
+ const record = object(node);
680
+ const children = Array.isArray(node) ? node : record ? Object.values(record) : [];
681
+ for (const child of children) stack.push([child, depth + 1]);
682
+ }
683
+ return true;
684
+ }
685
+ function allStringsWithin(value, maxBytes) {
686
+ if (typeof value === "string") return bytes(value) <= maxBytes;
687
+ if (Array.isArray(value)) return value.every((entry) => allStringsWithin(entry, maxBytes));
688
+ const record = object(value);
689
+ return !record || Object.values(record).every((entry) => allStringsWithin(entry, maxBytes));
690
+ }
691
+ function invalid(title, ordinal, reason) {
692
+ return { ordinal, title, status: "invalid", reason };
693
+ }
694
+ function unsupported(title, ordinal, reason) {
695
+ return { ordinal, title, status: "unsupported", reason };
696
+ }
697
+ function itemRecord(item, ordinal, maxCellBytes, maxJsonDepth, folders) {
698
+ const candidateTitle = typeof item.name === "string" ? item.name : `Item ${ordinal + 1}`;
699
+ const title = bytes(candidateTitle) <= maxCellBytes ? candidateTitle : `Item ${ordinal + 1}`;
700
+ if (!only(item, itemKeys)) return unsupported(title, ordinal, "The item has an unsupported field.");
701
+ if (!isRfc4122Uuid(item.id) || typeof item.name !== "string" || !exactInt(item.type, 1, 5)) return exactInt(item.type, 0, Number.MAX_SAFE_INTEGER) ? unsupported(title, ordinal, "The item type is unsupported.") : invalid(title, ordinal, "The item shape is not supported.");
702
+ if (!["folderId", "organizationId", "notes"].every((key) => item[key] === void 0 || stringOrNull(item[key])) || ["revisionDate", "creationDate", "deletedDate"].some((key) => item[key] !== void 0 && item[key] !== null && !timestamp(item[key])) || item.folderId != null && !isRfc4122Uuid(item.folderId) || item.organizationId != null && !isRfc4122Uuid(item.organizationId) || item.collectionIds != null && (!Array.isArray(item.collectionIds) || !item.collectionIds.every(isRfc4122Uuid)) || item.favorite != null && typeof item.favorite !== "boolean" || item.reprompt != null && !exactInt(item.reprompt, 0, 1)) return invalid(title, ordinal, "The item metadata is invalid.");
703
+ if (item.fields != null && (!Array.isArray(item.fields) || !item.fields.every((field) => {
704
+ const row = object(field);
705
+ return !!row && only(row, fieldKeys) && exactInt(row.type, 0, 3) && (row.name === void 0 || stringOrNull(row.name)) && (row.value === void 0 || stringOrNull(row.value)) && (row.linkedId === void 0 || row.linkedId === null || exactInt(row.linkedId, 0, 4294967295));
706
+ }))) return invalid(title, ordinal, "The custom fields are invalid.");
707
+ if (item.passwordHistory != null && (!Array.isArray(item.passwordHistory) || !item.passwordHistory.every((entry) => {
708
+ const row = object(entry);
709
+ return !!row && Object.keys(row).length === 2 && typeof row.password === "string" && timestamp(row.lastUsedDate);
710
+ }))) return invalid(title, ordinal, "The password history is invalid.");
711
+ if (item.attachments !== void 0 && item.attachments !== null && !Array.isArray(item.attachments)) return invalid(title, ordinal, "The attachment fields are invalid.");
712
+ if (!jsonDepthOk(item, maxJsonDepth) || !allStringsWithin(item, maxCellBytes)) return invalid(title, ordinal, "The item exceeds the import limits.");
713
+ const type = Number(item.type.value);
714
+ const matching = type === 1 ? "login" : type === 2 ? "secureNote" : type === 3 ? "card" : type === 4 ? "identity" : "sshKey";
715
+ for (const component2 of ["login", "secureNote", "card", "identity", "sshKey"]) if (component2 !== matching && item[component2] != null) return unsupported(title, ordinal, "The item has an unclassified component.");
716
+ if (Array.isArray(item.attachments) && item.attachments.length) return unsupported(title, ordinal, "Attachments require a later import path.");
717
+ const sourceRecord = stringify({ source_vendor: "bitwarden", format: "bitwarden-json-export-v1", item, folders: typeof item.folderId === "string" ? folders.filter((folder) => folder.id === item.folderId) : [] }) ?? "";
718
+ if (type === 1) {
719
+ const login = object(item.login);
720
+ if (!login) return invalid(title, ordinal, "The login fields are invalid.");
721
+ if (!only(login, loginKeys)) return unsupported(title, ordinal, "The login has an unsupported field.");
722
+ if (!["username", "password", "totp"].every((key) => login[key] === void 0 || stringOrNull(login[key])) || login.uris !== void 0 && !Array.isArray(login.uris) || login.fido2Credentials !== void 0 && !Array.isArray(login.fido2Credentials)) return invalid(title, ordinal, "The login fields are invalid.");
723
+ if (Array.isArray(login.fido2Credentials) && login.fido2Credentials.length) return unsupported(title, ordinal, "Passkeys require a later import path.");
724
+ const rawUrls = [];
725
+ for (const uri of login.uris ?? []) {
726
+ const row = object(uri);
727
+ if (!row || !only(row, uriKeys)) return unsupported(title, ordinal, "The login has an unsupported URL field.");
728
+ if (row.uri !== void 0 && !stringOrNull(row.uri) || row.match !== void 0 && row.match !== null && !exactInt(row.match, 0, 5)) return invalid(title, ordinal, "The login URL fields are invalid.");
729
+ if (typeof row.uri === "string") rawUrls.push(row.uri);
730
+ }
731
+ return { ordinal, title, kind: "website_login", status: "supported", sourceState: item.deletedDate ? "deleted" : "active", sourceRecord, urls: rawUrls.map(safeDestination).flatMap((x) => x.metadata ? [x.metadata] : []), username: typeof login.username === "string" ? login.username : null, password: typeof login.password === "string" ? login.password : null, hasOtp: typeof login.totp === "string" && login.totp.length > 0 };
732
+ }
733
+ if (type === 5) {
734
+ const key = object(item.sshKey);
735
+ if (!key || !only(key, sshKeys) || typeof key.privateKey !== "string" || !key.privateKey || typeof key.publicKey !== "string" || typeof key.keyFingerprint !== "string") return invalid(title, ordinal, "The SSH key fields are invalid.");
736
+ return { ordinal, title, kind: "ssh_key", status: "supported", sourceState: item.deletedDate ? "deleted" : "active", sourceRecord, hasOtp: false, privateKey: key.privateKey, publicKey: key.publicKey };
737
+ }
738
+ const component = object(item[matching]);
739
+ const allowed = type === 2 ? noteKeys : type === 3 ? cardKeys : identityKeys;
740
+ if (!component) return invalid(title, ordinal, "The item fields are invalid.");
741
+ if (!only(component, allowed)) return unsupported(title, ordinal, "The item has an unsupported field.");
742
+ if (type === 2 && !exactInt(component.type, 0, 0)) return invalid(title, ordinal, "The secure note type is invalid.");
743
+ if (Object.entries(component).some(([key, value]) => key !== "type" && !stringOrNull(value))) return invalid(title, ordinal, "The item fields are invalid.");
744
+ return { ordinal, title, kind: "custom", status: "supported", sourceState: item.deletedDate ? "deleted" : "active", sourceRecord, hasOtp: false };
745
+ }
746
+ function parseBitwardenExport(text, limits) {
747
+ if (bytes(text) > limits.maxFileBytes) throw new Error("The file exceeds this organization\u2019s import size limit.");
748
+ let root;
749
+ try {
750
+ root = object(parse2(text)) ?? {};
751
+ } catch {
752
+ throw new Error("The JSON export has duplicate keys or could not be read safely.");
753
+ }
754
+ if (!jsonDepthOk(root, limits.maxJsonDepth) || !only(root, rootKeys) || root.encrypted !== false || !Array.isArray(root.folders) || !Array.isArray(root.items)) throw new Error(root.encrypted === true ? "Encrypted Bitwarden exports need local decryption support before they can be imported." : "This is not a supported plain Bitwarden JSON export.");
755
+ if (root.items.length > limits.maxRecords) throw new Error("The export has more records than this organization allows.");
756
+ if (!root.folders.every((folder) => {
757
+ const row = object(folder);
758
+ return !!row && only(row, folderKeys) && isRfc4122Uuid(row.id) && typeof row.name === "string" && allStringsWithin(row, limits.maxCellBytes);
759
+ })) throw new Error("The export folders are not supported.");
760
+ return root.items.map((item, ordinal) => object(item) ? itemRecord(item, ordinal, limits.maxCellBytes, limits.maxJsonDepth, root.folders) : invalid(`Item ${ordinal + 1}`, ordinal, "The item is invalid."));
761
+ }
762
+
763
+ // src/io/bitwarden-json.worker.ts
764
+ function createBitwardenJsonWorkerMessageHandler(post) {
765
+ let active;
766
+ return async (request) => {
767
+ if (request.type === "cancel") {
768
+ if (active?.requestId === request.requestId) {
769
+ active.controller.abort();
770
+ active = void 0;
771
+ }
772
+ return;
773
+ }
774
+ active?.controller.abort();
775
+ const operation = {
776
+ requestId: request.requestId,
777
+ controller: new AbortController()
778
+ };
779
+ active = operation;
780
+ try {
781
+ if (request.file.size > request.limits.maxFileBytes)
782
+ throw new Error(
783
+ "The file exceeds this organization\u2019s import size limit."
784
+ );
785
+ const bytes2 = await request.file.arrayBuffer();
786
+ if (operation.controller.signal.aborted) return;
787
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
788
+ const records = parseBitwardenExport(text, request.limits);
789
+ if (active !== operation || operation.controller.signal.aborted) return;
790
+ post({
791
+ ok: true,
792
+ requestId: request.requestId,
793
+ records,
794
+ fileNotices: []
795
+ });
796
+ } catch {
797
+ if (active !== operation || operation.controller.signal.aborted) return;
798
+ post({
799
+ ok: false,
800
+ requestId: request.requestId,
801
+ error: "The JSON export could not be read."
802
+ });
803
+ } finally {
804
+ if (active === operation) active = void 0;
805
+ }
806
+ };
807
+ }
808
+ if (typeof self !== "undefined") {
809
+ const handle = createBitwardenJsonWorkerMessageHandler(
810
+ (response) => self.postMessage(response)
811
+ );
812
+ self.onmessage = (event) => {
813
+ void handle(event.data);
814
+ };
815
+ }
816
+ export {
817
+ createBitwardenJsonWorkerMessageHandler
818
+ };
819
+ //# sourceMappingURL=bitwarden-json.worker.js.map