@delali/narsil 0.2.4-next.59 → 0.3.1-next.101

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 (165) hide show
  1. package/README.md +9 -8
  2. package/dist/adapters/filesystem.d.ts +1 -1
  3. package/dist/adapters/filesystem.mjs +1 -1
  4. package/dist/adapters/indexeddb.d.ts +1 -1
  5. package/dist/adapters/indexeddb.mjs +1 -1
  6. package/dist/adapters/memory.d.ts +1 -1
  7. package/dist/{adapters-79OIa4xm.d.ts → adapters-BQFQ4PRz.d.ts} +27 -1
  8. package/dist/browser/chunk-BDOSMEEP.mjs +493 -0
  9. package/dist/browser/chunk-EJDUFWSO.mjs +602 -0
  10. package/dist/browser/chunk-HOZW3PKP.mjs +9 -0
  11. package/dist/browser/chunk-JOVZ6HMT.mjs +4358 -0
  12. package/dist/browser/chunk-JPTQZWJQ.mjs +10 -0
  13. package/dist/browser/chunk-KPJMDPHG.mjs +24558 -0
  14. package/dist/browser/chunk-PGIM3HIM.mjs +2743 -0
  15. package/dist/browser/chunk-RHG4O77A.mjs +206 -0
  16. package/dist/browser/chunk-RIJSLY2I.mjs +360 -0
  17. package/dist/browser/durability-wiring-SRUYT3VV.mjs +3875 -0
  18. package/dist/browser/module-CBB2ETYP.mjs +3111 -0
  19. package/dist/browser/release-76MXRPGV.mjs +33 -0
  20. package/dist/browser/replace-RURXTGVG.mjs +57 -0
  21. package/dist/browser/restore-queue-EEZQO6RF.mjs +35 -0
  22. package/dist/browser/runtime-7ZAHCHWR.mjs +557 -0
  23. package/dist/browser/snapshot-OAAA5UJ7.mjs +1210 -0
  24. package/dist/browser/write-7D6VIK6O.mjs +208 -0
  25. package/dist/{capabilities-DSsOGz6F.d.ts → capabilities-DiGlB6Sr.d.ts} +68 -7
  26. package/dist/chunk-2RIRGOUL.mjs +113 -0
  27. package/dist/chunk-37CD3OKS.mjs +87 -0
  28. package/dist/chunk-44W3CBNG.mjs +7 -0
  29. package/dist/chunk-46D6JQIG.mjs +426 -0
  30. package/dist/{chunk-VMRR3DQU.mjs → chunk-5JNA5SKS.mjs} +546 -35
  31. package/dist/chunk-747OHOUA.mjs +11 -0
  32. package/dist/chunk-75XIEF6H.mjs +126 -0
  33. package/dist/chunk-7X5JST5L.mjs +114 -0
  34. package/dist/chunk-BOFBLJFZ.mjs +209 -0
  35. package/dist/{chunk-USKFU7J5.mjs → chunk-BWJVNZPR.mjs} +8 -1
  36. package/dist/chunk-C7SLA6CM.mjs +19 -0
  37. package/dist/{chunk-POWOTUKJ.mjs → chunk-CQUMNIIG.mjs} +3 -6
  38. package/dist/chunk-CVXLLEQ3.mjs +1011 -0
  39. package/dist/chunk-DJHHF2L5.mjs +17 -0
  40. package/dist/chunk-E74YLAIG.mjs +24 -0
  41. package/dist/{chunk-UXNWQZST.mjs → chunk-EMRMGYRE.mjs} +236 -18
  42. package/dist/chunk-EWZLIYHV.mjs +57 -0
  43. package/dist/chunk-GBEEG5AN.mjs +35 -0
  44. package/dist/chunk-GES7U2PM.mjs +68 -0
  45. package/dist/chunk-HJSN7UYG.mjs +10 -0
  46. package/dist/chunk-HLPRHOSO.mjs +17 -0
  47. package/dist/chunk-HMFNFVP7.mjs +14 -0
  48. package/dist/chunk-J5QP52HA.mjs +1751 -0
  49. package/dist/{chunk-YNVIUGF5.mjs → chunk-JZVARCRZ.mjs} +3 -28
  50. package/dist/chunk-KOKM4PQN.mjs +52 -0
  51. package/dist/{chunk-B2TFROFX.mjs → chunk-KWTW6VTG.mjs} +465 -250
  52. package/dist/chunk-KZ3NX2P7.mjs +21 -0
  53. package/dist/chunk-L5ORED7V.mjs +25 -0
  54. package/dist/{chunk-THYRHHO2.mjs → chunk-LGAMKHA2.mjs} +2009 -2351
  55. package/dist/chunk-LKOB5COA.mjs +117 -0
  56. package/dist/chunk-LPQOEU5M.mjs +96 -0
  57. package/dist/{chunk-3LHGNRYE.mjs → chunk-LXWDQLTW.mjs} +7 -2
  58. package/dist/{chunk-L6TNPLAR.mjs → chunk-OEYI3KRB.mjs} +270 -108
  59. package/dist/chunk-OM362BRO.mjs +948 -0
  60. package/dist/chunk-OZDFA4WC.mjs +67 -0
  61. package/dist/chunk-P36MUFEJ.mjs +10 -0
  62. package/dist/chunk-PC2G76VW.mjs +2540 -0
  63. package/dist/{chunk-GCM3JFVA.mjs → chunk-PNEYIHA4.mjs} +11 -2
  64. package/dist/chunk-PNFKUCG3.mjs +1130 -0
  65. package/dist/chunk-Q6XWVUZX.mjs +44 -0
  66. package/dist/chunk-R27EMH5M.mjs +617 -0
  67. package/dist/{chunk-YMZCMH5M.mjs → chunk-R6A773WK.mjs} +19 -24
  68. package/dist/chunk-RF7PLG43.mjs +106 -0
  69. package/dist/chunk-RFBLQLLZ.mjs +16 -0
  70. package/dist/{chunk-Y3L5MDRV.mjs → chunk-RFVUDM5E.mjs} +17 -2
  71. package/dist/chunk-S7FL6UAH.mjs +521 -0
  72. package/dist/chunk-S7GNDRPS.mjs +651 -0
  73. package/dist/chunk-SP3NM3ZG.mjs +3537 -0
  74. package/dist/chunk-U476IXKQ.mjs +10 -0
  75. package/dist/chunk-UA3AUGNV.mjs +462 -0
  76. package/dist/chunk-UTG5YNXV.mjs +507 -0
  77. package/dist/chunk-VI4R6W25.mjs +8484 -0
  78. package/dist/chunk-WQBCBKY3.mjs +8 -0
  79. package/dist/{chunk-24RXHMEL.mjs → chunk-WVCOCKBU.mjs} +3794 -7570
  80. package/dist/chunk-X5CV2E2B.mjs +1 -0
  81. package/dist/chunk-XADZPPZI.mjs +614 -0
  82. package/dist/chunk-YEEQHT4V.mjs +212 -0
  83. package/dist/chunk-YTJCGKM4.mjs +56 -0
  84. package/dist/chunk-YYQIODMF.mjs +275 -0
  85. package/dist/chunk-ZI34TVOA.mjs +144 -0
  86. package/dist/{chunk-OOSIDHA3.mjs → chunk-ZKWYWW4Y.mjs} +1 -1
  87. package/dist/chunk-ZM7KU4YW.mjs +35 -0
  88. package/dist/{client-BQK6Tf6A.d.ts → client-BOStAkc5.d.ts} +160 -37
  89. package/dist/client.d.ts +11 -10
  90. package/dist/client.mjs +209 -45
  91. package/dist/{config-DmXULPa-.d.ts → config-Cjvzbs_j.d.ts} +51 -3
  92. package/dist/config-DffQlmRq.d.ts +421 -0
  93. package/dist/direct-executor-ZD64PPEZ.mjs +24 -0
  94. package/dist/distribution/coordinator/etcd.d.ts +79 -18
  95. package/dist/distribution/coordinator/etcd.mjs +553 -109
  96. package/dist/distribution/coordinator/in-memory.d.ts +4 -3
  97. package/dist/distribution/coordinator/in-memory.mjs +22 -3
  98. package/dist/distribution/transport/grpc.d.ts +2 -2
  99. package/dist/distribution/transport/grpc.mjs +79 -14
  100. package/dist/distribution/transport/in-memory.d.ts +2 -2
  101. package/dist/distribution/transport/in-memory.mjs +12 -7
  102. package/dist/distribution/transport/tcp.d.ts +2 -2
  103. package/dist/distribution/transport/tcp.mjs +50 -28
  104. package/dist/distribution.d.ts +144 -23
  105. package/dist/distribution.mjs +14479 -8173
  106. package/dist/durability-wiring-FEUBR5BT.mjs +3330 -0
  107. package/dist/embeddings/openai.d.ts +2 -2
  108. package/dist/embeddings/openai.mjs +22 -133
  109. package/dist/{engine-CIOyFozK.d.ts → engine-rC0vjjY-.d.ts} +165 -141
  110. package/dist/{memory-yFaVn2xZ.d.ts → events-DqOIg5xa.d.ts} +645 -136
  111. package/dist/{types-DAK7mnUZ.d.ts → index-Bkdt8nDw.d.ts} +182 -45
  112. package/dist/index.browser.mjs +4 -32180
  113. package/dist/index.d.ts +91 -20
  114. package/dist/index.mjs +33 -16
  115. package/dist/invalidation/broadcast-channel.d.ts +1 -1
  116. package/dist/invalidation/filesystem.d.ts +1 -1
  117. package/dist/invalidation/filesystem.mjs +2 -1
  118. package/dist/invalidation/noop.d.ts +1 -1
  119. package/dist/module-3S65MVCM.mjs +2151 -0
  120. package/dist/partial-words-DTIHO8G4.d.ts +19 -0
  121. package/dist/partial-words.d.ts +22 -0
  122. package/dist/partial-words.mjs +17 -0
  123. package/dist/pattern-Cledccbl.d.ts +18 -0
  124. package/dist/pattern.d.ts +22 -0
  125. package/dist/pattern.mjs +12 -0
  126. package/dist/persistence/durability/checkpoint-worker.d.ts +119 -72
  127. package/dist/persistence/durability/checkpoint-worker.mjs +51 -18
  128. package/dist/react.d.ts +279 -183
  129. package/dist/react.mjs +201 -48
  130. package/dist/release-BH3DKW3T.mjs +33 -0
  131. package/dist/replace-CEO5KJJ3.mjs +57 -0
  132. package/dist/rerank-K7C4WZFG.mjs +60 -0
  133. package/dist/rerankers/http.d.ts +50 -0
  134. package/dist/rerankers/http.mjs +104 -0
  135. package/dist/restore-queue-KQHA7ZV2.mjs +35 -0
  136. package/dist/runtime-6Y4ZYXOG.mjs +177 -0
  137. package/dist/{schema-d5Afu03A.d.ts → schema-4W_7tk1f.d.ts} +81 -11
  138. package/dist/server.d.ts +13 -12
  139. package/dist/server.mjs +611 -80
  140. package/dist/snapshot-QGZPODM5.mjs +799 -0
  141. package/dist/synonyms-CpOAHPa-.d.ts +52 -0
  142. package/dist/synonyms.d.ts +22 -0
  143. package/dist/synonyms.mjs +12 -0
  144. package/dist/{tasks-CH2Dod8w.d.ts → tasks-CwPTz-tP.d.ts} +10 -3
  145. package/dist/thread-N3IUGUS3.mjs +697 -0
  146. package/dist/{types-BQDlIvfS.d.ts → types-2qoitTXg.d.ts} +1 -1
  147. package/dist/{types-D5OwhtsQ.d.ts → types-Cz5okLml.d.ts} +2 -2
  148. package/dist/vector/search-worker.d.ts +46 -4
  149. package/dist/vector/search-worker.mjs +21 -11
  150. package/dist/workers/entry.mjs +9 -6
  151. package/dist/write-U5RI7MAX.mjs +241 -0
  152. package/package.json +55 -9
  153. package/dist/chunk-3L4U6EJQ.mjs +0 -49
  154. package/dist/chunk-IFBKLBGB.mjs +0 -7
  155. package/dist/chunk-ORBLD3EL.mjs +0 -6
  156. package/dist/chunk-U7KYW4BA.mjs +0 -135
  157. package/dist/chunk-ZJ4CSAB2.mjs +0 -13
  158. package/dist/chunk-ZNZBXMP5.mjs +0 -2117
  159. package/dist/chunk-ZZT3EAUC.mjs +0 -11168
  160. package/dist/config-BhldZgaK.d.ts +0 -194
  161. package/dist/direct-executor-ALAVE7FC.mjs +0 -12
  162. package/dist/serialization/crc32-worker.d.ts +0 -20
  163. package/dist/serialization/crc32-worker.mjs +0 -62
  164. package/dist/simd-DW5AtJ6B.d.ts +0 -41
  165. package/dist/thread-DYHEQRVY.mjs +0 -402
@@ -0,0 +1,10 @@
1
+ // src/serialization/constants.ts
2
+ var CHECKSUM_YIELD_CHUNK_BYTES = 4 * 1024 * 1024;
3
+ var NATIVE_CRC32_MIN_BYTES = 16;
4
+ var MAX_FILE_BYTES = 2147483647;
5
+ var MAX_DOCUMENT_ENCODING_DEPTH = 100;
6
+ var DOCUMENT_REPLY_ENVELOPE_DEPTH = 4;
7
+ var DOCUMENT_ENCODER_RETAINED_BUFFER_BYTES = 1048576;
8
+ var VALID_HNSW_METRICS = /* @__PURE__ */ new Set(["cosine", "dotProduct", "euclidean"]);
9
+
10
+ export { CHECKSUM_YIELD_CHUNK_BYTES, DOCUMENT_ENCODER_RETAINED_BUFFER_BYTES, DOCUMENT_REPLY_ENVELOPE_DEPTH, MAX_DOCUMENT_ENCODING_DEPTH, MAX_FILE_BYTES, NATIVE_CRC32_MIN_BYTES, VALID_HNSW_METRICS };
@@ -0,0 +1,462 @@
1
+ import { vectorsPerFile } from './chunk-S7GNDRPS.mjs';
2
+ import { writeLiveVectors, decodeSegmentManifest, openManifestPayload, listedKeysOf, decodeManifestPayload, SINGLE_NODE_PRIMARY_TERM } from './chunk-PNFKUCG3.mjs';
3
+ import { vectorsToBytes, VECTOR_FILE_PAYLOAD_VERSION } from './chunk-YYQIODMF.mjs';
4
+ import { writeCheckpointSegments, DEFAULT_COMPACTION_THRESHOLD, commitCheckpointManifest, manifestKey, manifestFileRefs, partitionContentsOf } from './chunk-J5QP52HA.mjs';
5
+ import { HEADER_SIZE } from './chunk-WVCOCKBU.mjs';
6
+ import { MAX_FILE_BYTES } from './chunk-U476IXKQ.mjs';
7
+ import { NarsilError, ErrorCodes } from './chunk-BWJVNZPR.mjs';
8
+
9
+ // src/persistence/archive/memory-store.ts
10
+ function joined(chunks) {
11
+ let total = 0;
12
+ for (const chunk of chunks) total += chunk.byteLength;
13
+ const bytes = new Uint8Array(total);
14
+ let offset = 0;
15
+ for (const chunk of chunks) {
16
+ bytes.set(chunk, offset);
17
+ offset += chunk.byteLength;
18
+ }
19
+ return bytes;
20
+ }
21
+ function memoryCheckpointStore() {
22
+ const files = /* @__PURE__ */ new Map();
23
+ return {
24
+ files,
25
+ read: async (key) => files.get(key) ?? null,
26
+ write: async (key, chunks) => {
27
+ files.set(key, joined(chunks));
28
+ },
29
+ remove: async (key) => {
30
+ files.delete(key);
31
+ },
32
+ list: async (prefix) => [...files.keys()].filter((key) => key.startsWith(prefix)).sort(),
33
+ byteLength: async (key) => files.get(key)?.byteLength ?? null
34
+ };
35
+ }
36
+
37
+ // src/persistence/archive/from-memory.ts
38
+ function frozenPlan(plan) {
39
+ const files = [];
40
+ for (let index = 0; index < plan.newFiles; index++) files.push(plan.readNewFile(index));
41
+ return { ...plan, readNewFile: (index) => files[index] };
42
+ }
43
+ function partitionVectorPlan(vectorIndex, docIds) {
44
+ const held = [];
45
+ const vectors = [];
46
+ for (const docId of docIds) {
47
+ const vector = vectorIndex.getVector(docId);
48
+ if (vector === null) continue;
49
+ held.push(docId);
50
+ vectors.push(Float32Array.from(vector));
51
+ }
52
+ const capacity = vectorsPerFile(vectorIndex.dimension, null);
53
+ const files = [];
54
+ for (let start = 0; start < held.length; start += capacity) {
55
+ const slice = held.slice(start, start + capacity);
56
+ const packed = new Float32Array(slice.length * vectorIndex.dimension);
57
+ for (let i = 0; i < slice.length; i++) packed.set(vectors[start + i], i * vectorIndex.dimension);
58
+ const payload = {
59
+ v: VECTOR_FILE_PAYLOAD_VERSION,
60
+ fieldName: vectorIndex.fieldName,
61
+ dimension: vectorIndex.dimension,
62
+ docIds: slice,
63
+ codes: null,
64
+ vectors: vectorsToBytes(packed)
65
+ };
66
+ files.push({ payload, ordinals: new Int32Array(slice.length), dead: null });
67
+ }
68
+ return {
69
+ unchanged: false,
70
+ kept: [],
71
+ keptFiles: [],
72
+ newFiles: files.length,
73
+ graphParts: null,
74
+ signature: { revision: 0, graphSize: -1, calibration: null },
75
+ readNewFile: (index) => files[index]
76
+ };
77
+ }
78
+ function capture(input) {
79
+ const partitionIds = input.partitionId === null ? Array.from({ length: input.manager.partitionCount }, (_, partitionId) => partitionId) : [input.partitionId];
80
+ const targets = partitionIds.map((partitionId) => ({
81
+ partitionId,
82
+ lastSeqNo: input.appliedSeqNo(partitionId),
83
+ primaryTerm: SINGLE_NODE_PRIMARY_TERM
84
+ }));
85
+ const contents = partitionIds.map((partitionId) => partitionContentsOf(input.manager, partitionId));
86
+ const plans = /* @__PURE__ */ new Map();
87
+ const partitionDocIds = input.partitionId === null ? null : [...input.manager.getPartition(input.partitionId).docIds()];
88
+ for (const [fieldPath, vectorIndex] of input.vectorIndexes) {
89
+ plans.set(
90
+ fieldPath,
91
+ partitionDocIds === null ? frozenPlan(vectorIndex.planCheckpoint(null)) : partitionVectorPlan(vectorIndex, partitionDocIds)
92
+ );
93
+ }
94
+ return { targets, contents, plans };
95
+ }
96
+ async function buildArchiveFromMemory(input) {
97
+ if (input.partitionId === null) {
98
+ for (const vectorIndex of input.vectorIndexes.values()) await vectorIndex.completeGraph();
99
+ }
100
+ const captured = capture(input);
101
+ const store = memoryCheckpointStore();
102
+ const written = await writeCheckpointSegments({
103
+ store,
104
+ metadata: input.metadata,
105
+ targets: captured.targets,
106
+ compactionThreshold: DEFAULT_COMPACTION_THRESHOLD,
107
+ prior: null,
108
+ wholePartitions: captured.contents
109
+ });
110
+ const vectors = await writeLiveVectors({ store, indexName: input.indexName, plans: captured.plans, priorVectors: [] });
111
+ const refs = vectors.refs;
112
+ await commitCheckpointManifest(store, input.metadata, written, refs);
113
+ const manifestBytes = store.files.get(manifestKey(input.indexName));
114
+ const decoded = manifestBytes === void 0 ? null : await decodeSegmentManifest(manifestBytes, input.indexName);
115
+ if (manifestBytes === void 0 || decoded === null || decoded.kind !== "current") {
116
+ throw new NarsilError(
117
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
118
+ `The archive of index "${input.indexName}" holds no manifest`
119
+ );
120
+ }
121
+ return {
122
+ manifestBytes,
123
+ manifest: decoded.manifest,
124
+ readFile: async (ref) => {
125
+ const bytes = store.files.get(ref.key);
126
+ if (bytes === void 0) {
127
+ throw new NarsilError(ErrorCodes.PERSISTENCE_SAVE_FAILED, `The archive file "${ref.key}" is missing`, {
128
+ key: ref.key
129
+ });
130
+ }
131
+ return bytes;
132
+ },
133
+ readRange: async (ref, offset, length) => {
134
+ const bytes = store.files.get(ref.key);
135
+ if (bytes === void 0 || offset + length > bytes.byteLength) {
136
+ throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `The archive file "${ref.key}" is missing`, {
137
+ key: ref.key
138
+ });
139
+ }
140
+ return bytes.subarray(offset, offset + length);
141
+ },
142
+ release: () => store.files.clear()
143
+ };
144
+ }
145
+
146
+ // src/persistence/archive/constants.ts
147
+ var MAX_PAX_HEADER_BYTES = 65536;
148
+
149
+ // src/persistence/archive/tar.ts
150
+ var TAR_BLOCK_BYTES = 512;
151
+ var NAME_OFFSET = 0;
152
+ var NAME_BYTES = 100;
153
+ var MODE_OFFSET = 100;
154
+ var OWNER_OFFSET = 108;
155
+ var GROUP_OFFSET = 116;
156
+ var ID_FIELD_BYTES = 8;
157
+ var SIZE_OFFSET = 124;
158
+ var SIZE_FIELD_BYTES = 12;
159
+ var SIZE_FIELD_DIGITS = 11;
160
+ var MTIME_OFFSET = 136;
161
+ var MTIME_FIELD_BYTES = 12;
162
+ var CHECKSUM_FIELD_OFFSET = 148;
163
+ var CHECKSUM_FIELD_BYTES = 8;
164
+ var CHECKSUM_DIGITS = 6;
165
+ var TYPEFLAG_OFFSET = 156;
166
+ var MAGIC_OFFSET = 257;
167
+ var MAGIC_BYTES = 6;
168
+ var VERSION_OFFSET = 263;
169
+ var VERSION_BYTES = 2;
170
+ var PREFIX_OFFSET = 345;
171
+ var PREFIX_BYTES = 155;
172
+ var MODE_OCTAL = "0000644";
173
+ var ZERO_OCTAL_7 = "0000000";
174
+ var ZERO_OCTAL_11 = "00000000000";
175
+ var REGULAR_FILE = 48;
176
+ var OLD_REGULAR_FILE = 0;
177
+ var PAX_EXTENDED_HEADER = 120;
178
+ var PAX_HEADER_NAME = "PaxHeader";
179
+ var encoder = new TextEncoder();
180
+ var decoder = new TextDecoder("utf-8", { fatal: true });
181
+ function writeString(block, offset, length, value) {
182
+ const bytes = encoder.encode(value);
183
+ block.set(bytes.subarray(0, length), offset);
184
+ }
185
+ function writeOctal(block, offset, digits, value) {
186
+ writeString(block, offset, digits, value.toString(8).padStart(digits, "0"));
187
+ }
188
+ function headerChecksum(block) {
189
+ let sum = 0;
190
+ const checksumEnd = CHECKSUM_FIELD_OFFSET + CHECKSUM_FIELD_BYTES;
191
+ for (let at = 0; at < TAR_BLOCK_BYTES; at++) {
192
+ sum += at >= CHECKSUM_FIELD_OFFSET && at < checksumEnd ? 32 : block[at];
193
+ }
194
+ return sum;
195
+ }
196
+ function ustarBlock(name, prefix, size, typeflag) {
197
+ const block = new Uint8Array(TAR_BLOCK_BYTES);
198
+ writeString(block, NAME_OFFSET, NAME_BYTES, name);
199
+ writeString(block, MODE_OFFSET, ID_FIELD_BYTES, MODE_OCTAL);
200
+ writeString(block, OWNER_OFFSET, ID_FIELD_BYTES, ZERO_OCTAL_7);
201
+ writeString(block, GROUP_OFFSET, ID_FIELD_BYTES, ZERO_OCTAL_7);
202
+ writeOctal(block, SIZE_OFFSET, SIZE_FIELD_DIGITS, size);
203
+ writeString(block, MTIME_OFFSET, MTIME_FIELD_BYTES, ZERO_OCTAL_11);
204
+ block[TYPEFLAG_OFFSET] = typeflag;
205
+ writeString(block, MAGIC_OFFSET, MAGIC_BYTES, "ustar");
206
+ writeString(block, VERSION_OFFSET, VERSION_BYTES, "00");
207
+ writeString(block, PREFIX_OFFSET, PREFIX_BYTES, prefix);
208
+ const checksum = headerChecksum(block);
209
+ writeString(block, CHECKSUM_FIELD_OFFSET, CHECKSUM_DIGITS, checksum.toString(8).padStart(CHECKSUM_DIGITS, "0"));
210
+ block[CHECKSUM_FIELD_OFFSET + CHECKSUM_DIGITS] = 0;
211
+ block[CHECKSUM_FIELD_OFFSET + CHECKSUM_DIGITS + 1] = 32;
212
+ return block;
213
+ }
214
+ function splitForUstar(name) {
215
+ if (encoder.encode(name).byteLength <= NAME_BYTES) return { name, prefix: "" };
216
+ for (let slash = name.indexOf("/"); slash >= 0; slash = name.indexOf("/", slash + 1)) {
217
+ const prefix = name.slice(0, slash);
218
+ const rest = name.slice(slash + 1);
219
+ if (encoder.encode(prefix).byteLength <= PREFIX_BYTES && encoder.encode(rest).byteLength <= NAME_BYTES) {
220
+ return { name: rest, prefix };
221
+ }
222
+ }
223
+ return null;
224
+ }
225
+ function paxRecord(key, value) {
226
+ const body = ` ${key}=${value}
227
+ `;
228
+ const bodyBytes = encoder.encode(body).byteLength;
229
+ let digits = 1;
230
+ while (String(bodyBytes + digits).length !== digits) digits += 1;
231
+ return `${bodyBytes + digits}${body}`;
232
+ }
233
+ function tarPadding(size) {
234
+ const remainder = size % TAR_BLOCK_BYTES;
235
+ return new Uint8Array(remainder === 0 ? 0 : TAR_BLOCK_BYTES - remainder);
236
+ }
237
+ function tarEntryHeaders(name, size) {
238
+ const split = splitForUstar(name);
239
+ if (split !== null) return [ustarBlock(split.name, split.prefix, size, REGULAR_FILE)];
240
+ const record = encoder.encode(paxRecord("path", name));
241
+ return [
242
+ ustarBlock(PAX_HEADER_NAME, "", record.byteLength, PAX_EXTENDED_HEADER),
243
+ record,
244
+ tarPadding(record.byteLength),
245
+ ustarBlock(name.slice(-NAME_BYTES).replace(/^[^/]*\//, ""), "", size, REGULAR_FILE)
246
+ ];
247
+ }
248
+ function tarEnd() {
249
+ return new Uint8Array(TAR_BLOCK_BYTES * 2);
250
+ }
251
+ function invalidArchive(message, details) {
252
+ throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `Invalid snapshot archive: ${message}`, details);
253
+ }
254
+ function readString(block, offset, length) {
255
+ let end = offset;
256
+ while (end < offset + length && block[end] !== 0) end++;
257
+ try {
258
+ return decoder.decode(block.subarray(offset, end));
259
+ } catch {
260
+ invalidArchive("an entry header holds a name that is not UTF-8");
261
+ }
262
+ }
263
+ function readOctal(block, offset, length, what) {
264
+ const text = readString(block, offset, length).trim();
265
+ if (!/^[0-7]+$/.test(text)) invalidArchive(`an entry header holds an invalid ${what}`);
266
+ const value = Number.parseInt(text, 8);
267
+ if (!Number.isSafeInteger(value)) invalidArchive(`an entry header holds an invalid ${what}`);
268
+ return value;
269
+ }
270
+ function isZeroBlock(block) {
271
+ for (let at = 0; at < block.length; at++) if (block[at] !== 0) return false;
272
+ return true;
273
+ }
274
+ function parseTarHeader(block) {
275
+ if (readOctal(block, CHECKSUM_FIELD_OFFSET, CHECKSUM_FIELD_BYTES, "checksum") !== headerChecksum(block)) {
276
+ invalidArchive("an entry header fails its checksum");
277
+ }
278
+ const typeflag = block[TYPEFLAG_OFFSET];
279
+ if (typeflag !== REGULAR_FILE && typeflag !== OLD_REGULAR_FILE && typeflag !== PAX_EXTENDED_HEADER) {
280
+ invalidArchive(`an entry has type ${String.fromCharCode(typeflag)}, while an archive holds regular files alone`);
281
+ }
282
+ const name = readString(block, NAME_OFFSET, NAME_BYTES);
283
+ const prefix = readString(block, PREFIX_OFFSET, PREFIX_BYTES);
284
+ return {
285
+ name: prefix.length > 0 ? `${prefix}/${name}` : name,
286
+ size: readOctal(block, SIZE_OFFSET, SIZE_FIELD_BYTES, "size"),
287
+ isPaxHeader: typeflag === PAX_EXTENDED_HEADER
288
+ };
289
+ }
290
+ var SPACE = 32;
291
+ var EQUALS = 61;
292
+ var NEWLINE = 10;
293
+ function decodeRecordText(bytes) {
294
+ try {
295
+ return decoder.decode(bytes);
296
+ } catch {
297
+ invalidArchive("a pax extended header is not UTF-8");
298
+ }
299
+ }
300
+ function parsePaxRecords(body) {
301
+ const records = /* @__PURE__ */ new Map();
302
+ let at = 0;
303
+ while (at < body.length) {
304
+ const space = body.indexOf(SPACE, at);
305
+ if (space < 0) invalidArchive("a pax extended header holds a malformed record");
306
+ const length = Number.parseInt(decodeRecordText(body.subarray(at, space)), 10);
307
+ if (!Number.isSafeInteger(length) || length <= space - at || at + length > body.length) {
308
+ invalidArchive("a pax extended header holds a malformed record");
309
+ }
310
+ const record = body.subarray(space + 1, at + length);
311
+ const equals = record.indexOf(EQUALS);
312
+ if (equals < 0 || record[record.length - 1] !== NEWLINE) {
313
+ invalidArchive("a pax extended header holds a record without a value");
314
+ }
315
+ records.set(decodeRecordText(record.subarray(0, equals)), decodeRecordText(record.subarray(equals + 1, -1)));
316
+ at += length;
317
+ }
318
+ return records;
319
+ }
320
+
321
+ // src/persistence/archive/read.ts
322
+ var ARCHIVE_CONFIG_ENTRY = "config";
323
+ var ARCHIVE_MANIFEST_ENTRY = "manifest";
324
+ var SEGMENTS_MARKER = "/segments/";
325
+ var CHECKSUM_OFFSET = 14;
326
+ async function readBlock(reader) {
327
+ const block = await reader.readExactly(TAR_BLOCK_BYTES);
328
+ if (block === null) return null;
329
+ if (block.byteLength < TAR_BLOCK_BYTES) invalidArchive("the archive ends inside an entry header");
330
+ return block;
331
+ }
332
+ async function readPadded(reader, size) {
333
+ const body = await reader.readExactly(size) ?? new Uint8Array(0);
334
+ if (body.byteLength < size) invalidArchive("the archive ends inside an entry");
335
+ const remainder = size % TAR_BLOCK_BYTES;
336
+ if (remainder !== 0) {
337
+ const padding = await reader.readExactly(TAR_BLOCK_BYTES - remainder);
338
+ if (padding === null || padding.byteLength < TAR_BLOCK_BYTES - remainder) {
339
+ invalidArchive("the archive ends inside the padding of an entry");
340
+ }
341
+ }
342
+ return body;
343
+ }
344
+ async function nextEntryHeader(reader) {
345
+ const block = await readBlock(reader);
346
+ if (block === null || isZeroBlock(block)) return null;
347
+ const header = parseTarHeader(block);
348
+ if (!header.isPaxHeader) return { name: header.name, size: header.size };
349
+ if (header.size > MAX_PAX_HEADER_BYTES) invalidArchive("a pax extended header is too long");
350
+ const records = parsePaxRecords(await readPadded(reader, header.size));
351
+ const next = await readBlock(reader);
352
+ if (next === null || isZeroBlock(next)) invalidArchive("a pax extended header precedes no entry");
353
+ const entry = parseTarHeader(next);
354
+ if (entry.isPaxHeader) invalidArchive("a pax extended header follows another");
355
+ const path = records.get("path");
356
+ const size = records.get("size");
357
+ const parsedSize = size === void 0 ? entry.size : Number.parseInt(size, 10);
358
+ if (!Number.isSafeInteger(parsedSize) || parsedSize < 0) invalidArchive("a pax extended header holds an invalid size");
359
+ return { name: path ?? entry.name, size: parsedSize };
360
+ }
361
+ async function readNamedEntry(reader, expected) {
362
+ const header = await nextEntryHeader(reader);
363
+ if (header === null) invalidArchive(`the archive ends before its ${expected} entry`);
364
+ if (header.name !== expected) invalidArchive(`the archive holds "${header.name}" where its ${expected} entry belongs`);
365
+ if (header.size > MAX_FILE_BYTES) invalidArchive(`the ${expected} entry passes the file size limit`);
366
+ return readPadded(reader, header.size);
367
+ }
368
+ function sourceIndexNameOf(keys) {
369
+ const first = keys[0];
370
+ if (first === void 0) return "archive";
371
+ const at = first.indexOf(SEGMENTS_MARKER);
372
+ if (at <= 0) invalidArchive(`the manifest lists the key "${first}" outside any index`);
373
+ return first.slice(0, at);
374
+ }
375
+ function headerChecksumOf(bytes) {
376
+ if (bytes.byteLength < HEADER_SIZE) return -1;
377
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(CHECKSUM_OFFSET, false);
378
+ }
379
+ async function readSnapshotArchive(reader, handlers) {
380
+ await handlers.config(await readNamedEntry(reader, ARCHIVE_CONFIG_ENTRY));
381
+ const raw = await openManifestPayload(await readNamedEntry(reader, ARCHIVE_MANIFEST_ENTRY));
382
+ const sourceIndexName = sourceIndexNameOf(listedKeysOf(raw));
383
+ const decoded = decodeManifestPayload(raw, sourceIndexName);
384
+ if (decoded.kind !== "current") invalidArchive("the manifest holds the layout of an earlier release");
385
+ const manifest = decoded.manifest;
386
+ await handlers.manifest(manifest, sourceIndexName);
387
+ const files = manifestFileRefs(manifest);
388
+ const prefix = `${sourceIndexName}/`;
389
+ const listedNames = new Set(files.map((file) => file.key.slice(prefix.length)));
390
+ const seen = /* @__PURE__ */ new Set();
391
+ for (const ref of files) {
392
+ const expected = ref.key.slice(prefix.length);
393
+ const header = await nextEntryHeader(reader);
394
+ if (header === null) invalidArchive(`the archive ends before it holds "${expected}"`);
395
+ if (header.name !== expected) {
396
+ const why = !listedNames.has(header.name) ? "that the manifest does not list" : seen.has(header.name) ? "twice" : "out of order";
397
+ invalidArchive(`the archive holds the entry "${header.name}" ${why}`, { entry: header.name });
398
+ }
399
+ if (header.size !== ref.bytes) {
400
+ invalidArchive(`the entry "${expected}" holds ${header.size} bytes where the manifest lists ${ref.bytes}`);
401
+ }
402
+ const bytes = await readPadded(reader, header.size);
403
+ if (headerChecksumOf(bytes) !== ref.checksum) {
404
+ invalidArchive(`the entry "${expected}" carries a checksum other than the manifest lists`, { entry: expected });
405
+ }
406
+ seen.add(expected);
407
+ await handlers.file(expected, ref, bytes);
408
+ }
409
+ const trailing = await nextEntryHeader(reader);
410
+ if (trailing !== null) {
411
+ invalidArchive(`the archive holds the entry "${trailing.name}" that the manifest does not list`, {
412
+ entry: trailing.name
413
+ });
414
+ }
415
+ }
416
+
417
+ // src/persistence/archive/write.ts
418
+ function entryChunks(name, bytes) {
419
+ return [...tarEntryHeaders(name, bytes.byteLength), bytes, tarPadding(bytes.byteLength)].filter(
420
+ (chunk) => chunk.byteLength > 0
421
+ );
422
+ }
423
+ async function* archiveChunks(source) {
424
+ yield* entryChunks(ARCHIVE_CONFIG_ENTRY, source.config);
425
+ yield* entryChunks(ARCHIVE_MANIFEST_ENTRY, source.manifestBytes);
426
+ const prefix = `${source.sourceIndexName}/`;
427
+ for (const ref of manifestFileRefs(source.manifest)) {
428
+ yield* entryChunks(ref.key.slice(prefix.length), await source.readFile(ref));
429
+ }
430
+ yield tarEnd();
431
+ }
432
+ function archiveStream(source) {
433
+ const chunks = archiveChunks(source);
434
+ let released = false;
435
+ const release = () => {
436
+ if (released) return;
437
+ released = true;
438
+ source.release();
439
+ };
440
+ return new ReadableStream({
441
+ async pull(controller) {
442
+ try {
443
+ const step = await chunks.next();
444
+ if (step.done) {
445
+ release();
446
+ controller.close();
447
+ return;
448
+ }
449
+ controller.enqueue(step.value);
450
+ } catch (error) {
451
+ release();
452
+ controller.error(error);
453
+ }
454
+ },
455
+ async cancel() {
456
+ release();
457
+ await chunks.return(void 0);
458
+ }
459
+ });
460
+ }
461
+
462
+ export { archiveStream, buildArchiveFromMemory, memoryCheckpointStore, readSnapshotArchive };