@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,205 @@
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";
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";
7
+ import { InMemoryProvenanceStore, ProvenanceHistory, ProvenanceListQuery, ProvenanceRecord, ProvenanceRecordInput, ProvenanceStore } from "@wazootech/worlds-sdk/quad-store";
8
+ import "@rdfjs/types";
9
+ import { Inconsistency } from "@wazootech/reasoner";
10
+ /**
11
+ * CloudflareWorldsSdkOptions configures Cloudflare D1 execution through D1RdfjsStore and quad indexes.
12
+ */
13
+ interface CloudflareWorldsSdkOptions extends D1ClientBaseOptions {
14
+ /** database is the raw D1 binding (miniflare or a real Worker binding). */
15
+ database: D1DatabaseLike;
16
+ /**
17
+ * worldId scopes all quad and search-index operations when provided.
18
+ * Required when `vectorize` is set: the Vectorize index is shared across
19
+ * worlds, so an unscoped SDK would write and query vectors across them.
20
+ */
21
+ worldId?: string;
22
+ /**
23
+ * candidateCount sizes the search-index candidate pool at the SQL level
24
+ * (provider-internal per the hosted search contract, worlds-api#30 D2).
25
+ * Routes pass `max(limit, world.topK)`. Defaults to the search index's
26
+ * `limit` (100) when unset.
27
+ */
28
+ candidateCount?: number;
29
+ /**
30
+ * vectorize is the Cloudflare Vectorize binding for the outside-D1 vector
31
+ * index (Phase C, worlds-api#1). The index must register `world_id` as a
32
+ * filterable metadata property. When set (with an embeddingService), imports
33
+ * populate vectors and searches fuse keyword + vector rankings.
34
+ */
35
+ vectorize?: VectorizeIndexLike;
36
+ }
37
+ /**
38
+ * createCloudflareWorldsSdk synthesizes a WorldsSdk for D1-backed quad indexes.
39
+ *
40
+ * The factory assembles the three strategy objects internally: a
41
+ * D1ConnectionDriver over the raw D1 binding, a D1SchemaBuilder, and a
42
+ * D1SearchQueryBuilder. Callers pass the plain D1 database binding.
43
+ */
44
+ export declare function createCloudflareWorldsSdk(options: CloudflareWorldsSdkOptions): Promise<WorldsSdkInterface>;
45
+ interface D1SchemaCompatibilityIssue {
46
+ table: string;
47
+ detail: string;
48
+ }
49
+ interface D1SchemaCompatibilityReport {
50
+ compatible: boolean;
51
+ issues: D1SchemaCompatibilityIssue[];
52
+ schemaVersion: number | null;
53
+ }
54
+ interface D1SchemaCompatibilityOptions {
55
+ worldId?: string;
56
+ /**
57
+ * requireDerivedColumn also requires `quads.derived`. Databases created
58
+ * before inference existed lack it; add it with
59
+ * `migrations/0001-quads-derived-column.sql`. Worlds that do not opt in to
60
+ * inference never need it, so the schema version is unchanged.
61
+ */
62
+ requireDerivedColumn?: boolean;
63
+ }
64
+ /** Inspect the actual D1 schema and report missing required tables or columns. */
65
+ export declare function checkD1SchemaCompatibility(connection: D1ConnectionDriver, options?: D1SchemaCompatibilityOptions): Promise<D1SchemaCompatibilityReport>;
66
+ /** Validate the schema and throw an actionable error before serving traffic. */
67
+ export declare function assertD1SchemaCompatible(connection: D1ConnectionDriver, options?: D1SchemaCompatibilityOptions): Promise<void>;
68
+ /**
69
+ * DEFAULT_D1_MAX_BATCH_WEIGHT is the estimated serialized bytes one D1
70
+ * `batch()` call may carry (16 MiB). The Worker-to-D1 RPC rejects a batch whose
71
+ * serialized arguments exceed 32 MiB (measured on a real D1, 2026-11-22, see
72
+ * README), so this leaves 2x headroom for the estimator's error.
73
+ */
74
+ export declare const DEFAULT_D1_MAX_BATCH_WEIGHT: number;
75
+ /**
76
+ * d1StatementWeight ESTIMATES the serialized bytes of one D1 statement: the SQL
77
+ * text length, a fixed overhead, and each bound parameter (strings by UTF-16
78
+ * code units, BLOBs at `BLOB_BYTE_WEIGHT` per byte, scalars a few bytes). It is
79
+ * calibrated from measured real-D1 points, not a contract, and errs high.
80
+ */
81
+ export declare function d1StatementWeight(statement: D1Statement): number;
82
+ /**
83
+ * DEFAULT_D1_MAX_WRITE_BATCH_SIZE limits statements per D1 batch() call (and is
84
+ * the atomic statement limit of a commit). It is a chosen size, 2,000: the
85
+ * largest count a real-D1 measurement (2026-11-22, see README) accepted at
86
+ * every vector dimension. D1 documents no per-batch statement cap, but the
87
+ * Worker-to-D1 RPC rejects a batch whose serialized arguments exceed 32 MiB,
88
+ * which heavy rows (1,536-dim chunks, about 22 KB each) reach well before 2,000
89
+ * statements; the commit driver guards that with a byte budget
90
+ * (`DEFAULT_D1_MAX_BATCH_WEIGHT`), not this count. The 100-parameter cap is per
91
+ * statement and is a separate limit.
92
+ */
93
+ export declare const DEFAULT_D1_MAX_WRITE_BATCH_SIZE = 2000;
94
+ /** D1ProvenanceStoreOptions scopes a D1ProvenanceStore. */
95
+ interface D1ProvenanceStoreOptions {
96
+ /** connection is the D1ConnectionDriver wrapping the D1 binding. */
97
+ connection: D1ConnectionDriver;
98
+ /** worldId scopes every read and write to one logical world. */
99
+ worldId?: string;
100
+ }
101
+ /**
102
+ * D1ProvenanceStore is the durable ProvenanceStore over the `provenance` table.
103
+ * Commits do not go through `record`: they write their records in the same batch
104
+ * as the quads (see `planD1Provenance`).
105
+ */
106
+ export declare class D1ProvenanceStore implements ProvenanceStore {
107
+ private readonly options;
108
+ constructor(options: D1ProvenanceStoreOptions);
109
+ /** record appends one record on its own, outside any commit. */
110
+ record(input: ProvenanceRecordInput): Promise<ProvenanceRecord>;
111
+ /** list returns matching records, oldest first. */
112
+ list(query?: ProvenanceListQuery): Promise<ProvenanceRecord[]>;
113
+ /** history walks what the quad replaced and what replaced it. */
114
+ history(quadId: string): Promise<ProvenanceHistory>;
115
+ /**
116
+ * load reads the records of `quadIds` in one query, with their full correction
117
+ * chains unless `chains` is false, into the SDK's in-memory store, so walks
118
+ * behave exactly as they do there.
119
+ */
120
+ load(quadIds: readonly string[], chains?: boolean): Promise<InMemoryProvenanceStore>;
121
+ }
122
+ /** InferenceSizeGuardError is thrown, before any write, when a world is too big to reason over. */
123
+ export declare class InferenceSizeGuardError extends Error {
124
+ readonly assertedQuads: number;
125
+ readonly maxAssertedQuads: number;
126
+ constructor(assertedQuads: number, maxAssertedQuads: number);
127
+ }
128
+ /** BackfillInferenceOptions selects the world and the reasoning settings. */
129
+ interface BackfillInferenceOptions {
130
+ /** database is the D1 binding. */
131
+ database: D1DatabaseLike;
132
+ /** worldId scopes the backfill to one world of a shared database. */
133
+ worldId?: string;
134
+ /** inference carries `graphs` and `maxAssertedQuads`, as for commits. */
135
+ inference?: Pick<InferenceOptions, "graphs" | "maxAssertedQuads">;
136
+ /** vectorDimensions matches the chunks table (default 1536). */
137
+ vectorDimensions?: number;
138
+ }
139
+ /** BackfillInferenceReport says what a backfill did. */
140
+ interface BackfillInferenceReport {
141
+ /** assertedQuads is how many asserted quads the reasoner read. */
142
+ assertedQuads: number;
143
+ /** derivedWritten is how many inferred rows exist after the backfill. */
144
+ derivedWritten: number;
145
+ /** derivedRemoved is how many inferred rows were cleared first. */
146
+ derivedRemoved: number;
147
+ /** inconsistencies are the OWL 2 RL `false` rules the data violates. */
148
+ inconsistencies: Inconsistency[];
149
+ }
150
+ /**
151
+ * backfillInference materializes inference for a world that already holds
152
+ * data, which enabling `inference` alone does not do (it only reacts to later
153
+ * writes). It reads every asserted quad, runs the reasoner once, clears the
154
+ * world's inferred rows, and writes the closure. Asserted rows are never
155
+ * touched, and the size guard (`maxAssertedQuads`) applies before any write.
156
+ *
157
+ * It is idempotent. The clear and the writes are separate D1 batches, so a
158
+ * failure part way leaves a subset of the inferred rows: run it again.
159
+ */
160
+ export declare function backfillInference(options: BackfillInferenceOptions): Promise<BackfillInferenceReport>;
161
+ /**
162
+ * PurgeWorldOptions configures purgeWorld.
163
+ */
164
+ interface PurgeWorldOptions {
165
+ /** connection is the D1 connection driver the SDK uses. */
166
+ connection: D1ConnectionDriver;
167
+ /** worldId is the world being deleted. Required and validated: a purge is
168
+ * irreversible, so it must never run unscoped across a shared database. */
169
+ worldId: string;
170
+ /** vectorSearch is the optional outside-D1 vector index bound to this
171
+ * world; when present its vectors for this world are deleted too. */
172
+ vectorSearch?: VectorSearchIndex;
173
+ }
174
+ /**
175
+ * PurgeWorldResult reports what purgeWorld removed.
176
+ */
177
+ interface PurgeWorldResult {
178
+ /** vectorsPurged is true when the vector index reported a successful purge. */
179
+ vectorsPurged: boolean;
180
+ /** vectorsSkipped is true when no vectorSearch was configured, so no
181
+ * vectors existed (or were reachable) for this purge. */
182
+ vectorsSkipped: boolean;
183
+ }
184
+ /**
185
+ * purgeWorld deletes every derived copy of a world's data: the `quads` rows
186
+ * (asserted and inference-derived alike), the `chunks` rows (whose AFTER
187
+ * DELETE trigger maintains `chunks_fts`), its `provenance` records, and — when a vectorSearch is
188
+ * configured — every vector the index holds for the world
189
+ * (worlds-cloudflare#71 item 6).
190
+ *
191
+ * The D1 statements run as one atomic batch, so the store is either fully
192
+ * purged or untouched. The vector purge runs after the D1 batch commits:
193
+ * if it throws, the D1 side is already gone and the error says so, so the
194
+ * caller can retry just the vector half rather than re-running the wipe.
195
+ */
196
+ export declare function purgeWorld(options: PurgeWorldOptions): Promise<PurgeWorldResult>;
197
+ /**
198
+ * validateWorldId rejects a caller-provided worldId that is not a non-empty
199
+ * string. Every scoping branch in the adapter is truthiness-based
200
+ * (`worldId ? scoped : unscoped`), so an empty-string worldId would silently
201
+ * disable world scoping and run SQL over a shared database instead of failing
202
+ * visibly (worlds-cloudflare#71).
203
+ */
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 };
package/dist/index.js ADDED
@@ -0,0 +1,354 @@
1
+ import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
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";
5
+ import { a as DEFAULT_D1_MAX_BATCH_WEIGHT, o as d1StatementWeight } from "./project-search-chunks-options-qI9m5FWz.js";
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";
9
+ 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
+ // src/cloudflare/search-index/vector-search/vectorize-provisioning.ts
11
+ /**
12
+ * Vectorize provisioning contract (worlds-cloudflare#38).
13
+ *
14
+ * `VectorizeVectorSearchIndex` only works against an index that was created
15
+ * with the right shape and has `world_id` registered as a filterable metadata
16
+ * property BEFORE vectors are written. This module is the single, testable
17
+ * statement of that shape: it plans the exact `wrangler` commands and checks
18
+ * an index that already exists, so provisioning is reproducible and a missing
19
+ * or misconfigured index fails loudly instead of degrading to keyword-only.
20
+ *
21
+ * It performs no I/O. `scripts/verify-vectorize.ts` feeds it `wrangler` output.
22
+ */
23
+ /** VECTORIZE_FILTERABLE_PROPERTY is the metadata key that scopes vectors per world. */
24
+ const VECTORIZE_FILTERABLE_PROPERTY = "world_id";
25
+ // src/cloudflare/search-index/vector-search/vectorize-vector-search-index.ts
26
+ /** RESULT_ID_KEY is the metadata key carrying the contract search-result id. */
27
+ const RESULT_ID_KEY = "result_id";
28
+ /** WORLD_ID_KEY is the filterable metadata key that scopes vectors per world. */
29
+ const WORLD_ID_KEY = VECTORIZE_FILTERABLE_PROPERTY;
30
+ /**
31
+ * VectorizeVectorSearchIndex implements VectorSearchIndex over a Cloudflare
32
+ * Vectorize binding.
33
+ *
34
+ * One Vectorize index is shared by every world, so this class is where world
35
+ * isolation is enforced rather than left to callers (worlds-cloudflare#41):
36
+ *
37
+ * - it cannot be constructed without a `worldId`;
38
+ * - every upserted vector carries `world_id`, and a conflicting one is refused;
39
+ * - every query is filtered on `world_id`, ANDed with any caller filter;
40
+ * - physical vector ids are namespaced by world. Contract search-result ids
41
+ * are derived from the chunk quad alone, so two worlds holding the same
42
+ * triple text would otherwise share an id and overwrite or delete each
43
+ * other's vectors. The contract id travels in `result_id` metadata and is
44
+ * what callers see in hits and pass to `deleteByIds`.
45
+ *
46
+ * The underlying index must be provisioned with `world_id` registered as a
47
+ * filterable metadata property (wrangler `vectorize create` with a metadata
48
+ * index config).
49
+ */
50
+ var VectorizeVectorSearchIndex = class {
51
+ options;
52
+ worldId;
53
+ constructor(options) {
54
+ this.options = options;
55
+ if (typeof options.worldId !== "string" || options.worldId.length === 0) throw new Error("VectorizeVectorSearchIndex requires a worldId: the Vectorize index is shared across worlds");
56
+ this.worldId = options.worldId;
57
+ }
58
+ async query(vector, options) {
59
+ const requested = options.filter?.[WORLD_ID_KEY];
60
+ if (requested !== void 0 && requested !== this.worldId) throw new Error(`Vector query filter targets world ${requested}, but this index is scoped to ${this.worldId}`);
61
+ return (await this.options.index.query(vector, {
62
+ topK: options.topK,
63
+ filter: {
64
+ ...options.filter,
65
+ [WORLD_ID_KEY]: this.worldId
66
+ },
67
+ returnValues: false,
68
+ returnMetadata: true
69
+ })).matches.map((match) => {
70
+ const metadata = metadataToRecord(match.metadata);
71
+ return {
72
+ id: metadata?.[RESULT_ID_KEY] ?? match.id,
73
+ score: typeof match.score === "number" ? match.score : 0,
74
+ metadata
75
+ };
76
+ });
77
+ }
78
+ async upsert(entries) {
79
+ if (entries.length === 0) return;
80
+ const vectors = [];
81
+ for (const entry of entries) {
82
+ const stated = entry.metadata[WORLD_ID_KEY];
83
+ if (stated !== void 0 && stated !== this.worldId) throw new Error(`Vector ${entry.id} is labelled for world ${stated}, but this index is scoped to ${this.worldId}`);
84
+ vectors.push({
85
+ id: await this.physicalId(entry.id),
86
+ values: Array.from(entry.vector),
87
+ metadata: {
88
+ ...entry.metadata,
89
+ [WORLD_ID_KEY]: this.worldId,
90
+ [RESULT_ID_KEY]: entry.id
91
+ }
92
+ });
93
+ }
94
+ await this.options.index.upsert(vectors);
95
+ }
96
+ async deleteByIds(ids) {
97
+ if (ids.length === 0) return;
98
+ await this.options.index.deleteByIds(await Promise.all(ids.map((id) => this.physicalId(id))));
99
+ }
100
+ async deleteAll() {
101
+ const deleter = this.options.index.deleteByMetadataFilter;
102
+ if (typeof deleter !== "function") throw new Error("deleteAll requires a Vectorize binding with deleteByMetadataFilter (and a metadata index on world_id); upgrade the binding and re-provision the metadata index");
103
+ await deleter.call(this.options.index, { filter: { [WORLD_ID_KEY]: this.worldId } });
104
+ }
105
+ /**
106
+ * physicalId namespaces a contract search-result id by world. Vectorize
107
+ * caps ids at 64 bytes, so the pair is hashed (SHA-256, base64url: 45
108
+ * characters with the prefix) instead of concatenated.
109
+ */
110
+ async physicalId(resultId) {
111
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${this.worldId}\u0000${resultId}`));
112
+ return `v.${base64Url(new Uint8Array(digest))}`;
113
+ }
114
+ };
115
+ function base64Url(bytes) {
116
+ let binary = "";
117
+ for (const byte of bytes) binary += String.fromCharCode(byte);
118
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
119
+ }
120
+ function metadataToRecord(metadata) {
121
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return;
122
+ const result = {};
123
+ for (const [key, value] of Object.entries(metadata)) result[key] = String(value);
124
+ return result;
125
+ }
126
+ // src/cloudflare/d1/d1-connection-driver.ts
127
+ var D1ConnectionDriver = class {
128
+ database;
129
+ worldId;
130
+ constructor(database, options) {
131
+ this.database = database;
132
+ this.worldId = options?.worldId;
133
+ }
134
+ /**
135
+ * execute runs a single parameterized statement and returns its rows.
136
+ */
137
+ async execute(statement) {
138
+ let prepared = this.database.prepare(statement.sql);
139
+ if (statement.args && statement.args.length > 0) prepared = prepared.bind(...statement.args);
140
+ return { rows: (await prepared.all()).results };
141
+ }
142
+ /**
143
+ * batch runs multiple statements atomically in one D1 batch transaction.
144
+ */
145
+ async batch(statements) {
146
+ if (statements.length === 0) return;
147
+ const prepared = statements.map((statement) => {
148
+ let preparedStatement = this.database.prepare(statement.sql);
149
+ if (statement.args && statement.args.length > 0) preparedStatement = preparedStatement.bind(...statement.args);
150
+ return preparedStatement;
151
+ });
152
+ await this.database.batch(prepared);
153
+ }
154
+ /**
155
+ * exec runs a multi-statement DDL/migration string (no bound parameters).
156
+ *
157
+ * D1's script executor splits the input on newlines — each statement must
158
+ * therefore be single-line, and statements are separated by newlines. For
159
+ * individual statements with internal formatting (e.g. shared sql-core DDL),
160
+ * prefer execute() instead.
161
+ */
162
+ async exec(sql) {
163
+ await this.database.exec(sql);
164
+ }
165
+ };
166
+ // src/cloudflare/provenance/provenance-sparql-engine.ts
167
+ /**
168
+ * ProvenanceSparqlEngine commits each SPARQL update with its request's writer
169
+ * and source. The engine opens transactions without saying which request they
170
+ * are for, so a request that names them gets an engine of its own: updates
171
+ * running at the same time cannot take each other's writer.
172
+ */
173
+ var ProvenanceSparqlEngine = class {
174
+ options;
175
+ shared;
176
+ constructor(options) {
177
+ this.options = options;
178
+ this.shared = this.engineFor();
179
+ }
180
+ execute(request) {
181
+ const { provenance, ...query } = request;
182
+ return (provenance ? this.engineFor(provenance) : this.shared).execute(query);
183
+ }
184
+ engineFor(provenance) {
185
+ const { store, quadStore } = this.options;
186
+ return new WazooSparqlEngine({
187
+ store,
188
+ createTransaction: () => quadStore.createTransaction(provenance && { provenance })
189
+ });
190
+ }
191
+ };
192
+ // src/cloudflare/create-cloudflare-sdk.ts
193
+ /**
194
+ * createCloudflareWorldsSdk synthesizes a WorldsSdk for D1-backed quad indexes.
195
+ *
196
+ * The factory assembles the three strategy objects internally: a
197
+ * D1ConnectionDriver over the raw D1 binding, a D1SchemaBuilder, and a
198
+ * D1SearchQueryBuilder. Callers pass the plain D1 database binding.
199
+ */
200
+ async function createCloudflareWorldsSdk(options) {
201
+ validateWorldId(options.worldId, "createCloudflareWorldsSdk");
202
+ if (options.vectorize && !options.worldId) throw new Error("createCloudflareWorldsSdk: worldId is required when vectorize is set; the Vectorize index is shared across worlds (worlds-cloudflare#41)");
203
+ const vectorDimensions = options.vectorDimensions ?? 1536;
204
+ const connection = new D1ConnectionDriver(options.database, { worldId: options.worldId });
205
+ const schema = new D1SchemaBuilder(vectorDimensions, {
206
+ worldId: options.worldId,
207
+ provenance: options.provenance?.enabled === true
208
+ });
209
+ const searchQuery = new D1SearchQueryBuilder(vectorDimensions, { worldId: options.worldId });
210
+ const d1RdfjsStore = new D1RdfjsStore({
211
+ connection,
212
+ matchPageSize: options.matchPageSize,
213
+ maxLookupChunkSize: options.maxLookupChunkSize,
214
+ maxWriteBatchSize: options.maxWriteBatchSize,
215
+ schemaBuilder: schema,
216
+ worldId: options.worldId,
217
+ requireDerivedColumn: options.inference?.enabled === true
218
+ });
219
+ await d1RdfjsStore.ensureSchema();
220
+ const textSplitter = options.textSplitter ?? new RecursiveCharacterTextSplitter({ chunkSize: 1e3 });
221
+ const vectorSearch = options.vectorize && options.worldId ? new VectorizeVectorSearchIndex({
222
+ index: options.vectorize,
223
+ worldId: options.worldId
224
+ }) : void 0;
225
+ const searchIndexProjector = new D1SearchIndexProjector({
226
+ ...options,
227
+ connection,
228
+ searchQueryBuilder: searchQuery,
229
+ textSplitter,
230
+ vectorSearch
231
+ });
232
+ const searchIndex = new CloudflareSearchIndex({
233
+ ...options,
234
+ connection,
235
+ searchQueryBuilder: searchQuery,
236
+ textSplitter,
237
+ vectorSearch
238
+ });
239
+ const quadStore = new D1QuadStore({
240
+ ...options,
241
+ connection,
242
+ store: d1RdfjsStore,
243
+ searchQueryBuilder: searchQuery,
244
+ searchIndexProjector
245
+ });
246
+ const sparqlEngine = new ProvenanceSparqlEngine({
247
+ store: d1RdfjsStore,
248
+ quadStore
249
+ });
250
+ return new WorldsSdk({
251
+ quadStore,
252
+ searchIndex,
253
+ sparqlEngine
254
+ });
255
+ }
256
+ // src/cloudflare/inference/backfill-inference.ts
257
+ /**
258
+ * backfillInference materializes inference for a world that already holds
259
+ * data, which enabling `inference` alone does not do (it only reacts to later
260
+ * writes). It reads every asserted quad, runs the reasoner once, clears the
261
+ * world's inferred rows, and writes the closure. Asserted rows are never
262
+ * touched, and the size guard (`maxAssertedQuads`) applies before any write.
263
+ *
264
+ * It is idempotent. The clear and the writes are separate D1 batches, so a
265
+ * failure part way leaves a subset of the inferred rows: run it again.
266
+ */
267
+ async function backfillInference(options) {
268
+ const { worldId } = options;
269
+ validateWorldId(worldId, "backfillInference");
270
+ const connection = new D1ConnectionDriver(options.database, { worldId });
271
+ await new D1RdfjsStore({
272
+ connection,
273
+ schemaBuilder: new D1SchemaBuilder(options.vectorDimensions ?? 1536, { worldId }),
274
+ worldId,
275
+ requireDerivedColumn: true
276
+ }).ensureSchema();
277
+ const asserted = await loadAssertedQuads(connection, {
278
+ worldId,
279
+ maxAssertedQuads: options.inference?.maxAssertedQuads ?? 1e5,
280
+ pendingInsertions: 0
281
+ });
282
+ const plan = planInference({
283
+ assertedBefore: [],
284
+ deletions: [],
285
+ insertions: asserted,
286
+ graphs: options.inference?.graphs
287
+ });
288
+ const before = await connection.execute({
289
+ sql: `SELECT COUNT(*) AS count FROM quads WHERE derived = 1${worldId ? " AND world_id = ?" : ""}`,
290
+ args: worldId ? [worldId] : []
291
+ });
292
+ const executor = new D1BatchExecutor({
293
+ connection,
294
+ writeBatchSize: DEFAULT_D1_MAX_WRITE_BATCH_SIZE
295
+ });
296
+ await executor.stage([buildDeleteAllDerivedQuads(worldId)]);
297
+ await executor.flush();
298
+ const rows = [];
299
+ const seen = /* @__PURE__ */ new Set();
300
+ for (const quad of plan.derivedToAdd) {
301
+ const row = await quadToInsertRow(quad);
302
+ if (seen.has(row.quad_id)) continue;
303
+ seen.add(row.quad_id);
304
+ rows.push({
305
+ ...row,
306
+ world_id: worldId,
307
+ derived: 1
308
+ });
309
+ }
310
+ await executor.stage(buildBulkInsertQuads(rows, { orIgnore: true }));
311
+ await executor.flush();
312
+ const after = await connection.execute({
313
+ sql: `SELECT COUNT(*) AS count FROM quads WHERE derived = 1${worldId ? " AND world_id = ?" : ""}`,
314
+ args: worldId ? [worldId] : []
315
+ });
316
+ return {
317
+ assertedQuads: asserted.length,
318
+ derivedWritten: Number(after.rows[0]?.count ?? 0),
319
+ derivedRemoved: Number(before.rows[0]?.count ?? 0),
320
+ inconsistencies: plan.inconsistencies
321
+ };
322
+ }
323
+ // src/cloudflare/purge-world.ts
324
+ /**
325
+ * purgeWorld deletes every derived copy of a world's data: the `quads` rows
326
+ * (asserted and inference-derived alike), the `chunks` rows (whose AFTER
327
+ * DELETE trigger maintains `chunks_fts`), its `provenance` records, and — when a vectorSearch is
328
+ * configured — every vector the index holds for the world
329
+ * (worlds-cloudflare#71 item 6).
330
+ *
331
+ * The D1 statements run as one atomic batch, so the store is either fully
332
+ * purged or untouched. The vector purge runs after the D1 batch commits:
333
+ * if it throws, the D1 side is already gone and the error says so, so the
334
+ * caller can retry just the vector half rather than re-running the wipe.
335
+ */
336
+ async function purgeWorld(options) {
337
+ const { worldId } = options;
338
+ if (typeof worldId !== "string" || worldId.length === 0) throw new Error("purgeWorld: worldId must be a non-empty string; refusing to run an unscoped purge across every world in the database");
339
+ const { rows } = await options.connection.execute({ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'provenance'" });
340
+ await options.connection.batch([...buildWipeAllGraphDataStatements(worldId), ...rows.length > 0 ? [{
341
+ sql: "DELETE FROM provenance WHERE world_id = ?",
342
+ args: [worldId]
343
+ }] : []]);
344
+ if (!options.vectorSearch) return {
345
+ vectorsPurged: false,
346
+ vectorsSkipped: true
347
+ };
348
+ await options.vectorSearch.deleteAll();
349
+ return {
350
+ vectorsPurged: true,
351
+ vectorsSkipped: false
352
+ };
353
+ }
354
+ export { CloudflareSearchIndex, D1ConnectionDriver, D1ProvenanceStore, D1QuadStore, D1QuadStream, D1RdfjsStore, D1SchemaBuilder, D1SearchIndexProjector, D1SearchQueryBuilder, D1VectorSync, DEFAULT_D1_MAX_BATCH_WEIGHT, DEFAULT_D1_MAX_WRITE_BATCH_SIZE, InferenceSizeGuardError, RRF_REFERENCE_CONSTANT, assertD1SchemaCompatible, backfillInference, buildChunkFtsValue, buildSearchResultId, checkD1SchemaCompatibility, createCloudflareWorldsSdk, createD1SearchIndexRebuilder, d1StatementWeight, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, purgeWorld, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, validateWorldId, vectorSyncSucceeded };
@@ -0,0 +1,52 @@
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";
3
+ import { t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
4
+ import { t as D1RdfjsStore } from "./mod-L9cQ_Ztm.js";
5
+ /**
6
+ * D1QuadStoreOptions defines the configurations for the D1QuadStore.
7
+ */
8
+ interface D1QuadStoreOptions extends D1ClientBaseOptions {
9
+ /** connection is the D1ConnectionDriver wrapping the D1 binding. */
10
+ connection: D1ConnectionDriver;
11
+ /** store is the underlying D1 RDF/JS ReadSource store. */
12
+ store: D1RdfjsStore;
13
+ /** searchQueryBuilder supplies dimension-aware SQL used for deletions and chunk replication. */
14
+ searchQueryBuilder: D1SearchQueryBuilder;
15
+ /** searchIndexProjector manages text chunk synchronisation. */
16
+ searchIndexProjector?: D1SearchIndexProjector;
17
+ /** maxWriteBatchSize caps how many statements are sent per D1 write batch, and so how large a commit can be and still be atomic. Defaults to 2,000. */
18
+ maxWriteBatchSize?: number;
19
+ /** worldId scopes all quad and search-index operations. */
20
+ worldId?: string;
21
+ }
22
+ /**
23
+ * D1QuadStore implements the QuadStoreInterface for D1 backed durable persistence.
24
+ * It encapsulates transaction routing, commits, and indexing synchronization.
25
+ */
26
+ declare class D1QuadStore implements QuadStoreInterface, ProvenanceQueryHandler {
27
+ private readonly options;
28
+ constructor(options: D1QuadStoreOptions);
29
+ /**
30
+ * import merges or replaces the underlying store with provided RDF source data.
31
+ *
32
+ * @param request The payload defining the ingestion source and overwrite mode.
33
+ */
34
+ import(request: ImportRequest): Promise<void>;
35
+ /**
36
+ * export extracts the graph contents in raw quads or serialized formats.
37
+ *
38
+ * @param request The desired format specifications.
39
+ */
40
+ export(request: ExportRequest): Promise<ExportResponse>;
41
+ /**
42
+ * provenanceQuery returns the records and correction history of the quads
43
+ * matching the pattern. It rejects when the world has not opted in.
44
+ */
45
+ provenanceQuery(request: ProvenanceQueryRequest): Promise<ProvenanceQueryResponse>;
46
+ /**
47
+ * createTransaction returns a pre-configured Transaction bound to internal commit hooks.
48
+ * Its commit uses `defaults` when it is given no context of its own.
49
+ */
50
+ createTransaction(defaults?: TransactionContext): Transaction;
51
+ }
52
+ export { D1QuadStoreOptions as n, D1QuadStore as t };