@wazootech/worlds-cloudflare 0.15.6 → 0.15.8

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.
package/README.md CHANGED
@@ -225,8 +225,44 @@ const sdk = await createCloudflareWorldsSdk({
225
225
  clear and the writes are separate batches, so after a failure run it again.
226
226
  - **Inconsistencies.** `backfillInference` returns the reasoner's
227
227
  `inconsistencies`; a commit does not report them and they do not block the
228
- write. SHACL validation does not exist in this package; if added, it must run
229
- after inference.
228
+ write. SHACL shapes do, and they see inferred quads.
229
+
230
+ ## SHACL shapes
231
+
232
+ A world can hold its own rules as [SHACL](https://www.w3.org/TR/shacl/) shapes, in
233
+ the named graph `https://wazoo.dev/ns/worlds#shapes`. Imports and SPARQL updates
234
+ that would break them are rejected before anything is written. This is on by
235
+ default and does nothing for a world without shapes.
236
+
237
+ ```ts
238
+ import { ShaclViolationError } from "@wazootech/worlds-sdk/shacl";
239
+
240
+ try {
241
+ await sdk.sparql({ query: "INSERT DATA { <urn:bob> a <urn:Person> }" });
242
+ } catch (error) {
243
+ if (error instanceof ShaclViolationError) console.log(error.violations);
244
+ }
245
+ ```
246
+
247
+ - **What is rejected.** Only new violations, so shapes can be added to data that
248
+ already breaks them. The rules of
249
+ [`validateWrite`](https://github.com/wazootech/worlds-sdk-ts/blob/main/ARCHITECTURE.md)
250
+ apply. Shapes that can't be used are refused with `InvalidShapesError`, and so is
251
+ a write that leaves more than 10,000 quads of them.
252
+ - **Who can change shapes.** Anyone who can write to the world. A replace import
253
+ replaces the shapes too.
254
+ - **Opting out.** `shacl: { enabled: false }` stores every write unchecked.
255
+ - **Inference.** With inference on, the quads a write adds or removes by inference
256
+ are checked with it. Shapes themselves are never inferred.
257
+ - **Cost.** A world without shapes pays one indexed read per commit, and the
258
+ validator isn't loaded. Otherwise a check reads the shapes and the facts they
259
+ look at, up to `shacl.maxCheckedFacts` (default 50,000). A write that needs more
260
+ fails with `ShaclLimitError`.
261
+ - **Simultaneous writes.** D1 has no transaction that could hold both the check and
262
+ the write. Two valid writes at the same moment can break a shape together.
263
+ - **Not checked.** Writes that go through `D1RdfjsStore` directly.
264
+ - **Existing databases.** Opening a world in a database that worlds share adds the
265
+ small index `idx_quads_shapes`. No migration is needed.
230
266
 
231
267
  ## Provenance (opt-in)
232
268
 
@@ -264,6 +300,17 @@ const { results } = await sdk.provenance({ subject });
264
300
  - **Deletion.** `purgeWorld` removes a world's records. A replace import keeps
265
301
  them.
266
302
 
303
+ ## Patterns in SPARQL
304
+
305
+ `REGEX` and `REPLACE` take patterns written like JavaScript's regular expressions.
306
+ They run on [`re2js`](https://www.npmjs.com/package/re2js), so the time a match
307
+ takes follows the length of the text.
308
+
309
+ - Look-ahead, look-behind, back-references and very large patterns are not
310
+ supported. A query that uses one fails with an error that names the pattern.
311
+ - `\s` matches a space, tab or line break, and not a non-breaking space. An emoji
312
+ counts as one character.
313
+
267
314
  ## Install
268
315
 
269
316
  ```sh
@@ -25,7 +25,8 @@ declare class D1SchemaBuilder {
25
25
  /**
26
26
  * buildIndexes returns DDL for 7 covering composite indexes on the quads table
27
27
  * (six subject-predicate-object-graph index orders + GPSO for graph-scoped access) enabling any quad pattern
28
- * to be resolved via a single index seek.
28
+ * to be resolved via a single index seek. A database that worlds share also gets a
29
+ * small index of SHACL shapes by world, because every write reads them.
29
30
  */
30
31
  buildIndexes(): string[];
31
32
  /**
@@ -1,5 +1,5 @@
1
+ import { a as buildProvenanceTable, t as SHAPES_GRAPH } from "./shapes-graph-6g22feyx.js";
1
2
  import { buildChunksQuadIdIndex } from "@wazootech/worlds-sqlite/sql-core";
2
- import { i as buildProvenanceTable } from "./d1-provenance-sql-jn_cwWxX.js";
3
3
  // src/cloudflare/validate-world-id.ts
4
4
  /**
5
5
  * validateWorldId rejects a caller-provided worldId that is not a non-empty
@@ -41,7 +41,8 @@ var D1SchemaBuilder = class {
41
41
  /**
42
42
  * buildIndexes returns DDL for 7 covering composite indexes on the quads table
43
43
  * (six subject-predicate-object-graph index orders + GPSO for graph-scoped access) enabling any quad pattern
44
- * to be resolved via a single index seek.
44
+ * to be resolved via a single index seek. A database that worlds share also gets a
45
+ * small index of SHACL shapes by world, because every write reads them.
45
46
  */
46
47
  buildIndexes() {
47
48
  return [
@@ -51,7 +52,8 @@ var D1SchemaBuilder = class {
51
52
  "CREATE INDEX IF NOT EXISTS idx_quads_pos ON quads(p, o, s)",
52
53
  "CREATE INDEX IF NOT EXISTS idx_quads_ospg ON quads(o, s, p, g)",
53
54
  "CREATE INDEX IF NOT EXISTS idx_quads_opsg ON quads(o, p, s, g)",
54
- "CREATE INDEX IF NOT EXISTS idx_quads_gpso ON quads(g, p, s, o)"
55
+ "CREATE INDEX IF NOT EXISTS idx_quads_gpso ON quads(g, p, s, o)",
56
+ ...this.worldId ? [`CREATE INDEX IF NOT EXISTS idx_quads_shapes ON quads(world_id) WHERE g = '${SHAPES_GRAPH}'`] : []
55
57
  ];
56
58
  }
57
59
  /**
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { WorldsSdkInterface } from "@wazootech/worlds-sdk";
2
- import { C as D1SearchQueryBuilder, D as D1ClientBaseOptions, E as sanitizeFtsQuery, O as InferenceOptions, S as VectorizeIndexLike, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, k as ProvenanceOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, x as VectorSearchIndex, y as recordVectorSyncError } from "./mod-Do_hSIzo.js";
2
+ import { A as ShaclOptions, C as D1SearchQueryBuilder, D as D1ClientBaseOptions, E as sanitizeFtsQuery, O as InferenceOptions, S as VectorizeIndexLike, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, k as ProvenanceOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, x as VectorSearchIndex, y as recordVectorSyncError } from "./mod-B4BJr5j0.js";
3
3
  import { a as D1Statement, i as D1Result, n as D1DatabaseLike, r as D1PreparedStatementLike, t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
4
- import { t as D1SchemaBuilder } from "./d1-schema-builder-sx3v-XjI.js";
5
- import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-L9cQ_Ztm.js";
6
- import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-BRtbH8pa.js";
4
+ import { t as D1SchemaBuilder } from "./d1-schema-builder-BLPr77rK.js";
5
+ import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-BjVVdQCh.js";
6
+ import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-BfGKU5Gt.js";
7
7
  import { InMemoryProvenanceStore, ProvenanceHistory, ProvenanceListQuery, ProvenanceRecord, ProvenanceRecordInput, ProvenanceStore } from "@wazootech/worlds-sdk/quad-store";
8
8
  import "@rdfjs/types";
9
9
  import { Inconsistency } from "@wazootech/reasoner";
@@ -202,4 +202,4 @@ export declare function purgeWorld(options: PurgeWorldOptions): Promise<PurgeWor
202
202
  * visibly (worlds-cloudflare#71).
203
203
  */
204
204
  export declare function validateWorldId(worldId: string | undefined, context: string): void;
205
- export { type BackfillInferenceOptions, type BackfillInferenceReport, type BuildSearchResultIdOptions, type CloudflareReindexResponse, CloudflareSearchIndex, type CloudflareSearchIndexOptions, type CloudflareWorldsSdkOptions, D1ConnectionDriver, type D1DatabaseLike, type D1PreparedStatementLike, type D1ProvenanceStoreOptions, D1QuadStore, type D1QuadStoreOptions, D1QuadStream, D1RdfjsStore, type D1RdfjsStoreOptions, type D1Result, D1SchemaBuilder, type D1SchemaCompatibilityIssue, type D1SchemaCompatibilityReport, D1SearchIndexProjector, D1SearchIndexProjectorOptions, D1SearchQueryBuilder, D1SearchQueryBuilderOptions, type D1Statement, type D1Transaction, D1VectorSync, type InferenceOptions, type ProjectSearchChunksOptions, type ProvenanceOptions, type PurgeWorldOptions, type PurgeWorldResult, RRF_REFERENCE_CONSTANT, ReadProjectSearchChunksOptions, RebuildD1SearchIndexFromQuadsResult, VectorSyncReport, buildChunkFtsValue, buildSearchResultId, createD1SearchIndexRebuilder, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, vectorSyncSucceeded };
205
+ export { type BackfillInferenceOptions, type BackfillInferenceReport, type BuildSearchResultIdOptions, type CloudflareReindexResponse, CloudflareSearchIndex, type CloudflareSearchIndexOptions, type CloudflareWorldsSdkOptions, D1ConnectionDriver, type D1DatabaseLike, type D1PreparedStatementLike, type D1ProvenanceStoreOptions, D1QuadStore, type D1QuadStoreOptions, D1QuadStream, D1RdfjsStore, type D1RdfjsStoreOptions, type D1Result, D1SchemaBuilder, type D1SchemaCompatibilityIssue, type D1SchemaCompatibilityReport, D1SearchIndexProjector, D1SearchIndexProjectorOptions, D1SearchQueryBuilder, D1SearchQueryBuilderOptions, type D1Statement, type D1Transaction, D1VectorSync, type InferenceOptions, type ProjectSearchChunksOptions, type ProvenanceOptions, type PurgeWorldOptions, type PurgeWorldResult, RRF_REFERENCE_CONSTANT, ReadProjectSearchChunksOptions, RebuildD1SearchIndexFromQuadsResult, type ShaclOptions, VectorSyncReport, buildChunkFtsValue, buildSearchResultId, createD1SearchIndexRebuilder, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, vectorSyncSucceeded };
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
2
2
  import { WorldsSdk } from "@wazootech/worlds-sdk";
3
3
  import { a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, d as recordVectorSyncError, f as vectorSyncSucceeded, h as sanitizeFtsQuery, i as CloudflareSearchIndex, l as logVectorSyncDrift, m as RRF_REFERENCE_CONSTANT, n as buildSearchResultId, o as rebuildD1SearchIndexFromQuads, p as D1SearchQueryBuilder, r as D1SearchIndexProjector, s as D1VectorSync, t as buildChunkFtsValue, u as mergeVectorSyncReports } from "./search-index-DVbbsc3z.js";
4
- import { a as loadAssertedQuads, i as InferenceSizeGuardError, n as D1ProvenanceStore, o as planInference, t as D1QuadStore } from "./quad-store-DX7Nqyjw.js";
4
+ import { a as loadAssertedQuads, i as InferenceSizeGuardError, n as D1ProvenanceStore, o as planInference, t as D1QuadStore } from "./quad-store-C1IJEz2D.js";
5
5
  import { a as DEFAULT_D1_MAX_BATCH_WEIGHT, o as d1StatementWeight } from "./project-search-chunks-options-qI9m5FWz.js";
6
6
  import { WazooSparqlEngine } from "@wazootech/sparql-engine";
7
- import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-B3w5noFV.js";
8
- import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-DmrQfhKJ.js";
7
+ import { RE2JS } from "re2js";
8
+ import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-DfmCIuVz.js";
9
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
9
10
  import { g as DEFAULT_D1_MAX_WRITE_BATCH_SIZE, h as D1BatchExecutor, m as quadToInsertRow, s as buildDeleteAllDerivedQuads, t as buildBulkInsertQuads, u as buildWipeAllGraphDataStatements } from "./d1-quad-insert-sql-B4ZiZZe8.js";
10
11
  // src/cloudflare/search-index/vector-search/vectorize-provisioning.ts
11
12
  /**
@@ -163,6 +164,106 @@ var D1ConnectionDriver = class {
163
164
  await this.database.exec(sql);
164
165
  }
165
166
  };
167
+ // src/cloudflare/patterns/linear-pattern.ts
168
+ /** LinearPattern matches in time that grows with the length of the text only. */
169
+ var LinearPattern = class {
170
+ compiled;
171
+ constructor(compiled) {
172
+ this.compiled = compiled;
173
+ }
174
+ test(text) {
175
+ return this.compiled.matcher(text).find();
176
+ }
177
+ replace(text, replacement) {
178
+ const match = this.compiled.matcher(text);
179
+ let result = "";
180
+ let end = 0;
181
+ while (match.find()) {
182
+ result += text.slice(end, match.start());
183
+ result += expandReplacement(replacement, match);
184
+ end = match.end();
185
+ }
186
+ return result + text.slice(end);
187
+ }
188
+ };
189
+ /**
190
+ * expandReplacement fills in a replacement as JavaScript does: `$&` is the match,
191
+ * `$1` to `$99` are its groups, and `$$` is a dollar sign. A number without a
192
+ * group stays as it is written.
193
+ */
194
+ function expandReplacement(replacement, match) {
195
+ return replacement.replace(/\$(?:([$&])|(\d\d?))/g, (written, symbol, digits = "") => {
196
+ if (symbol === "$") return "$";
197
+ if (symbol === "&") return match.group() ?? "";
198
+ for (const length of [2, 1]) {
199
+ const index = Number(digits.slice(0, length));
200
+ if (index > 0 && index <= match.groupCount()) return (match.group(index) ?? "") + digits.slice(length);
201
+ }
202
+ return written;
203
+ });
204
+ }
205
+ // src/cloudflare/patterns/create-pattern-compiler.ts
206
+ /** MAX_KEPT_PATTERNS is how many compiled patterns a compiler keeps. */
207
+ const MAX_KEPT_PATTERNS = 100;
208
+ /** MAX_PATTERN_LENGTH is how many characters a pattern may have. */
209
+ const MAX_PATTERN_LENGTH = 4e3;
210
+ /**
211
+ * MAX_PATTERN_STEPS is how large a compiled pattern may be. Matching takes up to
212
+ * this many steps for each character of the text, and `a{500}` alone has 500.
213
+ */
214
+ const MAX_PATTERN_STEPS = 1e3;
215
+ const FLAGS = {
216
+ i: RE2JS.CASE_INSENSITIVE,
217
+ m: RE2JS.MULTILINE,
218
+ s: RE2JS.DOTALL,
219
+ d: 0,
220
+ g: 0,
221
+ u: 0
222
+ };
223
+ /**
224
+ * createPatternCompiler prepares the patterns of REGEX and REPLACE for a service
225
+ * that runs other people's queries. They are written like JavaScript's regular
226
+ * expressions, without look-ahead, look-behind and back-references. A query with a
227
+ * pattern that isn't supported fails with an error that says so, and a malformed
228
+ * pattern is an evaluation error, as it is by default.
229
+ */
230
+ function createPatternCompiler() {
231
+ const kept = /* @__PURE__ */ new Map();
232
+ return (pattern, flags) => {
233
+ const key = `${flags}/${pattern}`;
234
+ if (kept.has(key)) return kept.get(key);
235
+ const compiled = compile(pattern, flags);
236
+ if (kept.size >= MAX_KEPT_PATTERNS) kept.clear();
237
+ kept.set(key, compiled);
238
+ return compiled;
239
+ };
240
+ }
241
+ function compile(pattern, flags) {
242
+ if (pattern.length > MAX_PATTERN_LENGTH) throw unsupported(pattern, "too long");
243
+ try {
244
+ new RegExp(pattern, flags);
245
+ } catch {
246
+ return;
247
+ }
248
+ let options = 0;
249
+ for (const flag of flags) {
250
+ const option = FLAGS[flag];
251
+ if (option === void 0) throw unsupported(pattern, `flag "${flag}"`);
252
+ options |= option;
253
+ }
254
+ let compiled;
255
+ try {
256
+ compiled = RE2JS.compile(RE2JS.translateRegExp(pattern), options);
257
+ } catch (error) {
258
+ throw unsupported(pattern, (error instanceof Error ? error.message : String(error)).replace("error parsing regexp: ", ""));
259
+ }
260
+ if (compiled.programSize() > MAX_PATTERN_STEPS) throw unsupported(pattern, "too complex");
261
+ return new LinearPattern(compiled);
262
+ }
263
+ function unsupported(pattern, reason) {
264
+ const start = pattern.length > 50 ? `${pattern.slice(0, 50)}…` : pattern;
265
+ return /* @__PURE__ */ new Error(`The pattern "${start}" is not supported: ${reason.slice(0, 100)}`);
266
+ }
166
267
  // src/cloudflare/provenance/provenance-sparql-engine.ts
167
268
  /**
168
269
  * ProvenanceSparqlEngine commits each SPARQL update with its request's writer
@@ -172,6 +273,7 @@ var D1ConnectionDriver = class {
172
273
  */
173
274
  var ProvenanceSparqlEngine = class {
174
275
  options;
276
+ compilePattern = createPatternCompiler();
175
277
  shared;
176
278
  constructor(options) {
177
279
  this.options = options;
@@ -185,6 +287,7 @@ var ProvenanceSparqlEngine = class {
185
287
  const { store, quadStore } = this.options;
186
288
  return new WazooSparqlEngine({
187
289
  store,
290
+ compilePattern: this.compilePattern,
188
291
  createTransaction: () => quadStore.createTransaction(provenance && { provenance })
189
292
  });
190
293
  }
@@ -41,6 +41,19 @@ interface ProvenanceOptions {
41
41
  */
42
42
  history?: boolean;
43
43
  }
44
+ /**
45
+ * ShaclOptions controls how writes are checked against the world's SHACL shapes,
46
+ * which are the quads in `https://wazoo.dev/ns/worlds#shapes`.
47
+ */
48
+ interface ShaclOptions {
49
+ /** enabled set to false stores every write unchecked. Checking is on by default. */
50
+ enabled?: boolean;
51
+ /**
52
+ * maxCheckedFacts is how many stored quads one check may read (default 50000). A
53
+ * write that needs more fails with `ShaclLimitError`.
54
+ */
55
+ maxCheckedFacts?: number;
56
+ }
44
57
  /**
45
58
  * D1ClientBaseOptions lists configuration shared by quad index Cloudflare D1 client factories.
46
59
  */
@@ -82,6 +95,11 @@ interface D1ClientBaseOptions extends QuadFilter {
82
95
  * world: a commit made without it leaves a gap.
83
96
  */
84
97
  provenance?: ProvenanceOptions;
98
+ /**
99
+ * shacl controls the check of each write against the world's own shapes. It is on
100
+ * by default and does nothing for a world without shapes.
101
+ */
102
+ shacl?: ShaclOptions;
85
103
  }
86
104
  /**
87
105
  * RRF_REFERENCE_CONSTANT is the reciprocal-rank constant used by both backends
@@ -449,4 +467,4 @@ declare function rebuildD1SearchIndexFromQuads(options: ReadProjectSearchChunksO
449
467
  * createD1SearchIndexRebuilder returns a closure that rebuilds search chunks using stable D1 dependencies.
450
468
  */
451
469
  declare function createD1SearchIndexRebuilder(dependencies: ReadProjectSearchChunksOptions): () => Promise<RebuildD1SearchIndexFromQuadsResult>;
452
- export { D1SearchQueryBuilder as C, D1ClientBaseOptions as D, sanitizeFtsQuery as E, InferenceOptions as O, VectorizeIndexLike as S, RRF_REFERENCE_CONSTANT as T, logVectorSyncDrift as _, RebuildD1SearchIndexFromQuadsResult as a, vectorSyncSucceeded as b, D1SearchIndexProjector as c, ProjectSearchChunksOptions as d, CloudflareSearchIndex as f, emptyVectorSyncReport as g, VectorSyncReport as h, ReadProjectSearchChunksOptions as i, ProvenanceOptions as k, D1SearchIndexProjectorOptions as l, CloudflareSearchIndexOptions as m, buildChunkFtsValue as n, createD1SearchIndexRebuilder as o, CloudflareReindexResponse as p, buildSearchResultId as r, rebuildD1SearchIndexFromQuads as s, BuildSearchResultIdOptions as t, D1VectorSync as u, mergeVectorSyncReports as v, D1SearchQueryBuilderOptions as w, VectorSearchIndex as x, recordVectorSyncError as y };
470
+ export { ShaclOptions as A, D1SearchQueryBuilder as C, D1ClientBaseOptions as D, sanitizeFtsQuery as E, InferenceOptions as O, VectorizeIndexLike as S, RRF_REFERENCE_CONSTANT as T, logVectorSyncDrift as _, RebuildD1SearchIndexFromQuadsResult as a, vectorSyncSucceeded as b, D1SearchIndexProjector as c, ProjectSearchChunksOptions as d, CloudflareSearchIndex as f, emptyVectorSyncReport as g, VectorSyncReport as h, ReadProjectSearchChunksOptions as i, ProvenanceOptions as k, D1SearchIndexProjectorOptions as l, CloudflareSearchIndexOptions as m, buildChunkFtsValue as n, createD1SearchIndexRebuilder as o, CloudflareReindexResponse as p, buildSearchResultId as r, rebuildD1SearchIndexFromQuads as s, BuildSearchResultIdOptions as t, D1VectorSync as u, mergeVectorSyncReports as v, D1SearchQueryBuilderOptions as w, VectorSearchIndex as x, recordVectorSyncError as y };
@@ -1,7 +1,7 @@
1
1
  import { ExportRequest, ExportResponse, ImportRequest, ProvenanceQueryHandler, ProvenanceQueryRequest, ProvenanceQueryResponse, QuadStoreInterface, Transaction, TransactionContext } from "@wazootech/worlds-sdk/quad-store";
2
- import { C as D1SearchQueryBuilder, D as D1ClientBaseOptions, c as D1SearchIndexProjector } from "./mod-Do_hSIzo.js";
2
+ import { C as D1SearchQueryBuilder, D as D1ClientBaseOptions, c as D1SearchIndexProjector } from "./mod-B4BJr5j0.js";
3
3
  import { t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
4
- import { t as D1RdfjsStore } from "./mod-L9cQ_Ztm.js";
4
+ import { t as D1RdfjsStore } from "./mod-BjVVdQCh.js";
5
5
  /**
6
6
  * D1QuadStoreOptions defines the configurations for the D1QuadStore.
7
7
  */
@@ -1,7 +1,7 @@
1
1
  import * as rdfjs from "@rdfjs/types";
2
2
  import { Patch, TransactionContext } from "@wazootech/worlds-sdk/quad-store";
3
3
  import { t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
4
- import { t as D1SchemaBuilder } from "./d1-schema-builder-sx3v-XjI.js";
4
+ import { t as D1SchemaBuilder } from "./d1-schema-builder-BLPr77rK.js";
5
5
  type Listener = (...args: any[]) => void;
6
6
  /**
7
7
  * D1QuadStream is a minimal RDF/JS Stream backed by an async page generator
@@ -1,10 +1,10 @@
1
- import { InMemoryProvenanceStore, Transaction, exportFromRdfjsStore, hashQuads, importViaTransaction, isReplaceImportCommit, preparePatch } from "@wazootech/worlds-sdk/quad-store";
1
+ import { InMemoryProvenanceStore, Transaction, exportFromRdfjsStore, filterQuads, hashQuads, importViaTransaction, isReplaceImportCommit, preparePatch } from "@wazootech/worlds-sdk/quad-store";
2
2
  import { planSearchIndexing } from "@wazootech/worlds-sdk/search-index";
3
3
  import { commitSqlPatch } from "@wazootech/worlds-sqlite/sql-core";
4
4
  import { _ as effectiveLookupChunkSize, a as buildSelectAssertedQuadsPage, d as DEFAULT_D1_MATCH_PAGE_SIZE, f as buildInsertRow, n as buildCountAssertedQuads, p as quadFromD1Row } from "./d1-quad-insert-sql-B4ZiZZe8.js";
5
- import { a as buildSelectProvenance, c as chunk, n as buildDeleteWriteRecords, o as buildSelectProvenanceChains, r as buildInsertProvenance, s as buildSelectQuadRecords, t as PROVENANCE_IDS_PER_STATEMENT } from "./d1-provenance-sql-jn_cwWxX.js";
6
- import { i as createD1CommitDriver, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
5
+ import { c as buildSelectQuadRecords, i as buildInsertProvenance, l as chunk, n as PROVENANCE_IDS_PER_STATEMENT, o as buildSelectProvenance, r as buildDeleteWriteRecords, s as buildSelectProvenanceChains, t as SHAPES_GRAPH } from "./shapes-graph-6g22feyx.js";
7
6
  import { Reasoner } from "@wazootech/reasoner";
7
+ import { i as createD1CommitDriver, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
8
8
  import { r as matchD1Pages } from "./d1-rdfjs-store-read-2QTEEe_a.js";
9
9
  // src/cloudflare/provenance/read-stored-quads.ts
10
10
  /** selectStored runs one read; it names `derived` only when inference guarantees the column. */
@@ -142,6 +142,96 @@ function dedupe(quads) {
142
142
  for (const quad of quads) seen.set(quadKey(quad), quad);
143
143
  return [...seen.values()];
144
144
  }
145
+ // src/cloudflare/shacl/create-d1-shacl-source.ts
146
+ /** MAX_SHAPE_QUADS is how large a world's shapes graph may be. */
147
+ const MAX_SHAPE_QUADS = 1e4;
148
+ const VALUES_PER_STATEMENT = 2e3;
149
+ const CHARACTERS_PER_STATEMENT = 4e5;
150
+ /** createD1ShaclSource reads the facts that a SHACL check asks for from D1. */
151
+ function createD1ShaclSource(options) {
152
+ const { connection, worldId, inferenceEnabled } = options;
153
+ async function select(condition, args, limit, world = "world_id") {
154
+ const { rows } = await connection.execute({
155
+ sql: `SELECT s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type FROM quads WHERE ${condition}${worldId ? ` AND ${world} = ?` : ""} LIMIT ${Math.min(Math.floor(limit), Number.MAX_SAFE_INTEGER)}`,
156
+ args: worldId ? [...args, worldId] : args
157
+ });
158
+ return rows.map(quadFromD1Row);
159
+ }
160
+ /** selectAmong runs one statement per group of values, up to one row over the limit. */
161
+ async function selectAmong(column, terms, predicates, limit) {
162
+ const found = [];
163
+ const among = (name) => `${name} IN (SELECT value FROM json_each(?))`;
164
+ for (const values of groupValues(terms)) {
165
+ const rows = await select(`${predicates ? `${among("p")} AND ` : ""}${among(column)} AND g <> '${SHAPES_GRAPH}'`, [...predicates ? [JSON.stringify(predicates)] : [], values], limit + 1 - found.length, "+world_id");
166
+ for (const row of rows) found.push(row);
167
+ if (found.length > limit) break;
168
+ }
169
+ return found;
170
+ }
171
+ return {
172
+ shapes: () => select(`g = '${SHAPES_GRAPH}'${inferenceEnabled ? " AND derived = 0" : ""}`, [], 10001),
173
+ outgoing: ({ subjects, predicates, limit }) => selectAmong("s", subjects, predicates, limit),
174
+ incoming: ({ objects, predicate, limit }) => selectAmong("o", objects, [predicate], limit)
175
+ };
176
+ }
177
+ /** groupValues packs the terms' values into JSON lists that fit a D1 parameter. */
178
+ function* groupValues(terms) {
179
+ let group = [];
180
+ let characters = 0;
181
+ for (const value of new Set(terms.map((term) => term.value))) {
182
+ if ((group.length >= VALUES_PER_STATEMENT || characters + value.length > CHARACTERS_PER_STATEMENT) && group.length > 0) {
183
+ yield JSON.stringify(group);
184
+ group = [];
185
+ characters = 0;
186
+ }
187
+ group.push(value);
188
+ characters += value.length;
189
+ }
190
+ if (group.length > 0) yield JSON.stringify(group);
191
+ }
192
+ // src/cloudflare/shacl/check-d1-patch.ts
193
+ /**
194
+ * checkD1Patch rejects when a commit would add violations of the world's SHACL
195
+ * shapes, counting the inferred quads it adds and removes. Call it before
196
+ * anything is written. A world without shapes costs one indexed read, and never
197
+ * loads the validator.
198
+ */
199
+ async function checkD1Patch(patch, context, options, derived) {
200
+ if (options.shacl?.enabled === false) return;
201
+ const matches = filterQuads(options);
202
+ const insertions = patch.insertions.filter(matches);
203
+ const deletions = patch.deletions.filter(matches);
204
+ const source = createD1ShaclSource({
205
+ connection: options.connection,
206
+ worldId: options.worldId,
207
+ inferenceEnabled: options.inference?.enabled === true
208
+ });
209
+ const shapes = isReplaceImportCommit(context) ? [] : await source.shapes();
210
+ if (shapes.length === 0 && !insertions.some(isShape)) return;
211
+ const { InvalidShapesError, validateWrite } = await import("@wazootech/worlds-sdk/shacl");
212
+ if (countShapesAfter(shapes, insertions, deletions) > 1e4) throw new InvalidShapesError([`A world can have at most ${MAX_SHAPE_QUADS} quads of shapes.`]);
213
+ await validateWrite({
214
+ patch: {
215
+ insertions: [...insertions, ...(derived?.added ?? []).filter((quad) => !isShape(quad))],
216
+ deletions: [...deletions, ...(derived?.removed ?? []).filter((quad) => !isShape(quad))]
217
+ },
218
+ context,
219
+ source: {
220
+ ...source,
221
+ shapes: () => Promise.resolve(shapes)
222
+ },
223
+ maxCheckedFacts: options.shacl?.maxCheckedFacts
224
+ });
225
+ }
226
+ function isShape(quad) {
227
+ return quad.graph.value === SHAPES_GRAPH;
228
+ }
229
+ function countShapesAfter(stored, insertions, deletions) {
230
+ const keys = new Set(stored.map(quadKey));
231
+ for (const quad of deletions) keys.delete(quadKey(quad));
232
+ for (const quad of insertions) if (isShape(quad)) keys.add(quadKey(quad));
233
+ return keys.size;
234
+ }
145
235
  // src/cloudflare/inference/load-asserted-quads.ts
146
236
  /** DEFAULT_MAX_ASSERTED_QUADS is the default inference size guard. */
147
237
  const DEFAULT_MAX_ASSERTED_QUADS = 1e5;
@@ -212,7 +302,9 @@ async function planD1DerivedChanges(patch, context, inference, driverOptions) {
212
302
  });
213
303
  return {
214
304
  removeIds: hashQuads(plan.derivedToRemove),
215
- addRows: [...addRows.values()]
305
+ addRows: [...addRows.values()],
306
+ removed: plan.derivedToRemove,
307
+ added: derived
216
308
  };
217
309
  }
218
310
  // src/cloudflare/commit/commit-d1-patch.ts
@@ -221,7 +313,8 @@ async function planD1DerivedChanges(patch, context, inference, driverOptions) {
221
313
  * (`commitSqlPatch`). D1 batches are not atomic with the outside-D1 Vectorize
222
314
  * index, which the platform forces: vectors sync after the D1 write lands, and
223
315
  * a failure there is logged drift that a reindex repairs. An embedding failure
224
- * throws before anything is written, so the caller can retry. Imports project
316
+ * throws before anything is written, so the caller can retry. So does a SHACL
317
+ * violation. Imports project
225
318
  * chunks during the commit (`searchIndexOnImport` defaults to the shared
226
319
  * `"incremental"`); `"deferred"` stays available as an option.
227
320
  */
@@ -235,6 +328,7 @@ async function commitD1Patch(patch, context, options) {
235
328
  beforePage: sync?.beforePage
236
329
  };
237
330
  const derived = options.inference?.enabled ? await planD1DerivedChanges(patch, context, options.inference, driverOptions) : void 0;
331
+ await checkD1Patch(patch, context, options, derived);
238
332
  const provenance = options.provenance?.enabled ? await planD1Provenance(patch, context, driverOptions) : void 0;
239
333
  const indexing = planSearchIndexing(options.searchIndexOnImport, context);
240
334
  const dialect = createD1CommitDialect({
@@ -1,2 +1,2 @@
1
- import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-BRtbH8pa.js";
1
+ import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-BfGKU5Gt.js";
2
2
  export { D1QuadStore, type D1QuadStoreOptions };
@@ -1 +1 @@
1
- export { t as D1QuadStore } from "./quad-store-DX7Nqyjw.js";
1
+ export { t as D1QuadStore } from "./quad-store-C1IJEz2D.js";
@@ -1,6 +1,6 @@
1
1
  import { DataFactory } from "@wazootech/sparql-engine";
2
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";
3
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
4
4
  import { hashQuads, isReplaceImportCommit } from "@wazootech/worlds-sdk/quad-store";
5
5
  import { i as removeMatchedQuads, n as countD1Matches, r as matchD1Pages, t as collectQuads } from "./d1-rdfjs-store-read-2QTEEe_a.js";
6
6
  // src/cloudflare/rdfjs-store/d1-quad-stream.ts
@@ -1,2 +1,2 @@
1
- import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-L9cQ_Ztm.js";
1
+ import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-BjVVdQCh.js";
2
2
  export { D1QuadStream, D1RdfjsStore, type D1RdfjsStoreOptions, type D1Transaction };
@@ -1 +1 @@
1
- export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-B3w5noFV.js";
1
+ export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-DfmCIuVz.js";
package/dist/schema.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { n as D1SchemaBuilderOptions, t as D1SchemaBuilder } from "./d1-schema-builder-sx3v-XjI.js";
1
+ import { n as D1SchemaBuilderOptions, t as D1SchemaBuilder } from "./d1-schema-builder-BLPr77rK.js";
2
2
  export { D1SchemaBuilder, D1SchemaBuilderOptions };
package/dist/schema.js CHANGED
@@ -1 +1 @@
1
- export { t as D1SchemaBuilder } from "./d1-schema-builder-DmrQfhKJ.js";
1
+ export { t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
@@ -1,2 +1,2 @@
1
- import { C as D1SearchQueryBuilder, E as sanitizeFtsQuery, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, y as recordVectorSyncError } from "./mod-Do_hSIzo.js";
1
+ import { C as D1SearchQueryBuilder, E as sanitizeFtsQuery, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, y as recordVectorSyncError } from "./mod-B4BJr5j0.js";
2
2
  export { type BuildSearchResultIdOptions, type CloudflareReindexResponse, CloudflareSearchIndex, type CloudflareSearchIndexOptions, D1SearchIndexProjector, D1SearchIndexProjectorOptions, D1SearchQueryBuilder, D1SearchQueryBuilderOptions, D1VectorSync, type ProjectSearchChunksOptions, RRF_REFERENCE_CONSTANT, ReadProjectSearchChunksOptions, RebuildD1SearchIndexFromQuadsResult, VectorSyncReport, buildChunkFtsValue, buildSearchResultId, createD1SearchIndexRebuilder, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, vectorSyncSucceeded };
@@ -96,4 +96,11 @@ function buildSelectProvenanceChains(quadIds, worldId) {
96
96
  ]
97
97
  };
98
98
  }
99
- export { buildSelectProvenance as a, chunk as c, buildProvenanceTable as i, buildDeleteWriteRecords as n, buildSelectProvenanceChains as o, buildInsertProvenance as r, buildSelectQuadRecords as s, PROVENANCE_IDS_PER_STATEMENT as t };
99
+ // src/cloudflare/shacl/shapes-graph.ts
100
+ /**
101
+ * SHAPES_GRAPH is the named graph that holds a world's SHACL shapes. It is the
102
+ * constant of the same name in `@wazootech/worlds-sdk/shacl`, written out so that
103
+ * a world without shapes never loads the validator.
104
+ */
105
+ const SHAPES_GRAPH = "https://wazoo.dev/ns/worlds#shapes";
106
+ export { buildProvenanceTable as a, buildSelectQuadRecords as c, buildInsertProvenance as i, chunk as l, PROVENANCE_IDS_PER_STATEMENT as n, buildSelectProvenance as o, buildDeleteWriteRecords as r, buildSelectProvenanceChains as s, SHAPES_GRAPH as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wazootech/worlds-cloudflare",
3
- "version": "0.15.6",
3
+ "version": "0.15.8",
4
4
  "description": "Store a Worlds knowledge graph in Cloudflare D1, with keyword search, optional Vectorize search, SPARQL and provenance. Made for Cloudflare Workers.",
5
5
  "keywords": [
6
6
  "wazoo",
@@ -59,6 +59,7 @@
59
59
  "build": "tsdown",
60
60
  "check": "bun check --no-script",
61
61
  "check:package": "bun scripts/check-package.ts",
62
+ "mutation": "stryker run",
62
63
  "ci": "bun run fmt:check && bun run lint && bun run check && bun run test",
63
64
  "fmt": "bun fmt --no-script",
64
65
  "fmt:check": "bun fmt --no-script --check",
@@ -71,11 +72,13 @@
71
72
  "@langchain/textsplitters": "^1.0.1",
72
73
  "@rdfjs/types": "^2.0.1",
73
74
  "@wazootech/reasoner": "^0.4.4",
74
- "@wazootech/sparql-engine": "^0.5.8",
75
- "@wazootech/worlds-sdk": "^0.11.3",
76
- "@wazootech/worlds-sqlite": "^0.8.4"
75
+ "@wazootech/sparql-engine": "^0.5.11",
76
+ "@wazootech/worlds-sdk": "^0.11.5",
77
+ "@wazootech/worlds-sqlite": "^0.8.4",
78
+ "re2js": "2.10.0"
77
79
  },
78
80
  "devDependencies": {
81
+ "@stryker-mutator/core": "10.1.1",
79
82
  "@types/node": "24.19.2",
80
83
  "esbuild": "0.28.2",
81
84
  "miniflare": "^4.20260730.0",