@yaks/d1 0.0.0-stage → 0.2.36

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Jeff Peterson
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,244 @@
1
- # Temporary Holding Version
1
+ # @yaks/d1
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Cloudflare D1 storage adapter for [@yaks/graph](../graph/README.md). It stores
4
+ graph data in the D1 database supplied by the application, using the schema and
5
+ write statements from [@yaks/sqlite](../sqlite/README.md). Reads and
6
+ transactions are asynchronous.
7
+
8
+ A **bundle** is one entity's components represented as a JSON object. A
9
+ **batch** is a list of bundles applied in one transaction. D1's `batch()` API
10
+ executes the SQL statements implementing those changes atomically. Application
11
+ reads made before that call are outside the database transaction; see
12
+ [The transaction](#the-transaction).
13
+
14
+ For graph write phases and adapter responsibilities, see the
15
+ [graph architecture](../graph/ARCHITECTURE.md).
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ deno add jsr:@yaks/d1 jsr:@yaks/graph jsr:@yaks/vocab
21
+ ```
22
+
23
+ ## What it is
24
+
25
+ `storage(binding, vocab, base?)` implements the graph `Storage` interface over a
26
+ D1 binding. It compiles queries, reads matching entities as bundles, and applies
27
+ patches. The graph handles validation, plugins, and deletion policy.
28
+
29
+ This Worker example assumes an existing D1 binding named `DB`. Its type is
30
+ expressed using the package's structural interface; a Cloudflare `D1Database`
31
+ satisfies that interface.
32
+
33
+ ```ts ignore
34
+ import { graph } from '@yaks/graph'
35
+ import { loadVocab } from '@yaks/vocab'
36
+ import { type D1Like, type Stmt, storage } from '@yaks/d1'
37
+
38
+ let vocab = loadVocab({
39
+ $defs: {
40
+ doc: {
41
+ component: true,
42
+ type: 'object',
43
+ kind: true,
44
+ properties: { title: { type: 'string' }, body: { type: 'string' } },
45
+ },
46
+ book: {
47
+ component: true,
48
+ type: 'object',
49
+ kind: true,
50
+ before: ['doc'],
51
+ properties: {
52
+ price: { type: 'number' },
53
+ status: { type: 'string', enum: ['draft', 'listed', 'sold'] },
54
+ },
55
+ },
56
+ review: {
57
+ component: true,
58
+ type: 'object',
59
+ kind: true,
60
+ properties: {
61
+ stars: { type: 'number' },
62
+ book: { type: 'string', ref: 'book', death: 'cascade' },
63
+ },
64
+ },
65
+ },
66
+ })
67
+
68
+ export default {
69
+ async fetch<S extends Stmt<S>>(_req: Request, env: { DB: D1Like<S> }) {
70
+ let store = storage(env.DB, vocab)
71
+ await store.install()
72
+ let g = graph({ storage: store, vocab })
73
+ await g.apply([
74
+ { entity: { eid: 'b1' }, doc: { title: 'Dune' }, book: { price: 12 } },
75
+ { entity: { eid: 'r1' }, review: { stars: 5, book: 'b1' } },
76
+ ])
77
+ return Response.json(
78
+ await g.read('.kind=book&.book.price<20&.order=-book.price'),
79
+ )
80
+ },
81
+ }
82
+ ```
83
+
84
+ The example initializes the schema and writes sample data on every request for
85
+ simplicity. Applications should initialize schema deliberately and map requests
86
+ to their own authorized operations. `install()` runs vocabulary-derived DDL and
87
+ brings tables that already stood to the vocabulary the way @yaks/sqlite's does:
88
+ missing columns added, a table whose keys or checks moved rebuilt in a batch of
89
+ its own, and one whose rows would not fit left as it stood and reported through
90
+ `base.report`.
91
+
92
+ ## API and exports
93
+
94
+ The package has one import path, `@yaks/d1`. `storage` returns a `Store` with:
95
+
96
+ | Method | Result |
97
+ | -------------------- | ------------------------------------------------------------------------------------------------------- |
98
+ | `ddl()` | SQL schema statements, synchronously |
99
+ | `install()` | Promise resolving after schema statements execute |
100
+ | `read(query, opts?)` | Promise of matching bundles |
101
+ | `rows(query, opts?)` | Promise of raw rows, including aggregates and projections |
102
+ | `get(eids, comps?)` | Promise of those entities as stored, or carrying only the components `comps` names, tombstones included |
103
+ | `tx(body)` | Promise of the callback result after its writes commit |
104
+
105
+ Read options are `@yaks/sql`'s bind options, such as `derived`, `extend`, and
106
+ `now`; per-call options override `base`. A D1 store numbers nothing: a series'
107
+ next number is a read before its write, and a batch is sent whole.
108
+
109
+ The root also exports `D1Like`, `Stmt`, `D1Stmt`, `D1Result`, value/row types,
110
+ `bind`/`unbind`, query/gather helpers, shared SQL write builders, graph
111
+ `Storage`/`Tx` types, and the secrets vault below. See [mod.ts](./mod.ts) for
112
+ the complete list.
113
+
114
+ ## Secrets
115
+
116
+ `d1Vault(db, key)` keeps a graph's secrets in D1, in two tables it creates on
117
+ first use: `yak_vault` holds each secret, and the salt its sentinels are hashed
118
+ under, encrypted with AES-GCM under `key`; `yak_vault_lock` holds the leases
119
+ that make a read, a change and its write back one step across isolates. It meets
120
+ [@yaks/secrets](../secrets)' vault by shape without importing it:
121
+
122
+ ```ts
123
+ import { d1Vault } from '@yaks/d1'
124
+
125
+ // let vault = d1Vault(env.DB, key) // a CryptoKey for AES-GCM
126
+ // graph({ storage, vocab, plugins: [secrets(vault, write, vocab)] }) // @yaks/secrets
127
+ ```
128
+
129
+ The database, its Time Travel history and its exports hold only ciphertext; the
130
+ key is the caller's to keep. A lease stands for 30 seconds if its holder dies
131
+ holding it, and a caller waits as long for one before it gives up.
132
+
133
+ ## Async, with sync pass-through
134
+
135
+ The graph accepts storage methods returning either values or promises. Over D1,
136
+ `read()` and `tx()` always return promises, so await graph operations. With
137
+ synchronous SQLite storage, graph operations can return immediately unless a
138
+ plugin makes them asynchronous.
139
+
140
+ `parity_test.ts` runs the shared storage conformance cases over D1 and embedded
141
+ SQLite, checking returned bundles, rejected changes, and asynchronous behavior.
142
+ These shared cases do not remove the D1 transaction limitations below.
143
+
144
+ ## The transaction
145
+
146
+ ### What D1 gives
147
+
148
+ D1's `batch()` executes statements sequentially in one implicit transaction and
149
+ rolls them all back if a statement fails. It does not provide an interactive
150
+ transaction in which application code reads, decides, and writes while retaining
151
+ a database lock.
152
+
153
+ ### What `tx()` does about it
154
+
155
+ | Operation | Behavior |
156
+ | ------------------ | -------------------------------------------------------------------------- |
157
+ | Read | Executes immediately against committed data, with pending changes overlaid |
158
+ | Write | Collects SQL statements without sending them |
159
+ | Callback completes | Sends collected statements in one D1 `batch()` |
160
+ | Callback fails | Discards unsent statements |
161
+
162
+ The callback may be asynchronous. Write statements resolve ids inside SQL, such
163
+ as `select id from entity where eid = ?`, so references created in the same
164
+ write resolve when the statements execute. Both this package and `@yaks/sqlite`
165
+ use the same statement builders.
166
+
167
+ An in-memory overlay supplies read-your-own-writes: the adapter keeps the
168
+ pending state of changed entities, replaces their committed results, and
169
+ evaluates those entities with [@yaks/match](../match/README.md). This lets
170
+ cascading deletion see reference changes made earlier in the same operation.
171
+ Before any pending writes, reads use the database result directly. Overlay
172
+ queries have the capabilities and limits of the in-memory matcher, including its
173
+ available reference data and extensions; they are not a second execution of SQL
174
+ against pending rows.
175
+
176
+ ### What is not promised
177
+
178
+ - **Serializable reads and writes:** reads are outside the final write
179
+ transaction. Another writer may commit between a read and the flush.
180
+ - **Complete concurrent `$was` protection:** the graph checks preconditions
181
+ against the values it can read, but a writer committing afterward and before
182
+ the flush can escape detection. Use storage with an interactive transaction
183
+ when these guards must prevent lost updates.
184
+ - **Immediate numbers:** when numbering is enabled, a new identity's `num` is
185
+ assigned by the insert inside the write transaction. `patch` initially returns
186
+ the identity without its number; the adapter fills it from `RETURNING` before
187
+ `tx()` resolves.
188
+ - **Nested rollback:** a nested `tx()` creates an independent write transaction;
189
+ D1 has no savepoints. The graph's normal `apply()` does not nest transactions.
190
+
191
+ The write statements are atomic even though the preceding reads are not isolated
192
+ from concurrent writes.
193
+
194
+ ### Ordering within a transaction
195
+
196
+ Overlay reads return unchanged committed matches in database order, followed by
197
+ matching pending entities in the matcher's order. Ordering and limits are
198
+ therefore applied separately to these parts, not to the combined result. Hooks
199
+ requiring a globally ordered or paginated view of pending changes cannot rely on
200
+ this overlay behavior.
201
+
202
+ ## Composition
203
+
204
+ `@yaks/d1`, `@yaks/sqlite`, and
205
+ [@yaks/durable-object](../durable-object/README.md) implement the same graph
206
+ storage interface, with different transaction guarantees. D1 uses the SQLite
207
+ layout: an identity table, component tables with integer references, tombstones,
208
+ declared indexes, and schema metadata. It does not open or provision the D1
209
+ database.
210
+
211
+ The adapter shares per-component read and write planning with SQLite. It sends
212
+ component gathers together in one D1 call instead of making a separate remote
213
+ call for each component. An ordinary query first selects matching ids and then
214
+ fetches their components; that is more than one call, and the selection and
215
+ gather are not one read snapshot.
216
+
217
+ ## Types
218
+
219
+ `D1Like<S>` describes `prepare` and `batch`. `Stmt<S>` describes statement
220
+ `bind` and `all` methods. The statement is generic because it is both returned
221
+ by `prepare` and accepted by `batch`; this preserves compatibility with the
222
+ binding's own statement type.
223
+
224
+ `conform.ts` checks these interfaces against `@cloudflare/workers-types` in the
225
+ Workers program of `deno task check:types`, keeping Workers globals out of other
226
+ packages:
227
+
228
+ ```sh
229
+ deno task check:types packages/d1/conform.ts
230
+ ```
231
+
232
+ ## Compatibility
233
+
234
+ Designed for a Cloudflare Worker with a D1 binding. The package imports no
235
+ Cloudflare runtime code and can also run under Deno or Node with an object
236
+ implementing the same binding interface, as the test harness does.
237
+
238
+ ## Values
239
+
240
+ `bind` passes strings, numbers, and booleans through, maps null/undefined to
241
+ null, converts bigints to numbers, and copies the selected range of a
242
+ `Uint8Array` into an `ArrayBuffer`. Converting a bigint to a number can lose
243
+ precision outside JavaScript's safe-integer range. `unbind` converts
244
+ array-valued BLOB results into `Uint8Array` values.
package/_dist/d1.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ /** A value D1 binds: its documented type table, and nothing else. A boolean is
2
+ * bound as the 0/1 an integer column holds; bytes are bound as an
3
+ * ArrayBuffer. */ export type D1Value = ArrayBuffer | string | number | boolean | null;
4
+ /** One row: its column values, keyed by column name. */ export type Row = Record<string, unknown>;
5
+ /** What a run hands back — the rows it selected. */ export type D1Result<T> = {
6
+ results: T[];
7
+ };
8
+ /**
9
+ * A prepared statement, generic over the type the binding hands back. The
10
+ * adapter treats one as opaque: it binds values, runs it for rows, or passes it
11
+ * straight back to {@link D1Like.batch}. Keeping the type a parameter is what
12
+ * lets a `D1PreparedStatement` be used as itself rather than narrowed to a
13
+ * slice — a statement appears both as a return and as an argument, and a
14
+ * narrowed slice cannot be both.
15
+ */ export type Prepared<S> = {
16
+ /** bind positional parameters, returning the bound statement */ bind: (...values: D1Value[]) => S;
17
+ /** run the statement and resolve its result rows */ all: <T = Row>() => Promise<D1Result<T>>;
18
+ };
19
+ /** The default statement shape, for a caller naming {@link D1Like} without a
20
+ * binding of its own: this package's own slice, closed over itself. */ export type D1Stmt = {
21
+ /** bind positional parameters, returning the bound statement */ bind: (...values: D1Value[]) => D1Stmt;
22
+ /** run the statement and resolve its result rows */ all: <T = Row>() => Promise<D1Result<T>>;
23
+ };
24
+ /**
25
+ * The async surface this adapter needs from a `D1Database`: prepare a
26
+ * statement, and send a list of them as one atomic batch. A Cloudflare
27
+ * `D1Database` satisfies it — see ./conform.ts.
28
+ */ export type D1Like<S extends Prepared<S> = D1Stmt> = {
29
+ /** prepare a parameterized statement for binding and running */ prepare: (sql: string) => S;
30
+ /** run these statements sequentially, as one all-or-nothing transaction */ batch: (statements: S[]) => Promise<D1Result<Row>[]>;
31
+ };
32
+ /**
33
+ * A value as D1 takes it. `undefined` and `null` are the same absence; a bigint
34
+ * becomes a number (D1 refuses one outright); a byte array becomes the
35
+ * ArrayBuffer it is a window onto. A boolean passes through — D1 stores it as
36
+ * 0/1 — so nothing here has to know a column's affinity.
37
+ */ export declare let bind: (value: unknown) => D1Value;
38
+ /**
39
+ * A row as the rest of the stack expects it. D1 hands a BLOB back as an array
40
+ * of byte values; every other adapter hands back bytes, so it is converted here
41
+ * and a caller never learns which database answered.
42
+ */ export declare let unbind: (row: Row) => Row;
43
+ //# sourceMappingURL=d1.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"d1.d.ts","sources":["../d1.ts"],"names":[],"mappings":"AAuBA;;gBAEgB,GAChB,YAAY,UAAU,cAAc,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI;AAEpE,sDAAsD,GACtD,YAAY,MAAM,OAAO,MAAM,EAAE,OAAO;AAExC,kDAAkD,GAClD,YAAY,SAAS;EAAO,SAAS;;AAErC;;;;;;;CAOC,GACD,YAAY,SAAS;EACnB,8DAA8D,GAC9D,OAAO,GAAG,QAAQ,cAAc;EAChC,kDAAkD,GAClD,MAAM,IAAI,UAAU,QAAQ,SAAS;;AAGvC;qEACqE,GACrE,YAAY;EACV,8DAA8D,GAC9D,OAAO,GAAG,QAAQ,cAAc;EAChC,kDAAkD,GAClD,MAAM,IAAI,UAAU,QAAQ,SAAS;;AAGvC;;;;CAIC,GACD,YAAY,OAAO,UAAU,SAAS,KAAK;EACzC,8DAA8D,GAC9D,UAAU,KAAK,MAAM,KAAK;EAC1B,yEAAyE,GACzE,QAAQ,YAAY,QAAQ,QAAQ,SAAS;;AAG/C;;;;;CAKC,GACD,OAAO,YAAI,OAAQ,OAAO,OAAO,KAAG,QAUd;AAEtB;;;;CAIC,GACD,OAAO,YAAI,SAAU,KAAK,QAAM,IAM/B"}
package/_dist/mod.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @yaks/d1 — the storage adapter that backs a yaks graph with Cloudflare D1.
3
+ *
4
+ * ## What it is
5
+ * D1 is a serverless SQLite reachable only over an async API, so this adapter
6
+ * is async end to end: every read and every write returns a promise. It
7
+ * composes the yaks query → vocabulary → SQL stack over a D1 binding to
8
+ * implement {@link https://jsr.io/@yaks/graph | @yaks/graph}'s `Storage`
9
+ * interface — a query in, whole bundles out; bundles patched into rows.
10
+ *
11
+ * ```ts
12
+ * import { graph } from '@yaks/graph'
13
+ * import { storage } from '@yaks/d1'
14
+ *
15
+ * // let store = storage(env.DB, vocab)
16
+ * // await store.install()
17
+ * // let g = graph({ storage: store, vocab })
18
+ * // await g.apply([{ entity: { eid: 'b1' }, doc: { title: 'Dune' } }])
19
+ * // await g.read('.kind=doc')
20
+ * ```
21
+ *
22
+ * Because `Storage` may be either asynchronous or synchronous, and @yaks/graph
23
+ * handles either (@yaks/fp's `after` awaits a promise and passes a plain value
24
+ * straight through), the same `apply()` is synchronous over @yaks/sqlite and
25
+ * asynchronous here. No caller in between has to know which.
26
+ *
27
+ * ## The transaction, in plain terms
28
+ * D1 has no interactive transaction — no call opens one, lets your code read
29
+ * and decide inside it, and commits at the end. What it has is `batch()`, which
30
+ * runs a list of statements sequentially in one implicit transaction and rolls
31
+ * the whole list back if any fails. So {@link storage}'s `tx` defers: reads run
32
+ * immediately against the committed database, writes are gathered as
33
+ * statements, returning flushes them as one atomic batch, and throwing discards
34
+ * them unsent. Reads inside the transaction see its own pending writes through
35
+ * an in-memory overlay evaluated by
36
+ * {@link https://jsr.io/@yaks/match | @yaks/match}.
37
+ *
38
+ * The write is atomic; the transaction is NOT serializable, because the reads
39
+ * cannot be enrolled in a batch that has not been sent. See the README's
40
+ * "The transaction" for exactly what that costs and when it matters.
41
+ *
42
+ * ## Secrets
43
+ * {@link d1Vault} keeps a graph's secrets in D1, each value encrypted under a
44
+ * key the caller holds. It meets @yaks/secrets' vault by shape, without this
45
+ * package importing it.
46
+ *
47
+ * ## Where it sits
48
+ * One of three interchangeable adapters behind the same seam:
49
+ * **@yaks/d1** (this package, async), {@link
50
+ * https://jsr.io/@yaks/durable-object | @yaks/durable-object} (a Durable
51
+ * Object's embedded SQLite, synchronous) and {@link
52
+ * https://jsr.io/@yaks/sqlite | @yaks/sqlite} (in-process, synchronous — and
53
+ * the reference every adapter is held to).
54
+ *
55
+ * @module
56
+ */ export { bind, type D1Like, type D1Result, type D1Stmt, type D1Value, type Prepared, type Row, unbind } from "./d1.js";
57
+ export { bundles, comps, gatherSql, type Query, spineSql, sql } from "./read.js";
58
+ export { dropSql, mintSql, patchSql, removeSql, touched, upsertSql } from "@yaks/sqlite";
59
+ export { storage, type Store } from "./store.js";
60
+ export { type D1Vault, d1Vault, type Sealed } from "./vault.js";
61
+ export type { Storage, Tx } from "@yaks/graph";
62
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sources":["../mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GAED,SACE,IAAI,EACJ,KAAK,MAAM,EACX,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,KAAK,GAAG,EACR,MAAM,kBACQ;AAChB,SAAS,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,KAAK,EAAE,QAAQ,EAAE,GAAG,oBAAmB;AAKhF,SACE,OAAO,EACP,OAAO,EACP,QAAQ,EACR,SAAS,EACT,OAAO,EACP,SAAS,4BACqB;AAChC,SAAS,OAAO,EAAE,KAAK,KAAK,qBAAoB;AAChD,SAAS,KAAK,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,qBAAoB;AAC/D,cAAc,OAAO,EAAE,EAAE,2BAAgC"}
@@ -0,0 +1,26 @@
1
+ import { type And } from "@yaks/query";
2
+ import { type BindOpts, type Raw, type Stmt } from "@yaks/sql";
3
+ import type { Bundle } from "@yaks/graph";
4
+ import type { Vocab } from "@yaks/vocab";
5
+ import type { Row } from "./d1.js";
6
+ /** A query, as text or as an already-built AST. Text is parsed; an AST passes
7
+ * through, so a caller may hand-build one with @yaks/query's builders. */ export type Query = string | And;
8
+ /** The compiled statement for a query. */ export declare let sql: (v: Vocab, query: Query, opts?: BindOpts) => Raw;
9
+ /** The identity of an eid, as stored: its `num`, and whether it is buried. One
10
+ * statement, so a gather of many entities is one batch. */ export declare let spineSql: (v: Vocab, eid: string) => Stmt;
11
+ /** What a gather asks about one entity: its spine, then one read per component
12
+ * the vocabulary declares, or per one of those `names` names. The order is
13
+ * what {@link bundles} reads back. */ export declare let gatherSql: (v: Vocab, eid: string, opts?: BindOpts, names?: string[]) => Stmt[];
14
+ /** The components a gather reads, in the vocabulary's order: every one, or
15
+ * those `names` names — the spine is the identity, not a component of its
16
+ * own. */ export declare let comps: (v: Vocab, names?: string[]) => string[];
17
+ /**
18
+ * Turn the answers to a gather back into bundles, one per eid, in the order the
19
+ * eids were asked about. An eid no entity has is simply absent; a tombstoned
20
+ * one comes back carrying `tombstone` (it is still an identity, just a dead one).
21
+ *
22
+ * `answers` is the flat result list `batch()` returns for
23
+ * `eids.flatMap((e) => gatherSql(v, e, opts, names))` — one entry per
24
+ * statement, in order.
25
+ */ export declare let bundles: (v: Vocab, eids: string[], answers: Row[][], names?: string[]) => Bundle[];
26
+ //# sourceMappingURL=read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.d.ts","sources":["../read.ts"],"names":[],"mappings":"AAyBA,SAAS,KAAK,GAAG,2BAAuC;AACxD,SAEE,KAAK,QAAQ,EAKb,KAAK,GAAG,EAER,KAAK,IAAI,yBAEkB;AAE7B,cAAc,MAAM,2BAA8C;AAElE,cAAc,KAAK,2BAAgC;AACnD,cAAc,GAAG,kBAAiB;AAElC;wEACwE,GACxE,YAAY,QAAQ,MAAM,GAAG;AAI7B,wCAAwC,GACxC,OAAO,YAAI,MAAO,GAAG,OAAO,OAAO,OAAO,OAAM,aAAgB,IAClC;AAE9B;yDACyD,GACzD,OAAO,YAAI,WAAY,GAAG,OAAO,KAAK,MAAM,KAAG,KACN;AAEzC;;oCAEoC,GACpC,OAAO,YAAI,YACT,GAAG,OACH,KAAK,MAAM,EACX,OAAM,UACN,QAAQ,MAAM,OACb,OAGF;AAED;;QAEQ,GACR,OAAO,YAAI,QAAS,GAAG,OAAO,QAAQ,MAAM,OAAK,MAAM,GACuB;AA2B9E;;;;;;;;CAQC,GACD,OAAO,YAAI,UACT,GAAG,OACH,MAAM,MAAM,IACZ,SAAS,SACT,QAAQ,MAAM,OACb,SAMF"}
@@ -0,0 +1,34 @@
1
+ import { type Trash, type TrashPage } from "@yaks/graph/trash";
2
+ import type { Bundle, Eid, Tx } from "@yaks/graph";
3
+ import { type Clock } from "@yaks/fp";
4
+ import { type BindOpts, type Stmt } from "@yaks/sql";
5
+ import type { Vocab } from "@yaks/vocab";
6
+ import { type D1Like, type Prepared, type Row } from "./d1.js";
7
+ import { type Query } from "./read.js";
8
+ /**
9
+ * A bound store: @yaks/graph's `Storage` over D1, every answer a promise.
10
+ *
11
+ * `tx` is declared as the seam declares it — the seam is async-or-sync and a
12
+ * synchronous adapter returns a plain value — but over D1 it always returns a
13
+ * promise, and it resolves only once the write batch has committed.
14
+ */ export type Store = {
15
+ /** Destructive transactions retained for recovery. */ trash: (eids?: Eid[], page?: TrashPage) => Promise<Trash[]>;
16
+ /** Purge one retained transaction after a person explicitly chooses it. */ purgeTrash: (id: string | string[]) => Promise<void>;
17
+ /** Whether a value this store reads for the property means its entity
18
+ * wears the component (@yaks/sql `worn`). */ worn: (comp: string, prop: string) => boolean;
19
+ /** the schema statements the bound vocabulary implies */ ddl: () => Stmt[];
20
+ /** run them — create the tables, indexes and triggers the vocabulary needs */ install: () => Promise<void>;
21
+ /** a query → its entities, with `comps` only where named */ read: (query: Query, opts?: BindOpts, comps?: string[]) => Promise<Bundle[]>;
22
+ /** a query → the compiled statement's raw rows (counts, tallies) */ rows: (query: Query, opts?: BindOpts) => Promise<Row[]>;
23
+ /** these entities as they stand, carrying the components `comps` names or
24
+ * every one: D1 holds no lock to take */ get: (eids: Eid[], comps?: string[]) => Promise<Bundle[]>;
25
+ /** run `body` against a transaction: flush its writes as one atomic batch on
26
+ * return, discard them on throw */ tx: <R>(body: (tx: Tx) => R) => Promise<Awaited<R>>;
27
+ };
28
+ /** What a D1 store is bound with: @yaks/sql's read options. */ export type Opts = BindOpts & {
29
+ /** Where a failure the store outlives is told, as @yaks/sqlite's `report`:
30
+ * one line on the console, by default. */ report?: (error: Error) => void;
31
+ /** Time used for D1 recovery and write receipts. */ clock?: Clock;
32
+ };
33
+ export declare let storage: <S extends Prepared<S>>(db: D1Like<S>, vocab: Vocab, base?: Opts) => Store;
34
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sources":["../store.ts"],"names":[],"mappings":"AAAA,SAAqB,KAAK,KAAK,EAAE,KAAK,SAAS,iCAAsC;AA4DrF,cACE,MAAM,EAGN,GAAG,EAIH,EAAE,2BAC2B;AAG/B,SAAS,KAAK,KAAK,wBAAqC;AAExD,SAGE,KAAK,QAAQ,EAWb,KAAK,IAAI,yBAIkB;AA2B7B,cAAc,KAAK,2BAAgC;AACnD,SAEE,KAAK,MAAM,EAEX,KAAK,QAAQ,EACb,KAAK,GAAG,kBAEM;AAEhB,SAIE,KAAK,KAAK,oBAIM;AAIlB;;;;;;CAMC,GACD,YAAY;EACV,oDAAoD,GACpD,QAAQ,OAAO,OAAO,OAAO,cAAc,QAAQ;EACnD,yEAAyE,GACzE,aAAa,IAAI,MAAM,GAAG,MAAM,OAAO,QAAQ,IAAI;EAEnD;6CAC2C,GAC3C,OAAO,MAAM,MAAM,EAAE,MAAM,MAAM,KAAK,OAAO;EAC7C,uDAAuD,GACvD,WAAW;EACX,4EAA4E,GAC5E,eAAe,QAAQ,IAAI;EAC3B,0DAA0D,GAC1D,OAAO,OAAO,OAAO,OAAO,UAAU,QAAQ,MAAM,OAAO,QAAQ;EACnE,kEAAkE,GAClE,OAAO,OAAO,OAAO,OAAO,aAAa,QAAQ;EACjD;yCACuC,GACvC,MAAM,MAAM,OAAO,QAAQ,MAAM,OAAO,QAAQ;EAChD;mCACiC,GACjC,KAAK,GAAG,OAAO,IAAI,OAAO,MAAM,QAAQ,QAAQ;;AAmDlD,6DAA6D,GAC7D,YAAY,OAAO;EACjB;0CACwC,GACxC,UAAU,OAAO,UAAU,IAAI;EAC/B,kDAAkD,GAClD,QAAQ;;AAGV,OAAO,YAAI,UAAW,UAAU,SAAS,IACvC,IAAI,OAAO,IACX,OAAO,OACP,OAAM,SACL,MA8dF"}