@affordance/core 0.1.0 → 0.2.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 (82) hide show
  1. package/README.md +17 -6
  2. package/dist/engine/compute.d.ts +2 -2
  3. package/dist/engine/compute.js.map +1 -1
  4. package/dist/engine/engine.d.ts +14 -22
  5. package/dist/engine/engine.js +35 -17
  6. package/dist/engine/engine.js.map +1 -1
  7. package/dist/errors.d.ts +3 -9
  8. package/dist/errors.js +17 -0
  9. package/dist/errors.js.map +1 -1
  10. package/dist/execution/delta.d.ts +1 -1
  11. package/dist/execution/delta.js +1 -1
  12. package/dist/execution/delta.js.map +1 -1
  13. package/dist/execution/execute.d.ts +19 -18
  14. package/dist/execution/execute.js +22 -25
  15. package/dist/execution/execute.js.map +1 -1
  16. package/dist/execution/index.d.ts +1 -3
  17. package/dist/execution/index.js +1 -3
  18. package/dist/execution/index.js.map +1 -1
  19. package/dist/execution/journal.d.ts +4 -12
  20. package/dist/execution/journal.js +20 -93
  21. package/dist/execution/journal.js.map +1 -1
  22. package/dist/execution/port.d.ts +15 -44
  23. package/dist/execution/port.js +1 -100
  24. package/dist/execution/port.js.map +1 -1
  25. package/dist/execution/replay.d.ts +1 -1
  26. package/dist/execution/replay.js.map +1 -1
  27. package/dist/index.d.ts +7 -5
  28. package/dist/index.js +4 -4
  29. package/dist/index.js.map +1 -1
  30. package/dist/ingestion/correlation.d.ts +0 -32
  31. package/dist/ingestion/correlation.js +1 -77
  32. package/dist/ingestion/correlation.js.map +1 -1
  33. package/dist/ingestion/index.d.ts +1 -2
  34. package/dist/ingestion/index.js +1 -2
  35. package/dist/ingestion/index.js.map +1 -1
  36. package/dist/ingestion/ingest.d.ts +10 -16
  37. package/dist/ingestion/ingest.js +12 -100
  38. package/dist/ingestion/ingest.js.map +1 -1
  39. package/dist/migration/migrate.d.ts +6 -7
  40. package/dist/migration/migrate.js +11 -40
  41. package/dist/migration/migrate.js.map +1 -1
  42. package/dist/model/casetype.d.ts +8 -8
  43. package/dist/model/casetype.js.map +1 -1
  44. package/dist/model/handler.d.ts +21 -15
  45. package/dist/model/handler.js.map +1 -1
  46. package/dist/model/index.d.ts +3 -3
  47. package/dist/model/index.js +1 -1
  48. package/dist/model/index.js.map +1 -1
  49. package/dist/model/step.d.ts +18 -13
  50. package/dist/model/step.js +2 -1
  51. package/dist/model/step.js.map +1 -1
  52. package/dist/model/target.d.ts +12 -15
  53. package/dist/model/target.js +2 -5
  54. package/dist/model/target.js.map +1 -1
  55. package/dist/storage.d.ts +93 -0
  56. package/dist/storage.js +4 -0
  57. package/dist/storage.js.map +1 -0
  58. package/dist/store/ids.d.ts +1 -2
  59. package/dist/store/ids.js +1 -2
  60. package/dist/store/ids.js.map +1 -1
  61. package/dist/store/index.d.ts +3 -8
  62. package/dist/store/index.js +2 -6
  63. package/dist/store/index.js.map +1 -1
  64. package/dist/store/resolve.d.ts +7 -14
  65. package/dist/store/resolve.js +4 -11
  66. package/dist/store/resolve.js.map +1 -1
  67. package/dist/store/store.d.ts +4 -41
  68. package/dist/store/store.js +1 -95
  69. package/dist/store/store.js.map +1 -1
  70. package/package.json +8 -8
  71. package/dist/execution/transaction.d.ts +0 -24
  72. package/dist/execution/transaction.js +0 -49
  73. package/dist/execution/transaction.js.map +0 -1
  74. package/dist/store/bootstrap.d.ts +0 -57
  75. package/dist/store/bootstrap.js +0 -268
  76. package/dist/store/bootstrap.js.map +0 -1
  77. package/dist/store/queryable.d.ts +0 -60
  78. package/dist/store/queryable.js +0 -7
  79. package/dist/store/queryable.js.map +0 -1
  80. package/dist/store/sql.d.ts +0 -26
  81. package/dist/store/sql.js +0 -21
  82. package/dist/store/sql.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@affordance/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "author": "Mochicode LLC (https://mochicode.com)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -8,22 +8,23 @@
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
10
10
  "import": "./dist/index.js"
11
+ },
12
+ "./storage": {
13
+ "types": "./dist/storage.d.ts",
14
+ "import": "./dist/storage.js"
11
15
  }
12
16
  },
13
17
  "dependencies": {
14
- "@standard-schema/spec": "^1.1.0",
15
- "@types/pg": "^8.11.10",
16
- "@affordance/contract": "0.1.0"
18
+ "@standard-schema/spec": "^1.1.0"
17
19
  },
18
20
  "devDependencies": {
19
21
  "@types/node": "^24.0.0",
20
22
  "typescript": "^5.7.2",
21
23
  "vitest": "^3.2.0",
22
- "pg": "^8.13.1",
23
24
  "zod": "^4.4.3",
24
25
  "@affordance/testkit": "0.0.0"
25
26
  },
26
- "description": "Adaptive case management with guarded steps, async execution, and a Postgres journal.",
27
+ "description": "Adaptive case management with guarded steps, async execution, and pluggable storage.",
27
28
  "main": "./dist/index.js",
28
29
  "types": "./dist/index.d.ts",
29
30
  "files": [
@@ -46,8 +47,7 @@
46
47
  "keywords": [
47
48
  "affordance",
48
49
  "case-management",
49
- "typescript",
50
- "postgres"
50
+ "typescript"
51
51
  ],
52
52
  "publishConfig": {
53
53
  "access": "public",
@@ -1,24 +0,0 @@
1
- /**
2
- * The transaction seam.
3
- *
4
- * The claim and the commit are each one short transaction; the handler runs
5
- * between them, outside both — so no transaction is ever held open
6
- * across a handler's external calls. `withTransaction` is how the execution
7
- * lifecycle gets one, and it is also what a handler's `ctx.onCommit` writes
8
- * ride along inside.
9
- */
10
- import type { DatabaseAccess, Transaction } from '../store/index.js';
11
- /**
12
- * Run `fn` inside a transaction and hand it the handle to use — a checked-out
13
- * client when the caller brought a pool, the client itself when they brought
14
- * one (issuing `begin` on a *pool* would put each statement on a different
15
- * connection, so the distinction is not cosmetic). Which case applies is the
16
- * caller's declaration — {@link DatabaseAccess} — never sniffed from the
17
- * object.
18
- *
19
- * Commits on return, rolls back on throw, and always releases what it
20
- * checked out. A rollback that itself fails is swallowed: the original error
21
- * is what the caller needs, and a connection too broken to roll back is
22
- * discarded by the pool anyway.
23
- */
24
- export declare const withTransaction: <T>(db: DatabaseAccess, fn: (tx: Transaction) => Promise<T>) => Promise<T>;
@@ -1,49 +0,0 @@
1
- /**
2
- * The transaction seam.
3
- *
4
- * The claim and the commit are each one short transaction; the handler runs
5
- * between them, outside both — so no transaction is ever held open
6
- * across a handler's external calls. `withTransaction` is how the execution
7
- * lifecycle gets one, and it is also what a handler's `ctx.onCommit` writes
8
- * ride along inside.
9
- */
10
- /**
11
- * Run `fn` inside a transaction and hand it the handle to use — a checked-out
12
- * client when the caller brought a pool, the client itself when they brought
13
- * one (issuing `begin` on a *pool* would put each statement on a different
14
- * connection, so the distinction is not cosmetic). Which case applies is the
15
- * caller's declaration — {@link DatabaseAccess} — never sniffed from the
16
- * object.
17
- *
18
- * Commits on return, rolls back on throw, and always releases what it
19
- * checked out. A rollback that itself fails is swallowed: the original error
20
- * is what the caller needs, and a connection too broken to roll back is
21
- * discarded by the pool anyway.
22
- */
23
- export const withTransaction = async (db, fn) => {
24
- if (!('pool' in db))
25
- return runTransaction(db.client, fn);
26
- const client = await db.pool.connect();
27
- try {
28
- return await runTransaction(client, fn);
29
- }
30
- finally {
31
- client.release();
32
- }
33
- };
34
- const runTransaction = async (handle, fn) => {
35
- // The one place the brand is applied: past the `begin` below, this handle
36
- // really is inside a transaction.
37
- const tx = handle;
38
- await tx.query('begin');
39
- try {
40
- const result = await fn(tx);
41
- await tx.query('commit');
42
- return result;
43
- }
44
- catch (error) {
45
- await tx.query('rollback').catch(() => undefined);
46
- throw error;
47
- }
48
- };
49
- //# sourceMappingURL=transaction.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"transaction.js","sourceRoot":"","sources":["../../src/execution/transaction.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,EAClC,EAAkB,EAClB,EAAmC,EACvB,EAAE;IACd,IAAI,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC;QAAE,OAAO,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;IACzD,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,CAAA;IACtC,IAAI,CAAC;QACH,OAAO,MAAM,cAAc,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;IACzC,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,OAAO,EAAE,CAAA;IAClB,CAAC;AACH,CAAC,CAAA;AAED,MAAM,cAAc,GAAG,KAAK,EAC1B,MAAiB,EACjB,EAAmC,EACvB,EAAE;IACd,0EAA0E;IAC1E,kCAAkC;IAClC,MAAM,EAAE,GAAG,MAAqB,CAAA;IAChC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;IACvB,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,CAAC,CAAA;QAC3B,MAAM,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QACxB,OAAO,MAAM,CAAA;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAA;QACjD,MAAM,KAAK,CAAA;IACb,CAAC;AACH,CAAC,CAAA","sourcesContent":["/**\n * The transaction seam.\n *\n * The claim and the commit are each one short transaction; the handler runs\n * between them, outside both — so no transaction is ever held open\n * across a handler's external calls. `withTransaction` is how the execution\n * lifecycle gets one, and it is also what a handler's `ctx.onCommit` writes\n * ride along inside.\n */\n\nimport type { DatabaseAccess, Queryable, Transaction } from '../store/index.js'\n\n/**\n * Run `fn` inside a transaction and hand it the handle to use — a checked-out\n * client when the caller brought a pool, the client itself when they brought\n * one (issuing `begin` on a *pool* would put each statement on a different\n * connection, so the distinction is not cosmetic). Which case applies is the\n * caller's declaration — {@link DatabaseAccess} — never sniffed from the\n * object.\n *\n * Commits on return, rolls back on throw, and always releases what it\n * checked out. A rollback that itself fails is swallowed: the original error\n * is what the caller needs, and a connection too broken to roll back is\n * discarded by the pool anyway.\n */\nexport const withTransaction = async <T>(\n db: DatabaseAccess,\n fn: (tx: Transaction) => Promise<T>,\n): Promise<T> => {\n if (!('pool' in db)) return runTransaction(db.client, fn)\n const client = await db.pool.connect()\n try {\n return await runTransaction(client, fn)\n } finally {\n client.release()\n }\n}\n\nconst runTransaction = async <T>(\n handle: Queryable,\n fn: (tx: Transaction) => Promise<T>,\n): Promise<T> => {\n // The one place the brand is applied: past the `begin` below, this handle\n // really is inside a transaction.\n const tx = handle as Transaction\n await tx.query('begin')\n try {\n const result = await fn(tx)\n await tx.query('commit')\n return result\n } catch (error) {\n await tx.query('rollback').catch(() => undefined)\n throw error\n }\n}\n"]}
@@ -1,57 +0,0 @@
1
- import type { Queryable } from './queryable.js';
2
- /**
3
- * Dedicated Postgres schema owning all framework tables.
4
- * Named `affordance` because `case` itself is a SQL reserved word.
5
- */
6
- export declare const FRAMEWORK_SCHEMA = "affordance";
7
- /**
8
- * The DDL revision below. Bump it whenever the DDL changes: a database
9
- * already carrying this version skips the DDL entirely, which is what keeps
10
- * a start-up from touching a busy database at all.
11
- */
12
- export declare const SCHEMA_VERSION = 4;
13
- /**
14
- * Every framework table that holds rows belonging to one case, with the
15
- * column that names the case — listed in an order safe to delete from
16
- * (children first; everything references `cases`). **The one answer to
17
- * "which tables does the framework own"** outside the DDL above: a consumer
18
- * that sweeps per-case rows (a dev console's case purge, a test harness's
19
- * cleanup) iterates this instead of keeping a private copy that goes stale
20
- * the release a table is added.
21
- *
22
- * `ingested_events.case_id` is nullable — an unrouted event belongs to no
23
- * case and survives a per-case sweep, which is correct: it was never about
24
- * the deleted case.
25
- */
26
- export declare const CASE_TABLES: readonly [{
27
- readonly table: "journal";
28
- readonly caseColumn: "case_id";
29
- }, {
30
- readonly table: "claims";
31
- readonly caseColumn: "case_id";
32
- }, {
33
- readonly table: "correlations";
34
- readonly caseColumn: "case_id";
35
- }, {
36
- readonly table: "ingested_events";
37
- readonly caseColumn: "case_id";
38
- }, {
39
- readonly table: "cases";
40
- readonly caseColumn: "id";
41
- }];
42
- /**
43
- * Idempotent DDL bootstrap for the framework schema. Safe to call on every
44
- * app start and from concurrent processes: the statements are sent as one
45
- * multi-statement simple query, which Postgres runs on one connection inside
46
- * a single implicit transaction, and the leading `pg_advisory_xact_lock`
47
- * serializes racing bootstraps (concurrent `CREATE ... IF NOT EXISTS` can
48
- * otherwise fail on catalog uniqueness).
49
- *
50
- * Also safe to call against a *busy* database, which is the harder promise,
51
- * and is answered twice over. First, a bootstrap with nothing to do does
52
- * nothing at all: {@link isCurrent} checks the version marker and returns
53
- * before any DDL runs, so the common case takes no table locks whatsoever.
54
- * Second, when there *is* work, the transaction bounds its own lock wait and
55
- * this retries it — schema management yields to live work, never the reverse.
56
- */
57
- export declare const bootstrap: (db: Queryable, attempts?: number) => Promise<void>;
@@ -1,268 +0,0 @@
1
- /**
2
- * Dedicated Postgres schema owning all framework tables.
3
- * Named `affordance` because `case` itself is a SQL reserved word.
4
- */
5
- export const FRAMEWORK_SCHEMA = 'affordance';
6
- /**
7
- * The DDL revision below. Bump it whenever the DDL changes: a database
8
- * already carrying this version skips the DDL entirely, which is what keeps
9
- * a start-up from touching a busy database at all.
10
- */
11
- export const SCHEMA_VERSION = 4;
12
- /**
13
- * Framework DDL, `IF NOT EXISTS` throughout — no migration framework.
14
- *
15
- * `cases` columns:
16
- * - `id` text — a typed id (`case:<uuid>`), minted by the store on
17
- * creation; every framework id carries its kind (see `ids.ts`)
18
- * - `case_type` the Case Type name (the code definition floats; only the
19
- * name is persisted)
20
- * - `state` the materialized Case State document
21
- * - `seq` per-case monotonic sequence counter, starts at 0; bumped by
22
- * every committed Execution
23
- * - `ended_at` dormancy marker written by `end()` — null while active;
24
- * dormancy, never a freeze (spec §Core model)
25
- *
26
- * `journal` is the immutable per-Execution record. The framework
27
- * only ever **inserts** into it — no update or delete path exists anywhere in
28
- * the library. One Execution contributes several entries (`claimed`, then any
29
- * `attempt-failed`, then a terminal `completed` / `failed` / `expired`), each
30
- * self-contained so a per-track audit is a filter, never a join:
31
- * - `ordinal` bigserial — total insertion order; per-case order is
32
- * `(case_id, ordinal)`
33
- * - `entry` which lifecycle moment this row records
34
- * - `step`/`scope_key`/`actor`/`input` — the Execution's identity, repeated on
35
- * every entry so `where scope_key = …` is the per-track audit
36
- * - `as_of`/`guard`/`state` — on `claimed`: the transactional guard
37
- * re-evaluation, the instant it was evaluated as of, and the
38
- * Case State it was evaluated against. Together they make
39
- * audit reconstruction exact rather than approximate.
40
- * - `delta` on `completed`: the JSON-Patch delta (previous → next)
41
- * - `dormancy` on `completed`: `end()` / `reopen()` called by the handler
42
- * - `error` on `attempt-failed` / `failed` / `expired`
43
- *
44
- * `correlations` and `ingested_events` are the two integration primitives.
45
- * A correlation maps an external identifier to (case, scope
46
- * element); it is written by the handler that starts the external
47
- * interaction, and `unique (system, external_id)` makes re-registering the
48
- * same envelope idempotent — a repeat changes nothing. `ingested_events` is
49
- * both the dedup gate and the dead-letter surface: `unique (idempotency_key)`
50
- * is what makes "three deliveries, one Execution" a database fact rather than
51
- * a hope, and the `status` / `reason` columns are why an event that changed
52
- * nothing is still visible.
53
- *
54
- * `claims` is the opposite kind of table: mutable, transient lease
55
- * bookkeeping, one row per **in-flight** Execution, deleted the moment the
56
- * Execution settles. `case_id` is its primary key — that single constraint is
57
- * "one in-flight execution per case". `expires_at` is what keeps a crash
58
- * from stranding a case: a crashed handler stops heartbeating and the next
59
- * claimant takes the case over (journaling an `expired` entry for the
60
- * abandoned Execution).
61
- */
62
- const DDL = `
63
- select pg_advisory_xact_lock(hashtextextended('${FRAMEWORK_SCHEMA}.bootstrap', 0));
64
-
65
- -- DDL must never be what blocks live work. "create index if not exists" and
66
- -- friends take table locks whether or not they have anything to do, so a
67
- -- bootstrap running against a busy database can queue behind -- or deadlock
68
- -- with -- Executions committing. Bounding the wait makes this transaction
69
- -- the one that yields, and bootstrap() retries it.
70
- set local lock_timeout = '2s';
71
-
72
- create schema if not exists ${FRAMEWORK_SCHEMA};
73
-
74
- -- Schema v2 stores typed text ids ('case:<uuid>', 'execution:<uuid>', …); v1
75
- -- stored bare uuids in uuid columns, which cannot hold them. There is no DDL
76
- -- migration framework, so a v1 database fails loudly here rather than
77
- -- corrupting silently on the first insert.
78
- do $$
79
- begin
80
- if exists (
81
- select 1 from information_schema.columns
82
- where table_schema = '${FRAMEWORK_SCHEMA}' and table_name = 'cases'
83
- and column_name = 'id' and data_type = 'uuid'
84
- ) then
85
- raise exception 'affordance schema v1 detected (uuid ids); v2 ids are text of the form kind:uuid. No automatic conversion exists — export anything you need, then: drop schema ${FRAMEWORK_SCHEMA} cascade; and re-bootstrap.';
86
- end if;
87
- end $$;
88
-
89
- create table if not exists ${FRAMEWORK_SCHEMA}.cases (
90
- id text primary key,
91
- case_type text not null,
92
- state jsonb not null,
93
- seq bigint not null default 0,
94
- ended_at timestamptz,
95
- created_at timestamptz not null default now(),
96
- updated_at timestamptz not null default now()
97
- );
98
-
99
- create table if not exists ${FRAMEWORK_SCHEMA}.journal (
100
- ordinal bigserial primary key,
101
- id text not null unique,
102
- case_id text not null references ${FRAMEWORK_SCHEMA}.cases (id),
103
- execution_id text not null,
104
- entry text not null,
105
- attempt integer not null default 1,
106
- step text not null,
107
- scope_key text,
108
- actor jsonb,
109
- input jsonb,
110
- as_of timestamptz,
111
- guard jsonb,
112
- state jsonb,
113
- delta jsonb,
114
- dormancy text,
115
- error jsonb,
116
- recorded_at timestamptz not null default now()
117
- );
118
-
119
- -- Schema v4 removed rule automation, and with it the \`cause\` column (the
120
- -- causality record an automatic Execution carried). The column is left in
121
- -- place on a database that has it: journal rows are immutable history, and
122
- -- old automatic Executions keep the cause they were recorded with. New
123
- -- entries simply never write it.
124
-
125
- create index if not exists journal_case_idx
126
- on ${FRAMEWORK_SCHEMA}.journal (case_id, ordinal);
127
- create index if not exists journal_scope_idx
128
- on ${FRAMEWORK_SCHEMA}.journal (case_id, scope_key, ordinal);
129
- create index if not exists journal_execution_idx
130
- on ${FRAMEWORK_SCHEMA}.journal (execution_id, ordinal);
131
-
132
- create table if not exists ${FRAMEWORK_SCHEMA}.claims (
133
- case_id text primary key references ${FRAMEWORK_SCHEMA}.cases (id),
134
- execution_id text not null,
135
- step text not null,
136
- scope_key text,
137
- attempt integer not null default 1,
138
- claimed_at timestamptz not null default now(),
139
- heartbeat_at timestamptz not null default now(),
140
- expires_at timestamptz not null
141
- );
142
-
143
- -- Schema v3 removed timer scheduling. Timer rows were derived state (a
144
- -- case's future time-flips, recomputable from nothing but Case State), so
145
- -- dropping the table on a v2 database loses no facts.
146
- drop table if exists ${FRAMEWORK_SCHEMA}.timers;
147
-
148
- create table if not exists ${FRAMEWORK_SCHEMA}.correlations (
149
- id text primary key,
150
- system text not null,
151
- external_id text not null,
152
- case_id text not null references ${FRAMEWORK_SCHEMA}.cases (id),
153
- scope_key text,
154
- step text,
155
- metadata jsonb,
156
- created_at timestamptz not null default now(),
157
- unique (system, external_id)
158
- );
159
-
160
- create index if not exists correlations_case_idx
161
- on ${FRAMEWORK_SCHEMA}.correlations (case_id, scope_key);
162
-
163
- create table if not exists ${FRAMEWORK_SCHEMA}.ingested_events (
164
- id text primary key,
165
- system text not null,
166
- external_id text not null,
167
- type text not null,
168
- idempotency_key text not null unique,
169
- case_id text,
170
- scope_key text,
171
- step text,
172
- status text not null,
173
- reason text,
174
- detail text,
175
- execution_id text,
176
- event jsonb not null,
177
- received_at timestamptz not null default now()
178
- );
179
-
180
- create index if not exists ingested_events_dead_letter_idx
181
- on ${FRAMEWORK_SCHEMA}.ingested_events (status, received_at desc);
182
-
183
- create table if not exists ${FRAMEWORK_SCHEMA}.schema_version (
184
- version integer primary key,
185
- applied_at timestamptz not null default now()
186
- );
187
-
188
- insert into ${FRAMEWORK_SCHEMA}.schema_version (version)
189
- values (${SCHEMA_VERSION}) on conflict do nothing;
190
- `;
191
- /**
192
- * Every framework table that holds rows belonging to one case, with the
193
- * column that names the case — listed in an order safe to delete from
194
- * (children first; everything references `cases`). **The one answer to
195
- * "which tables does the framework own"** outside the DDL above: a consumer
196
- * that sweeps per-case rows (a dev console's case purge, a test harness's
197
- * cleanup) iterates this instead of keeping a private copy that goes stale
198
- * the release a table is added.
199
- *
200
- * `ingested_events.case_id` is nullable — an unrouted event belongs to no
201
- * case and survives a per-case sweep, which is correct: it was never about
202
- * the deleted case.
203
- */
204
- export const CASE_TABLES = [
205
- { table: 'journal', caseColumn: 'case_id' },
206
- { table: 'claims', caseColumn: 'case_id' },
207
- { table: 'correlations', caseColumn: 'case_id' },
208
- { table: 'ingested_events', caseColumn: 'case_id' },
209
- { table: 'cases', caseColumn: 'id' },
210
- ];
211
- /**
212
- * Whether the schema is already at {@link SCHEMA_VERSION} — two catalog reads
213
- * that take no lock any Execution could ever be waiting on.
214
- *
215
- * This is what makes `bootstrap` free on every start after the first. The DDL
216
- * below is idempotent, but idempotent is not the same as *harmless*: `create
217
- * index if not exists` takes a table lock whether or not it has work to do,
218
- * and a bootstrap holding one while Executions commit can deadlock with them
219
- * — not as a rare race, but predictably, on every start against a busy
220
- * database. Asking first means the locks are only ever taken when there is
221
- * genuinely something to create.
222
- */
223
- const isCurrent = async (db) => {
224
- const marker = await db.query(`select to_regclass('${FRAMEWORK_SCHEMA}.schema_version') is not null as present`);
225
- if (marker.rows[0]?.present !== true)
226
- return false;
227
- const applied = await db.query(`select max(version) as version from ${FRAMEWORK_SCHEMA}.schema_version`);
228
- return (applied.rows[0]?.version ?? 0) >= SCHEMA_VERSION;
229
- };
230
- /** Postgres says the transaction lost a race it can retry: deadlock, or the bounded lock wait. */
231
- const isContention = (error) => {
232
- const code = error?.code;
233
- return code === '40P01' || code === '55P03' || code === '40001';
234
- };
235
- const wait = (ms) => new Promise((resolve) => {
236
- setTimeout(resolve, ms);
237
- });
238
- /**
239
- * Idempotent DDL bootstrap for the framework schema. Safe to call on every
240
- * app start and from concurrent processes: the statements are sent as one
241
- * multi-statement simple query, which Postgres runs on one connection inside
242
- * a single implicit transaction, and the leading `pg_advisory_xact_lock`
243
- * serializes racing bootstraps (concurrent `CREATE ... IF NOT EXISTS` can
244
- * otherwise fail on catalog uniqueness).
245
- *
246
- * Also safe to call against a *busy* database, which is the harder promise,
247
- * and is answered twice over. First, a bootstrap with nothing to do does
248
- * nothing at all: {@link isCurrent} checks the version marker and returns
249
- * before any DDL runs, so the common case takes no table locks whatsoever.
250
- * Second, when there *is* work, the transaction bounds its own lock wait and
251
- * this retries it — schema management yields to live work, never the reverse.
252
- */
253
- export const bootstrap = async (db, attempts = 5) => {
254
- if (await isCurrent(db))
255
- return;
256
- for (let attempt = 1;; attempt += 1) {
257
- try {
258
- await db.query(DDL);
259
- return;
260
- }
261
- catch (error) {
262
- if (attempt >= attempts || !isContention(error))
263
- throw error;
264
- await wait(50 * attempt);
265
- }
266
- }
267
- };
268
- //# sourceMappingURL=bootstrap.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../src/store/bootstrap.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,YAAY,CAAA;AAE5C;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAA;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,MAAM,GAAG,GAAG;iDACqC,gBAAgB;;;;;;;;;8BASnC,gBAAgB;;;;;;;;;;4BAUlB,gBAAgB;;;qLAGyI,gBAAgB;;;;6BAIxK,gBAAgB;;;;;;;;;;6BAUhB,gBAAgB;;;qCAGR,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;OAwB9C,gBAAgB;;OAEhB,gBAAgB;;OAEhB,gBAAgB;;6BAEM,gBAAgB;wCACL,gBAAgB;;;;;;;;;;;;;uBAajC,gBAAgB;;6BAEV,gBAAgB;;;;qCAIR,gBAAgB;;;;;;;;;OAS9C,gBAAgB;;6BAEM,gBAAgB;;;;;;;;;;;;;;;;;;OAkBtC,gBAAgB;;6BAEM,gBAAgB;;;;;cAK/B,gBAAgB;UACpB,cAAc;CACvB,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE;IAC3C,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE;IAC1C,EAAE,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,SAAS,EAAE;IAChD,EAAE,KAAK,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE;IACnD,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE;CAC5B,CAAA;AAEV;;;;;;;;;;;GAWG;AACH,MAAM,SAAS,GAAG,KAAK,EAAE,EAAa,EAAoB,EAAE;IAC1D,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,KAAK,CAC3B,uBAAuB,gBAAgB,0CAA0C,CAClF,CAAA;IACD,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,KAAK,IAAI;QAAE,OAAO,KAAK,CAAA;IAClD,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC,KAAK,CAC5B,uCAAuC,gBAAgB,iBAAiB,CACzE,CAAA;IACD,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,CAAC,IAAI,cAAc,CAAA;AAC1D,CAAC,CAAA;AAED,kGAAkG;AAClG,MAAM,YAAY,GAAG,CAAC,KAAc,EAAW,EAAE;IAC/C,MAAM,IAAI,GAAI,KAAmC,EAAE,IAAI,CAAA;IACvD,OAAO,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAA;AACjE,CAAC,CAAA;AAED,MAAM,IAAI,GAAG,CAAC,EAAU,EAAiB,EAAE,CACzC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;IACtB,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;AACzB,CAAC,CAAC,CAAA;AAEJ;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,EAAE,EAAa,EAAE,QAAQ,GAAG,CAAC,EAAiB,EAAE;IAC5E,IAAI,MAAM,SAAS,CAAC,EAAE,CAAC;QAAE,OAAM;IAC/B,KAAK,IAAI,OAAO,GAAG,CAAC,GAAI,OAAO,IAAI,CAAC,EAAE,CAAC;QACrC,IAAI,CAAC;YACH,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;YACnB,OAAM;QACR,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,OAAO,IAAI,QAAQ,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;gBAAE,MAAM,KAAK,CAAA;YAC5D,MAAM,IAAI,CAAC,EAAE,GAAG,OAAO,CAAC,CAAA;QAC1B,CAAC;IACH,CAAC;AACH,CAAC,CAAA","sourcesContent":["import type { Queryable } from './queryable.js'\n\n/**\n * Dedicated Postgres schema owning all framework tables.\n * Named `affordance` because `case` itself is a SQL reserved word.\n */\nexport const FRAMEWORK_SCHEMA = 'affordance'\n\n/**\n * The DDL revision below. Bump it whenever the DDL changes: a database\n * already carrying this version skips the DDL entirely, which is what keeps\n * a start-up from touching a busy database at all.\n */\nexport const SCHEMA_VERSION = 4\n\n/**\n * Framework DDL, `IF NOT EXISTS` throughout — no migration framework.\n *\n * `cases` columns:\n * - `id` text — a typed id (`case:<uuid>`), minted by the store on\n * creation; every framework id carries its kind (see `ids.ts`)\n * - `case_type` the Case Type name (the code definition floats; only the\n * name is persisted)\n * - `state` the materialized Case State document\n * - `seq` per-case monotonic sequence counter, starts at 0; bumped by\n * every committed Execution\n * - `ended_at` dormancy marker written by `end()` — null while active;\n * dormancy, never a freeze (spec §Core model)\n *\n * `journal` is the immutable per-Execution record. The framework\n * only ever **inserts** into it — no update or delete path exists anywhere in\n * the library. One Execution contributes several entries (`claimed`, then any\n * `attempt-failed`, then a terminal `completed` / `failed` / `expired`), each\n * self-contained so a per-track audit is a filter, never a join:\n * - `ordinal` bigserial — total insertion order; per-case order is\n * `(case_id, ordinal)`\n * - `entry` which lifecycle moment this row records\n * - `step`/`scope_key`/`actor`/`input` — the Execution's identity, repeated on\n * every entry so `where scope_key = …` is the per-track audit\n * - `as_of`/`guard`/`state` — on `claimed`: the transactional guard\n * re-evaluation, the instant it was evaluated as of, and the\n * Case State it was evaluated against. Together they make\n * audit reconstruction exact rather than approximate.\n * - `delta` on `completed`: the JSON-Patch delta (previous → next)\n * - `dormancy` on `completed`: `end()` / `reopen()` called by the handler\n * - `error` on `attempt-failed` / `failed` / `expired`\n *\n * `correlations` and `ingested_events` are the two integration primitives.\n * A correlation maps an external identifier to (case, scope\n * element); it is written by the handler that starts the external\n * interaction, and `unique (system, external_id)` makes re-registering the\n * same envelope idempotent — a repeat changes nothing. `ingested_events` is\n * both the dedup gate and the dead-letter surface: `unique (idempotency_key)`\n * is what makes \"three deliveries, one Execution\" a database fact rather than\n * a hope, and the `status` / `reason` columns are why an event that changed\n * nothing is still visible.\n *\n * `claims` is the opposite kind of table: mutable, transient lease\n * bookkeeping, one row per **in-flight** Execution, deleted the moment the\n * Execution settles. `case_id` is its primary key — that single constraint is\n * \"one in-flight execution per case\". `expires_at` is what keeps a crash\n * from stranding a case: a crashed handler stops heartbeating and the next\n * claimant takes the case over (journaling an `expired` entry for the\n * abandoned Execution).\n */\nconst DDL = `\nselect pg_advisory_xact_lock(hashtextextended('${FRAMEWORK_SCHEMA}.bootstrap', 0));\n\n-- DDL must never be what blocks live work. \"create index if not exists\" and\n-- friends take table locks whether or not they have anything to do, so a\n-- bootstrap running against a busy database can queue behind -- or deadlock\n-- with -- Executions committing. Bounding the wait makes this transaction\n-- the one that yields, and bootstrap() retries it.\nset local lock_timeout = '2s';\n\ncreate schema if not exists ${FRAMEWORK_SCHEMA};\n\n-- Schema v2 stores typed text ids ('case:<uuid>', 'execution:<uuid>', …); v1\n-- stored bare uuids in uuid columns, which cannot hold them. There is no DDL\n-- migration framework, so a v1 database fails loudly here rather than\n-- corrupting silently on the first insert.\ndo $$\nbegin\n if exists (\n select 1 from information_schema.columns\n where table_schema = '${FRAMEWORK_SCHEMA}' and table_name = 'cases'\n and column_name = 'id' and data_type = 'uuid'\n ) then\n raise exception 'affordance schema v1 detected (uuid ids); v2 ids are text of the form kind:uuid. No automatic conversion exists — export anything you need, then: drop schema ${FRAMEWORK_SCHEMA} cascade; and re-bootstrap.';\n end if;\nend $$;\n\ncreate table if not exists ${FRAMEWORK_SCHEMA}.cases (\n id text primary key,\n case_type text not null,\n state jsonb not null,\n seq bigint not null default 0,\n ended_at timestamptz,\n created_at timestamptz not null default now(),\n updated_at timestamptz not null default now()\n);\n\ncreate table if not exists ${FRAMEWORK_SCHEMA}.journal (\n ordinal bigserial primary key,\n id text not null unique,\n case_id text not null references ${FRAMEWORK_SCHEMA}.cases (id),\n execution_id text not null,\n entry text not null,\n attempt integer not null default 1,\n step text not null,\n scope_key text,\n actor jsonb,\n input jsonb,\n as_of timestamptz,\n guard jsonb,\n state jsonb,\n delta jsonb,\n dormancy text,\n error jsonb,\n recorded_at timestamptz not null default now()\n);\n\n-- Schema v4 removed rule automation, and with it the \\`cause\\` column (the\n-- causality record an automatic Execution carried). The column is left in\n-- place on a database that has it: journal rows are immutable history, and\n-- old automatic Executions keep the cause they were recorded with. New\n-- entries simply never write it.\n\ncreate index if not exists journal_case_idx\n on ${FRAMEWORK_SCHEMA}.journal (case_id, ordinal);\ncreate index if not exists journal_scope_idx\n on ${FRAMEWORK_SCHEMA}.journal (case_id, scope_key, ordinal);\ncreate index if not exists journal_execution_idx\n on ${FRAMEWORK_SCHEMA}.journal (execution_id, ordinal);\n\ncreate table if not exists ${FRAMEWORK_SCHEMA}.claims (\n case_id text primary key references ${FRAMEWORK_SCHEMA}.cases (id),\n execution_id text not null,\n step text not null,\n scope_key text,\n attempt integer not null default 1,\n claimed_at timestamptz not null default now(),\n heartbeat_at timestamptz not null default now(),\n expires_at timestamptz not null\n);\n\n-- Schema v3 removed timer scheduling. Timer rows were derived state (a\n-- case's future time-flips, recomputable from nothing but Case State), so\n-- dropping the table on a v2 database loses no facts.\ndrop table if exists ${FRAMEWORK_SCHEMA}.timers;\n\ncreate table if not exists ${FRAMEWORK_SCHEMA}.correlations (\n id text primary key,\n system text not null,\n external_id text not null,\n case_id text not null references ${FRAMEWORK_SCHEMA}.cases (id),\n scope_key text,\n step text,\n metadata jsonb,\n created_at timestamptz not null default now(),\n unique (system, external_id)\n);\n\ncreate index if not exists correlations_case_idx\n on ${FRAMEWORK_SCHEMA}.correlations (case_id, scope_key);\n\ncreate table if not exists ${FRAMEWORK_SCHEMA}.ingested_events (\n id text primary key,\n system text not null,\n external_id text not null,\n type text not null,\n idempotency_key text not null unique,\n case_id text,\n scope_key text,\n step text,\n status text not null,\n reason text,\n detail text,\n execution_id text,\n event jsonb not null,\n received_at timestamptz not null default now()\n);\n\ncreate index if not exists ingested_events_dead_letter_idx\n on ${FRAMEWORK_SCHEMA}.ingested_events (status, received_at desc);\n\ncreate table if not exists ${FRAMEWORK_SCHEMA}.schema_version (\n version integer primary key,\n applied_at timestamptz not null default now()\n);\n\ninsert into ${FRAMEWORK_SCHEMA}.schema_version (version)\nvalues (${SCHEMA_VERSION}) on conflict do nothing;\n`\n\n/**\n * Every framework table that holds rows belonging to one case, with the\n * column that names the case — listed in an order safe to delete from\n * (children first; everything references `cases`). **The one answer to\n * \"which tables does the framework own\"** outside the DDL above: a consumer\n * that sweeps per-case rows (a dev console's case purge, a test harness's\n * cleanup) iterates this instead of keeping a private copy that goes stale\n * the release a table is added.\n *\n * `ingested_events.case_id` is nullable — an unrouted event belongs to no\n * case and survives a per-case sweep, which is correct: it was never about\n * the deleted case.\n */\nexport const CASE_TABLES = [\n { table: 'journal', caseColumn: 'case_id' },\n { table: 'claims', caseColumn: 'case_id' },\n { table: 'correlations', caseColumn: 'case_id' },\n { table: 'ingested_events', caseColumn: 'case_id' },\n { table: 'cases', caseColumn: 'id' },\n] as const\n\n/**\n * Whether the schema is already at {@link SCHEMA_VERSION} — two catalog reads\n * that take no lock any Execution could ever be waiting on.\n *\n * This is what makes `bootstrap` free on every start after the first. The DDL\n * below is idempotent, but idempotent is not the same as *harmless*: `create\n * index if not exists` takes a table lock whether or not it has work to do,\n * and a bootstrap holding one while Executions commit can deadlock with them\n * — not as a rare race, but predictably, on every start against a busy\n * database. Asking first means the locks are only ever taken when there is\n * genuinely something to create.\n */\nconst isCurrent = async (db: Queryable): Promise<boolean> => {\n const marker = await db.query<{ present: boolean }>(\n `select to_regclass('${FRAMEWORK_SCHEMA}.schema_version') is not null as present`,\n )\n if (marker.rows[0]?.present !== true) return false\n const applied = await db.query<{ version: number }>(\n `select max(version) as version from ${FRAMEWORK_SCHEMA}.schema_version`,\n )\n return (applied.rows[0]?.version ?? 0) >= SCHEMA_VERSION\n}\n\n/** Postgres says the transaction lost a race it can retry: deadlock, or the bounded lock wait. */\nconst isContention = (error: unknown): boolean => {\n const code = (error as { code?: unknown } | null)?.code\n return code === '40P01' || code === '55P03' || code === '40001'\n}\n\nconst wait = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n\n/**\n * Idempotent DDL bootstrap for the framework schema. Safe to call on every\n * app start and from concurrent processes: the statements are sent as one\n * multi-statement simple query, which Postgres runs on one connection inside\n * a single implicit transaction, and the leading `pg_advisory_xact_lock`\n * serializes racing bootstraps (concurrent `CREATE ... IF NOT EXISTS` can\n * otherwise fail on catalog uniqueness).\n *\n * Also safe to call against a *busy* database, which is the harder promise,\n * and is answered twice over. First, a bootstrap with nothing to do does\n * nothing at all: {@link isCurrent} checks the version marker and returns\n * before any DDL runs, so the common case takes no table locks whatsoever.\n * Second, when there *is* work, the transaction bounds its own lock wait and\n * this retries it — schema management yields to live work, never the reverse.\n */\nexport const bootstrap = async (db: Queryable, attempts = 5): Promise<void> => {\n if (await isCurrent(db)) return\n for (let attempt = 1; ; attempt += 1) {\n try {\n await db.query(DDL)\n return\n } catch (error) {\n if (attempt >= attempts || !isContention(error)) throw error\n await wait(50 * attempt)\n }\n }\n}\n"]}
@@ -1,60 +0,0 @@
1
- import type { QueryResult, QueryResultRow } from 'pg';
2
- /**
3
- * Minimal query surface satisfied by pg.Pool, pg.Client, and pg.PoolClient.
4
- *
5
- * Every store internal takes a Queryable rather than a Pool so a future
6
- * caller can run case-store queries on an existing client/transaction —
7
- * the shared-transaction seam (spec §Mechanics/Persistence: handlers may
8
- * join the framework transaction so app-table writes commit atomically
9
- * with case state).
10
- */
11
- export interface Queryable {
12
- query<R extends QueryResultRow = QueryResultRow>(text: string, values?: unknown[]): Promise<QueryResult<R>>;
13
- }
14
- /**
15
- * A pooled connection source: `connect()` checks out a client that must be
16
- * released. `pg.Pool` satisfies this structurally, and so does any
17
- * multiplexing wrapper (an instrumented pool, a proxy) that declares
18
- * checkout the same way.
19
- */
20
- export interface PoolLike extends Queryable {
21
- connect(): Promise<Queryable & {
22
- release(): void;
23
- }>;
24
- }
25
- /**
26
- * The database as the engine's caller supplies it. The union states, in the
27
- * type, the one fact a transaction must know: whether `begin` needs a
28
- * checked-out connection first. A pool multiplexes — issuing `begin` on it
29
- * would put each statement on a different connection — so `pool` promises
30
- * checkout via `connect()`, and `client` asserts a connection dedicated to
31
- * the engine, safe to run a transaction on directly. The caller declares
32
- * which they have; nothing downstream sniffs the object to guess.
33
- */
34
- export type DatabaseAccess = {
35
- readonly pool: PoolLike;
36
- } | {
37
- readonly client: Queryable;
38
- };
39
- /**
40
- * The plain query surface of either arm — what a single self-contained
41
- * statement (a journal read, a heartbeat) runs against, where pool vs.
42
- * client makes no difference.
43
- */
44
- export declare const queryableOf: (db: DatabaseAccess) => Queryable;
45
- declare const transactionBrand: unique symbol;
46
- /**
47
- * A {@link Queryable} known to be inside an open transaction — the handle
48
- * `withTransaction` passes to its callback, and the only place the brand is
49
- * ever applied.
50
- *
51
- * Some operations are meaningless (or silently wrong) against a pool: a
52
- * `select … for update` whose lock vanishes with the statement, a write
53
- * that must commit in the same transaction as the state it accompanies.
54
- * Those take a `Transaction`, so "pass the transaction handle, not a pool"
55
- * is a compile error rather than a sentence a caller has to have read.
56
- */
57
- export interface Transaction extends Queryable {
58
- readonly [transactionBrand]: true;
59
- }
60
- export {};
@@ -1,7 +0,0 @@
1
- /**
2
- * The plain query surface of either arm — what a single self-contained
3
- * statement (a journal read, a heartbeat) runs against, where pool vs.
4
- * client makes no difference.
5
- */
6
- export const queryableOf = (db) => 'pool' in db ? db.pool : db.client;
7
- //# sourceMappingURL=queryable.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"queryable.js","sourceRoot":"","sources":["../../src/store/queryable.ts"],"names":[],"mappings":"AAyCA;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,EAAkB,EAAa,EAAE,CAC3D,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM,CAAA","sourcesContent":["import type { QueryResult, QueryResultRow } from 'pg'\n\n/**\n * Minimal query surface satisfied by pg.Pool, pg.Client, and pg.PoolClient.\n *\n * Every store internal takes a Queryable rather than a Pool so a future\n * caller can run case-store queries on an existing client/transaction —\n * the shared-transaction seam (spec §Mechanics/Persistence: handlers may\n * join the framework transaction so app-table writes commit atomically\n * with case state).\n */\nexport interface Queryable {\n query<R extends QueryResultRow = QueryResultRow>(\n text: string,\n values?: unknown[],\n ): Promise<QueryResult<R>>\n}\n\n/**\n * A pooled connection source: `connect()` checks out a client that must be\n * released. `pg.Pool` satisfies this structurally, and so does any\n * multiplexing wrapper (an instrumented pool, a proxy) that declares\n * checkout the same way.\n */\nexport interface PoolLike extends Queryable {\n connect(): Promise<Queryable & { release(): void }>\n}\n\n/**\n * The database as the engine's caller supplies it. The union states, in the\n * type, the one fact a transaction must know: whether `begin` needs a\n * checked-out connection first. A pool multiplexes — issuing `begin` on it\n * would put each statement on a different connection — so `pool` promises\n * checkout via `connect()`, and `client` asserts a connection dedicated to\n * the engine, safe to run a transaction on directly. The caller declares\n * which they have; nothing downstream sniffs the object to guess.\n */\nexport type DatabaseAccess =\n | { readonly pool: PoolLike }\n | { readonly client: Queryable }\n\n/**\n * The plain query surface of either arm — what a single self-contained\n * statement (a journal read, a heartbeat) runs against, where pool vs.\n * client makes no difference.\n */\nexport const queryableOf = (db: DatabaseAccess): Queryable =>\n 'pool' in db ? db.pool : db.client\n\ndeclare const transactionBrand: unique symbol\n\n/**\n * A {@link Queryable} known to be inside an open transaction — the handle\n * `withTransaction` passes to its callback, and the only place the brand is\n * ever applied.\n *\n * Some operations are meaningless (or silently wrong) against a pool: a\n * `select … for update` whose lock vanishes with the statement, a write\n * that must commit in the same transaction as the state it accompanies.\n * Those take a `Transaction`, so \"pass the transaction handle, not a pool\"\n * is a compile error rather than a sentence a caller has to have read.\n */\nexport interface Transaction extends Queryable {\n readonly [transactionBrand]: true\n}\n"]}
@@ -1,26 +0,0 @@
1
- /**
2
- * The one idiom behind every filtered read in the package: a `where` clause
3
- * assembled from a list of AND-ed conditions and a positional values array.
4
- * The journal, the dead-letter surface, and the migration candidate query
5
- * each read a different table, but they all number their placeholders and
6
- * join their conditions the same way — stated once here, so a new filter
7
- * cannot number a placeholder wrong.
8
- */
9
- /** A `where` clause under assembly. */
10
- export interface SqlWhere {
11
- /** The AND-ed conditions; push to add one. */
12
- readonly conditions: string[];
13
- /** The bound values, positionally matching the `$n` placeholders. */
14
- readonly values: unknown[];
15
- /** Append a value and return its `$n` placeholder. */
16
- readonly bind: (value: unknown) => string;
17
- /** The conditions joined with ` and ` — the body of the `where` clause. */
18
- readonly where: () => string;
19
- }
20
- /**
21
- * Start a `where` clause. Fixed conditions and their values are the seed —
22
- * a seeded condition may spell its own `$n` as long as it matches the
23
- * value's position — and optional conditions are pushed with placeholders
24
- * from `bind`.
25
- */
26
- export declare const sqlWhere: (conditions?: string[], values?: unknown[]) => SqlWhere;
package/dist/store/sql.js DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * The one idiom behind every filtered read in the package: a `where` clause
3
- * assembled from a list of AND-ed conditions and a positional values array.
4
- * The journal, the dead-letter surface, and the migration candidate query
5
- * each read a different table, but they all number their placeholders and
6
- * join their conditions the same way — stated once here, so a new filter
7
- * cannot number a placeholder wrong.
8
- */
9
- /**
10
- * Start a `where` clause. Fixed conditions and their values are the seed —
11
- * a seeded condition may spell its own `$n` as long as it matches the
12
- * value's position — and optional conditions are pushed with placeholders
13
- * from `bind`.
14
- */
15
- export const sqlWhere = (conditions = [], values = []) => ({
16
- conditions,
17
- values,
18
- bind: (value) => `$${values.push(value)}`,
19
- where: () => conditions.join(' and '),
20
- });
21
- //# sourceMappingURL=sql.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sql.js","sourceRoot":"","sources":["../../src/store/sql.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAcH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,aAAuB,EAAE,EACzB,SAAoB,EAAE,EACZ,EAAE,CAAC,CAAC;IACd,UAAU;IACV,MAAM;IACN,IAAI,EAAE,CAAC,KAAc,EAAU,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;IAC1D,KAAK,EAAE,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC;CACtC,CAAC,CAAA","sourcesContent":["/**\n * The one idiom behind every filtered read in the package: a `where` clause\n * assembled from a list of AND-ed conditions and a positional values array.\n * The journal, the dead-letter surface, and the migration candidate query\n * each read a different table, but they all number their placeholders and\n * join their conditions the same way — stated once here, so a new filter\n * cannot number a placeholder wrong.\n */\n\n/** A `where` clause under assembly. */\nexport interface SqlWhere {\n /** The AND-ed conditions; push to add one. */\n readonly conditions: string[]\n /** The bound values, positionally matching the `$n` placeholders. */\n readonly values: unknown[]\n /** Append a value and return its `$n` placeholder. */\n readonly bind: (value: unknown) => string\n /** The conditions joined with ` and ` — the body of the `where` clause. */\n readonly where: () => string\n}\n\n/**\n * Start a `where` clause. Fixed conditions and their values are the seed —\n * a seeded condition may spell its own `$n` as long as it matches the\n * value's position — and optional conditions are pushed with placeholders\n * from `bind`.\n */\nexport const sqlWhere = (\n conditions: string[] = [],\n values: unknown[] = [],\n): SqlWhere => ({\n conditions,\n values,\n bind: (value: unknown): string => `$${values.push(value)}`,\n where: () => conditions.join(' and '),\n})\n"]}