@wazootech/worlds-cloudflare 0.15.7 → 0.15.9

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
 
@@ -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,12 +1,12 @@
1
1
  import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
2
2
  import { WorldsSdk } from "@wazootech/worlds-sdk";
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";
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-_yyeZAVm.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
7
  import { RE2JS } from "re2js";
8
- import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-B3w5noFV.js";
9
- import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-DmrQfhKJ.js";
8
+ import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-YJhcJ8eq.js";
9
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
10
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";
11
11
  // src/cloudflare/search-index/vector-search/vectorize-provisioning.ts
12
12
  /**
@@ -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
@@ -168,7 +168,7 @@ var D1TransactionImpl = class {
168
168
  this.inserted.set(quadKey(quad), quad);
169
169
  }
170
170
  delete(quad) {
171
- if (this.inserted.delete(quadKey(quad))) return;
171
+ this.inserted.delete(quadKey(quad));
172
172
  this.deleted.set(quadKey(quad), quad);
173
173
  }
174
174
  commit() {
@@ -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-YJhcJ8eq.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";
@@ -2,7 +2,8 @@ import { RRF_FUSION_K, buildChunkFtsValue, buildIncludeExcludeFilterClauses, bui
2
2
  import { normalizeRrfScore } from "@wazootech/worlds-sdk/search-index";
3
3
  import { _ as effectiveLookupChunkSize } from "./d1-quad-insert-sql-B4ZiZZe8.js";
4
4
  import { i as createD1CommitDriver, n as toProjectionOptions, r as vectorSyncEnabled, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
5
- import { hashQuads } from "@wazootech/worlds-sdk/quad-store";
5
+ import { filterQuads, hashQuads } from "@wazootech/worlds-sdk/quad-store";
6
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
6
7
  // src/cloudflare/search-index/d1-world-scoped-fts.ts
7
8
  /** RRF constant shared with the generic keyword plan (1 / (60 + rank)). */
8
9
  const RRF_K = 60;
@@ -489,6 +490,20 @@ function hitToSearchResult(hit) {
489
490
  function clampCosine(score) {
490
491
  return Math.max(0, Math.min(1, score));
491
492
  }
493
+ // src/cloudflare/search-index/filter-vector-hits.ts
494
+ const { literal, namedNode, quad } = DataFactory;
495
+ /**
496
+ * filterVectorHits keeps the hits that match a request's include and exclude,
497
+ * in order, with the meaning they have for stored facts and for the keyword
498
+ * query. The vector index can only filter on `world_id`, so this runs after its
499
+ * query. The index then returns its nearest `candidateCount` hits of the whole
500
+ * world, and a narrow filter can leave fewer vector results than that. The
501
+ * keyword query filters in SQL and is not affected.
502
+ */
503
+ function filterVectorHits(hits, filter) {
504
+ const matches = filterQuads(filter);
505
+ return hits.filter(({ metadata }) => matches(quad(namedNode(metadata?.subject ?? ""), namedNode(metadata?.predicate ?? ""), literal(metadata?.value ?? ""), namedNode(metadata?.graph ?? ""))));
506
+ }
492
507
  // src/cloudflare/search-index/cloudflare-search-index.ts
493
508
  /**
494
509
  * CloudflareSearchIndex implements the query pathway over D1's FTS5
@@ -540,10 +555,10 @@ var CloudflareSearchIndex = class {
540
555
  if (this.options.embeddingService && this.options.vectorSearch) try {
541
556
  const embedded = await this.options.embeddingService.embed([request.query]);
542
557
  const queryVector = embedded[0] ? new Float32Array(embedded[0]) : void 0;
543
- if (queryVector) vectorHits = await this.options.vectorSearch.query(Array.from(queryVector), {
558
+ if (queryVector) vectorHits = filterVectorHits(await this.options.vectorSearch.query(Array.from(queryVector), {
544
559
  topK: candidateCount,
545
560
  ...this.options.worldId ? { filter: { world_id: this.options.worldId } } : {}
546
- });
561
+ }), request);
547
562
  } catch (error) {
548
563
  console.warn("[Search Warning] vector query failed; falling back to keyword-only", error);
549
564
  }
@@ -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 };
@@ -1 +1 @@
1
- export { i as CloudflareSearchIndex, r as D1SearchIndexProjector, p as D1SearchQueryBuilder, s as D1VectorSync, m as RRF_REFERENCE_CONSTANT, t as buildChunkFtsValue, n as buildSearchResultId, a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, l as logVectorSyncDrift, u as mergeVectorSyncReports, o as rebuildD1SearchIndexFromQuads, d as recordVectorSyncError, h as sanitizeFtsQuery, f as vectorSyncSucceeded } from "./search-index-DVbbsc3z.js";
1
+ export { i as CloudflareSearchIndex, r as D1SearchIndexProjector, p as D1SearchQueryBuilder, s as D1VectorSync, m as RRF_REFERENCE_CONSTANT, t as buildChunkFtsValue, n as buildSearchResultId, a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, l as logVectorSyncDrift, u as mergeVectorSyncReports, o as rebuildD1SearchIndexFromQuads, d as recordVectorSyncError, h as sanitizeFtsQuery, f as vectorSyncSucceeded } from "./search-index-_yyeZAVm.js";
@@ -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.7",
3
+ "version": "0.15.9",
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,12 +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.11",
75
- "@wazootech/worlds-sdk": "^0.11.3",
76
- "@wazootech/worlds-sqlite": "^0.8.4",
75
+ "@wazootech/sparql-engine": "^0.5.12",
76
+ "@wazootech/worlds-sdk": "^0.11.6",
77
+ "@wazootech/worlds-sqlite": "^0.8.5",
77
78
  "re2js": "2.10.0"
78
79
  },
79
80
  "devDependencies": {
81
+ "@stryker-mutator/core": "10.1.1",
80
82
  "@types/node": "24.19.2",
81
83
  "esbuild": "0.28.2",
82
84
  "miniflare": "^4.20260730.0",