fatedb 0.0.0-stage → 0.10.0

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.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +264 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +3 -0
  5. package/dist/cli.d.ts +15 -0
  6. package/dist/cli.js +256 -0
  7. package/dist/client.d.ts +152 -0
  8. package/dist/client.js +416 -0
  9. package/dist/cloudflare.d.ts +197 -0
  10. package/dist/cloudflare.js +159 -0
  11. package/dist/datalog/ast.d.ts +35 -0
  12. package/dist/datalog/ast.js +40 -0
  13. package/dist/datalog/evaluator.d.ts +14 -0
  14. package/dist/datalog/evaluator.js +395 -0
  15. package/dist/datalog/fact-source.d.ts +30 -0
  16. package/dist/datalog/fact-source.js +1 -0
  17. package/dist/datalog/fingerprint.d.ts +12 -0
  18. package/dist/datalog/fingerprint.js +50 -0
  19. package/dist/datalog/parser.d.ts +3 -0
  20. package/dist/datalog/parser.js +302 -0
  21. package/dist/datalog/value.d.ts +34 -0
  22. package/dist/datalog/value.js +104 -0
  23. package/dist/domain/date-validation.d.ts +2 -0
  24. package/dist/domain/date-validation.js +32 -0
  25. package/dist/domain/fact-value.d.ts +91 -0
  26. package/dist/domain/fact-value.js +167 -0
  27. package/dist/domain/fact.d.ts +14 -0
  28. package/dist/domain/fact.js +47 -0
  29. package/dist/domain/failure.d.ts +44 -0
  30. package/dist/domain/failure.js +30 -0
  31. package/dist/domain/graph-id.d.ts +7 -0
  32. package/dist/domain/graph-id.js +10 -0
  33. package/dist/domain/histogram.d.ts +29 -0
  34. package/dist/domain/histogram.js +48 -0
  35. package/dist/domain/identifiers.d.ts +26 -0
  36. package/dist/domain/identifiers.js +75 -0
  37. package/dist/domain/numbers.d.ts +12 -0
  38. package/dist/domain/numbers.js +77 -0
  39. package/dist/domain/projection.d.ts +252 -0
  40. package/dist/domain/projection.js +51 -0
  41. package/dist/domain/query-metrics.d.ts +31 -0
  42. package/dist/domain/query-metrics.js +35 -0
  43. package/dist/domain/read-token.d.ts +37 -0
  44. package/dist/domain/read-token.js +93 -0
  45. package/dist/domain/result.d.ts +22 -0
  46. package/dist/domain/result.js +16 -0
  47. package/dist/domain/schema-observation.d.ts +20 -0
  48. package/dist/domain/schema-observation.js +61 -0
  49. package/dist/domain/string-order.d.ts +2 -0
  50. package/dist/domain/string-order.js +15 -0
  51. package/dist/domain/vocabulary.d.ts +101 -0
  52. package/dist/domain/vocabulary.js +276 -0
  53. package/dist/index.d.ts +15 -0
  54. package/dist/index.js +14 -0
  55. package/dist/projection-config.d.ts +3 -0
  56. package/dist/projection-config.js +212 -0
  57. package/dist/server/access.d.ts +32 -0
  58. package/dist/server/access.js +117 -0
  59. package/dist/server/admin.d.ts +233 -0
  60. package/dist/server/admin.js +483 -0
  61. package/dist/server/authorization.d.ts +35 -0
  62. package/dist/server/authorization.js +76 -0
  63. package/dist/server/console-assets.d.ts +6 -0
  64. package/dist/server/console-assets.js +2 -0
  65. package/dist/server/console.d.ts +8 -0
  66. package/dist/server/console.js +301 -0
  67. package/dist/server/index.d.ts +122 -0
  68. package/dist/server/index.js +487 -0
  69. package/dist/server/mcp.d.ts +31 -0
  70. package/dist/server/mcp.js +169 -0
  71. package/dist/server/telemetry-do.d.ts +31 -0
  72. package/dist/server/telemetry-do.js +342 -0
  73. package/dist/server/telemetry.d.ts +27 -0
  74. package/dist/server/telemetry.js +191 -0
  75. package/dist/storage/constants.d.ts +20 -0
  76. package/dist/storage/constants.js +21 -0
  77. package/dist/storage/environment.d.ts +438 -0
  78. package/dist/storage/environment.js +145 -0
  79. package/dist/storage/facts.d.ts +41 -0
  80. package/dist/storage/facts.js +73 -0
  81. package/dist/storage/http.d.ts +55 -0
  82. package/dist/storage/http.js +169 -0
  83. package/dist/storage/keys.d.ts +50 -0
  84. package/dist/storage/keys.js +84 -0
  85. package/dist/storage/layout.d.ts +67 -0
  86. package/dist/storage/layout.js +134 -0
  87. package/dist/storage/log.d.ts +41 -0
  88. package/dist/storage/log.js +137 -0
  89. package/dist/storage/manifest.d.ts +26 -0
  90. package/dist/storage/manifest.js +206 -0
  91. package/dist/storage/operations.d.ts +303 -0
  92. package/dist/storage/operations.js +719 -0
  93. package/dist/storage/partition.d.ts +125 -0
  94. package/dist/storage/partition.js +816 -0
  95. package/dist/storage/projection.d.ts +72 -0
  96. package/dist/storage/projection.js +1349 -0
  97. package/dist/storage/root.d.ts +120 -0
  98. package/dist/storage/root.js +596 -0
  99. package/dist/storage/segment.d.ts +145 -0
  100. package/dist/storage/segment.js +451 -0
  101. package/dist/storage/shard.d.ts +82 -0
  102. package/dist/storage/shard.js +710 -0
  103. package/dist/storage/source.d.ts +60 -0
  104. package/dist/storage/source.js +199 -0
  105. package/dist/telemetry/model.d.ts +123 -0
  106. package/dist/telemetry/model.js +292 -0
  107. package/dist/version.d.ts +4 -0
  108. package/dist/version.js +6 -0
  109. package/package.json +82 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leandro Ostera
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,265 @@
1
- # Temporary Holding Version
1
+ # `fatedb`
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 semantic graph database that runs in your own Cloudflare account, the way you would run your own Postgres rather than use a hosted one. `fatedb create` makes a project that deploys an **instance**: a Worker whose Durable Objects and R2 bucket hold your graphs. Your Workers bind to it and call it over RPC. Version 0.x has no stable compatibility promise.
4
+
5
+ ## Create your database
6
+
7
+ ```sh
8
+ bunx fatedb create my_db
9
+ cd my_db
10
+ bun install
11
+ bun run deploy
12
+ ```
13
+
14
+ `my_db/index.ts` re-exports the instance Worker from this package, and `my_db/cloudflare.config.ts` configures it with `fatedb({ name, entrypoint, grants })` from `fatedb/cloudflare`. The first deploy creates the Worker `my-db`, its Durable Objects and the R2 bucket `my-db-index`. It needs the Workers Paid plan: the instance raises its CPU and subrequest limits for large queries. Without a [console](#the-console-and-agents), the instance has no public URL: only Workers in the same account can reach it, through a service binding.
15
+
16
+ ## Use it from your Worker
17
+
18
+ Bind the instance in your app's `cloudflare.config.ts`, with the client id that its grants name:
19
+
20
+ ```ts
21
+ env: {
22
+ FATEDB: bindings.worker({ worker: "my-db", props: { clientId: "my-app" } }),
23
+ },
24
+ ```
25
+
26
+ Install `fatedb` in the app for its types, and call the instance:
27
+
28
+ ```ts
29
+ import type FateDBService from "fatedb/server";
30
+
31
+ type Env = { FATEDB: Service<FateDBService> };
32
+
33
+ export default {
34
+ async fetch(request: Request, env: Env): Promise<Response> {
35
+ using graph = await env.FATEDB.getGraph({ graphId: "release-assistant" });
36
+ // Keep the token and the exact facts if you may need to retry after an unavailable write.
37
+ const written = await graph.transact([
38
+ {
39
+ source: "agent:release-assistant",
40
+ entity: "app:service:auth-api",
41
+ field: "app:service:blocked-by",
42
+ value: { type: "reference", value: "app:task:rotate-key" },
43
+ },
44
+ {
45
+ source: "agent:release-assistant",
46
+ entity: "app:task:rotate-key",
47
+ field: "app:task:status",
48
+ value: { type: "text", value: "open" },
49
+ },
50
+ ], { clientRequestToken: "release:seed-001" });
51
+ if (!written.ok) return Response.json(written.error, { status: 400 });
52
+ // The handle sends the read token of its last answer, so this query sees the write at once.
53
+ const read = await graph.query(
54
+ 'app:service:blocked-by(Service, Task), app:task:status(Task, "open")',
55
+ );
56
+ if (!read.ok) return Response.json(read.error, { status: 400 });
57
+ const { txId, readToken } = written.value;
58
+ const { rows, watermark } = read.value;
59
+ return Response.json({ txId, readToken, watermark, rows });
60
+ },
61
+ };
62
+ ```
63
+
64
+ `getGraph` returns a handle with `transact`, `query` and `getSchema`. Every operation answers a plain `Result` (`{ ok: true, value }` or `{ ok: false, error }`), so the same typed value crosses Workers RPC and Durable Objects without rebuilding ([RFD0015](../../docs/rfds/RFD0015-results.md)): a read-only grant's handle answers `{ ok: false, error: { kind: "denied", … } }` from `transact`. Two complete apps do this: the [quickstart](../../examples/quickstart/) and a shared [TODO list](../../examples/shared-todo/) with live updates. For one independent read, `env.FATEDB.query({ graphId, query, readToken? })` returns the result without a handle, in its own execution context and request budgets.
65
+
66
+ ## Values
67
+
68
+ A fact's value is tagged with its type. Write it as JavaScript holds it, and a query returns it the same way ([RFD0014](../../docs/rfds/RFD0014-typed-values.md)):
69
+
70
+ | Type | A write gives | A query returns |
71
+ | --- | --- | --- |
72
+ | `text`, `reference` | a string | a string |
73
+ | `number` | an integer of any size: a bigint, a safe integer, or its digits | a bigint |
74
+ | `decimal` | a decimal of any precision: a finite number, or a string such as `"19.90"` or `"1.5e-3"` | its digits, written out, as a string: `"19.9"` |
75
+ | `boolean` | `true` or `false` | a boolean |
76
+ | `date` | a `Date`, or `"YYYY-MM-DD"` | a `Date` at its midnight in UTC |
77
+ | `date_time` | a `Date`, or RFC 3339 with an offset | a `Date`; it is stored in UTC, to the millisecond |
78
+ | `bytes` | a `Uint8Array`, or byte values | a `Uint8Array` |
79
+ | `list`, `map` | an array, or an object, of tagged values | an array, or an object, of values |
80
+ | `null` | `{ type: "null" }` | `null` |
81
+
82
+ Each variable of a row holds the value of the fact that first binds it, and an entity is its id. An atom matches a value of its own kind: `"open"` matches text and references, `42` an integer, `4.2` a decimal. `=`, `<` and the other comparisons compare integers and decimals by value. `JSON.stringify` cannot hold a bigint, so turn numbers into strings or numbers before you send rows on as JSON.
83
+
84
+ ## Local development
85
+
86
+ `bun run dev` in the instance's project runs it on its own. An app's own `cf dev` session should run the instance too, so that the binding's props reach it: a call from another dev session arrives without them, and is denied. In the app's `vite.config.ts`:
87
+
88
+ ```ts
89
+ import { cloudflare } from "@cloudflare/vite-plugin";
90
+ import { devInstance } from "fatedb/cloudflare";
91
+ import { defineConfig } from "vite";
92
+
93
+ export default defineConfig({
94
+ plugins: [cloudflare({
95
+ auxiliaryWorkers: [devInstance({ name: "my-db", grants: { "my-app": { "*": ["read", "write"] } } })],
96
+ })],
97
+ });
98
+ ```
99
+
100
+ It runs only in dev: the app deploys alone, and binds to the instance its own project deploys. Local data lives in the app's `.cloudflare/state/`.
101
+
102
+ ## Grants
103
+
104
+ `grants` in the instance's `cloudflare.config.ts` say which apps may read or write which graphs, by the `clientId` each app binds with: `{ "my-app": { "tasks": ["read", "write"], "*": ["read"] } }`. `"*"` covers every graph the client has no entry of its own for, and an entry with no permissions denies its graph. Writing requires reading. Without grants, every call is denied. The config fails to load on a malformed grant, naming it. Change them and deploy again.
105
+
106
+ Any Worker in the account can bind with any client id, so grants keep apps apart; they do not protect a graph from someone who can deploy to the account.
107
+
108
+ ## The console and agents
109
+
110
+ An instance can serve a console, and an MCP endpoint for agents, on a hostname of a zone in its account ([RFD0012](../../docs/rfds/RFD0012-console-and-agents.md)). The console shows its graphs, their partitions, index shards and lag, schemas, entities and what references them, a query console, and the grants. Put a [Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/applications/configure-apps/self-hosted-public-app/) application on the hostname first, then:
111
+
112
+ ```ts
113
+ worker: fatedb({
114
+ name: "my-db",
115
+ entrypoint,
116
+ grants: {
117
+ "my-app": { "*": ["read", "write"] },
118
+ console: { "*": ["read"] },
119
+ },
120
+ console: {
121
+ hostname: "db.example.com",
122
+ access: { teamDomain: "<team>.cloudflareaccess.com", aud: "<the application's AUD tag>" },
123
+ },
124
+ }),
125
+ ```
126
+
127
+ The instance checks the Access token on every request, and refuses all of them without one. Everyone Access lets in acts as the client id `console` (or `console.clientId`), so the grants decide what they see; with the write grant, the console can also make graphs.
128
+
129
+ Agents connect to `https://db.example.com/mcp`, with an Access service token's `CF-Access-Client-Id` and `CF-Access-Client-Secret` headers. It has one tool, `execute`: the agent writes JavaScript against a typed, read-only API (`fatedb.graphs()`, and per graph `query`, `schema`, `status` and `entity`), and the instance runs it in a sandbox with no network ([Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/)) and returns what it returns. A Worker in the account reaches the same endpoint through its binding, as its own client id, with no console: `env.FATEDB.fetch("https://fatedb/mcp", { method: "POST", body })`.
130
+
131
+ ## Describe your graph
132
+
133
+ A graph's schema is facts too: its classes, fields and value types are entities, and facts in the `schema:*` fields say what they are, in the style of RDF Schema and OWL ([RFD0013](../../docs/rfds/RFD0013-schemas.md)). Write them with `transact`, like any facts; writing them again changes nothing.
134
+
135
+ ```ts
136
+ import { SCHEMA, valueType } from "fatedb";
137
+
138
+ const source = "todo:schema:v1";
139
+ const ref = (value: string) => ({ type: "reference", value }) as const;
140
+ const text = (value: string) => ({ type: "text", value }) as const;
141
+ await graph.transact([
142
+ { source, entity: "todo:kind:task", field: SCHEMA.type, value: ref(SCHEMA.class) },
143
+ { source, entity: "todo:kind:task", field: SCHEMA.label, value: text("Task") },
144
+ { source, entity: "todo:task:title", field: SCHEMA.type, value: ref(SCHEMA.field) },
145
+ { source, entity: "todo:task:title", field: SCHEMA.label, value: text("Title") },
146
+ { source, entity: "todo:task:title", field: SCHEMA.doc, value: text("What the task is.") },
147
+ { source, entity: "todo:task:title", field: SCHEMA.domain, value: ref("todo:kind:task") },
148
+ { source, entity: "todo:task:title", field: SCHEMA.range, value: ref(valueType("text")) },
149
+ { source, entity: "todo:task:title", field: SCHEMA.subfieldOf, value: ref(SCHEMA.label) },
150
+ { source, entity: "todo:task:title", field: SCHEMA.functional, value: { type: "boolean", value: true } },
151
+ ]);
152
+ ```
153
+
154
+ The vocabulary covers labels and docs, a class's superclasses (`subclassOf`), a field's `domain`, `range`, `subfieldOf` and `inverseOf`, and whether it is `functional`, `inverseFunctional`, `transitive` or `symmetric`. An entity names its classes in `SCHEMA.type`, or in a field of yours that is a subfield of it. A schema describes and never refuses a write: the console's Schema tab shows each class and field, and checks the facts against what the schema declares.
155
+
156
+ ## Projections
157
+
158
+ Declare projections statically in `cloudflare.config.ts` to stream watermark-sealed entity changes out of a graph without slowing `transact` ([RFD0016](../../docs/rfds/RFD0016-projections.md)). Each projection selects changed entities by entity kind, field, or Datalog `where` clause, deduplicates entity IDs per batch, retries failures with backoff, optionally parks exhausted batches in a dead-letter queue, and supports start/stop, replay, and online backfill from the Console's **Projections** tab.
159
+
160
+ ```ts
161
+ fatedb({
162
+ name: "my-db",
163
+ entrypoint,
164
+ grants,
165
+ projections: {
166
+ "crew-sync": {
167
+ graph: "onepiece",
168
+ select: { entityKind: "onepiece:class:crew", fields: ["onepiece:bounty"] },
169
+ sink: { kind: "worker", worker: "crew-projector", entrypoint: "CrewProjector" },
170
+ },
171
+ "entities-r2": {
172
+ graph: "onepiece",
173
+ select: { entityKind: "onepiece:class:crew" },
174
+ sink: { kind: "r2", bucket: "my-entities-export" },
175
+ },
176
+ },
177
+ });
178
+ ```
179
+
180
+ A Worker RPC sink implements `ProjectionSink`:
181
+
182
+ ```ts
183
+ import { WorkerEntrypoint } from "cloudflare:workers";
184
+ import type { ProjectionDelivery, ProjectionSink } from "fatedb";
185
+
186
+ export class CrewProjector extends WorkerEntrypoint implements ProjectionSink {
187
+ async onProjectionBatch(batch: ProjectionDelivery): Promise<void> {
188
+ // Handle changed entity IDs inline (query FateDB) or enqueue to a Cloudflare Queue.
189
+ console.log(batch.graph, batch.watermark, batch.entities);
190
+ }
191
+ }
192
+ ```
193
+
194
+ The built-in R2 projection (`kind: "r2"`) writes one JSON object per entity (`{ id, graph, watermark, updatedAt, facts }`) to `entities/{ns}/{kind}/{id}.json` by default (customizable via `prefix`). When all facts on an entity are retracted, the object remains with `facts: []` as an explicit tombstone.
195
+
196
+ ## Upgrading
197
+
198
+ ```sh
199
+ bun add fatedb@0.5
200
+ bun run deploy
201
+ ```
202
+
203
+ Releases are MAJOR.minor, and the patch number stays 0: `0.1.0`, `0.2.0`, `0.3.0`, `0.4.0`, `0.5.0`, `0.6.0`, `0.7.0`, `0.8.0`, `0.9.0`, `0.10.0`, … Before 1.0 any minor release may break, and `^0.10.0` never upgrades across one, so read the release's notes before you change the version. The instance project needs no other change: `index.ts` re-exports whatever the package's instance Worker exports.
204
+
205
+ ## Never change once there is data
206
+
207
+ - **The Worker's name.** It owns the Durable Objects of every graph: under another name, the instance starts empty.
208
+ - **The bucket,** `<name>-index` unless the config names another.
209
+
210
+ ## Reading your writes
211
+
212
+ A graph's index trails its writes by a few seconds: a query reads the index at the graph's **watermark**, the newest moment it holds every write of. A write is acknowledged once its partition has stored it, before the index has it. Each graph handle therefore keeps a **read token**, merged from every answer it gets and sent with every call, and a query adds the caller's own writes above the watermark: one handle always reads its own writes. Other callers see them once the watermark passes them.
213
+
214
+ - `readToken` sends another token for one call instead, such as the `readToken` of an answer another request got. The handle's own token is left as it is.
215
+ - `consistency: "snapshot"` reads at a watermark that covers the token's writes, waiting up to five seconds for the index (then `{ ok: false, error: { kind: "unavailable", … } }`), instead of adding them from partitions: every caller reading at that watermark gets the same answer. The default is `"own-writes"`.
216
+
217
+ The instance mints a transaction ID for each submission and returns it only in the successful receipt, `{ txId, replayed, readToken }`. Failures do not expose it, because delivery may be unknown (`kind: "unavailable"`). Nothing retries automatically. To retry one logical request safely, provide the same optional `clientRequestToken` (a non-empty string of at most 256 UTF-8 bytes) and exact facts: within the graph's token window (five minutes by default) a retry answers with the original transaction and `replayed: true`, concurrent duplicates share one outcome, and changed facts answer `{ ok: false, error: { kind: "conflict", … } }`. After the window, the same call is a new transaction, ordered after everything before it. Without a token, each submission is a new transaction.
218
+
219
+ ## API and architecture limits
220
+
221
+ `query` accepts the supported Datalog **source string**. Query objects/builders are not currently a public request format. `getSchema()` is a read-only observation of active fields and root FactValue tags at one watermark, plus the caller's own writes; it is not schema enforcement or a completeness claim. A graph needs no registration or schema: its first write creates it. To say what its fields and kinds of entities mean, see [Describe your graph](#describe-your-graph).
222
+
223
+ The instance stores each graph in partitioned logs ([RFD0008](../../docs/rfds/RFD0008-fast-state-facts.md)). A write is one row in one of the graph's partitions, picked by the write's client request token, or at random without one. Index shards move each closed 50 ms epoch of every partition into immutable segments in R2, and the watermark is the newest epoch all of them hold. A graph starts with 16 partitions and one index shard, and grows as it is written: past about 300 calls a second a partition it at least doubles its partitions, up to 512, and an index shard that falls behind splits in two ([RFD0011](../../docs/rfds/RFD0011-growing-graphs.md)). Writes are ordered by their keys, (epoch, partition, offset) on a hybrid clock, not by one graph-wide sequence; a fact is active when its last write in that order asserts it. Retracting an inactive fact is stored and changes nothing. A transaction holds at most 1,000 facts and 1,000,000 bytes; a query returns at most 10,000 rows, reads at most 50,000 facts and answers within 10 seconds.
224
+
225
+ ## The HTTP client
226
+
227
+ `createDatabase({ url, graphId })` speaks FateDB's graph routes over HTTP (`/v1/graphs/:id/transactions`, `query`, `schema`), with the same calls, read tokens and `Result` failures as a graph handle, and accepts `headers` and an injectable `fetch`. An instance serves those routes only over RPC: the instance Worker runs this client in process. Its hostname, when it has a console, serves the console's API and `/mcp`, not these routes.
228
+
229
+ ## Portable fact and query primitives
230
+
231
+ ```ts
232
+ import { parseFactDrafts, parseDatalogQuery } from "fatedb";
233
+
234
+ const facts = parseFactDrafts([{
235
+ source: "agent:release-assistant",
236
+ entity: "app:task:rotate-key",
237
+ field: "app:task:status",
238
+ value: { type: "text", value: "open" },
239
+ }]);
240
+ if (!facts.ok) throw new Error(facts.error.message);
241
+
242
+ const query = parseDatalogQuery('app:task:status(Task, "open")');
243
+ if (!query.ok) throw new Error(query.error.message);
244
+ ```
245
+
246
+ Parsers return typed `ParseResult` values rather than silently coercing malformed input. The package also exports fact/value/identifier types, the Datalog AST, `FactSource`, and the evaluator. Query syntax is a bounded subset; it is not general SQL or recursive Datalog. These entries run anywhere: only `fatedb/server` needs the Workers runtime, and only `fatedb/cloudflare` needs the `cf` CLI's config.
247
+
248
+ ## Build and publish
249
+
250
+ The package name is scoped because the unscoped npm name `fatedb` is already taken. `publishConfig.access` is set to `public`; `prepublishOnly` runs the local package checks and `prepack` builds ESM JavaScript and TypeScript declarations into `dist/` before packing.
251
+
252
+ ```sh
253
+ # From the repository root:
254
+ bun install --frozen-lockfile
255
+ bun run build:package
256
+ cd packages/fatedb
257
+ npm pack --dry-run
258
+ npm publish --access public
259
+ ```
260
+
261
+ Publishing requires an npm account authorized for the `fatedb` package and a fresh version in `package.json`. Versions are MAJOR.minor: every release bumps one of them and the patch number stays 0.
262
+
263
+ ## License
264
+
265
+ MIT, see [LICENSE](LICENSE).
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./cli.js";
3
+ process.exitCode = main(process.argv.slice(2));
package/dist/cli.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ export type CreateOptions = Readonly<{
2
+ directory: string;
3
+ name?: string;
4
+ }>;
5
+ export type Created = Readonly<{
6
+ directory: string;
7
+ name: string;
8
+ files: readonly string[];
9
+ }>;
10
+ export declare function packageVersion(): string;
11
+ /** A Worker name from a directory name: `my_db` → `my-db`. */
12
+ export declare function workerNameFor(directory: string): string;
13
+ export declare function createInstance(options: CreateOptions): Created;
14
+ export declare function templates(name: string, version: string): Readonly<Record<string, string>>;
15
+ export declare function main(argv: readonly string[], userAgent?: string): number;
package/dist/cli.js ADDED
@@ -0,0 +1,256 @@
1
+ // `fatedb create <directory>`: a project that deploys a FateDB instance to your own
2
+ // Cloudflare account. Its index.ts re-exports the instance Worker from this package, and its
3
+ // cloudflare.config.ts binds the instance's Durable Objects and R2 bucket. Apps bind to it by name.
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
5
+ import { basename, join, relative, resolve } from "node:path";
6
+ /** The tooling the generated project builds and deploys with: the versions this release is tested with. */
7
+ const TOOLING = {
8
+ "@cloudflare/vite-plugin": "2.0.0-beta.sha-91c870c02",
9
+ cf: "1.0.0-beta.14",
10
+ vite: "8.3.4",
11
+ };
12
+ const WORKER_NAME = /^[a-z0-9](?:[a-z0-9-]{0,55}[a-z0-9])?$/; // leaves room for the bucket's "-index"
13
+ export function packageVersion() {
14
+ const raw = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
15
+ if (typeof raw !== "object" || raw === null || !("version" in raw) || typeof raw.version !== "string") {
16
+ throw new Error("package.json is missing a string version");
17
+ }
18
+ return raw.version;
19
+ }
20
+ /** A Worker name from a directory name: `my_db` → `my-db`. */
21
+ export function workerNameFor(directory) {
22
+ return basename(resolve(directory)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
23
+ }
24
+ export function createInstance(options) {
25
+ const directory = resolve(options.directory);
26
+ const name = options.name ?? workerNameFor(directory);
27
+ if (!WORKER_NAME.test(name)) {
28
+ throw new RangeError(`${JSON.stringify(name)} is not a usable Worker name: use 1 to 57 lowercase letters, digits and hyphens (--name)`);
29
+ }
30
+ if (existsSync(directory) && (!statSync(directory).isDirectory() || readdirSync(directory).length > 0)) {
31
+ throw new RangeError(`${directory} already exists and is not an empty directory`);
32
+ }
33
+ const files = templates(name, packageVersion());
34
+ mkdirSync(directory, { recursive: true });
35
+ for (const [file, contents] of Object.entries(files))
36
+ writeFileSync(join(directory, file), contents);
37
+ return { directory, name, files: Object.keys(files) };
38
+ }
39
+ export function templates(name, version) {
40
+ return {
41
+ "package.json": `${JSON.stringify({
42
+ name,
43
+ private: true,
44
+ type: "module",
45
+ scripts: { dev: "cf dev", deploy: "cf deploy", types: "cf workers types" },
46
+ dependencies: { "fatedb": `^${version}` },
47
+ devDependencies: TOOLING,
48
+ }, null, 2)}\n`,
49
+ "index.ts": `// This Worker is your FateDB instance: your apps bind to it, and its Durable Objects and R2
50
+ // bucket hold your graphs. All of it comes from the package, so an upgrade is a version bump and a
51
+ // deploy, with no change here.
52
+ export * from "fatedb/server";
53
+ export { default } from "fatedb/server";
54
+ `,
55
+ "cloudflare.config.ts": `import { defineConfig } from "cf/config";
56
+ import { fatedb } from "fatedb/cloudflare";
57
+ import * as entrypoint from "./index.ts" with { type: "cf-worker" };
58
+
59
+ export default defineConfig({
60
+ worker: fatedb({
61
+ // Apps bind to this name. The Worker owns the Durable Objects that hold your graphs: never
62
+ // change the name once there is data, or the instance starts empty.
63
+ name: ${JSON.stringify(name)},
64
+ entrypoint,
65
+ // Which apps may use which graphs. An app binds this Worker with props: { clientId: "my-app" },
66
+ // and "*" covers every graph.
67
+ grants: {
68
+ "my-app": { "*": ["read", "write"] },
69
+ // The console and its agents read as this client id.
70
+ // console: { "*": ["read"] },
71
+ },
72
+ // A console, and /mcp for agents, on a hostname of one of your zones. Put a Cloudflare Access
73
+ // application on the hostname first: the instance refuses every request without its token.
74
+ // console: {
75
+ // hostname: "db.example.com",
76
+ // access: { teamDomain: "<team>.cloudflareaccess.com", aud: "<the application's AUD tag>" },
77
+ // },
78
+ }),
79
+ });
80
+ `,
81
+ "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin";
82
+ import { defineConfig } from "vite";
83
+
84
+ // cf dev and cf build run through Vite.
85
+ export default defineConfig({ plugins: [cloudflare()] });
86
+ `,
87
+ "tsconfig.json": `${JSON.stringify({
88
+ compilerOptions: {
89
+ target: "ES2024", module: "ESNext", moduleResolution: "Bundler", allowImportingTsExtensions: true,
90
+ strict: true, noEmit: true, skipLibCheck: true, types: [],
91
+ },
92
+ include: ["*.ts", ".cloudflare/types/**/*.d.ts"],
93
+ }, null, 2)}\n`,
94
+ ".gitignore": "node_modules/\n.cloudflare/\n.wrangler/\n",
95
+ "README.md": `# ${name}
96
+
97
+ A [FateDB](https://github.com/leostera/fatedb) instance: a graph database that runs in your own
98
+ Cloudflare account. Your apps bind to this Worker and call it over RPC.
99
+
100
+ ## Deploy
101
+
102
+ \`\`\`sh
103
+ bun install
104
+ bun run deploy
105
+ \`\`\`
106
+
107
+ The first deploy creates the Worker \`${name}\`, its Durable Objects and the R2 bucket \`${name}-index\`.
108
+ It needs the Workers Paid plan: the instance raises its CPU and subrequest limits for large queries.
109
+ \`bun run dev\` runs it locally.
110
+
111
+ ## Use it from an app
112
+
113
+ Bind it in the app's \`cloudflare.config.ts\`, with the client id its grant names:
114
+
115
+ \`\`\`ts
116
+ env: {
117
+ FATEDB: bindings.worker({ worker: "${name}", props: { clientId: "my-app" } }),
118
+ },
119
+ \`\`\`
120
+
121
+ Then, with \`fatedb\` installed in the app for its types:
122
+
123
+ \`\`\`ts
124
+ import type FateDBService from "fatedb/server";
125
+
126
+ type Env = { FATEDB: Service<FateDBService> };
127
+
128
+ export default {
129
+ async fetch(request: Request, env: Env): Promise<Response> {
130
+ using tasks = await env.FATEDB.getGraph({ graphId: "tasks" });
131
+ const written = await tasks.transact([
132
+ { source: "my-app:api", entity: "my-app:task:1", field: "my-app:task:title", value: { type: "text", value: "Ship it" } },
133
+ ]);
134
+ if (!written.ok) return Response.json(written.error, { status: 400 });
135
+ // A graph handle reads its own writes. To read them in a later request, pass that request
136
+ // the readToken of this one's answers: query(source, { readToken }).
137
+ const read = await tasks.query("my-app:task:title(Task, Title)");
138
+ if (!read.ok) return Response.json(read.error, { status: 400 });
139
+ return Response.json(read.value.rows);
140
+ },
141
+ };
142
+ \`\`\`
143
+
144
+ ## Local development
145
+
146
+ \`bun run dev\` runs the instance on its own. An app's own \`cf dev\` session should run it too, so
147
+ that its binding's props reach it (a call from another dev session arrives without them, and is
148
+ denied). In the app's \`vite.config.ts\`:
149
+
150
+ \`\`\`ts
151
+ import { devInstance } from "fatedb/cloudflare";
152
+
153
+ export default defineConfig({
154
+ plugins: [cloudflare({
155
+ auxiliaryWorkers: [devInstance({ name: "${name}", grants: { "my-app": { "*": ["read", "write"] } } })],
156
+ })],
157
+ });
158
+ \`\`\`
159
+
160
+ It runs only in dev: the app deploys alone, and binds to the instance this project deploys.
161
+
162
+ ## Grants
163
+
164
+ \`grants\` in \`cloudflare.config.ts\` says which apps may read or write which graphs, by the
165
+ \`clientId\` each app binds with. \`"*"\` covers every graph the client has no entry of its own for.
166
+ Change them and deploy again.
167
+
168
+ ## Console and agents
169
+
170
+ With \`console\` set in \`cloudflare.config.ts\`, the instance serves a console on that hostname:
171
+ its graphs, their layout and index, schemas, entities and a query console. Agents connect to
172
+ \`https://<hostname>/mcp\`, where they read the graphs by writing code. Put a Cloudflare Access
173
+ application on the hostname before you deploy, and copy its AUD tag into the config. The console
174
+ and agents read as the client id \`console\`, so grant it the graphs they may see. Apps in the
175
+ account reach /mcp through their binding instead, as their own client id.
176
+
177
+ ## Upgrade
178
+
179
+ \`\`\`sh
180
+ bun add fatedb@<version>
181
+ bun run deploy
182
+ \`\`\`
183
+
184
+ Releases are MAJOR.minor. Before 1.0 a minor release may break, so read its notes first.
185
+
186
+ ## Never change once there is data
187
+
188
+ - The Worker name, \`${name}\`: it owns the Durable Objects of every graph.
189
+ - The bucket, \`${name}-index\`.
190
+ `,
191
+ };
192
+ }
193
+ const USAGE = `Usage: fatedb create <directory> [--name <worker-name>]
194
+
195
+ Creates a project that deploys a FateDB instance to your Cloudflare account. The Worker's name
196
+ defaults to the directory's name, in lowercase letters, digits and hyphens.`;
197
+ export function main(argv, userAgent = process.env["npm_config_user_agent"] ?? "") {
198
+ const [command, ...rest] = argv;
199
+ if (command === undefined || command === "-h" || command === "--help") {
200
+ process.stdout.write(`${USAGE}\n`);
201
+ return command === undefined ? 2 : 0;
202
+ }
203
+ if (command === "-v" || command === "--version") {
204
+ process.stdout.write(`${packageVersion()}\n`);
205
+ return 0;
206
+ }
207
+ if (command !== "create") {
208
+ console.error(`Unknown command ${JSON.stringify(command)}.\n\n${USAGE}`);
209
+ return 2;
210
+ }
211
+ let directory;
212
+ let name;
213
+ for (let i = 0; i < rest.length; i++) {
214
+ const arg = rest[i];
215
+ if (arg === undefined)
216
+ break;
217
+ if (arg === "--name")
218
+ name = rest[++i];
219
+ else if (arg.startsWith("--name="))
220
+ name = arg.slice("--name=".length);
221
+ else if (!arg.startsWith("-") && directory === undefined)
222
+ directory = arg;
223
+ else {
224
+ console.error(`Unexpected argument ${JSON.stringify(arg)}.\n\n${USAGE}`);
225
+ return 2;
226
+ }
227
+ }
228
+ if (directory === undefined) {
229
+ console.error(USAGE);
230
+ return 2;
231
+ }
232
+ let created;
233
+ try {
234
+ created = createInstance({ directory, ...(name === undefined ? {} : { name }) });
235
+ }
236
+ catch (error) {
237
+ if (!(error instanceof RangeError))
238
+ throw error;
239
+ console.error(`fatedb: ${error.message}`);
240
+ return 1;
241
+ }
242
+ const run = userAgent.startsWith("bun") ? "bun" : userAgent.startsWith("pnpm") ? "pnpm" : userAgent.startsWith("yarn") ? "yarn" : "npm";
243
+ const where = relative(process.cwd(), created.directory) || ".";
244
+ process.stdout.write(`Created ${where}: the FateDB instance "${created.name}".
245
+
246
+ cd ${where}
247
+ ${run} install
248
+ ${run} run deploy
249
+
250
+ Then bind it from your app's cloudflare.config.ts:
251
+
252
+ FATEDB: bindings.worker({ worker: "${created.name}", props: { clientId: "my-app" } }),
253
+
254
+ and use it: \`using graph = await env.FATEDB.getGraph({ graphId: "tasks" })\`. See ${where}/README.md.\n`);
255
+ return 0;
256
+ }