@wazootech/worlds-cloudflare 0.0.0-stage → 0.15.6

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,668 @@
1
+ import { DataFactory } from "@wazootech/sparql-engine";
2
+ import { _ as effectiveLookupChunkSize, h as D1BatchExecutor, l as buildDeleteQuadsByQuadIds, m as quadToInsertRow, o as buildSelectExistingQuadIds, t as buildBulkInsertQuads, u as buildWipeAllGraphDataStatements } from "./d1-quad-insert-sql-B4ZiZZe8.js";
3
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-DmrQfhKJ.js";
4
+ import { hashQuads, isReplaceImportCommit } from "@wazootech/worlds-sdk/quad-store";
5
+ import { i as removeMatchedQuads, n as countD1Matches, r as matchD1Pages, t as collectQuads } from "./d1-rdfjs-store-read-2QTEEe_a.js";
6
+ // src/cloudflare/rdfjs-store/d1-quad-stream.ts
7
+ /**
8
+ * D1QuadStream is a minimal RDF/JS Stream backed by an async page generator
9
+ * (D1 keyset-paginated match queries), with the same listener semantics as
10
+ * the postgres, indexeddb, and sqlite streams:
11
+ *
12
+ * - attaching a `data` listener switches to flow mode and emits each quad
13
+ * as pages arrive,
14
+ * - attaching a `readable` listener (or calling `read()`) enables pull mode,
15
+ * - attaching only `end`/`error` listeners (a bare completion signal) runs
16
+ * the generator to exhaustion and ends,
17
+ * - `end` is only emitted after the generator is exhausted and every quad
18
+ * has been consumed.
19
+ *
20
+ * It implements the full EventEmitter surface required by the `rdfjs.Stream`
21
+ * interface without depending on Node's `events` module.
22
+ */
23
+ var D1QuadStream = class {
24
+ quads;
25
+ _listeners = /* @__PURE__ */ new Map();
26
+ _maxListeners = 10;
27
+ _ended = false;
28
+ _flowing = false;
29
+ _readStarted = false;
30
+ _started = false;
31
+ _buffer = [];
32
+ /** quads supplies the quads as an async generator (one page per chunk). */
33
+ constructor(quads) {
34
+ this.quads = quads;
35
+ }
36
+ read() {
37
+ this._readStarted = true;
38
+ this._ensureStarted();
39
+ const quad = this._buffer.shift();
40
+ if (quad === void 0) return null;
41
+ return quad;
42
+ }
43
+ [Symbol.iterator]() {
44
+ return this._buffer[Symbol.iterator]();
45
+ }
46
+ destroy(error) {
47
+ if (error) this.emit("error", error);
48
+ this._ended = true;
49
+ this.removeAllListeners();
50
+ }
51
+ addListener(eventName, listener) {
52
+ return this.on(eventName, listener);
53
+ }
54
+ on(eventName, listener) {
55
+ const list = this._listeners.get(eventName);
56
+ if (list) list.push(listener);
57
+ else this._listeners.set(eventName, [listener]);
58
+ if (eventName === "data" && !this._ended && !this._flowing) {
59
+ this._flowing = true;
60
+ this._ensureStarted();
61
+ }
62
+ if (eventName === "readable" && !this._ended) {
63
+ this._readStarted = true;
64
+ this._ensureStarted();
65
+ }
66
+ if (eventName === "end" && !this._ended) this._ensureStarted();
67
+ return this;
68
+ }
69
+ once(eventName, listener) {
70
+ const wrapper = (...args) => {
71
+ this.removeListener(eventName, wrapper);
72
+ listener(...args);
73
+ };
74
+ return this.on(eventName, wrapper);
75
+ }
76
+ prependListener(eventName, listener) {
77
+ const list = this._listeners.get(eventName);
78
+ if (list) list.unshift(listener);
79
+ else this._listeners.set(eventName, [listener]);
80
+ return this;
81
+ }
82
+ prependOnceListener(eventName, listener) {
83
+ const wrapper = (...args) => {
84
+ this.removeListener(eventName, wrapper);
85
+ listener(...args);
86
+ };
87
+ return this.prependListener(eventName, wrapper);
88
+ }
89
+ removeListener(eventName, listener) {
90
+ const list = this._listeners.get(eventName);
91
+ if (list) {
92
+ const index = list.indexOf(listener);
93
+ if (index >= 0) list.splice(index, 1);
94
+ }
95
+ return this;
96
+ }
97
+ off(eventName, listener) {
98
+ return this.removeListener(eventName, listener);
99
+ }
100
+ removeAllListeners(eventName) {
101
+ if (eventName === void 0) this._listeners.clear();
102
+ else this._listeners.delete(eventName);
103
+ return this;
104
+ }
105
+ setMaxListeners(n) {
106
+ this._maxListeners = n;
107
+ return this;
108
+ }
109
+ getMaxListeners() {
110
+ return this._maxListeners;
111
+ }
112
+ listeners(eventName) {
113
+ return [...this._listeners.get(eventName) ?? []];
114
+ }
115
+ rawListeners(eventName) {
116
+ return [...this._listeners.get(eventName) ?? []];
117
+ }
118
+ emit(eventName, ...args) {
119
+ const list = this._listeners.get(eventName);
120
+ if (!list || list.length === 0) return false;
121
+ for (const fn of list.slice()) fn.apply(this, args);
122
+ return true;
123
+ }
124
+ listenerCount(eventName) {
125
+ return this._listeners.get(eventName)?.length ?? 0;
126
+ }
127
+ eventNames() {
128
+ return [...this._listeners.keys()];
129
+ }
130
+ /** _ensureStarted lazily pumps the generator on a microtask. */
131
+ _ensureStarted() {
132
+ if (this._started || this._ended) return;
133
+ this._started = true;
134
+ queueMicrotask(async () => {
135
+ if (this._ended) return;
136
+ try {
137
+ for await (const quad of this.quads()) {
138
+ if (this._ended) return;
139
+ if (this._flowing) this.emit("data", quad);
140
+ else if (this._readStarted) {
141
+ this._buffer.push(quad);
142
+ this.emit("readable");
143
+ }
144
+ }
145
+ if (!this._ended) this._end();
146
+ } catch (error) {
147
+ if (!this._ended) this.emit("error", error instanceof Error ? error : new Error(String(error)));
148
+ }
149
+ });
150
+ }
151
+ _end() {
152
+ if (this._ended) return;
153
+ this._ended = true;
154
+ this.emit("end");
155
+ }
156
+ };
157
+ // src/cloudflare/rdfjs-store/d1-rdfjs-transaction.ts
158
+ /** D1TransactionImpl buffers a SPARQL update patch for atomic commit. */
159
+ var D1TransactionImpl = class {
160
+ store;
161
+ inserted = /* @__PURE__ */ new Map();
162
+ deleted = /* @__PURE__ */ new Map();
163
+ constructor(store) {
164
+ this.store = store;
165
+ }
166
+ add(quad) {
167
+ this.deleted.delete(quadKey(quad));
168
+ this.inserted.set(quadKey(quad), quad);
169
+ }
170
+ delete(quad) {
171
+ if (this.inserted.delete(quadKey(quad))) return;
172
+ this.deleted.set(quadKey(quad), quad);
173
+ }
174
+ commit() {
175
+ return this.store.applyPatch({
176
+ insertions: [...this.inserted.values()],
177
+ deletions: [...this.deleted.values()]
178
+ });
179
+ }
180
+ rollback() {
181
+ this.inserted.clear();
182
+ this.deleted.clear();
183
+ }
184
+ };
185
+ /** quadKey builds a deduplication key for a quad (subject/predicate/object/graph values). */
186
+ function quadKey(quad) {
187
+ const literal = quad.object.termType === "Literal" ? quad.object : null;
188
+ return [
189
+ quad.subject.termType,
190
+ quad.subject.value,
191
+ quad.predicate.value,
192
+ quad.object.termType,
193
+ quad.object.value,
194
+ literal?.datatype?.value ?? "",
195
+ literal?.language ?? "",
196
+ quad.graph.termType,
197
+ quad.graph.value
198
+ ].join("\0");
199
+ }
200
+ // src/cloudflare/rdfjs-store/d1-rdfjs-store-patch.ts
201
+ /**
202
+ * applyD1Patch persists a patch atomically in one D1 batch (chunked only when
203
+ * staged statements exceed the write batch size). Callers serialize it.
204
+ */
205
+ async function applyD1Patch(deps, patch, context) {
206
+ const executor = new D1BatchExecutor({
207
+ connection: deps.connection,
208
+ writeBatchSize: deps.writeBatchSize
209
+ });
210
+ if (isReplaceImportCommit(context)) await executor.stage(buildWipeAllGraphDataStatements(deps.worldId));
211
+ const targetedDeletions = patch.deletions ?? [];
212
+ const targetedInsertions = patch.insertions ?? [];
213
+ if (targetedDeletions.length > 0) await stageChunked(executor, await hashQuads(targetedDeletions), deps.lookupChunkSize, (chunk) => [buildDeleteQuadsByQuadIds(chunk, deps.worldId)]);
214
+ if (targetedInsertions.length > 0) {
215
+ const proposedIds = await hashQuads(targetedInsertions);
216
+ const existingIds = await queryCachePresence(deps.connection, proposedIds, deps.lookupChunkSize, deps.worldId);
217
+ const novelRows = [];
218
+ for (let index = 0; index < targetedInsertions.length; index++) {
219
+ if (existingIds.has(proposedIds[index])) continue;
220
+ novelRows.push(await quadToInsertRow(targetedInsertions[index]));
221
+ }
222
+ if (novelRows.length > 0) await executor.stage(buildBulkInsertQuads(novelRows.map((row) => ({
223
+ ...row,
224
+ world_id: deps.worldId
225
+ }))));
226
+ }
227
+ try {
228
+ await executor.flush();
229
+ } catch (cause) {
230
+ const detail = cause instanceof Error ? cause.message : String(cause);
231
+ throw new Error(`failed to execute D1 batch: ${detail}`, { cause });
232
+ }
233
+ }
234
+ /** stageChunked slices ids into chunks and stages the generated statements per chunk. */
235
+ async function stageChunked(executor, ids, chunkSize, build) {
236
+ for (let index = 0; index < ids.length; index += chunkSize) {
237
+ const chunk = ids.slice(index, index + chunkSize);
238
+ await executor.stage(build(chunk));
239
+ }
240
+ }
241
+ /** queryCachePresence polls D1 for which quad ids are already persisted. */
242
+ async function queryCachePresence(connection, quadIds, lookupChunkSize, worldId) {
243
+ const cachedIds = /* @__PURE__ */ new Set();
244
+ for (let index = 0; index < quadIds.length; index += lookupChunkSize) {
245
+ const chunk = quadIds.slice(index, index + lookupChunkSize);
246
+ const result = await connection.execute(buildSelectExistingQuadIds(chunk, worldId));
247
+ for (const row of result.rows) if (row.id) cachedIds.add(String(row.id));
248
+ }
249
+ return cachedIds;
250
+ }
251
+ /** insertD1Quad writes one quad row in its own batch. */
252
+ async function insertD1Quad(connection, worldId, quad) {
253
+ await connection.batch(buildBulkInsertQuads([{
254
+ ...await quadToInsertRow(quad),
255
+ world_id: worldId
256
+ }]));
257
+ }
258
+ /** deleteD1Quad deletes one quad row by its content-addressed id. */
259
+ async function deleteD1Quad(connection, worldId, quad) {
260
+ const [id] = await hashQuads([quad]);
261
+ await connection.batch([buildDeleteQuadsByQuadIds([id], worldId)]);
262
+ }
263
+ const SCHEMA_VERSION_TABLE = "worlds_data_plane_schema";
264
+ const REQUIRED_COLUMNS = {
265
+ quads: [
266
+ "quad_id",
267
+ "s",
268
+ "s_type",
269
+ "p",
270
+ "o",
271
+ "o_type",
272
+ "o_datatype",
273
+ "o_lang",
274
+ "g",
275
+ "g_type"
276
+ ],
277
+ chunks: [
278
+ "chunk_id",
279
+ "quad_id",
280
+ "subject",
281
+ "predicate",
282
+ "graph",
283
+ "value",
284
+ "fts_value",
285
+ "vector"
286
+ ]
287
+ };
288
+ /**
289
+ * REQUIRED_PRIMARY_KEYS lists the accepted primary-key column sets per table.
290
+ * `quads` accepts the legacy quad_id key so a Worker deployed before
291
+ * migrations/0002-quads-world-scoped-key.sql has run still starts; only the
292
+ * composite (world_id, quad_id) key isolates worlds that hold the same triple.
293
+ */
294
+ const REQUIRED_PRIMARY_KEYS = {
295
+ [SCHEMA_VERSION_TABLE]: [["schema_version_id"]],
296
+ quads: [["quad_id"], ["quad_id", "world_id"]],
297
+ chunks: [["chunk_id"]]
298
+ };
299
+ /** Inspect the actual D1 schema and report missing required tables or columns. */
300
+ async function checkD1SchemaCompatibility(connection, options = {}) {
301
+ const issues = [];
302
+ let schemaVersion = null;
303
+ if ((await connection.execute({
304
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
305
+ args: [SCHEMA_VERSION_TABLE]
306
+ })).rows.length === 0) issues.push({
307
+ table: SCHEMA_VERSION_TABLE,
308
+ detail: "missing schema version table"
309
+ });
310
+ else {
311
+ const versionTableInfo = await connection.execute({ sql: `PRAGMA table_info(${SCHEMA_VERSION_TABLE})` });
312
+ const versionColumns = new Set(versionTableInfo.rows.map((column) => column.name));
313
+ for (const column of [
314
+ "schema_version_id",
315
+ "version",
316
+ "applied_at"
317
+ ]) if (!versionColumns.has(column)) issues.push({
318
+ table: SCHEMA_VERSION_TABLE,
319
+ detail: `missing column ${column}`
320
+ });
321
+ const versionPrimaryKeys = versionTableInfo.rows.filter((column) => Number(column.pk) > 0);
322
+ if (versionPrimaryKeys.length !== 1 || versionPrimaryKeys[0]?.name !== REQUIRED_PRIMARY_KEYS[SCHEMA_VERSION_TABLE][0][0]) {
323
+ const found = versionPrimaryKeys.map((column) => column.name).join(", ") || "none";
324
+ issues.push({
325
+ table: SCHEMA_VERSION_TABLE,
326
+ detail: `expected primary key ${REQUIRED_PRIMARY_KEYS[SCHEMA_VERSION_TABLE][0][0]}, found ${found}`
327
+ });
328
+ }
329
+ if (versionColumns.has("version")) {
330
+ const versionResult = await connection.execute({ sql: `SELECT version FROM ${SCHEMA_VERSION_TABLE} ORDER BY version DESC LIMIT 1` });
331
+ schemaVersion = versionResult.rows[0]?.version == null ? null : Number(versionResult.rows[0].version);
332
+ }
333
+ }
334
+ if (schemaVersion !== null && schemaVersion !== 4) issues.push({
335
+ table: SCHEMA_VERSION_TABLE,
336
+ detail: `expected schema version 4, found ${schemaVersion}`
337
+ });
338
+ const requiredColumns = Object.fromEntries(Object.entries(REQUIRED_COLUMNS).map(([table, columns]) => [table, [
339
+ ...columns,
340
+ ...options.worldId ? ["world_id"] : [],
341
+ ...options.requireDerivedColumn && table === "quads" ? ["derived"] : []
342
+ ]]));
343
+ for (const [table, columns] of Object.entries(requiredColumns)) {
344
+ if ((await connection.execute({
345
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
346
+ args: [table]
347
+ })).rows.length === 0) {
348
+ issues.push({
349
+ table,
350
+ detail: "missing table"
351
+ });
352
+ continue;
353
+ }
354
+ const columnResult = await connection.execute({ sql: `PRAGMA table_info(${table})` });
355
+ const actual = new Set(columnResult.rows.map((row) => row.name));
356
+ if (actual.has("id")) issues.push({
357
+ table,
358
+ detail: "legacy id column remains"
359
+ });
360
+ if (options.worldId === void 0 && table === "quads" && actual.has("world_id")) issues.push({
361
+ table,
362
+ detail: "world-scoped schema present but no worldId was provided; reopen with a worldId"
363
+ });
364
+ for (const column of columns) if (!actual.has(column)) issues.push({
365
+ table,
366
+ detail: `missing column ${column}`
367
+ });
368
+ const primaryKeys = columnResult.rows.filter((column) => Number(column.pk) > 0);
369
+ const expectedPrimaryKeys = REQUIRED_PRIMARY_KEYS[table] ?? [];
370
+ const actualKey = primaryKeys.map((column) => column.name).sort().join(",");
371
+ if (!expectedPrimaryKeys.some((key) => [...key].sort().join(",") === actualKey)) {
372
+ const expectedPrimaryKey = expectedPrimaryKeys.map((key) => key.join(" + ")).join(" or ");
373
+ const found = primaryKeys.map((column) => column.name).join(", ") || "none";
374
+ issues.push({
375
+ table,
376
+ detail: `expected primary key ${expectedPrimaryKey}, found ${found}`
377
+ });
378
+ }
379
+ }
380
+ const ftsSql = (await connection.execute({ sql: "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'chunks_fts'" })).rows[0]?.sql;
381
+ if (!ftsSql) issues.push({
382
+ table: "chunks_fts",
383
+ detail: "missing table"
384
+ });
385
+ const ftsColumnResult = await connection.execute({ sql: "PRAGMA table_info(chunks_fts)" });
386
+ const ftsColumns = new Set(ftsColumnResult.rows.map((row) => row.name));
387
+ if (!ftsColumns.has("fts_value")) issues.push({
388
+ table: "chunks_fts",
389
+ detail: "missing column fts_value"
390
+ });
391
+ for (const legacyColumn of ["quad_id"]) if (ftsColumns.has(legacyColumn)) issues.push({
392
+ table: "chunks_fts",
393
+ detail: `legacy ${legacyColumn} column remains`
394
+ });
395
+ const normalizedFtsSql = (ftsSql ?? "").replaceAll(/\s+/g, "").toLowerCase();
396
+ if (!normalizedFtsSql.includes("content='chunks'") || !normalizedFtsSql.includes("content_rowid='chunk_id'") || ftsColumns.size !== 1) issues.push({
397
+ table: "chunks_fts",
398
+ detail: "not canonical external-content FTS5 schema"
399
+ });
400
+ return {
401
+ compatible: issues.length === 0,
402
+ issues,
403
+ schemaVersion
404
+ };
405
+ }
406
+ /** Validate the schema and throw an actionable error before serving traffic. */
407
+ async function assertD1SchemaCompatible(connection, options = {}) {
408
+ const report = await checkD1SchemaCompatibility(connection, options);
409
+ if (!report.compatible) {
410
+ const issues = report.issues.map((issue) => `${issue.table}: ${issue.detail}`).join(", ");
411
+ throw new Error(`D1 schema is incompatible with @wazootech/worlds-cloudflare: ${issues}. Automatic schema creation is not an in-place migration. Apply the documented clean reset before serving traffic (a missing quads.derived column, needed only for inference, is added by migrations/0001-quads-derived-column.sql).`);
412
+ }
413
+ }
414
+ // src/cloudflare/rdfjs-store/d1-rdfjs-store-lifecycle.ts
415
+ /**
416
+ * applyD1Schema creates the quads/chunks tables, covering indexes, and the
417
+ * FTS5 external-content table + triggers (idempotent), then stamps and
418
+ * verifies the data-plane schema version.
419
+ *
420
+ * Statements run through the prepared-statement path (not exec()) because
421
+ * D1's script executor splits on newlines, which would truncate the
422
+ * shared sql-core emitters' multi-line DDL.
423
+ */
424
+ async function applyD1Schema(connection, schemaBuilder, options) {
425
+ if ((await connection.execute({ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('quads', 'chunks', 'chunks_fts', 'worlds_data_plane_schema')" })).rows.length > 0) await assertD1SchemaCompatible(connection, {
426
+ worldId: options.worldId,
427
+ requireDerivedColumn: options.requireDerivedColumn
428
+ });
429
+ const statements = [
430
+ ...schemaBuilder.buildTables(),
431
+ ...schemaBuilder.buildIndexes(),
432
+ schemaBuilder.buildD1ChunksQuadIdIndex(),
433
+ schemaBuilder.buildD1ChunksFtsTable(),
434
+ ...schemaBuilder.buildD1ChunksTriggers()
435
+ ];
436
+ for (const ddl of statements) await connection.execute({ sql: ddl });
437
+ await connection.execute({ sql: `CREATE TABLE IF NOT EXISTS worlds_data_plane_schema (schema_version_id INTEGER PRIMARY KEY, version INTEGER NOT NULL UNIQUE, applied_at TEXT NOT NULL DEFAULT (datetime('now')))` });
438
+ await assertD1SchemaCompatible(connection, {
439
+ worldId: options.worldId,
440
+ requireDerivedColumn: options.requireDerivedColumn
441
+ });
442
+ await connection.execute({
443
+ sql: "INSERT OR IGNORE INTO worlds_data_plane_schema (version) VALUES (?)",
444
+ args: [4]
445
+ });
446
+ await assertD1SchemaCompatible(connection, {
447
+ worldId: options.worldId,
448
+ requireDerivedColumn: options.requireDerivedColumn
449
+ });
450
+ }
451
+ /** countD1Quads returns the row count of the quads table, scoped to worldId. */
452
+ async function countD1Quads(connection, worldId) {
453
+ const result = await connection.execute({
454
+ sql: worldId ? "SELECT COUNT(*) AS count FROM quads WHERE world_id = ?" : "SELECT COUNT(*) AS count FROM quads",
455
+ args: worldId ? [worldId] : []
456
+ });
457
+ return Number(result.rows[0]?.count ?? 0);
458
+ }
459
+ // src/cloudflare/rdfjs-store/d1-write-queue.ts
460
+ /**
461
+ * D1WriteQueue serializes mutations (each runs after the previous one) and
462
+ * keeps the synchronous size approximation refreshed after every write.
463
+ */
464
+ var D1WriteQueue = class {
465
+ connection;
466
+ worldId;
467
+ /** serialized write queue: every mutation runs after the previous one. */
468
+ mutationQueue = Promise.resolve();
469
+ /** Write failures recorded since the last flush() report. */
470
+ pendingFailures = [];
471
+ /** synchronous size approximation, refreshed after every write. */
472
+ liveCount = 0;
473
+ constructor(connection, worldId) {
474
+ this.connection = connection;
475
+ this.worldId = worldId;
476
+ }
477
+ async refreshCount() {
478
+ this.liveCount = await countD1Quads(this.connection, this.worldId);
479
+ }
480
+ /**
481
+ * flush resolves once every queued write has committed, and rejects with an
482
+ * AggregateError listing every failure since the previous flush (capped at
483
+ * the first 10 plus a count of the rest, so a long outage does not produce
484
+ * hundreds of copies of the same error). The queue itself keeps draining
485
+ * later writes.
486
+ */
487
+ flush() {
488
+ return this.mutationQueue.then(() => {
489
+ const failures = this.pendingFailures;
490
+ this.pendingFailures = [];
491
+ if (failures.length === 0) return;
492
+ const capped = failures.slice(0, MAX_REPORTED_FAILURES);
493
+ const suppressed = failures.length - capped.length;
494
+ const errors = suppressed > 0 ? [...capped, /* @__PURE__ */ new Error(`${suppressed} more write failure(s) suppressed; see the logged errors`)] : capped;
495
+ throw new AggregateError(errors, `${failures.length} queued write(s) failed`);
496
+ });
497
+ }
498
+ /**
499
+ * enqueueWrite serializes a write batch behind all prior writes and
500
+ * refreshes the live count on completion.
501
+ */
502
+ enqueueWrite(work) {
503
+ const next = this.mutationQueue.then(async () => {
504
+ try {
505
+ await work();
506
+ await this.refreshCount();
507
+ } catch (error) {
508
+ this.pendingFailures.push(error);
509
+ throw error;
510
+ }
511
+ });
512
+ this.mutationQueue = next.then(() => {}, () => {});
513
+ return next;
514
+ }
515
+ };
516
+ /** flush() reports at most this many of the failures it aggregates. */
517
+ const MAX_REPORTED_FAILURES = 10;
518
+ // src/cloudflare/rdfjs-store/d1-rdfjs-store.ts
519
+ /**
520
+ * logWriteFailure reports a fire-and-forget write failure (addQuad/removeQuad
521
+ * return synchronously, so their rejections would otherwise vanish); the write
522
+ * queue keeps draining, and the next flush() rejects with an AggregateError listing every failure since the previous flush.
523
+ */
524
+ function logWriteFailure(operation, worldId, error) {
525
+ console.error(`[d1-rdfjs-store] ${operation} write failed for world "${worldId ?? "<unscoped>"}"; awaiting flush() rejects with an AggregateError including it`, error);
526
+ }
527
+ /**
528
+ * D1RdfjsStore is a durable RDF/JS Store over Cloudflare D1. It mirrors the
529
+ * libsql reference shape (10-column `quads` table + 7 covering indexes) and
530
+ * the libsql patch-commit flow, adapted to D1's constraints:
531
+ *
532
+ * - D1 has no interactive transactions; the atomic unit is one `db.batch()`
533
+ * call, which rolls back the whole sequence on any failure. commit() and
534
+ * applyPatch() persist each patch in one batch (chunked only when the
535
+ * staged statements exceed the write batch size),
536
+ * - the 100-bound-params-per-statement cap is respected by inserting
537
+ * 10 quads per statement (10 columns × 10 rows = 100 params),
538
+ * - quad ids are content-addressed (`hashQuads`, RDFC-1.0 canonical ids)
539
+ * exactly like the libsql reference, so the same quad always maps to the
540
+ * same row and insertions are idempotent,
541
+ * - `size` is a synchronous approximation refreshed after every write
542
+ * transaction, mirroring the postgres/sqlite stores.
543
+ *
544
+ * The engine remains store-agnostic and consumes this store through its
545
+ * `createTransaction` hook:
546
+ *
547
+ * const store = new D1RdfjsStore({ connection });
548
+ * const engine = new WazooSparqlEngine({
549
+ * store,
550
+ * createTransaction: () => store.createTransaction(),
551
+ * });
552
+ */
553
+ var D1RdfjsStore = class {
554
+ connection;
555
+ matchPageSize;
556
+ writeBatchSize;
557
+ lookupChunkSize;
558
+ schemaBuilder;
559
+ worldId;
560
+ requireDerivedColumn;
561
+ writes;
562
+ constructor(options) {
563
+ validateWorldId(options.worldId, "D1RdfjsStore");
564
+ this.connection = options.connection;
565
+ this.matchPageSize = options.matchPageSize ?? 1e3;
566
+ this.writeBatchSize = options.maxWriteBatchSize ?? 2e3;
567
+ this.worldId = options.worldId;
568
+ this.lookupChunkSize = effectiveLookupChunkSize(options.maxLookupChunkSize, Boolean(this.worldId));
569
+ this.schemaBuilder = options.schemaBuilder ?? new D1SchemaBuilder(32, { worldId: options.worldId });
570
+ this.requireDerivedColumn = options.requireDerivedColumn ?? false;
571
+ this.writes = new D1WriteQueue(this.connection, this.worldId);
572
+ }
573
+ /**
574
+ * ensureSchema creates the quads/chunks tables, covering indexes, and the
575
+ * FTS5 external-content table + triggers (idempotent) and seeds the live
576
+ * count. Called by the SDK factory; safe to call again.
577
+ *
578
+ * Statements run through the prepared-statement path (not exec()) because
579
+ * D1's script executor splits on newlines, which would truncate the
580
+ * shared sql-core emitters' multi-line DDL.
581
+ */
582
+ async ensureSchema() {
583
+ await applyD1Schema(this.connection, this.schemaBuilder, {
584
+ worldId: this.worldId,
585
+ requireDerivedColumn: this.requireDerivedColumn
586
+ });
587
+ await this.writes.refreshCount();
588
+ }
589
+ /** flush resolves once every queued write has committed. */
590
+ flush() {
591
+ return this.writes.flush();
592
+ }
593
+ /**
594
+ * applyPatch persists a patch atomically in one D1 batch (chunked only when
595
+ * staged statements exceed the write batch size). Quad ids are
596
+ * content-addressed via hashQuads; only truly novel ids are inserted.
597
+ * context.importMode === "replace" clears quads and chunks first (the SDK's
598
+ * replace-import contract).
599
+ */
600
+ applyPatch(patch, context) {
601
+ return this.writes.enqueueWrite(async () => {
602
+ await applyD1Patch({
603
+ connection: this.connection,
604
+ writeBatchSize: this.writeBatchSize,
605
+ lookupChunkSize: this.lookupChunkSize,
606
+ worldId: this.worldId
607
+ }, patch, context);
608
+ });
609
+ }
610
+ /** createTransaction returns a fresh transaction over this store. */
611
+ createTransaction() {
612
+ return new D1TransactionImpl(this);
613
+ }
614
+ addQuad(quadOrSubject, predicate, object, graph) {
615
+ const quad = predicate !== void 0 && object !== void 0 ? DataFactory.quad(quadOrSubject, predicate, object, graph) : quadOrSubject;
616
+ this.writes.enqueueWrite(() => insertD1Quad(this.connection, this.worldId, quad)).catch((error) => logWriteFailure("addQuad", this.worldId, error));
617
+ return this;
618
+ }
619
+ removeQuad(quad) {
620
+ this.writes.enqueueWrite(() => deleteD1Quad(this.connection, this.worldId, quad)).catch((error) => logWriteFailure("removeQuad", this.worldId, error));
621
+ return this;
622
+ }
623
+ remove(stream) {
624
+ stream.on("data", (quad) => this.removeQuad(quad));
625
+ return stream;
626
+ }
627
+ import(stream) {
628
+ stream.on("data", (quad) => this.addQuad(quad));
629
+ return stream;
630
+ }
631
+ /**
632
+ * match returns a stream of quads matching the given quad pattern.
633
+ * Queries resolve via a single hexastore index seek with no in-memory
634
+ * hydration; reads are keyset-paged by content-addressed quad id.
635
+ */
636
+ match(subject, predicate, object, graph) {
637
+ return new D1QuadStream(() => matchD1Pages(this.connection, this.matchPageSize, this.worldId, subject, predicate, object, graph));
638
+ }
639
+ /** getQuads collects the matching quads into an array. */
640
+ getQuads(subject, predicate, object, graph) {
641
+ return collectQuads(this.match(subject, predicate, object, graph));
642
+ }
643
+ /** countQuads returns the number of quads matching the pattern. */
644
+ countQuads(subject, predicate, object, graph) {
645
+ return countD1Matches(this.connection, this.worldId, subject, predicate, object, graph);
646
+ }
647
+ /**
648
+ * removeMatches deletes every matching quad in one D1 batch and streams the
649
+ * removed quads.
650
+ */
651
+ removeMatches(subject, predicate, object, graph) {
652
+ return new D1QuadStream(() => removeMatchedQuads(this, subject, predicate, object, graph));
653
+ }
654
+ /** deleteGraph removes every quad in the named graph. */
655
+ deleteGraph(graph) {
656
+ const graphTerm = typeof graph === "string" ? DataFactory.namedNode(graph) : graph;
657
+ return this.removeMatches(null, null, null, graphTerm);
658
+ }
659
+ /**
660
+ * size is the synchronous count approximation — refreshed after every
661
+ * write transaction and on ensureSchema. D1 has no synchronous count;
662
+ * consumers needing the exact count await countQuads() instead.
663
+ */
664
+ get size() {
665
+ return this.writes.liveCount;
666
+ }
667
+ };
668
+ export { D1QuadStream as i, assertD1SchemaCompatible as n, checkD1SchemaCompatibility as r, D1RdfjsStore as t };
@@ -0,0 +1,2 @@
1
+ import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-L9cQ_Ztm.js";
2
+ export { D1QuadStream, D1RdfjsStore, type D1RdfjsStoreOptions, type D1Transaction };
@@ -0,0 +1 @@
1
+ export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-B3w5noFV.js";
@@ -0,0 +1,2 @@
1
+ import { n as D1SchemaBuilderOptions, t as D1SchemaBuilder } from "./d1-schema-builder-sx3v-XjI.js";
2
+ export { D1SchemaBuilder, D1SchemaBuilderOptions };
package/dist/schema.js ADDED
@@ -0,0 +1 @@
1
+ export { t as D1SchemaBuilder } from "./d1-schema-builder-DmrQfhKJ.js";