@wazootech/worlds-sdk 0.0.0-stage → 0.11.3

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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +288 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/dist/ai-sdk.d.ts +27 -0
  5. package/dist/ai-sdk.js +28 -0
  6. package/dist/build-search-result-id-qxdmXp0V.js +12 -0
  7. package/dist/chunk-and-embed-0crm0xLl.js +75 -0
  8. package/dist/client-BJ45zmXU.d.ts +74 -0
  9. package/dist/client-BWh0UAM0.js +45 -0
  10. package/dist/embedding-service-DebRMVmn.d.ts +15 -0
  11. package/dist/embedding-service.d.ts +3 -0
  12. package/dist/embedding-service.js +19 -0
  13. package/dist/index.d.ts +8 -0
  14. package/dist/index.js +9 -0
  15. package/dist/memory.d.ts +26 -0
  16. package/dist/memory.js +29 -0
  17. package/dist/mod-8Zh1f9vW.d.ts +24 -0
  18. package/dist/mod-BuF_B_xU.d.ts +362 -0
  19. package/dist/mod-CHiiyEER.d.ts +79 -0
  20. package/dist/mod-ClDFMN-C.d.ts +625 -0
  21. package/dist/mod-Dmrdrb03.d.ts +13 -0
  22. package/dist/quad-chunker.d.ts +2 -0
  23. package/dist/quad-chunker.js +1 -0
  24. package/dist/quad-store-BGCOUBxK.js +851 -0
  25. package/dist/quad-store.d.ts +2 -0
  26. package/dist/quad-store.js +3 -0
  27. package/dist/rdf-formats-BkGt5RDB.js +93 -0
  28. package/dist/rdfjs-BNVjLSNL.js +190 -0
  29. package/dist/rdfjs.d.ts +79 -0
  30. package/dist/rdfjs.js +1 -0
  31. package/dist/search-index.d.ts +2 -0
  32. package/dist/search-index.js +219 -0
  33. package/dist/sparql-engine.d.ts +2 -0
  34. package/dist/sparql-engine.js +0 -0
  35. package/dist/testing.d.ts +301 -0
  36. package/dist/testing.js +786 -0
  37. package/dist/tfjs-use.d.ts +42 -0
  38. package/dist/tfjs-use.js +315 -0
  39. package/dist/wazoo.d.ts +86 -0
  40. package/dist/wazoo.js +347 -0
  41. package/package.json +119 -4
@@ -0,0 +1,851 @@
1
+ import { i as exportQuadsResponse, o as materializeImportQuads, r as collectQuadsFromStream } from "./rdf-formats-BkGt5RDB.js";
2
+ import { sha256Hex } from "@wazootech/sparql-engine/term";
3
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
4
+ import { EventEmitter } from "node:events";
5
+ // src/client/quad-store/provenance/in-memory-provenance-store.ts
6
+ /**
7
+ * InMemoryProvenanceStore is an append-only provenance store. Records are
8
+ * never mutated or deleted; indexes over quadId and supersedesQuadId keep
9
+ * list and history walks off linear scans.
10
+ */
11
+ var InMemoryProvenanceStore = class {
12
+ records = [];
13
+ byQuadId = /* @__PURE__ */ new Map();
14
+ bySupersedes = /* @__PURE__ */ new Map();
15
+ record(input) {
16
+ const record = {
17
+ ...input,
18
+ recordedAt: input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString()
19
+ };
20
+ this.records.push(record);
21
+ appendToIndex(this.byQuadId, record.quadId, record);
22
+ if (record.supersedesQuadId) appendToIndex(this.bySupersedes, record.supersedesQuadId, record);
23
+ return Promise.resolve(record);
24
+ }
25
+ list(query) {
26
+ let matches;
27
+ if (query?.quadId !== void 0) matches = this.byQuadId.get(query.quadId) ?? [];
28
+ else matches = this.records;
29
+ const filtered = query?.type !== void 0 ? matches.filter((record) => (record.type ?? "write") === query.type) : matches;
30
+ return Promise.resolve([...filtered]);
31
+ }
32
+ history(quadId) {
33
+ return Promise.resolve({
34
+ quadId,
35
+ supersedes: this.walkAncestors(quadId),
36
+ supersededBy: this.walkDescendants(quadId)
37
+ });
38
+ }
39
+ walkAncestors(quadId) {
40
+ const ancestorIds = /* @__PURE__ */ new Set();
41
+ const visited = /* @__PURE__ */ new Set([quadId]);
42
+ const queue = [quadId];
43
+ while (queue.length > 0) {
44
+ const current = queue.shift();
45
+ for (const record of this.byQuadId.get(current) ?? []) {
46
+ const previous = record.supersedesQuadId;
47
+ if (!previous || visited.has(previous)) continue;
48
+ visited.add(previous);
49
+ ancestorIds.add(previous);
50
+ queue.push(previous);
51
+ }
52
+ }
53
+ const latest = /* @__PURE__ */ new Map();
54
+ for (const id of ancestorIds) for (const record of this.byQuadId.get(id) ?? []) latest.set(id, record);
55
+ return [...latest.values()];
56
+ }
57
+ walkDescendants(quadId) {
58
+ const chain = [];
59
+ const visited = /* @__PURE__ */ new Set([quadId]);
60
+ const queue = [quadId];
61
+ while (queue.length > 0) {
62
+ const current = queue.shift();
63
+ for (const record of this.bySupersedes.get(current) ?? []) {
64
+ if (visited.has(record.quadId)) continue;
65
+ visited.add(record.quadId);
66
+ chain.push(record);
67
+ queue.push(record.quadId);
68
+ }
69
+ }
70
+ return chain;
71
+ }
72
+ };
73
+ function appendToIndex(index, key, record) {
74
+ const bucket = index.get(key);
75
+ if (bucket) bucket.push(record);
76
+ else index.set(key, [record]);
77
+ }
78
+ // src/client/quad-store/transaction-context.ts
79
+ /**
80
+ * isImportCommit returns true when commit context carries bulk import semantics.
81
+ */
82
+ function isImportCommit(context) {
83
+ return context?.importMode !== void 0;
84
+ }
85
+ /**
86
+ * isReplaceImportCommit returns true when commit context requests replace import semantics.
87
+ */
88
+ function isReplaceImportCommit(context) {
89
+ return context?.importMode === "replace";
90
+ }
91
+ /**
92
+ * deduplicateBuffers removes quads that appear in both insert and delete buffers.
93
+ */
94
+ function deduplicateBuffers(insertBuffer, deleteBuffer) {
95
+ const removeFromInsert = [];
96
+ for (let insertIndex = insertBuffer.length - 1; insertIndex >= 0; insertIndex--) for (let deleteIndex = deleteBuffer.length - 1; deleteIndex >= 0; deleteIndex--) if (insertBuffer[insertIndex].equals(deleteBuffer[deleteIndex])) {
97
+ removeFromInsert.push(insertIndex);
98
+ deleteBuffer.splice(deleteIndex, 1);
99
+ break;
100
+ }
101
+ for (const insertIndex of removeFromInsert) insertBuffer.splice(insertIndex, 1);
102
+ }
103
+ // src/client/quad-store/quad-filter.ts
104
+ /**
105
+ * filterQuads compiles nested, declarative boundary conditions into a highly optimized, pre-compiled O(1) evaluation predicate.
106
+ *
107
+ * @param filter Optional declarative boundaries to evaluate.
108
+ * @returns A high-performance closure predicate compatible with Array.prototype.filter.
109
+ */
110
+ function filterQuads(filter) {
111
+ if (!filter) return () => true;
112
+ const { include, exclude } = filter;
113
+ const includeSubjects = include?.subjects?.length ? new Set(include.subjects) : null;
114
+ const includePredicates = include?.predicates?.length ? new Set(include.predicates) : null;
115
+ const includeGraphs = include?.graphs?.length ? new Set(include.graphs) : null;
116
+ const excludeSubjects = exclude?.subjects?.length ? new Set(exclude.subjects) : null;
117
+ const excludePredicates = exclude?.predicates?.length ? new Set(exclude.predicates) : null;
118
+ const excludeGraphs = exclude?.graphs?.length ? new Set(exclude.graphs) : null;
119
+ if (!includeSubjects && !includePredicates && !includeGraphs && !excludeSubjects && !excludePredicates && !excludeGraphs) return () => true;
120
+ return (quad) => {
121
+ if (includeSubjects && !includeSubjects.has(quad.subject.value)) return false;
122
+ if (includePredicates && !includePredicates.has(quad.predicate.value)) return false;
123
+ if (includeGraphs && !includeGraphs.has(quad.graph.value)) return false;
124
+ if (excludeSubjects && excludeSubjects.has(quad.subject.value)) return false;
125
+ if (excludePredicates && excludePredicates.has(quad.predicate.value)) return false;
126
+ if (excludeGraphs && excludeGraphs.has(quad.graph.value)) return false;
127
+ return true;
128
+ };
129
+ }
130
+ // src/client/quad-store/is-textual-literal.ts
131
+ const XSD_STRING$2 = "http://www.w3.org/2001/XMLSchema#string";
132
+ const RDF_LANGSTRING = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";
133
+ /**
134
+ * isTextualLiteral evaluates whether an RDF Term is a physical textual string.
135
+ * It returns true for untyped, xsd:string, and rdf:langString literals, and
136
+ * explicitly rejects structured numeric, boolean, or temporal data primitives.
137
+ *
138
+ * @param term The candidate RDF node.
139
+ * @returns boolean True if physical termType matches canonical string boundaries.
140
+ */
141
+ function isTextualLiteral(term) {
142
+ if (term.termType !== "Literal") return false;
143
+ const datatype = term.datatype?.value;
144
+ return !datatype || datatype === XSD_STRING$2 || datatype === RDF_LANGSTRING;
145
+ }
146
+ // node_modules/@std/encoding/_common16.js
147
+ const alphabet$3 = new TextEncoder().encode("0123456789abcdef");
148
+ const rAlphabet$3 = (/* @__PURE__ */ new Uint8Array(128)).fill(16);
149
+ alphabet$3.forEach((byte, i) => rAlphabet$3[byte] = i);
150
+ new TextEncoder().encode("ABCDEF").forEach((byte, i) => rAlphabet$3[byte] = i + 10);
151
+ function decode(buffer, i, o, alphabet) {
152
+ if ((buffer.length - o) % 2 === 1) throw new RangeError(`Cannot decode input as hex: Length (${buffer.length - o}) must be divisible by 2`);
153
+ i += 1;
154
+ for (; i < buffer.length; i += 2) buffer[o++] = getByte(buffer[i - 1], alphabet) << 4 | getByte(buffer[i], alphabet);
155
+ return o;
156
+ }
157
+ function getByte(char, alphabet) {
158
+ const byte = alphabet[char] ?? 16;
159
+ if (byte === 16) throw new TypeError(`Cannot decode input as hex: Invalid character (${String.fromCharCode(char)})`);
160
+ return byte;
161
+ }
162
+ // node_modules/@std/encoding/_common_detach.js
163
+ function detach(buffer, maxSize) {
164
+ const originalSize = buffer.length;
165
+ if (buffer.byteOffset) {
166
+ const b = new Uint8Array(buffer.buffer);
167
+ b.set(buffer);
168
+ buffer = b.subarray(0, originalSize);
169
+ }
170
+ buffer = new Uint8Array(buffer.buffer.transfer(maxSize));
171
+ buffer.set(buffer.subarray(0, originalSize), maxSize - originalSize);
172
+ return [buffer, maxSize - originalSize];
173
+ }
174
+ // node_modules/@std/encoding/hex.js
175
+ /**
176
+ * Port of the Go
177
+ * {@link https://github.com/golang/go/blob/go1.12.5/src/encoding/hex/hex.go | encoding/hex}
178
+ * library.
179
+ *
180
+ * ```ts
181
+ * import {
182
+ * decodeHex,
183
+ * encodeHex,
184
+ * } from "@std/encoding/hex";
185
+ * import { assertEquals } from "@std/assert";
186
+ *
187
+ * assertEquals(encodeHex("abc"), "616263");
188
+ *
189
+ * assertEquals(
190
+ * decodeHex("616263"),
191
+ * new TextEncoder().encode("abc"),
192
+ * );
193
+ * ```
194
+ *
195
+ * @module
196
+ */ const alphabet$2 = new TextEncoder().encode("0123456789abcdef");
197
+ const rAlphabet$2 = (/* @__PURE__ */ new Uint8Array(128)).fill(16);
198
+ alphabet$2.forEach((byte, i) => rAlphabet$2[byte] = i);
199
+ new TextEncoder().encode("ABCDEF").forEach((byte, i) => rAlphabet$2[byte] = i + 10);
200
+ /**
201
+ * Decodes the given hex-encoded string. If the input is malformed, an error is
202
+ * thrown.
203
+ *
204
+ * @param src The hex-encoded string to decode.
205
+ *
206
+ * @returns The decoded data.
207
+ *
208
+ * @example Usage
209
+ * ```ts
210
+ * import { decodeHex } from "@std/encoding/hex";
211
+ * import { assertEquals } from "@std/assert";
212
+ *
213
+ * assertEquals(
214
+ * decodeHex("616263"),
215
+ * new TextEncoder().encode("abc"),
216
+ * );
217
+ * ```
218
+ */ function decodeHex(src) {
219
+ const output = new TextEncoder().encode(src);
220
+ return new Uint8Array(output.buffer.transfer(decode(output, 0, 0, rAlphabet$2)));
221
+ }
222
+ "=".charCodeAt(0);
223
+ const alphabet$1 = {
224
+ base64: new TextEncoder().encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),
225
+ base64url: new TextEncoder().encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
226
+ };
227
+ const rAlphabet$1 = {
228
+ base64: (/* @__PURE__ */ new Uint8Array(128)).fill(64),
229
+ base64url: (/* @__PURE__ */ new Uint8Array(128)).fill(64)
230
+ };
231
+ alphabet$1.base64.forEach((byte, i) => rAlphabet$1.base64[byte] = i);
232
+ alphabet$1.base64url.forEach((byte, i) => rAlphabet$1.base64url[byte] = i);
233
+ /**
234
+ * Calculate the output size needed to encode a given input size for
235
+ * {@linkcode encodeIntoBase64}.
236
+ *
237
+ * @param originalSize The size of the input buffer.
238
+ * @returns The size of the output buffer.
239
+ *
240
+ * @example Basic Usage
241
+ * ```ts
242
+ * import { assertEquals } from "@std/assert";
243
+ * import { calcSizeBase64 } from "@std/encoding/unstable-base64";
244
+ *
245
+ * assertEquals(calcSizeBase64(1), 4);
246
+ * ```
247
+ */ function calcSizeBase64(originalSize) {
248
+ return ((originalSize + 2) / 3 | 0) * 4;
249
+ }
250
+ function encode(buffer, i, o, alphabet, padding) {
251
+ i += 2;
252
+ for (; i < buffer.length; i += 3) {
253
+ const x = buffer[i - 2] << 16 | buffer[i - 1] << 8 | buffer[i];
254
+ buffer[o++] = alphabet[x >> 18];
255
+ buffer[o++] = alphabet[x >> 12 & 63];
256
+ buffer[o++] = alphabet[x >> 6 & 63];
257
+ buffer[o++] = alphabet[x & 63];
258
+ }
259
+ switch (i) {
260
+ case buffer.length + 1: {
261
+ const x = buffer[i - 2] << 16;
262
+ buffer[o++] = alphabet[x >> 18];
263
+ buffer[o++] = alphabet[x >> 12 & 63];
264
+ buffer[o++] = padding;
265
+ buffer[o++] = padding;
266
+ break;
267
+ }
268
+ case buffer.length: {
269
+ const x = buffer[i - 2] << 16 | buffer[i - 1] << 8;
270
+ buffer[o++] = alphabet[x >> 18];
271
+ buffer[o++] = alphabet[x >> 12 & 63];
272
+ buffer[o++] = alphabet[x >> 6 & 63];
273
+ buffer[o++] = padding;
274
+ break;
275
+ }
276
+ }
277
+ return o;
278
+ }
279
+ // node_modules/@std/encoding/base64url.js
280
+ /**
281
+ * Utilities for
282
+ * {@link https://www.rfc-editor.org/rfc/rfc4648.html#section-5 | base64url}
283
+ * encoding and decoding.
284
+ *
285
+ * @module
286
+ */ const padding = "=".charCodeAt(0);
287
+ const alphabet = new TextEncoder().encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
288
+ const rAlphabet = (/* @__PURE__ */ new Uint8Array(128)).fill(64);
289
+ alphabet.forEach((byte, i) => rAlphabet[byte] = i);
290
+ /**
291
+ * Convert data into a base64url-encoded string.
292
+ *
293
+ * @see {@link https://www.rfc-editor.org/rfc/rfc4648.html#section-5}
294
+ *
295
+ * @param data The data to encode.
296
+ * @returns The base64url-encoded string.
297
+ *
298
+ * @example Usage
299
+ * ```ts
300
+ * import { encodeBase64Url } from "@std/encoding/base64url";
301
+ * import { assertEquals } from "@std/assert";
302
+ *
303
+ * assertEquals(encodeBase64Url("foobar"), "Zm9vYmFy");
304
+ * ```
305
+ */ function encodeBase64Url(data) {
306
+ if (typeof data === "string") data = new TextEncoder().encode(data);
307
+ else if (data instanceof ArrayBuffer) data = new Uint8Array(data).slice();
308
+ else data = data.slice();
309
+ const [output, i] = detach(data, calcSizeBase64(data.length));
310
+ let o = encode(output, i, 0, alphabet, padding);
311
+ o = output.indexOf(padding, o - 2);
312
+ return new TextDecoder().decode(o > 0 ? new Uint8Array(output.buffer.transfer(o)) : output);
313
+ }
314
+ // src/client/quad-store/canonical-nquads.ts
315
+ const XSD_STRING$1 = "http://www.w3.org/2001/XMLSchema#string";
316
+ /**
317
+ * serializeQuadToCanonicalNQuads serializes a single RDF/JS quad to the
318
+ * canonical N-Quads form (RDF 1.1 N-Quads) emitted by RDFC-1.0 dataset
319
+ * canonicalization (rdf-canonize) for blank-node-free quads: one statement
320
+ * terminated by a trailing newline.
321
+ *
322
+ * Canonical literal rules: plain xsd:string literals omit the datatype,
323
+ * language-tagged literals serialize as "..."@lang, RDF 1.2 directional
324
+ * literals as "..."@lang--dir, and every other datatype as "..."^^<iri>.
325
+ *
326
+ * Blank nodes are serialized with their dataset-local label as-is
327
+ * (label-based, like the Statement Hash scheme); this package does not
328
+ * perform RDFC-1.0's dataset-level blank-node relabeling, so quads with
329
+ * blank nodes are NOT byte-identical to RDFC-1.0 output.
330
+ *
331
+ * RDF-star triple terms and variables are rejected — N-Quads has no
332
+ * representation for them.
333
+ */
334
+ function serializeQuadToCanonicalNQuads(quad) {
335
+ const subject = serializeTerm(quad.subject, "subject");
336
+ const predicate = serializeTerm(quad.predicate, "predicate");
337
+ const object = serializeTerm(quad.object, "object");
338
+ const graph = quad.graph.termType === "DefaultGraph" ? "" : serializeTerm(quad.graph, "graph");
339
+ return subject + " " + predicate + " " + object + (graph ? " " + graph : "") + " .\n";
340
+ }
341
+ function serializeTerm(term, position) {
342
+ switch (term.termType) {
343
+ case "NamedNode": return "<" + escapeIri(term.value) + ">";
344
+ case "BlankNode": return "_:" + term.value;
345
+ case "Literal":
346
+ if (position !== "object") throw new Error("N-Quads cannot serialize a Literal term in " + position + " position");
347
+ return serializeLiteral(term);
348
+ case "Quad": throw new Error("N-Quads does not support RDF-star triple terms; refusing to serialize");
349
+ case "Variable": throw new Error("N-Quads cannot serialize a Variable term");
350
+ default: throw new Error("Unsupported RDF term type: " + term.termType);
351
+ }
352
+ }
353
+ function serializeLiteral(literal) {
354
+ const lexical = "\"" + escapeNQuadsString(literal.value) + "\"";
355
+ if (literal.language) {
356
+ const direction = literal.direction ? "--" + literal.direction : "";
357
+ return lexical + "@" + literal.language + direction;
358
+ }
359
+ const datatype = literal.datatype?.value ?? XSD_STRING$1;
360
+ if (datatype === XSD_STRING$1) return lexical;
361
+ return lexical + "^^<" + escapeIri(datatype) + ">";
362
+ }
363
+ function escapeNQuadsString(value) {
364
+ let out = "";
365
+ for (const ch of value) switch (ch) {
366
+ case "\\":
367
+ out += "\\\\";
368
+ break;
369
+ case "\"":
370
+ out += "\\\"";
371
+ break;
372
+ case "\n":
373
+ out += "\\n";
374
+ break;
375
+ case "\r":
376
+ out += "\\r";
377
+ break;
378
+ case " ":
379
+ out += "\\t";
380
+ break;
381
+ default: {
382
+ const code = ch.codePointAt(0) ?? 0;
383
+ out += code < 32 || code === 127 ? escapeControlChar(ch) : ch;
384
+ }
385
+ }
386
+ return out;
387
+ }
388
+ function escapeIri(value) {
389
+ let out = "";
390
+ for (const ch of value) {
391
+ if (ch === "\\") {
392
+ out += "\\\\";
393
+ continue;
394
+ }
395
+ const code = ch.codePointAt(0) ?? 0;
396
+ if (code < 32 || code === 127 || ch === "<" || ch === ">" || ch === "\"" || ch === "{" || ch === "}" || ch === "|" || ch === "^" || ch === "`") out += escapeControlChar(ch);
397
+ else out += ch;
398
+ }
399
+ return out;
400
+ }
401
+ function escapeControlChar(ch) {
402
+ const code = ch.codePointAt(0) ?? 0;
403
+ if (code <= 65535) return "\\u" + code.toString(16).toUpperCase().padStart(4, "0");
404
+ return "\\U" + code.toString(16).toUpperCase().padStart(8, "0");
405
+ }
406
+ // src/client/quad-store/hash-quad.ts
407
+ /**
408
+ * SCHEME_TAG identifies the quad ID scheme so old and new IDs are
409
+ * distinguishable at a glance and mixed-scheme data is detectable.
410
+ */
411
+ const SCHEME_TAG = "q2.";
412
+ /**
413
+ * hashQuad computes a content-addressed ID for a single quad: the SHA-256
414
+ * digest of the quad's canonical N-Quads serialization, base64url-encoded
415
+ * and prefixed with the scheme tag (2 + 43 = 46 chars total).
416
+ *
417
+ * For blank-node-free quads the serialization is byte-identical to the
418
+ * RDFC-1.0 canonical form (rdf-canonize), so IDs are interoperable with
419
+ * RDFC-1.0-based content-addressed systems. Blank nodes are label-based
420
+ * (dataset-local), per the Statement Hash convention — see
421
+ * serializeQuadToCanonicalNQuads.
422
+ */
423
+ function hashQuad(quad) {
424
+ const canonical = serializeQuadToCanonicalNQuads(quad);
425
+ const digest = decodeHex(sha256Hex(canonical));
426
+ return SCHEME_TAG + encodeBase64Url(digest);
427
+ }
428
+ /**
429
+ * hashQuads computes deterministic content-addressed IDs for multiple quads.
430
+ */
431
+ function hashQuads(quads) {
432
+ try {
433
+ return quads.map((quad) => hashQuad(quad));
434
+ } catch (cause) {
435
+ throw new Error("failed to compute content hashes for incoming quads", { cause });
436
+ }
437
+ }
438
+ // src/client/quad-store/hexastore-indexes.ts
439
+ /**
440
+ * HEXASTORE_INDEXES defines the 7 covering composite indexes on the quads table
441
+ * enabling any quad pattern to be resolved via a single index seek.
442
+ */
443
+ const HEXASTORE_INDEXES = [
444
+ {
445
+ name: "idx_quads_spog",
446
+ columns: [
447
+ "s",
448
+ "p",
449
+ "o",
450
+ "g"
451
+ ]
452
+ },
453
+ {
454
+ name: "idx_quads_sopg",
455
+ columns: [
456
+ "s",
457
+ "o",
458
+ "p",
459
+ "g"
460
+ ]
461
+ },
462
+ {
463
+ name: "idx_quads_pso",
464
+ columns: [
465
+ "p",
466
+ "s",
467
+ "o"
468
+ ]
469
+ },
470
+ {
471
+ name: "idx_quads_pos",
472
+ columns: [
473
+ "p",
474
+ "o",
475
+ "s"
476
+ ]
477
+ },
478
+ {
479
+ name: "idx_quads_ospg",
480
+ columns: [
481
+ "o",
482
+ "s",
483
+ "p",
484
+ "g"
485
+ ]
486
+ },
487
+ {
488
+ name: "idx_quads_opsg",
489
+ columns: [
490
+ "o",
491
+ "p",
492
+ "s",
493
+ "g"
494
+ ]
495
+ },
496
+ {
497
+ name: "idx_quads_gpso",
498
+ columns: [
499
+ "g",
500
+ "p",
501
+ "s",
502
+ "o"
503
+ ]
504
+ }
505
+ ];
506
+ // src/client/quad-store/term.ts
507
+ const { namedNode: namedNode$1, blankNode, literal, defaultGraph } = DataFactory;
508
+ const XSD_STRING = "http://www.w3.org/2001/XMLSchema#string";
509
+ /**
510
+ * fromRdfjsTerm flattens an RDF/JS term into a backend-neutral Term.
511
+ */
512
+ function fromRdfjsTerm(rdfjsTerm) {
513
+ if (rdfjsTerm.termType === "Literal") {
514
+ const literalTerm = rdfjsTerm;
515
+ return {
516
+ termType: rdfjsTerm.termType,
517
+ value: rdfjsTerm.value,
518
+ language: literalTerm.language || void 0,
519
+ datatype: literalTerm.datatype?.value || void 0
520
+ };
521
+ }
522
+ return {
523
+ termType: rdfjsTerm.termType,
524
+ value: rdfjsTerm.value
525
+ };
526
+ }
527
+ /**
528
+ * toRdfjsTerm reconstitutes an RDF/JS term from a backend-neutral Term.
529
+ */
530
+ function toRdfjsTerm(storedTerm) {
531
+ switch (storedTerm.termType) {
532
+ case "NamedNode": return namedNode$1(storedTerm.value);
533
+ case "BlankNode": return blankNode(storedTerm.value);
534
+ case "Literal":
535
+ if (storedTerm.language && storedTerm.language.trim().length > 0) return literal(storedTerm.value, storedTerm.language);
536
+ if (storedTerm.datatype && storedTerm.datatype !== XSD_STRING) return literal(storedTerm.value, namedNode$1(storedTerm.datatype));
537
+ return literal(storedTerm.value);
538
+ case "DefaultGraph": return defaultGraph();
539
+ default: throw new Error(`Unsupported term type: ${storedTerm.termType}`);
540
+ }
541
+ }
542
+ // src/client/quad-store/quad-row-reader.ts
543
+ const { quad: quad$1 } = DataFactory;
544
+ /**
545
+ * quadFromRow reconstructs an RDF/JS quad from a QuadRowReader impl, eliminating per-backend row mapping duplication.
546
+ */
547
+ function quadFromRow(row) {
548
+ const subject = toRdfjsTerm({
549
+ termType: row.sType,
550
+ value: row.s
551
+ });
552
+ const predicate = toRdfjsTerm({
553
+ termType: "NamedNode",
554
+ value: row.p
555
+ });
556
+ const object = toRdfjsTerm({
557
+ termType: row.oType,
558
+ value: row.o,
559
+ language: row.oLang ?? void 0,
560
+ datatype: row.oDatatype ?? void 0
561
+ });
562
+ const graph = toRdfjsTerm({
563
+ termType: row.gType,
564
+ value: row.g
565
+ });
566
+ return quad$1(subject, predicate, object, graph);
567
+ }
568
+ // src/client/quad-store/quad.ts
569
+ const { quad } = DataFactory;
570
+ /**
571
+ * fromRdfjsQuad flattens an RDF/JS quad into a backend-neutral Quad.
572
+ */
573
+ function fromRdfjsQuad(rdfjsQuad) {
574
+ return {
575
+ subject: fromRdfjsTerm(rdfjsQuad.subject),
576
+ predicate: fromRdfjsTerm(rdfjsQuad.predicate),
577
+ object: fromRdfjsTerm(rdfjsQuad.object),
578
+ graph: fromRdfjsTerm(rdfjsQuad.graph)
579
+ };
580
+ }
581
+ /**
582
+ * toRdfjsQuad reconstitutes an RDF/JS quad from a backend-neutral Quad.
583
+ */
584
+ function toRdfjsQuad(storedQuad) {
585
+ return quad(toRdfjsTerm(storedQuad.subject), toRdfjsTerm(storedQuad.predicate), toRdfjsTerm(storedQuad.object), toRdfjsTerm(storedQuad.graph));
586
+ }
587
+ // src/client/quad-store/import-export-via-transaction.ts
588
+ /**
589
+ * importViaTransaction drains an ImportRequest directly into a transactional patch.
590
+ */
591
+ async function importViaTransaction(request, options) {
592
+ const mode = request.mode ?? "merge";
593
+ const quads = await materializeImportQuads(request.source);
594
+ const tx = options.createTransaction();
595
+ try {
596
+ for (const quad of quads) tx.addQuad(quad);
597
+ await tx.commit({
598
+ importMode: mode,
599
+ provenance: request.provenance
600
+ });
601
+ } catch (error) {
602
+ tx.rollback();
603
+ throw error;
604
+ }
605
+ }
606
+ /**
607
+ * exportFromRdfjsStore streams all quads from an RDF/JS store and serializes the export response.
608
+ */
609
+ async function exportFromRdfjsStore(rdfjsStore, request) {
610
+ const stream = rdfjsStore.match(null, null, null, null);
611
+ const quads = await collectQuadsFromStream(stream);
612
+ return await exportQuadsResponse(quads, request);
613
+ }
614
+ // src/client/quad-store/rdfjs-store-commit-handler.ts
615
+ /**
616
+ * createRdfjsStoreCommitHandler returns a commit function that applies Patches
617
+ * directly to an underlying rdfjs.Store by using its native add/delete/remove methods.
618
+ * For robust usage, the underlying store should support synchronous add/delete.
619
+ */
620
+ function createRdfjsStoreCommitHandler(store) {
621
+ return async (patch, context) => {
622
+ if ("applyPatch" in store && typeof store.applyPatch === "function") return store.applyPatch(patch, context);
623
+ if (context?.importMode === "replace") {
624
+ const stream = store.match(null, null, null, null);
625
+ await new Promise((resolve, reject) => {
626
+ stream.on("data", (quad) => {
627
+ if ("removeQuad" in store && typeof store.removeQuad === "function") store.removeQuad(quad);
628
+ else if ("delete" in store && typeof store.delete === "function") store.delete(quad);
629
+ });
630
+ stream.on("end", resolve);
631
+ stream.on("error", reject);
632
+ });
633
+ }
634
+ for (const quad of patch.deletions) if ("removeQuad" in store && typeof store.removeQuad === "function") store.removeQuad(quad);
635
+ else if ("delete" in store && typeof store.delete === "function") store.delete(quad);
636
+ for (const quad of patch.insertions) if ("addQuad" in store && typeof store.addQuad === "function") store.addQuad(quad);
637
+ else if ("add" in store && typeof store.add === "function") store.add(quad);
638
+ return Promise.resolve();
639
+ };
640
+ }
641
+ // src/client/quad-store/transaction.ts
642
+ const { namedNode } = DataFactory;
643
+ /**
644
+ * Transaction collects mutations natively before flushing them as a deduplicated Patch.
645
+ * It deeply implements the mutation boundary for an rdfjs.Store, providing rich bulk
646
+ * ingestion without requiring wrapper classes.
647
+ */
648
+ var Transaction = class {
649
+ options;
650
+ insertBuffer = [];
651
+ deleteBuffer = [];
652
+ constructor(options) {
653
+ this.options = options;
654
+ }
655
+ /** add buffers a single quad for insertion on the next commit. */
656
+ add(quad) {
657
+ this.insertBuffer.push(quad);
658
+ return this;
659
+ }
660
+ /** addQuad buffers a single quad for insertion on the next commit. */
661
+ addQuad(quad) {
662
+ return this.add(quad);
663
+ }
664
+ /** addQuads buffers multiple quads for insertion on the next commit. */
665
+ addQuads(quads) {
666
+ for (const quad of quads) this.insertBuffer.push(quad);
667
+ return this;
668
+ }
669
+ /** removeQuads buffers multiple quads for deletion on the next commit. */
670
+ removeQuads(quads) {
671
+ for (const quad of quads) this.deleteBuffer.push(quad);
672
+ return this;
673
+ }
674
+ /** delete buffers a single quad for deletion on the next commit. */
675
+ delete(quad) {
676
+ this.deleteBuffer.push(quad);
677
+ return this;
678
+ }
679
+ /** removeQuad buffers a single quad for deletion on the next commit. */
680
+ removeQuad(quad) {
681
+ return this.delete(quad);
682
+ }
683
+ /** import consumes an RDF/JS stream, buffering all quads for later commit. */
684
+ import(stream) {
685
+ return bridgeStreamToBuffer(stream, this.insertBuffer);
686
+ }
687
+ /** remove consumes a stream and buffers all quads from it for deletion on commit. */
688
+ remove(stream) {
689
+ return bridgeStreamToBuffer(stream, this.deleteBuffer);
690
+ }
691
+ /** removeMatches buffers all quads matching the given quad pattern for deletion on commit. */
692
+ removeMatches(match, subject, predicate, object, graph) {
693
+ return bridgeStreamToBuffer(match(subject, predicate, object, graph), this.deleteBuffer);
694
+ }
695
+ /** deleteGraph buffers all quads in the named graph for deletion on commit. */
696
+ deleteGraph(match, graph) {
697
+ const graphTerm = typeof graph === "string" ? namedNode(graph) : graph;
698
+ return this.removeMatches(match, null, null, null, graphTerm);
699
+ }
700
+ /** commit deduplicates buffers and persists through the configured commitHandler. */
701
+ async commit(context) {
702
+ deduplicateBuffers(this.insertBuffer, this.deleteBuffer);
703
+ if (this.insertBuffer.length === 0 && this.deleteBuffer.length === 0) return;
704
+ const patch = {
705
+ insertions: this.insertBuffer,
706
+ deletions: this.deleteBuffer
707
+ };
708
+ if (this.options.commit) await this.options.commit(patch, context);
709
+ else if (this.options.fallbackCommit) await this.options.fallbackCommit(patch, context);
710
+ this.clearBuffer();
711
+ }
712
+ /** rollback discards any uncommitted insertions and deletions. */
713
+ rollback() {
714
+ this.clearBuffer();
715
+ }
716
+ clearBuffer() {
717
+ this.insertBuffer = [];
718
+ this.deleteBuffer = [];
719
+ }
720
+ };
721
+ /**
722
+ * bridgeStreamToBuffer connects an RDF/JS quad stream to a target buffer array.
723
+ */
724
+ function bridgeStreamToBuffer(stream, targetBuffer) {
725
+ const emitter = new EventEmitter();
726
+ stream.on("data", (quad) => {
727
+ targetBuffer.push(quad);
728
+ });
729
+ stream.on("end", () => {
730
+ emitter.emit("end");
731
+ });
732
+ stream.on("error", (error) => {
733
+ emitter.emit("error", error);
734
+ });
735
+ return emitter;
736
+ }
737
+ // src/client/quad-store/transactional-rdfjs-store.ts
738
+ /**
739
+ * TransactionalRdfjsStore is an explicit wrapper that satisfies the full `rdfjs.Store`
740
+ * interface by routing reads to a ReadonlyStore and mutations to a Transaction buffer.
741
+ * It replaces proxy-based interception with a concrete class for better JIT optimization
742
+ * and clearer architectural boundaries.
743
+ */
744
+ var TransactionalRdfjsStore = class {
745
+ options;
746
+ constructor(options) {
747
+ this.options = options;
748
+ }
749
+ match(subject, predicate, object, graph) {
750
+ return this.options.readStore.match(subject, predicate, object, graph);
751
+ }
752
+ add(quad) {
753
+ this.options.transaction.add(quad);
754
+ return this;
755
+ }
756
+ addQuad(quad) {
757
+ this.options.transaction.addQuad(quad);
758
+ return this;
759
+ }
760
+ addQuads(quads) {
761
+ this.options.transaction.addQuads(quads);
762
+ return this;
763
+ }
764
+ delete(quad) {
765
+ this.options.transaction.delete(quad);
766
+ return this;
767
+ }
768
+ removeQuad(quad) {
769
+ this.options.transaction.removeQuad(quad);
770
+ return this;
771
+ }
772
+ removeQuads(quads) {
773
+ this.options.transaction.removeQuads(quads);
774
+ return this;
775
+ }
776
+ import(stream) {
777
+ return this.options.transaction.import(stream);
778
+ }
779
+ remove(stream) {
780
+ return this.options.transaction.remove(stream);
781
+ }
782
+ removeMatches(subject, predicate, object, graph) {
783
+ return this.options.transaction.removeMatches(this.options.readStore.match.bind(this.options.readStore), subject, predicate, object, graph);
784
+ }
785
+ deleteGraph(graph) {
786
+ return this.options.transaction.deleteGraph(this.options.readStore.match.bind(this.options.readStore), graph);
787
+ }
788
+ };
789
+ // src/client/quad-store/novel-quads.ts
790
+ /**
791
+ * preparePatch applies the include/exclude filter to both sides of a patch and
792
+ * hashes what is left. It does not deduplicate within a side: the same quad
793
+ * inserted twice appears twice, as in every durable backend today.
794
+ */
795
+ function preparePatch(patch, filter) {
796
+ const matches = filterQuads(filter);
797
+ const deletions = patch.deletions?.filter(matches) ?? [];
798
+ const insertions = patch.insertions?.filter(matches) ?? [];
799
+ return {
800
+ deletions,
801
+ deletionIds: deletions.length ? hashQuads(deletions) : [],
802
+ insertions,
803
+ insertionIds: insertions.length ? hashQuads(insertions) : []
804
+ };
805
+ }
806
+ /**
807
+ * selectNovelQuads keeps an insertion when the store does not hold it yet, or
808
+ * when the same patch also deletes it (delete-then-re-add must write it back).
809
+ * This is the deduplication rule of `@wazootech/worlds-libsql`, the reference backend.
810
+ */
811
+ async function selectNovelQuads(prepared, options) {
812
+ const keyOf = options.keyOf ?? ((_quad, id) => id);
813
+ const { insertions, insertionIds, deletions, deletionIds } = prepared;
814
+ if (insertions.length === 0) return {
815
+ novelInsertions: [],
816
+ novelQuadIds: []
817
+ };
818
+ const insertionKeys = insertions.map((q, i) => keyOf(q, insertionIds[i]));
819
+ const deletedKeys = new Set(deletions.map((q, i) => keyOf(q, deletionIds[i])));
820
+ const existing = options.replacing ? /* @__PURE__ */ new Set() : await options.lookupExisting(insertionKeys);
821
+ const novelInsertions = [];
822
+ const novelQuadIds = [];
823
+ for (let i = 0; i < insertions.length; i++) {
824
+ const key = insertionKeys[i];
825
+ if (!existing.has(key) || deletedKeys.has(key)) {
826
+ novelInsertions.push(insertions[i]);
827
+ novelQuadIds.push(insertionIds[i]);
828
+ }
829
+ }
830
+ return {
831
+ novelInsertions,
832
+ novelQuadIds
833
+ };
834
+ }
835
+ /**
836
+ * computeNovelQuads is preparePatch followed by selectNovelQuads, for backends
837
+ * with no write between the two. Backends that wipe on replace-import hash
838
+ * first and look up after the wipe call the two steps separately.
839
+ */
840
+ async function computeNovelQuads(patch, options) {
841
+ const { include, exclude } = options;
842
+ const prepared = preparePatch(patch, {
843
+ include,
844
+ exclude
845
+ });
846
+ return {
847
+ ...prepared,
848
+ ...await selectNovelQuads(prepared, options)
849
+ };
850
+ }
851
+ export { InMemoryProvenanceStore as S, isTextualLiteral as _, Transaction as a, isImportCommit as b, importViaTransaction as c, quadFromRow as d, fromRdfjsTerm as f, hashQuads as g, hashQuad as h, TransactionalRdfjsStore as i, fromRdfjsQuad as l, HEXASTORE_INDEXES as m, preparePatch as n, createRdfjsStoreCommitHandler as o, toRdfjsTerm as p, selectNovelQuads as r, exportFromRdfjsStore as s, computeNovelQuads as t, toRdfjsQuad as u, filterQuads as v, isReplaceImportCommit as x, deduplicateBuffers as y };