@rexezuge/d1 1.9.4 → 1.11.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @rexezuge/d1
2
2
 
3
- D1 retry engine, error classifier, `BaseDAO`, SQL splitter, and AES-GCM envelope.
3
+ D1 retry engine, error classifier, `BaseDAO` (+ `EncryptedDAO`, `BackgroundTaskRunDAO`), D1 Sessions bookmarks, SQL splitter, and AES-GCM envelope.
4
4
 
5
5
  Depends on `@rexezuge/errors` (failures surface as `DatabaseError` with the classifier's verdict in `retryable`) and `@rexezuge/shared` (base64 for the crypto envelope).
6
6
 
@@ -36,6 +36,8 @@ class UserDAO extends BaseDAO {
36
36
  }
37
37
  ```
38
38
 
39
+ Generic helpers every DAO inherits: `findRowById<T>(table, id, { idColumn?, columns? })` (metered, `T | null`) and `deleteRowsOlderThan(table, timeColumn, cutoff, limit, { idColumn?, extraCondition? })` — one bounded `DELETE … WHERE id IN (SELECT … LIMIT ?)` batch, which is also a runtime `PruningTarget` in one line. The static `BaseDAO.deleteOlderThan(db, …)` stays for callers outside a DAO.
40
+
39
41
  `BaseDAO` wraps every statement in the retry engine. `D1Queryable` / `D1PreparedStatement` / `D1Result` are structural types, so fakes, Miniflare, and real D1 bindings all satisfy them. `assertSqlIdentifier` guards the one thing bindings cannot parameterize — table/column names.
40
42
 
41
43
  ## 3. SQL splitting and schema errors
@@ -65,6 +67,64 @@ const cleartext = await decryptSecret({ ciphertext, iv }, env.BACKUP_ENCRYPTION_
65
67
 
66
68
  Key material is base64 of exactly 32 bytes; a missing or wrong-sized key throws `AesGcmKeyError` rather than storing the secret in the clear. The IV is random per call — reusing one under a key destroys GCM's guarantees, which is why it is returned alongside the ciphertext instead of being internal.
67
69
 
70
+ ## 5. `EncryptedDAO`
71
+
72
+ A DAO whose rows hold AES-GCM envelopes. The key is a constructor **port** — one base64 key, or keys in preference order for rotation — resolved by the composition root, never read from `env` inside the DAO:
73
+
74
+ ```ts
75
+ class ConnectedApplicationDAO extends EncryptedDAO {
76
+ public async save(id: string, credentials: Credentials) {
77
+ const { ciphertext, iv } = await this.sealJson(credentials); // always under keys[0]
78
+ await this.run('UPDATE apps SET encrypted_credentials = ?, credentials_iv = ? WHERE id = ?', [ciphertext, iv, id]);
79
+ }
80
+ public async load(row: Row) {
81
+ return this.openJson<Credentials>({ ciphertext: row.encrypted_credentials, iv: row.credentials_iv }); // tries each key, fails closed
82
+ }
83
+ }
84
+ new ConnectedApplicationDAO(env.DB, [env.MASTER_KEY, env.PREVIOUS_MASTER_KEY], meter);
85
+ ```
86
+
87
+ `this.masterKey` (the write key) stays readable for subclasses that call `encryptSecret` themselves. An empty key list throws `AesGcmKeyError` at construction.
88
+
89
+ ## 6. `BackgroundTaskRunDAO`
90
+
91
+ The `background_task_runs` table, implementing `@rexezuge/runtime`'s `TaskRunRecorder` (`startRun` / `succeedRun` / `failRun` / `skipRun`) and `PruningTarget` (`deleteOlderThan`) **structurally** — `d1` does not depend on `runtime`:
92
+
93
+ ```ts
94
+ const runs = new BackgroundTaskRunDAO(env.DB, meter, { clock, ids }); // Clock / IdGenerator ports from @rexezuge/shared
95
+ class RefreshTask extends AbstractScheduledTask<Env> {
96
+ protected createRunRecorder() {
97
+ return runs;
98
+ }
99
+ }
100
+ await runs.listRuns({ taskType: 'refresh', limit: 25, cursor }); // keyset-paginated, newest first
101
+ ```
102
+
103
+ `partial_success` is derived from `itemsFailed > 0`; a skip reason is a summary; the prune never deletes a `running` row. Ship the table with `BACKGROUND_TASK_RUNS_SCHEMA` (idempotent DDL; `BACKGROUND_TASK_RUNS_MIGRATION` is the `{ name, sql }` form). A table that predates `application_id` applies `BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID` once.
104
+
105
+ ## 7. D1 Sessions bookmarks
106
+
107
+ Framework-free primitives for the `x-d1-bookmark` round-trip (`@rexezuge/http` owns the middleware form):
108
+
109
+ ```ts
110
+ import { openSession, readBookmark, withBookmark } from '@rexezuge/d1';
111
+
112
+ const session = openSession(env.DB, readBookmark(request)); // bookmark, else 'first-primary'
113
+ const response = await app.fetch(request, { ...env, DB: session }, ctx);
114
+ return withBookmark(response, session); // stamps the header + Access-Control-Expose-Headers; copies immutable responses
115
+ ```
116
+
117
+ ## Extending
118
+
119
+ | Owned by the kit | Yours |
120
+ | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
121
+ | Retry schedule, error normalisation, per-statement metering, identifier allow-listing | Your SQL in `BaseDAO` subclasses; the `billedRowsForTable` port |
122
+ | Cipher, IV policy, write-under-first-key, fail-closed decrypt (`EncryptedDAO`) | Where the keys come from (the constructor port), which columns hold envelopes |
123
+ | Run status derivation, `running`-row retention, keyset paging (`BackgroundTaskRunDAO`) | Ownership-scoped queries in a subclass (reuse `toRun` / `RUN_COLUMNS_SQL`); `Clock` / `IdGenerator` |
124
+ | Header name, constraint default, immutable-response handling (bookmarks) | Which requests get a session, and which binding |
125
+
126
+ See [`docs/design-charter.md`](../../docs/design-charter.md).
127
+
68
128
  ---
69
129
 
70
130
  ## Verifying this package
@@ -0,0 +1,86 @@
1
+ import type { Clock, IdGenerator, SubrequestMeter } from '@rexezuge/shared';
2
+ import { BaseDAO } from './BaseDAO.ts';
3
+ import type { BilledRowsForTable } from './BaseDAO.ts';
4
+ import type { D1Queryable } from './D1Types.ts';
5
+ import type { BackgroundTaskRun, BackgroundTaskRunList, BackgroundTaskRunRow, CompleteTaskRunInput, ListTaskRunsOptions, StartTaskRunInput } from './backgroundTaskRunsSchema.ts';
6
+ interface BackgroundTaskRunDAOOptions {
7
+ /**
8
+ Wall clock for `started_at` / `completed_at`. Default: the system clock.
9
+ */
10
+ clock?: Clock;
11
+ /**
12
+ Run-id source. Default: `crypto.randomUUID`.
13
+ */
14
+ ids?: IdGenerator;
15
+ /**
16
+ Forwarded to `BaseDAO`.
17
+ */
18
+ billedRowsForTable?: BilledRowsForTable;
19
+ }
20
+ /**
21
+ * Cron task-run history: the `background_task_runs` table.
22
+ *
23
+ * Implements `@rexezuge/runtime`'s `TaskRunRecorder` port **structurally**
24
+ * (`startRun` / `succeedRun` / `failRun` / `skipRun`) — `d1` does not depend on
25
+ * `runtime`, so the shape is matched rather than imported, and a composition
26
+ * root passes an instance straight to `AbstractScheduledTask.createRunRecorder`.
27
+ * It is also a runtime `PruningTarget` through {@link deleteOlderThan}.
28
+ *
29
+ * Converged from `packages/backend-data/src/dao/BackgroundTaskRunDAO.ts` in
30
+ * AWS-AccessBridge, Mail-Bee, Mail-Meow and Mail-Otter. Decisions taken once:
31
+ *
32
+ * - `partial_success` is derived (`itemsFailed > 0`), never chosen by a caller.
33
+ * - A skip reason is a **summary**, not an `error_message` (AWS wrote the
34
+ * latter, so a skipped tick read as an error on the task-runs screen).
35
+ * - The prune never deletes a `running` row: a run old *because it is stuck*
36
+ * is the row an operator needs to see.
37
+ * - Listing is keyset-paginated on `(started_at, run_id)`; an offset would
38
+ * skip a run whenever a concurrent prune deleted one.
39
+ * - `details` that fail to parse come back as the raw string, not an exception.
40
+ *
41
+ * ## Extending
42
+ *
43
+ * Ownership scoping (the Mail-* `listForUser` join through
44
+ * `connected_applications`) is the repo's domain: subclass and add the query,
45
+ * reusing {@link toRun} and {@link RUN_COLUMNS_SQL}.
46
+ */
47
+ declare class BackgroundTaskRunDAO extends BaseDAO {
48
+ /**
49
+ The column list every read selects, for a subclass query.
50
+ */
51
+ protected static readonly RUN_COLUMNS_SQL: string;
52
+ private readonly clock;
53
+ private readonly ids;
54
+ constructor(database: D1Queryable, meter?: SubrequestMeter, options?: BackgroundTaskRunDAOOptions);
55
+ startRun(input: StartTaskRunInput): Promise<string>;
56
+ succeedRun(runId: string, input: CompleteTaskRunInput): Promise<void>;
57
+ /**
58
+ * `errorMessage` reaches a user through the task-runs screen; the caller
59
+ * (`AbstractScheduledTask.describeFailure`) is where it is redacted.
60
+ */
61
+ failRun(runId: string, errorMessage: string, partial?: Partial<CompleteTaskRunInput>): Promise<void>;
62
+ skipRun(runId: string, reason?: string): Promise<void>;
63
+ getById(runId: string): Promise<BackgroundTaskRun | null>;
64
+ /**
65
+ * One page of runs, newest first. `limit` is clamped to 1–100 (default 25).
66
+ * A malformed cursor restarts from the first page rather than failing.
67
+ */
68
+ listRuns(options?: ListTaskRunsOptions): Promise<BackgroundTaskRunList>;
69
+ /**
70
+ * One bounded batch of finished runs started before `cutoff` (unix seconds,
71
+ * exclusive). `running` rows are kept — see the class note. This is the
72
+ * runtime `PruningTarget` port.
73
+ */
74
+ deleteOlderThan(cutoff: number, limit: number): Promise<number>;
75
+ /**
76
+ The external shape of one row.
77
+ */
78
+ protected static toRun(row: BackgroundTaskRunRow): BackgroundTaskRun;
79
+ private complete;
80
+ private nowSeconds;
81
+ private static parseDetails;
82
+ private static parseCursor;
83
+ }
84
+ export { BackgroundTaskRunDAO };
85
+ export type { BackgroundTaskRunDAOOptions };
86
+ //# sourceMappingURL=BackgroundTaskRunDAO.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BackgroundTaskRunDAO.d.ts","sourceRoot":"","sources":["../src/BackgroundTaskRunDAO.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAC5E,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,KAAK,EACV,iBAAiB,EACjB,qBAAqB,EACrB,oBAAoB,EAEpB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,+BAA+B,CAAC;AAKvC,UAAU,2BAA2B;IACnC;;MAEE;IACF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd;;MAEE;IACF,GAAG,CAAC,EAAE,WAAW,CAAC;IAClB;;MAEE;IACF,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,OAAO,CAAC,MAAM,CAAC,WAAW;CAK3B;AAED,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAChC,YAAY,EAAE,2BAA2B,EAAE,CAAC"}
@@ -0,0 +1,5 @@
1
+ var R=Object.defineProperty;var _=(y,t)=>R(y,"name",{value:t,configurable:!0});import{CryptoIdGenerator as S,CursorCodec as p,SYSTEM_CLOCK as I,UNMETERED_SUBREQUESTS as C}from"@rexezuge/shared";import{BaseDAO as T}from"./BaseDAO.js";import{BACKGROUND_TASK_RUNS_TABLE as r}from"./backgroundTaskRunsSchema.js";const h="run_id, task_type, application_id, status, items_processed, items_failed, summary, details, error_message, started_at, completed_at, created_at";class i extends T{static{_(this,"BackgroundTaskRunDAO")}static RUN_COLUMNS_SQL=h;clock;ids;constructor(t,s=C,e={}){super(t,s,{billedRowsForTable:e.billedRowsForTable}),this.clock=e.clock??I,this.ids=e.ids??new S}async startRun(t){const s=this.ids.randomUUID(),e=this.nowSeconds();return await this.run(`INSERT INTO ${r}
2
+ (run_id, task_type, application_id, status, items_processed, items_failed, started_at, created_at)
3
+ VALUES (?, ?, ?, 'running', 0, 0, ?, ?)`,[s,t.taskType,t.applicationId??null,e,e]),s}async succeedRun(t,s){const e=s.itemsFailed>0?"partial_success":"success";await this.complete(t,e,null,s)}async failRun(t,s,e){await this.complete(t,"error",s,e??{})}async skipRun(t,s){await this.run(`UPDATE ${r} SET status = 'skipped', summary = ?, completed_at = ? WHERE run_id = ?`,[s??null,this.nowSeconds(),t])}async getById(t){const s=await this.findRowById(r,t,{idColumn:"run_id"});return s?i.toRun(s):null}async listRuns(t={}){const s=Math.min(Math.max(Math.trunc(t.limit??25),1),100),e=[],a=[],E=[["task_type",t.taskType],["application_id",t.applicationId],["status",t.status]];for(const[c,m]of E)m!==void 0&&(e.push(`${c} = ?`),a.push(m));const n=i.parseCursor(t.cursor);n&&(e.push("(started_at < ? OR (started_at = ? AND run_id < ?))"),a.push(n.startedAt,n.startedAt,n.runId));const f=e.length>0?`WHERE ${e.join(" AND ")}`:"",l=await this.all(`SELECT ${h} FROM ${r} ${f} ORDER BY started_at DESC, run_id DESC LIMIT ?`,[...a,s+1]),u=l.slice(0,s),d=u.at(-1),o={runs:u.map(c=>i.toRun(c))};return l.length>s&&d&&(o.nextCursor=p.encode({startedAt:d.started_at,runId:d.run_id})),o}deleteOlderThan(t,s){return this.deleteRowsOlderThan(r,"started_at",t,s,{idColumn:"run_id",extraCondition:"status != 'running'"})}static toRun(t){return{runId:t.run_id,taskType:t.task_type,applicationId:t.application_id,status:t.status,itemsProcessed:t.items_processed,itemsFailed:t.items_failed,summary:t.summary,details:i.parseDetails(t.details),errorMessage:t.error_message,startedAt:t.started_at,completedAt:t.completed_at,createdAt:t.created_at}}async complete(t,s,e,a){await this.run(`UPDATE ${r}
4
+ SET status = ?, error_message = ?, items_processed = ?, items_failed = ?, summary = ?, details = ?, completed_at = ?
5
+ WHERE run_id = ?`,[s,e,a.itemsProcessed??0,a.itemsFailed??0,a.summary??null,a.details===void 0?null:JSON.stringify(a.details),this.nowSeconds(),t])}nowSeconds(){return Math.floor(this.clock.now()/1e3)}static parseDetails(t){if(t===null)return null;try{return JSON.parse(t)}catch{return t}}static parseCursor(t){const s=p.decode(t);return!s||typeof s.startedAt!="number"||typeof s.runId!="string"?null:{startedAt:s.startedAt,runId:s.runId}}}export{i as BackgroundTaskRunDAO};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/BackgroundTaskRunDAO.ts"],
4
+ "sourcesContent": ["import { CryptoIdGenerator, CursorCodec, SYSTEM_CLOCK, UNMETERED_SUBREQUESTS } from '@rexezuge/shared';\nimport type { Clock, IdGenerator, SubrequestMeter } from '@rexezuge/shared';\nimport { BaseDAO } from './BaseDAO.ts';\nimport type { BilledRowsForTable } from './BaseDAO.ts';\nimport type { D1Queryable } from './D1Types.ts';\nimport { BACKGROUND_TASK_RUNS_TABLE } from './backgroundTaskRunsSchema.ts';\nimport type {\n BackgroundTaskRun,\n BackgroundTaskRunList,\n BackgroundTaskRunRow,\n BackgroundTaskRunStatus,\n CompleteTaskRunInput,\n ListTaskRunsOptions,\n StartTaskRunInput,\n} from './backgroundTaskRunsSchema.ts';\n\nconst RUN_COLUMNS =\n 'run_id, task_type, application_id, status, items_processed, items_failed, summary, details, error_message, started_at, completed_at, created_at';\n\ninterface BackgroundTaskRunDAOOptions {\n /**\n Wall clock for `started_at` / `completed_at`. Default: the system clock.\n */\n clock?: Clock;\n /**\n Run-id source. Default: `crypto.randomUUID`.\n */\n ids?: IdGenerator;\n /**\n Forwarded to `BaseDAO`.\n */\n billedRowsForTable?: BilledRowsForTable;\n}\n\n/**\n * Cron task-run history: the `background_task_runs` table.\n *\n * Implements `@rexezuge/runtime`'s `TaskRunRecorder` port **structurally**\n * (`startRun` / `succeedRun` / `failRun` / `skipRun`) — `d1` does not depend on\n * `runtime`, so the shape is matched rather than imported, and a composition\n * root passes an instance straight to `AbstractScheduledTask.createRunRecorder`.\n * It is also a runtime `PruningTarget` through {@link deleteOlderThan}.\n *\n * Converged from `packages/backend-data/src/dao/BackgroundTaskRunDAO.ts` in\n * AWS-AccessBridge, Mail-Bee, Mail-Meow and Mail-Otter. Decisions taken once:\n *\n * - `partial_success` is derived (`itemsFailed > 0`), never chosen by a caller.\n * - A skip reason is a **summary**, not an `error_message` (AWS wrote the\n * latter, so a skipped tick read as an error on the task-runs screen).\n * - The prune never deletes a `running` row: a run old *because it is stuck*\n * is the row an operator needs to see.\n * - Listing is keyset-paginated on `(started_at, run_id)`; an offset would\n * skip a run whenever a concurrent prune deleted one.\n * - `details` that fail to parse come back as the raw string, not an exception.\n *\n * ## Extending\n *\n * Ownership scoping (the Mail-* `listForUser` join through\n * `connected_applications`) is the repo's domain: subclass and add the query,\n * reusing {@link toRun} and {@link RUN_COLUMNS_SQL}.\n */\nclass BackgroundTaskRunDAO extends BaseDAO {\n /**\n The column list every read selects, for a subclass query.\n */\n protected static readonly RUN_COLUMNS_SQL: string = RUN_COLUMNS;\n\n private readonly clock: Clock;\n private readonly ids: IdGenerator;\n\n public constructor(database: D1Queryable, meter: SubrequestMeter = UNMETERED_SUBREQUESTS, options: BackgroundTaskRunDAOOptions = {}) {\n super(database, meter, { billedRowsForTable: options.billedRowsForTable });\n this.clock = options.clock ?? SYSTEM_CLOCK;\n this.ids = options.ids ?? new CryptoIdGenerator();\n }\n\n public async startRun(input: StartTaskRunInput): Promise<string> {\n const runId = this.ids.randomUUID();\n const now = this.nowSeconds();\n await this.run(\n `INSERT INTO ${BACKGROUND_TASK_RUNS_TABLE}\n (run_id, task_type, application_id, status, items_processed, items_failed, started_at, created_at)\n VALUES (?, ?, ?, 'running', 0, 0, ?, ?)`,\n [runId, input.taskType, input.applicationId ?? null, now, now],\n );\n return runId;\n }\n\n public async succeedRun(runId: string, input: CompleteTaskRunInput): Promise<void> {\n const status: BackgroundTaskRunStatus = input.itemsFailed > 0 ? 'partial_success' : 'success';\n await this.complete(runId, status, null, input);\n }\n\n /**\n * `errorMessage` reaches a user through the task-runs screen; the caller\n * (`AbstractScheduledTask.describeFailure`) is where it is redacted.\n */\n public async failRun(runId: string, errorMessage: string, partial?: Partial<CompleteTaskRunInput>): Promise<void> {\n await this.complete(runId, 'error', errorMessage, partial ?? {});\n }\n\n public async skipRun(runId: string, reason?: string): Promise<void> {\n await this.run(`UPDATE ${BACKGROUND_TASK_RUNS_TABLE} SET status = 'skipped', summary = ?, completed_at = ? WHERE run_id = ?`, [\n reason ?? null,\n this.nowSeconds(),\n runId,\n ]);\n }\n\n public async getById(runId: string): Promise<BackgroundTaskRun | null> {\n const row = await this.findRowById<BackgroundTaskRunRow>(BACKGROUND_TASK_RUNS_TABLE, runId, { idColumn: 'run_id' });\n return row ? BackgroundTaskRunDAO.toRun(row) : null;\n }\n\n /**\n * One page of runs, newest first. `limit` is clamped to 1–100 (default 25).\n * A malformed cursor restarts from the first page rather than failing.\n */\n public async listRuns(options: ListTaskRunsOptions = {}): Promise<BackgroundTaskRunList> {\n const limit = Math.min(Math.max(Math.trunc(options.limit ?? 25), 1), 100);\n const conditions: string[] = [];\n const bindings: Array<string | number> = [];\n const filters: Array<[string, string | undefined]> = [\n ['task_type', options.taskType],\n ['application_id', options.applicationId],\n ['status', options.status],\n ];\n for (const [column, value] of filters) {\n if (value === undefined) continue;\n conditions.push(`${column} = ?`);\n bindings.push(value);\n }\n const cursor = BackgroundTaskRunDAO.parseCursor(options.cursor);\n if (cursor) {\n conditions.push('(started_at < ? OR (started_at = ? AND run_id < ?))');\n bindings.push(cursor.startedAt, cursor.startedAt, cursor.runId);\n }\n const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';\n const rows = await this.all<BackgroundTaskRunRow>(\n `SELECT ${RUN_COLUMNS} FROM ${BACKGROUND_TASK_RUNS_TABLE} ${where} ORDER BY started_at DESC, run_id DESC LIMIT ?`,\n [...bindings, limit + 1],\n );\n const page = rows.slice(0, limit);\n const last = page.at(-1);\n const list: BackgroundTaskRunList = { runs: page.map((row) => BackgroundTaskRunDAO.toRun(row)) };\n if (rows.length > limit && last) list.nextCursor = CursorCodec.encode({ startedAt: last.started_at, runId: last.run_id });\n return list;\n }\n\n /**\n * One bounded batch of finished runs started before `cutoff` (unix seconds,\n * exclusive). `running` rows are kept — see the class note. This is the\n * runtime `PruningTarget` port.\n */\n public deleteOlderThan(cutoff: number, limit: number): Promise<number> {\n return this.deleteRowsOlderThan(BACKGROUND_TASK_RUNS_TABLE, 'started_at', cutoff, limit, {\n idColumn: 'run_id',\n extraCondition: \"status != 'running'\",\n });\n }\n\n /**\n The external shape of one row.\n */\n protected static toRun(row: BackgroundTaskRunRow): BackgroundTaskRun {\n return {\n runId: row.run_id,\n taskType: row.task_type,\n applicationId: row.application_id,\n status: row.status,\n itemsProcessed: row.items_processed,\n itemsFailed: row.items_failed,\n summary: row.summary,\n details: BackgroundTaskRunDAO.parseDetails(row.details),\n errorMessage: row.error_message,\n startedAt: row.started_at,\n completedAt: row.completed_at,\n createdAt: row.created_at,\n };\n }\n\n private async complete(\n runId: string,\n status: BackgroundTaskRunStatus,\n errorMessage: string | null,\n input: Partial<CompleteTaskRunInput>,\n ): Promise<void> {\n await this.run(\n `UPDATE ${BACKGROUND_TASK_RUNS_TABLE}\n SET status = ?, error_message = ?, items_processed = ?, items_failed = ?, summary = ?, details = ?, completed_at = ?\n WHERE run_id = ?`,\n [\n status,\n errorMessage,\n input.itemsProcessed ?? 0,\n input.itemsFailed ?? 0,\n input.summary ?? null,\n input.details === undefined ? null : JSON.stringify(input.details),\n this.nowSeconds(),\n runId,\n ],\n );\n }\n\n private nowSeconds(): number {\n return Math.floor(this.clock.now() / 1000);\n }\n\n private static parseDetails(details: string | null): unknown {\n if (details === null) return null;\n try {\n return JSON.parse(details) as unknown;\n } catch {\n return details;\n }\n }\n\n private static parseCursor(cursor: string | undefined): { startedAt: number; runId: string } | null {\n const parsed = CursorCodec.decode<{ startedAt?: unknown; runId?: unknown }>(cursor);\n if (!parsed || typeof parsed.startedAt !== 'number' || typeof parsed.runId !== 'string') return null;\n return { startedAt: parsed.startedAt, runId: parsed.runId };\n }\n}\n\nexport { BackgroundTaskRunDAO };\nexport type { BackgroundTaskRunDAOOptions };\n"],
5
+ "mappings": "+EAAA,OAAS,qBAAAA,EAAmB,eAAAC,EAAa,gBAAAC,EAAc,yBAAAC,MAA6B,mBAEpF,OAAS,WAAAC,MAAe,eAGxB,OAAS,8BAAAC,MAAkC,gCAW3C,MAAMC,EACJ,kJA4CF,MAAMC,UAA6BH,CAAO,CA7D1C,MA6D0C,CAAAI,EAAA,6BAI9B,OAAgB,gBAA0BF,EAEnC,MACA,IAEjB,YAAmBG,EAAuBC,EAAyBP,EAAuBQ,EAAuC,CAAA,EAAE,CACjI,MAAMF,EAAUC,EAAO,CAAE,mBAAoBC,EAAQ,kBAAkB,CAAE,EACzE,KAAK,MAAQA,EAAQ,OAAST,EAC9B,KAAK,IAAMS,EAAQ,KAAO,IAAIX,CAChC,CAEO,MAAM,SAASY,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YAAU,CAChB,OAAO,KAAK,MAAM,KAAK,MAAM,IAAG,EAAK,GAAI,CAC3C,CAEQ,OAAO,aAAaoB,EAAsB,CAChD,GAAIA,IAAY,KAAM,OAAO,KAC7B,GAAI,CACF,OAAO,KAAK,MAAMA,CAAO,CAC3B,MAAQ,CACN,OAAOA,CACT,CACF,CAEQ,OAAO,YAAYP,EAA0B,CACnD,MAAMQ,EAASjC,EAAY,OAAiDyB,CAAM,EAClF,MAAI,CAACQ,GAAU,OAAOA,EAAO,WAAc,UAAY,OAAOA,EAAO,OAAU,SAAiB,KACzF,CAAE,UAAWA,EAAO,UAAW,MAAOA,EAAO,KAAK,CAC3D",
6
+ "names": ["CryptoIdGenerator", "CursorCodec", "SYSTEM_CLOCK", "UNMETERED_SUBREQUESTS", "BaseDAO", "BACKGROUND_TASK_RUNS_TABLE", "RUN_COLUMNS", "BackgroundTaskRunDAO", "__name", "database", "meter", "options", "input", "runId", "now", "status", "errorMessage", "partial", "reason", "row", "limit", "conditions", "bindings", "filters", "column", "value", "cursor", "where", "rows", "page", "last", "list", "cutoff", "details", "parsed"]
7
+ }
package/dist/BaseDAO.d.ts CHANGED
@@ -194,6 +194,24 @@ declare abstract class BaseDAO {
194
194
  * @param context Named in the refusal, because this reaches a client as a 413.
195
195
  */
196
196
  protected assertSubrequestBudget(statements: number, context?: string): void;
197
+ /**
198
+ * One row by its key, or `null`. The metered, retried form of the free
199
+ * `findRowById` the Mail-* repos kept; identifiers are allow-listed.
200
+ */
201
+ protected findRowById<T>(table: string, id: string | number, options?: {
202
+ idColumn?: string;
203
+ columns?: readonly string[];
204
+ }): Promise<T | null>;
205
+ /**
206
+ * Delete one bounded batch older than `cutoff` (exclusive); answers the count.
207
+ * The metered instance form of the static `deleteOlderThan`, and a runtime
208
+ * `PruningTarget` in one line. `extraCondition` is a trusted SQL fragment
209
+ * ANDed into the subquery (e.g. `status != 'running'`), never input.
210
+ */
211
+ protected deleteRowsOlderThan(table: string, timeColumn: string, cutoff: number | string, limit: number, options?: {
212
+ idColumn?: string;
213
+ extraCondition?: string;
214
+ }): Promise<number>;
197
215
  /**
198
216
  * Charge the meter and account a completed write against the schema's cost.
199
217
  */
@@ -210,24 +228,7 @@ declare abstract class BaseDAO {
210
228
  */
211
229
  protected static get retryDefaults(): typeof D1_RETRY_DEFAULTS;
212
230
  }
213
- /**
214
- * Allow-list one SQL identifier segment. Values never go through this — they
215
- * are always bound; this exists purely for the table/column names that
216
- * parameter binding cannot express.
217
- */
218
- declare function assertSqlIdentifier(value: string, label: string): void;
219
- /**
220
- * The write verb's table name, or `null` when the SQL does not name one.
221
- *
222
- * The verb is anchored at the **start** of the statement, after leading
223
- * whitespace and comments — a bare `/\bINSERT\s+INTO\s+(\w+)/` also matches a
224
- * verb quoted inside a string literal, and a table read out of a `SELECT`'s
225
- * projection is worse than no answer at all. An unreadable statement returns
226
- * `null` for the caller to charge the worst case against, rather than throwing:
227
- * accounting must not be the thing that turns a failed write into a crashed
228
- * request.
229
- */
230
- declare function statementTable(sql: string): string | null;
231
- export { BaseDAO, assertSqlIdentifier, statementTable };
231
+ export { BaseDAO };
232
232
  export type { BilledRowsForTable, TrackedStatement, WriteResult };
233
+ export { assertSqlIdentifier, statementTable } from './sqlStatement.ts';
233
234
  //# sourceMappingURL=BaseDAO.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDAO.d.ts","sourceRoot":"","sources":["../src/BaseDAO.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGxD,OAAO,EAAE,iBAAiB,EAAoB,MAAM,cAAc,CAAC;AACnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAU/E;;;;;;;;;GASG;AACH,UAAU,gBAAgB;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,mBAAmB,CAAC;IAC/B,IAAI,CAAC,GAAG,QAAQ,EAAE,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,EAAE,EAAE,MAAM,GAAG,MAAM,EACnB,OAAO,GAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;KAAO,GAC/D,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;IAUpB;;;;;OAKG;cACa,mBAAmB,CACjC,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GAAG,MAAM,EACvB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAA;KAAO,GAC3D,OAAO,CAAC,MAAM,CAAC;IAalB;;OAEG;IACH,OAAO,CAAC,YAAY;IAOpB;;;;;OAKG;qBACoB,eAAe,CACpC,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GAAG,MAAM,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC;IAsBlB;;MAEE;IACF,SAAS,CAAC,MAAM,KAAK,aAAa,IAAI,OAAO,iBAAiB,CAE7D;CACF;AAED,OAAO,EAAE,OAAO,EAAE,CAAC;AACnB,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,WAAW,EAAE,CAAC;AAElE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC"}
package/dist/BaseDAO.js CHANGED
@@ -1,7 +1,6 @@
1
- var b=Object.defineProperty;var i=(s,e)=>b(s,"name",{value:e,configurable:!0});import{UNMETERED_SUBREQUESTS as p}from"@rexezuge/shared";import{SubrequestBudgetExhaustedError as E}from"@rexezuge/errors";import{DatabaseError as g}from"@rexezuge/errors";import{D1_RETRY_DEFAULTS as R,executeWithRetry as c}from"./D1Retry.js";class T{static{i(this,"BaseDAO")}database;meter;options;constructor(e,t=p,r={}){this.database=e,this.meter=t,this.options=r}get subrequests(){return this.meter}statement(e,t=[]){return t.length>0?this.database.prepare(e).bind(...t):this.database.prepare(e)}tracked(e,t=[]){const r=i(n=>({sql:e,statement:n,bind:i((...o)=>r(n.bind(...o)),"bind")}),"make");return r(this.statement(e,t))}async run(e,t=[]){return this.meter.charge(1,"d1"),c(()=>this.statement(e,t).run(),"run statement")}async first(e,t=[]){return this.meter.charge(1,"d1"),(await c(async()=>({success:!0,value:await this.statement(e,t).first()}),"read a row")).value}async all(e,t=[]){return this.meter.charge(1,"d1"),(await c(async()=>({success:!0,value:(await this.statement(e,t).all()).results??[]}),"read rows")).value}async count(e,t=[]){return(await this.first(e,t))?.count??0}async batch(e){if(e.length===0)return[];if(this.meter.charge(1,"d1"),this.database.batch===void 0)throw new g("The D1 binding exposes no batch() \u2014 a multi-statement transaction is not available here");return(await c(async()=>{const r=await this.database.batch(e),n=r.find(o=>!o.success);return{success:n===void 0,error:n?.error,value:r}},"run a batch")).value}async runTracked(e){const t=await c(()=>e.statement.run(),"run a write");return this.accountWrite(e.sql,t)}async runTrackedBatch(e){const t=await this.batch(e.map(a=>a.statement));let r=0,n=this.options.billedRowsForTable!==void 0;for(const[a,u]of t.entries()){const d=e[a];if(!d){n=!1;break}const f=this.accountWrite(d.sql,u);if(f.billedRows===null){n=!1;break}r+=f.billedRows}return{changes:t.reduce((a,u)=>a+m(u),0),billedRows:n?r:null}}fitToSubrequestBudget(e){const t=this.meter.remaining;return Number.isFinite(t)?Math.max(0,Math.min(e,Math.floor(t))):Math.max(0,e)}assertSubrequestBudget(e,t="this request"){if(!this.meter.canAfford(e))throw new E(`${t} needs ${e} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`)}accountWrite(e,t){const r=m(t),n=this.options.billedRowsForTable;return n?{changes:r,billedRows:n(w(e)??"",r)}:{changes:r,billedRows:null}}static async deleteOlderThan(e,t,r,n,o,a){return l(t,"table"),l(r,"timeColumn"),l(a,"idColumn"),(await c(()=>e.prepare(`DELETE FROM ${t}
2
- WHERE ${a} IN (
3
- SELECT ${a} FROM ${t}
1
+ var f=Object.defineProperty;var l=(h,e)=>f(h,"name",{value:e,configurable:!0});import{UNMETERED_SUBREQUESTS as w}from"@rexezuge/shared";import{SubrequestBudgetExhaustedError as b}from"@rexezuge/errors";import{DatabaseError as E}from"@rexezuge/errors";import{D1_RETRY_DEFAULTS as R,executeWithRetry as u}from"./D1Retry.js";import{assertSqlIdentifier as i,changesOf as d,statementTable as p}from"./sqlStatement.js";class T{static{l(this,"BaseDAO")}database;meter;options;constructor(e,t=w,r={}){this.database=e,this.meter=t,this.options=r}get subrequests(){return this.meter}statement(e,t=[]){return t.length>0?this.database.prepare(e).bind(...t):this.database.prepare(e)}tracked(e,t=[]){const r=l(n=>({sql:e,statement:n,bind:l((...a)=>r(n.bind(...a)),"bind")}),"make");return r(this.statement(e,t))}async run(e,t=[]){return this.meter.charge(1,"d1"),u(()=>this.statement(e,t).run(),"run statement")}async first(e,t=[]){return this.meter.charge(1,"d1"),(await u(async()=>({success:!0,value:await this.statement(e,t).first()}),"read a row")).value}async all(e,t=[]){return this.meter.charge(1,"d1"),(await u(async()=>({success:!0,value:(await this.statement(e,t).all()).results??[]}),"read rows")).value}async count(e,t=[]){return(await this.first(e,t))?.count??0}async batch(e){if(e.length===0)return[];if(this.meter.charge(1,"d1"),this.database.batch===void 0)throw new E("The D1 binding exposes no batch() \u2014 a multi-statement transaction is not available here");return(await u(async()=>{const r=await this.database.batch(e),n=r.find(a=>!a.success);return{success:n===void 0,error:n?.error,value:r}},"run a batch")).value}async runTracked(e){const t=await u(()=>e.statement.run(),"run a write");return this.accountWrite(e.sql,t)}async runTrackedBatch(e){const t=await this.batch(e.map(s=>s.statement));let r=0,n=this.options.billedRowsForTable!==void 0;for(const[s,o]of t.entries()){const c=e[s];if(!c){n=!1;break}const m=this.accountWrite(c.sql,o);if(m.billedRows===null){n=!1;break}r+=m.billedRows}return{changes:t.reduce((s,o)=>s+d(o),0),billedRows:n?r:null}}fitToSubrequestBudget(e){const t=this.meter.remaining;return Number.isFinite(t)?Math.max(0,Math.min(e,Math.floor(t))):Math.max(0,e)}assertSubrequestBudget(e,t="this request"){if(!this.meter.canAfford(e))throw new b(`${t} needs ${e} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`)}async findRowById(e,t,r={}){const n=r.idColumn??"id";i(e,"table"),i(n,"idColumn");const a=r.columns??[];for(const o of a)i(o,"column");const s=a.length>0?a.join(", "):"*";return this.first(`SELECT ${s} FROM ${e} WHERE ${n} = ? LIMIT 1`,[t])}async deleteRowsOlderThan(e,t,r,n,a={}){const s=a.idColumn??"id";i(e,"table"),i(t,"timeColumn"),i(s,"idColumn");const o=a.extraCondition===void 0?"":` AND (${a.extraCondition})`,c=await this.run(`DELETE FROM ${e} WHERE ${s} IN (SELECT ${s} FROM ${e} WHERE ${t} < ?${o} ORDER BY ${t} LIMIT ?)`,[r,n]);return d(c)}accountWrite(e,t){const r=d(t),n=this.options.billedRowsForTable;return n?{changes:r,billedRows:n(p(e)??"",r)}:{changes:r,billedRows:null}}static async deleteOlderThan(e,t,r,n,a,s){return i(t,"table"),i(r,"timeColumn"),i(s,"idColumn"),(await u(()=>e.prepare(`DELETE FROM ${t}
2
+ WHERE ${s} IN (
3
+ SELECT ${s} FROM ${t}
4
4
  WHERE ${r} < ?
5
5
  LIMIT ?
6
- )`).bind(n,o).run(),`delete old rows from ${t}`)).meta?.changes??0}static get retryDefaults(){return R}}function l(s,e){if(!/^[A-Z_]\w*$/i.test(s))throw new Error(`Unsafe SQL identifier for ${e}: ${JSON.stringify(s)}`)}i(l,"assertSqlIdentifier");function m(s){return s.meta?.changes??0}i(m,"changesOf");function w(s){if(typeof s!="string")return null;let e=s.replace(/^\s+/,"");for(;e.startsWith("--");){const r=e.indexOf(`
7
- `);if(r===-1)return null;e=e.slice(r+1).replace(/^\s+/,"")}const t=/^(?:INSERT|REPLACE|UPDATE|DELETE)\b/i.exec(e);return t?(e=h(e.slice(t[0].length)),e=h(e,/^(?:OR\s+[A-Z_]+\s+)?/i),e=h(e,/^(?:INTO\s+|FROM\s+)?/i),/^["`[]?([A-Z_]\w*)/i.exec(e)?.[1]??null):null}i(w,"statementTable");function h(s,e){const t=e?.exec(s)?.[0]??"";return s.slice(t.length).replace(/^\s+/,"")}i(h,"consume");export{T as BaseDAO,l as assertSqlIdentifier,w as statementTable};
6
+ )`).bind(n,a).run(),`delete old rows from ${t}`)).meta?.changes??0}static get retryDefaults(){return R}}import{assertSqlIdentifier as I,statementTable as O}from"./sqlStatement.js";export{T as BaseDAO,I as assertSqlIdentifier,O as statementTable};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/BaseDAO.ts"],
4
- "sourcesContent": ["import { UNMETERED_SUBREQUESTS } from '@rexezuge/shared';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { SubrequestBudgetExhaustedError } from '@rexezuge/errors';\nimport { DatabaseError } from '@rexezuge/errors';\nimport { D1_RETRY_DEFAULTS, executeWithRetry } from './D1Retry.ts';\nimport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\n\n/**\n * A statement result plus the payload it produced, so the retry engine (which\n * inspects `success`) also handles wrapped results like batch arrays.\n */\ninterface StatementEnvelope<T> extends D1Result {\n value: T;\n}\n\n/**\n * A prepared statement with the SQL that produced it.\n *\n * The platform's `D1PreparedStatement` carries no `sql` member, so a layer that\n * needs to know *what* it is about to run — to account for a write, to assert a\n * table's billing multiplier, to log a rejected statement in terms a reader can\n * act on — has nowhere to read it from. Carrying it beside the statement is\n * that place, and `bind()` returns a new pair for the same reason the platform's\n * does: bindings are immutable on a prepared statement.\n */\ninterface TrackedStatement {\n sql: string;\n statement: D1PreparedStatement;\n bind(...bindings: unknown[]): TrackedStatement;\n}\n\n/**\n * How many rows a write to `table` costs.\n *\n * A **port, not an implementation**, because the answer is a property of the\n * schema rather than of this layer: D1 bills a write as the table row *plus\n * every index entry it rewrote*, so the multiplier belongs to whoever owns the\n * migrations. This package owns the accounting *shape* — carrying the figure\n * beside `changes` on every write result — and the consumer supplies the table.\n *\n * Returning `null` means \"I do not know this table\", which is a different answer\n * from \"this costs one row\" and must not collapse into it: an unknown table\n * errs toward the worst case, because an under-count costs the outage.\n */\ntype BilledRowsForTable = (table: string, logicalRows: number) => number | null;\n\n/**\n * What a write cost, and what it changed.\n *\n * `changes` is progress — how many table rows the statement touched — and\n * `billedRows` is cost. They are not the same number and neither replaces the\n * other: `changes` is what a convergence test measures, `billedRows` is what a\n * daily-allowance budget must be spent against. A caller that reads only\n * `changes` believes it has roughly an order of magnitude more headroom than it\n * does on an indexed table.\n *\n * `billedRows` is `null` — absent, not zero — when no {@link BilledRowsForTable}\n * port is configured, so the type forces the caller to notice that nothing is\n * being accounted rather than reporting a confident `0`.\n */\ninterface WriteResult {\n changes: number;\n billedRows: number | null;\n}\n\n/**\n * Canonical DAO base: retry is a policy, methods are a promise.\n *\n * Converged from the nine consumer repos' BaseDAOs. The API is the **sql-first**\n * shape CalDAV-Bridge and ChordDHT-Tracker used, not the closure-first shape\n * Durable-DAV's family used: a DAO states its SQL and bindings directly, and\n * the retry/normalization wrapper is invisible at the call site. The closure\n * form made every read site pay for a wrapper 90% of them never needed, and\n * each of the two shapes drifted its own method names (`withRetry` vs\n * `run(sql, bindings)`); the sql-first form is what survived.\n *\n * ### Every statement is charged\n *\n * D1 counts its own queries against the Workers per-invocation subrequest\n * ceiling, so a statement that spends one without telling anybody makes every\n * number that budgets work wrong — and it has **no symptom** until the platform\n * terminates the invocation, by which point the rows were right and the suite\n * was green. The meter is therefore a constructor dependency rather than a\n * module singleton, and the charge happens here because this is the one path\n * every statement takes; a charge at each call site is a hundred chances to\n * forget one.\n *\n * The charge is **per logical statement, not per attempt**: a retried statement\n * is one statement that the platform refused once and then answered. Charging\n * per attempt would make the ceiling track the fault rate instead of the work.\n *\n * Non-DAO concerns stay out: cursor pagination lives in `@rexezuge/shared`\n * (`CursorCodec`). Retry policy lives in `D1Retry` — one schedule, one\n * classifier, one place the `Failed to <context>` prefix is added.\n */\nabstract class BaseDAO {\n /**\n * Public, and deliberately so.\n *\n * A composition root instantiates concrete DAOs directly — that is the whole\n * point of a DI container, which binds `() => new UserDAO(db)` rather than\n * handing the container a factory that hides the construction. A `protected`\n * constructor blocks that and buys nothing: the class is `abstract`, so nobody\n * can instantiate `BaseDAO` itself regardless, and the access modifier\n * prevented exactly zero illegal constructions while forcing every concrete\n * DAO to redeclare a pass-through constructor that added no invariant.\n *\n * It was `protected` to keep `database` from being reached as\n * `BaseDAO.database` — but every field below carries its own `protected`, so\n * the field's own modifier is what enforces that, and making the constructor\n * public does not weaken it.\n *\n * @param database The binding.\n * @param meter The invocation's subrequest counter, or an unmetered default.\n * @param options `billedRowsForTable` supplies the schema's write cost.\n */\n constructor(\n protected readonly database: D1Queryable,\n protected readonly meter: SubrequestMeter = UNMETERED_SUBREQUESTS,\n private readonly options: { billedRowsForTable?: BilledRowsForTable } = {},\n ) {}\n\n /**\n * The invocation's meter, for a DAO that constructs another DAO.\n *\n * A `protected get` rather than a public field, because handing the meter out\n * is how a DAO builds a collaborator correctly: `new SongIdLookupDAO(this.database)`\n * drops it, and the charge that goes missing has no symptom.\n */\n protected get subrequests(): SubrequestMeter {\n return this.meter;\n }\n\n /**\n A prepared statement with its bindings applied. Bindings are always parameters, never interpolation.\n */\n protected statement(sql: string, bindings: unknown[] = []): D1PreparedStatement {\n return bindings.length > 0 ? this.database.prepare(sql).bind(...bindings) : this.database.prepare(sql);\n }\n\n /**\n * The same statement, carrying the SQL beside it.\n *\n * Use this wherever the SQL matters downstream — a write whose cost is\n * accounted, a statement named in an error — and {@link statement} for reads,\n * where nothing reads the SQL back and the pair is one allocation of waste.\n */\n protected tracked(sql: string, bindings: unknown[] = []): TrackedStatement {\n const make = (prepared: D1PreparedStatement): TrackedStatement => ({\n sql,\n statement: prepared,\n bind: (...next: unknown[]): TrackedStatement => make(prepared.bind(...next)),\n });\n return make(this.statement(sql, bindings));\n }\n\n /**\n * Run a statement. D1 reports a constraint violation or a missing table by\n * returning `success: false` rather than by throwing, so both forms are\n * normalized to a `DatabaseError` here — ignoring the result form is what\n * let a `UNIQUE` failure reach a caller as an opaque 500.\n */\n protected async run(sql: string, bindings: unknown[] = []): Promise<D1Result> {\n this.meter.charge(1, 'd1');\n return executeWithRetry((): Promise<D1Result> => this.statement(sql, bindings).run(), 'run statement');\n }\n\n /**\n Read one row. A `null` result is \"no row\", a success, not an error; only a\n rejected statement is retried and normalized.\n\n `null` rather than `undefined` because that is what the platform says\n (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back\n what it was given. It also makes this layer agree with `KvCache`, which has\n always returned `null` for a miss, so one convention covers both.\n */\n protected async first<T>(sql: string, bindings: unknown[] = []): Promise<T | null> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T | null>> => {\n const row: T | null = await this.statement(sql, bindings).first<T>();\n return { success: true, value: row };\n }, 'read a row');\n return envelope.value;\n }\n\n /**\n A list read. `.all()` returning `[]` is a success like `first()`'s null.\n */\n protected async all<T>(sql: string, bindings: unknown[] = []): Promise<T[]> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T[]>> => {\n const rows = await this.statement(sql, bindings).all<T>();\n return { success: true, value: rows.results ?? [] };\n }, 'read rows');\n return envelope.value;\n }\n\n /**\n A scalar count from a `SELECT count(*)` row; 0 when absent.\n */\n protected async count(sql: string, bindings: unknown[] = []): Promise<number> {\n const row = await this.first<{ count: number }>(sql, bindings);\n return row?.count ?? 0;\n }\n\n /**\n * A batch of prepared statements — one transaction and one subrequest,\n * however many statements it carries. Each result is checked, so a single\n * failure inside the batch raises rather than passing silently.\n */\n protected async batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {\n if (statements.length === 0) return [];\n this.meter.charge(1, 'd1');\n if (this.database.batch === undefined) {\n throw new DatabaseError('The D1 binding exposes no batch() — a multi-statement transaction is not available here');\n }\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<D1Result[]>> => {\n const results: D1Result[] = await (this.database.batch as NonNullable<D1Queryable['batch']>)(statements);\n const failed: D1Result | undefined = results.find((result): boolean => !result.success);\n return { success: failed === undefined, error: failed?.error, value: results };\n }, 'run a batch');\n return envelope.value;\n }\n\n /**\n * Run one write and report what it cost.\n *\n * Takes a {@link TrackedStatement} rather than SQL because the cost is read off\n * the table the SQL names, and the SQL is only available if it was carried.\n * `billedRows` is `null` when no port is configured.\n */\n protected async runTracked(tracked: TrackedStatement): Promise<WriteResult> {\n const result = await executeWithRetry((): Promise<D1Result> => tracked.statement.run(), 'run a write');\n return this.accountWrite(tracked.sql, result);\n }\n\n /**\n * Run a batch of writes and report what the whole batch cost.\n *\n * Billed rows are **summed across the batch**, and an unaccountable statement\n * poisons the total to `null` rather than being skipped: a partial figure next\n * to a real one is the one that reads as complete.\n */\n protected async runTrackedBatch(tracked: readonly TrackedStatement[]): Promise<WriteResult> {\n const results = await this.batch(tracked.map((entry) => entry.statement));\n let billedRows = 0;\n let accounted = this.options.billedRowsForTable !== undefined;\n for (const [index, result] of results.entries()) {\n const entry = tracked[index];\n if (!entry) {\n accounted = false;\n break;\n }\n const one = this.accountWrite(entry.sql, result);\n if (one.billedRows === null) {\n accounted = false;\n break;\n }\n billedRows += one.billedRows;\n }\n const changes = results.reduce((total, result) => total + changesOf(result), 0);\n return { changes, billedRows: accounted ? billedRows : null };\n }\n\n /**\n * The writes these statements fit into the invocation's remaining budget.\n *\n * \"How many may I issue\", as distinct from {@link assertSubrequestBudget}'s\n * \"may I issue all of these\" — a caller truncating a work list needs the\n * number, and a caller that must not truncate needs the refusal. An unmetered\n * counter answers `Infinity`, so a deployment that does not meter is never\n * clamped by a budget it does not have.\n */\n protected fitToSubrequestBudget(requested: number): number {\n const remaining = this.meter.remaining;\n return Number.isFinite(remaining) ? Math.max(0, Math.min(requested, Math.floor(remaining))) : Math.max(0, requested);\n }\n\n /**\n * Refuse a set of statements the invocation's remaining budget cannot carry.\n *\n * For a write with no partial form — a play queue, a playlist's count, a\n * backfill — because half a queue is a _shorter_ queue, which is a wrong\n * answer rather than an unfinished one. A caller that may truncate uses\n * {@link fitToSubrequestBudget} instead and reports that it did.\n *\n * @param statements How many statements the work needs.\n * @param context Named in the refusal, because this reaches a client as a 413.\n */\n protected assertSubrequestBudget(statements: number, context = 'this request'): void {\n if (this.meter.canAfford(statements)) return;\n throw new SubrequestBudgetExhaustedError(\n `${context} needs ${statements} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`,\n );\n }\n\n /**\n * Charge the meter and account a completed write against the schema's cost.\n */\n private accountWrite(sql: string, result: D1Result): WriteResult {\n const changes = changesOf(result);\n const port = this.options.billedRowsForTable;\n if (!port) return { changes, billedRows: null };\n return { changes, billedRows: port(statementTable(sql) ?? '', changes) };\n }\n\n /**\n * Generic batched delete of rows older than a cutoff, in ID order, with\n * retry. Mirrors the per-DAO `DELETE ... WHERE id IN (SELECT ... LIMIT ?)`\n * pattern that every repo re-implemented per table. The cutoff is exclusive:\n * a delete never touches a row at exactly the boundary timestamp.\n */\n protected static async deleteOlderThan(\n db: D1Queryable,\n table: string,\n timeColumn: string,\n cutoff: number | string,\n limit: number,\n idColumn: string,\n ): Promise<number> {\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(timeColumn, 'timeColumn');\n assertSqlIdentifier(idColumn, 'idColumn');\n const result: D1Result = await executeWithRetry(\n (): Promise<D1Result> =>\n db\n .prepare(\n `DELETE FROM ${table}\n WHERE ${idColumn} IN (\n SELECT ${idColumn} FROM ${table}\n WHERE ${timeColumn} < ?\n LIMIT ?\n )`,\n )\n .bind(cutoff, limit)\n .run(),\n `delete old rows from ${table}`,\n );\n return (result.meta as { changes?: number })?.changes ?? 0;\n }\n\n /**\n The retry schedule, for callers that surface it (health checks, tests).\n */\n protected static get retryDefaults(): typeof D1_RETRY_DEFAULTS {\n return D1_RETRY_DEFAULTS;\n }\n}\n\n/**\n * Allow-list one SQL identifier segment. Values never go through this — they\n * are always bound; this exists purely for the table/column names that\n * parameter binding cannot express.\n */\nfunction assertSqlIdentifier(value: string, label: string): void {\n if (!/^[A-Z_]\\w*$/i.test(value)) {\n throw new Error(`Unsafe SQL identifier for ${label}: ${JSON.stringify(value)}`);\n }\n}\n\nfunction changesOf(result: D1Result): number {\n return (result.meta as { changes?: number })?.changes ?? 0;\n}\n\n/**\n * The write verb's table name, or `null` when the SQL does not name one.\n *\n * The verb is anchored at the **start** of the statement, after leading\n * whitespace and comments — a bare `/\\bINSERT\\s+INTO\\s+(\\w+)/` also matches a\n * verb quoted inside a string literal, and a table read out of a `SELECT`'s\n * projection is worse than no answer at all. An unreadable statement returns\n * `null` for the caller to charge the worst case against, rather than throwing:\n * accounting must not be the thing that turns a failed write into a crashed\n * request.\n */\nfunction statementTable(sql: string): string | null {\n if (typeof sql !== 'string') return null;\n let rest = sql.replace(/^\\s+/, '');\n // A `while` rather than a repeated strip: comments are the only noise, and a\n // bounded loop cannot be made quadratic by a statement full of them.\n while (rest.startsWith('--')) {\n const newline = rest.indexOf('\\n');\n if (newline === -1) return null;\n rest = rest.slice(newline + 1).replace(/^\\s+/, '');\n }\n const verb = /^(?:INSERT|REPLACE|UPDATE|DELETE)\\b/i.exec(rest);\n if (!verb) return null;\n rest = consume(rest.slice(verb[0].length));\n\n // `INSERT OR REPLACE`, `UPDATE OR IGNORE` — a conflict clause between the verb and\n // the table. This is why the parse is stepwise rather than one anchored pattern:\n // a single pattern either grows a nested quantifier the complexity gate rejects,\n // or drops the clause and reads `REPLACE` as a table name.\n rest = consume(rest, /^(?:OR\\s+[A-Z_]+\\s+)?/i);\n rest = consume(rest, /^(?:INTO\\s+|FROM\\s+)?/i);\n return /^[\"`[]?([A-Z_]\\w*)/i.exec(rest)?.[1] ?? null;\n}\n\n/**\n * Drop a leading match and the whitespace after it.\n */\nfunction consume(sql: string, pattern?: RegExp): string {\n const matched = pattern?.exec(sql)?.[0] ?? '';\n return sql.slice(matched.length).replace(/^\\s+/, '');\n}\n\nexport { BaseDAO, assertSqlIdentifier, statementTable };\nexport type { BilledRowsForTable, TrackedStatement, WriteResult };\n"],
5
- "mappings": "+EAAA,OAAS,yBAAAA,MAA6B,mBAEtC,OAAS,kCAAAC,MAAsC,mBAC/C,OAAS,iBAAAC,MAAqB,mBAC9B,OAAS,qBAAAC,EAAmB,oBAAAC,MAAwB,eA2FpD,MAAeC,CAAO,CA/FtB,MA+FsB,CAAAC,EAAA,gBAsBC,SACA,MACF,QAHnB,YACqBC,EACAC,EAAyBR,EAC3BS,EAAuD,CAAA,EAAE,CAFvD,KAAA,SAAAF,EACA,KAAA,MAAAC,EACF,KAAA,QAAAC,CAChB,CASH,IAAc,aAAW,CACvB,OAAO,KAAK,KACd,CAKU,UAAUC,EAAaC,EAAsB,CAAA,EAAE,CACvD,OAAOA,EAAS,OAAS,EAAI,KAAK,SAAS,QAAQD,CAAG,EAAE,KAAK,GAAGC,CAAQ,EAAI,KAAK,SAAS,QAAQD,CAAG,CACvG,CASU,QAAQA,EAAaC,EAAsB,CAAA,EAAE,CACrD,MAAMC,EAAON,EAACO,IAAqD,CACjE,IAAAH,EACA,UAAWG,EACX,KAAMP,EAAA,IAAIQ,IAAsCF,EAAKC,EAAS,KAAK,GAAGC,CAAI,CAAC,EAArE,UAHK,QAKb,OAAOF,EAAK,KAAK,UAAUF,EAAKC,CAAQ,CAAC,CAC3C,CAQU,MAAM,IAAID,EAAaC,EAAsB,CAAA,EAAE,CACvD,YAAK,MAAM,OAAO,EAAG,IAAI,EAClBP,EAAiB,IAAyB,KAAK,UAAUM,EAAKC,CAAQ,EAAE,IAAG,EAAI,eAAe,CACvG,CAWU,MAAM,MAASD,EAAaC,EAAsB,CAAA,EAAE,CAC5D,YAAK,MAAM,OAAO,EAAG,IAAI,GACR,MAAMP,EAAiB,UAE/B,CAAE,QAAS,GAAM,MADF,MAAM,KAAK,UAAUM,EAAK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C3D,CAKU,WAAW,eAAa,CAChC,OAAO/B,CACT,EAQF,SAASoC,EAAoBC,EAAeC,EAAa,CACvD,GAAI,CAAC,eAAe,KAAKD,CAAK,EAC5B,MAAM,IAAI,MAAM,6BAA6BC,CAAK,KAAK,KAAK,UAAUD,CAAK,CAAC,EAAE,CAElF,CAJSlC,EAAAiC,EAAA,uBAMT,SAASb,EAAUR,EAAgB,CACjC,OAAQA,EAAO,MAA+B,SAAW,CAC3D,CAFSZ,EAAAoB,EAAA,aAeT,SAASM,EAAetB,EAAW,CACjC,GAAI,OAAOA,GAAQ,SAAU,OAAO,KACpC,IAAIgC,EAAOhC,EAAI,QAAQ,OAAQ,EAAE,EAGjC,KAAOgC,EAAK,WAAW,IAAI,GAAG,CAC5B,MAAMC,EAAUD,EAAK,QAAQ;CAAI,EACjC,GAAIC,IAAY,GAAI,OAAO,KAC3BD,EAAOA,EAAK,MAAMC,EAAU,CAAC,EAAE,QAAQ,OAAQ,EAAE,CACnD,CACA,MAAMC,EAAO,uCAAuC,KAAKF,CAAI,EAC7D,OAAKE,GACLF,EAAOG,EAAQH,EAAK,MAAME,EAAK,CAAC,EAAE,MAAM,CAAC,EAMzCF,EAAOG,EAAQH,EAAM,wBAAwB,EAC7CA,EAAOG,EAAQH,EAAM,wBAAwB,EACtC,sBAAsB,KAAKA,CAAI,IAAI,CAAC,GAAK,MAT9B,IAUpB,CArBSpC,EAAA0B,EAAA,kBA0BT,SAASa,EAAQnC,EAAaoC,EAAgB,CAC5C,MAAMC,EAAUD,GAAS,KAAKpC,CAAG,IAAI,CAAC,GAAK,GAC3C,OAAOA,EAAI,MAAMqC,EAAQ,MAAM,EAAE,QAAQ,OAAQ,EAAE,CACrD,CAHSzC,EAAAuC,EAAA",
6
- "names": ["UNMETERED_SUBREQUESTS", "SubrequestBudgetExhaustedError", "DatabaseError", "D1_RETRY_DEFAULTS", "executeWithRetry", "BaseDAO", "__name", "database", "meter", "options", "sql", "bindings", "make", "prepared", "next", "statements", "results", "failed", "result", "tracked", "entry", "billedRows", "accounted", "index", "one", "total", "changesOf", "requested", "remaining", "context", "changes", "port", "statementTable", "db", "table", "timeColumn", "cutoff", "limit", "idColumn", "assertSqlIdentifier", "value", "label", "rest", "newline", "verb", "consume", "pattern", "matched"]
4
+ "sourcesContent": ["import { UNMETERED_SUBREQUESTS } from '@rexezuge/shared';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { SubrequestBudgetExhaustedError } from '@rexezuge/errors';\nimport { DatabaseError } from '@rexezuge/errors';\nimport { D1_RETRY_DEFAULTS, executeWithRetry } from './D1Retry.ts';\nimport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\nimport { assertSqlIdentifier, changesOf, statementTable } from './sqlStatement.ts';\n\n/**\n * A statement result plus the payload it produced, so the retry engine (which\n * inspects `success`) also handles wrapped results like batch arrays.\n */\ninterface StatementEnvelope<T> extends D1Result {\n value: T;\n}\n\n/**\n * A prepared statement with the SQL that produced it.\n *\n * The platform's `D1PreparedStatement` carries no `sql` member, so a layer that\n * needs to know *what* it is about to run — to account for a write, to assert a\n * table's billing multiplier, to log a rejected statement in terms a reader can\n * act on — has nowhere to read it from. Carrying it beside the statement is\n * that place, and `bind()` returns a new pair for the same reason the platform's\n * does: bindings are immutable on a prepared statement.\n */\ninterface TrackedStatement {\n sql: string;\n statement: D1PreparedStatement;\n bind(...bindings: unknown[]): TrackedStatement;\n}\n\n/**\n * How many rows a write to `table` costs.\n *\n * A **port, not an implementation**, because the answer is a property of the\n * schema rather than of this layer: D1 bills a write as the table row *plus\n * every index entry it rewrote*, so the multiplier belongs to whoever owns the\n * migrations. This package owns the accounting *shape* — carrying the figure\n * beside `changes` on every write result — and the consumer supplies the table.\n *\n * Returning `null` means \"I do not know this table\", which is a different answer\n * from \"this costs one row\" and must not collapse into it: an unknown table\n * errs toward the worst case, because an under-count costs the outage.\n */\ntype BilledRowsForTable = (table: string, logicalRows: number) => number | null;\n\n/**\n * What a write cost, and what it changed.\n *\n * `changes` is progress — how many table rows the statement touched — and\n * `billedRows` is cost. They are not the same number and neither replaces the\n * other: `changes` is what a convergence test measures, `billedRows` is what a\n * daily-allowance budget must be spent against. A caller that reads only\n * `changes` believes it has roughly an order of magnitude more headroom than it\n * does on an indexed table.\n *\n * `billedRows` is `null` — absent, not zero — when no {@link BilledRowsForTable}\n * port is configured, so the type forces the caller to notice that nothing is\n * being accounted rather than reporting a confident `0`.\n */\ninterface WriteResult {\n changes: number;\n billedRows: number | null;\n}\n\n/**\n * Canonical DAO base: retry is a policy, methods are a promise.\n *\n * Converged from the nine consumer repos' BaseDAOs. The API is the **sql-first**\n * shape CalDAV-Bridge and ChordDHT-Tracker used, not the closure-first shape\n * Durable-DAV's family used: a DAO states its SQL and bindings directly, and\n * the retry/normalization wrapper is invisible at the call site. The closure\n * form made every read site pay for a wrapper 90% of them never needed, and\n * each of the two shapes drifted its own method names (`withRetry` vs\n * `run(sql, bindings)`); the sql-first form is what survived.\n *\n * ### Every statement is charged\n *\n * D1 counts its own queries against the Workers per-invocation subrequest\n * ceiling, so a statement that spends one without telling anybody makes every\n * number that budgets work wrong — and it has **no symptom** until the platform\n * terminates the invocation, by which point the rows were right and the suite\n * was green. The meter is therefore a constructor dependency rather than a\n * module singleton, and the charge happens here because this is the one path\n * every statement takes; a charge at each call site is a hundred chances to\n * forget one.\n *\n * The charge is **per logical statement, not per attempt**: a retried statement\n * is one statement that the platform refused once and then answered. Charging\n * per attempt would make the ceiling track the fault rate instead of the work.\n *\n * Non-DAO concerns stay out: cursor pagination lives in `@rexezuge/shared`\n * (`CursorCodec`). Retry policy lives in `D1Retry` — one schedule, one\n * classifier, one place the `Failed to <context>` prefix is added.\n */\nabstract class BaseDAO {\n /**\n * Public, and deliberately so.\n *\n * A composition root instantiates concrete DAOs directly — that is the whole\n * point of a DI container, which binds `() => new UserDAO(db)` rather than\n * handing the container a factory that hides the construction. A `protected`\n * constructor blocks that and buys nothing: the class is `abstract`, so nobody\n * can instantiate `BaseDAO` itself regardless, and the access modifier\n * prevented exactly zero illegal constructions while forcing every concrete\n * DAO to redeclare a pass-through constructor that added no invariant.\n *\n * It was `protected` to keep `database` from being reached as\n * `BaseDAO.database` — but every field below carries its own `protected`, so\n * the field's own modifier is what enforces that, and making the constructor\n * public does not weaken it.\n *\n * @param database The binding.\n * @param meter The invocation's subrequest counter, or an unmetered default.\n * @param options `billedRowsForTable` supplies the schema's write cost.\n */\n constructor(\n protected readonly database: D1Queryable,\n protected readonly meter: SubrequestMeter = UNMETERED_SUBREQUESTS,\n private readonly options: { billedRowsForTable?: BilledRowsForTable } = {},\n ) {}\n\n /**\n * The invocation's meter, for a DAO that constructs another DAO.\n *\n * A `protected get` rather than a public field, because handing the meter out\n * is how a DAO builds a collaborator correctly: `new SongIdLookupDAO(this.database)`\n * drops it, and the charge that goes missing has no symptom.\n */\n protected get subrequests(): SubrequestMeter {\n return this.meter;\n }\n\n /**\n A prepared statement with its bindings applied. Bindings are always parameters, never interpolation.\n */\n protected statement(sql: string, bindings: unknown[] = []): D1PreparedStatement {\n return bindings.length > 0 ? this.database.prepare(sql).bind(...bindings) : this.database.prepare(sql);\n }\n\n /**\n * The same statement, carrying the SQL beside it.\n *\n * Use this wherever the SQL matters downstream — a write whose cost is\n * accounted, a statement named in an error — and {@link statement} for reads,\n * where nothing reads the SQL back and the pair is one allocation of waste.\n */\n protected tracked(sql: string, bindings: unknown[] = []): TrackedStatement {\n const make = (prepared: D1PreparedStatement): TrackedStatement => ({\n sql,\n statement: prepared,\n bind: (...next: unknown[]): TrackedStatement => make(prepared.bind(...next)),\n });\n return make(this.statement(sql, bindings));\n }\n\n /**\n * Run a statement. D1 reports a constraint violation or a missing table by\n * returning `success: false` rather than by throwing, so both forms are\n * normalized to a `DatabaseError` here — ignoring the result form is what\n * let a `UNIQUE` failure reach a caller as an opaque 500.\n */\n protected async run(sql: string, bindings: unknown[] = []): Promise<D1Result> {\n this.meter.charge(1, 'd1');\n return executeWithRetry((): Promise<D1Result> => this.statement(sql, bindings).run(), 'run statement');\n }\n\n /**\n Read one row. A `null` result is \"no row\", a success, not an error; only a\n rejected statement is retried and normalized.\n\n `null` rather than `undefined` because that is what the platform says\n (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back\n what it was given. It also makes this layer agree with `KvCache`, which has\n always returned `null` for a miss, so one convention covers both.\n */\n protected async first<T>(sql: string, bindings: unknown[] = []): Promise<T | null> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T | null>> => {\n const row: T | null = await this.statement(sql, bindings).first<T>();\n return { success: true, value: row };\n }, 'read a row');\n return envelope.value;\n }\n\n /**\n A list read. `.all()` returning `[]` is a success like `first()`'s null.\n */\n protected async all<T>(sql: string, bindings: unknown[] = []): Promise<T[]> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T[]>> => {\n const rows = await this.statement(sql, bindings).all<T>();\n return { success: true, value: rows.results ?? [] };\n }, 'read rows');\n return envelope.value;\n }\n\n /**\n A scalar count from a `SELECT count(*)` row; 0 when absent.\n */\n protected async count(sql: string, bindings: unknown[] = []): Promise<number> {\n const row = await this.first<{ count: number }>(sql, bindings);\n return row?.count ?? 0;\n }\n\n /**\n * A batch of prepared statements — one transaction and one subrequest,\n * however many statements it carries. Each result is checked, so a single\n * failure inside the batch raises rather than passing silently.\n */\n protected async batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {\n if (statements.length === 0) return [];\n this.meter.charge(1, 'd1');\n if (this.database.batch === undefined) {\n throw new DatabaseError('The D1 binding exposes no batch() — a multi-statement transaction is not available here');\n }\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<D1Result[]>> => {\n const results: D1Result[] = await (this.database.batch as NonNullable<D1Queryable['batch']>)(statements);\n const failed: D1Result | undefined = results.find((result): boolean => !result.success);\n return { success: failed === undefined, error: failed?.error, value: results };\n }, 'run a batch');\n return envelope.value;\n }\n\n /**\n * Run one write and report what it cost.\n *\n * Takes a {@link TrackedStatement} rather than SQL because the cost is read off\n * the table the SQL names, and the SQL is only available if it was carried.\n * `billedRows` is `null` when no port is configured.\n */\n protected async runTracked(tracked: TrackedStatement): Promise<WriteResult> {\n const result = await executeWithRetry((): Promise<D1Result> => tracked.statement.run(), 'run a write');\n return this.accountWrite(tracked.sql, result);\n }\n\n /**\n * Run a batch of writes and report what the whole batch cost.\n *\n * Billed rows are **summed across the batch**, and an unaccountable statement\n * poisons the total to `null` rather than being skipped: a partial figure next\n * to a real one is the one that reads as complete.\n */\n protected async runTrackedBatch(tracked: readonly TrackedStatement[]): Promise<WriteResult> {\n const results = await this.batch(tracked.map((entry) => entry.statement));\n let billedRows = 0;\n let accounted = this.options.billedRowsForTable !== undefined;\n for (const [index, result] of results.entries()) {\n const entry = tracked[index];\n if (!entry) {\n accounted = false;\n break;\n }\n const one = this.accountWrite(entry.sql, result);\n if (one.billedRows === null) {\n accounted = false;\n break;\n }\n billedRows += one.billedRows;\n }\n const changes = results.reduce((total, result) => total + changesOf(result), 0);\n return { changes, billedRows: accounted ? billedRows : null };\n }\n\n /**\n * The writes these statements fit into the invocation's remaining budget.\n *\n * \"How many may I issue\", as distinct from {@link assertSubrequestBudget}'s\n * \"may I issue all of these\" — a caller truncating a work list needs the\n * number, and a caller that must not truncate needs the refusal. An unmetered\n * counter answers `Infinity`, so a deployment that does not meter is never\n * clamped by a budget it does not have.\n */\n protected fitToSubrequestBudget(requested: number): number {\n const remaining = this.meter.remaining;\n return Number.isFinite(remaining) ? Math.max(0, Math.min(requested, Math.floor(remaining))) : Math.max(0, requested);\n }\n\n /**\n * Refuse a set of statements the invocation's remaining budget cannot carry.\n *\n * For a write with no partial form — a play queue, a playlist's count, a\n * backfill — because half a queue is a _shorter_ queue, which is a wrong\n * answer rather than an unfinished one. A caller that may truncate uses\n * {@link fitToSubrequestBudget} instead and reports that it did.\n *\n * @param statements How many statements the work needs.\n * @param context Named in the refusal, because this reaches a client as a 413.\n */\n protected assertSubrequestBudget(statements: number, context = 'this request'): void {\n if (this.meter.canAfford(statements)) return;\n throw new SubrequestBudgetExhaustedError(\n `${context} needs ${statements} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`,\n );\n }\n\n /**\n * One row by its key, or `null`. The metered, retried form of the free\n * `findRowById` the Mail-* repos kept; identifiers are allow-listed.\n */\n protected async findRowById<T>(\n table: string,\n id: string | number,\n options: { idColumn?: string; columns?: readonly string[] } = {},\n ): Promise<T | null> {\n const idColumn = options.idColumn ?? 'id';\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(idColumn, 'idColumn');\n const columns = options.columns ?? [];\n for (const column of columns) assertSqlIdentifier(column, 'column');\n const projection = columns.length > 0 ? columns.join(', ') : '*';\n return this.first<T>(`SELECT ${projection} FROM ${table} WHERE ${idColumn} = ? LIMIT 1`, [id]);\n }\n\n /**\n * Delete one bounded batch older than `cutoff` (exclusive); answers the count.\n * The metered instance form of the static `deleteOlderThan`, and a runtime\n * `PruningTarget` in one line. `extraCondition` is a trusted SQL fragment\n * ANDed into the subquery (e.g. `status != 'running'`), never input.\n */\n protected async deleteRowsOlderThan(\n table: string,\n timeColumn: string,\n cutoff: number | string,\n limit: number,\n options: { idColumn?: string; extraCondition?: string } = {},\n ): Promise<number> {\n const idColumn = options.idColumn ?? 'id';\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(timeColumn, 'timeColumn');\n assertSqlIdentifier(idColumn, 'idColumn');\n const extra = options.extraCondition === undefined ? '' : ` AND (${options.extraCondition})`;\n const result = await this.run(\n `DELETE FROM ${table} WHERE ${idColumn} IN (SELECT ${idColumn} FROM ${table} WHERE ${timeColumn} < ?${extra} ORDER BY ${timeColumn} LIMIT ?)`,\n [cutoff, limit],\n );\n return changesOf(result);\n }\n\n /**\n * Charge the meter and account a completed write against the schema's cost.\n */\n private accountWrite(sql: string, result: D1Result): WriteResult {\n const changes = changesOf(result);\n const port = this.options.billedRowsForTable;\n if (!port) return { changes, billedRows: null };\n return { changes, billedRows: port(statementTable(sql) ?? '', changes) };\n }\n\n /**\n * Generic batched delete of rows older than a cutoff, in ID order, with\n * retry. Mirrors the per-DAO `DELETE ... WHERE id IN (SELECT ... LIMIT ?)`\n * pattern that every repo re-implemented per table. The cutoff is exclusive:\n * a delete never touches a row at exactly the boundary timestamp.\n */\n protected static async deleteOlderThan(\n db: D1Queryable,\n table: string,\n timeColumn: string,\n cutoff: number | string,\n limit: number,\n idColumn: string,\n ): Promise<number> {\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(timeColumn, 'timeColumn');\n assertSqlIdentifier(idColumn, 'idColumn');\n const result: D1Result = await executeWithRetry(\n (): Promise<D1Result> =>\n db\n .prepare(\n `DELETE FROM ${table}\n WHERE ${idColumn} IN (\n SELECT ${idColumn} FROM ${table}\n WHERE ${timeColumn} < ?\n LIMIT ?\n )`,\n )\n .bind(cutoff, limit)\n .run(),\n `delete old rows from ${table}`,\n );\n return (result.meta as { changes?: number })?.changes ?? 0;\n }\n\n /**\n The retry schedule, for callers that surface it (health checks, tests).\n */\n protected static get retryDefaults(): typeof D1_RETRY_DEFAULTS {\n return D1_RETRY_DEFAULTS;\n }\n}\n\nexport { BaseDAO };\nexport type { BilledRowsForTable, TrackedStatement, WriteResult };\n\nexport { assertSqlIdentifier, statementTable } from './sqlStatement.ts';\n"],
5
+ "mappings": "+EAAA,OAAS,yBAAAA,MAA6B,mBAEtC,OAAS,kCAAAC,MAAsC,mBAC/C,OAAS,iBAAAC,MAAqB,mBAC9B,OAAS,qBAAAC,EAAmB,oBAAAC,MAAwB,eAEpD,OAAS,uBAAAC,EAAqB,aAAAC,EAAW,kBAAAC,MAAsB,oBA0F/D,MAAeC,CAAO,CAhGtB,MAgGsB,CAAAC,EAAA,gBAsBC,SACA,MACF,QAHnB,YACqBC,EACAC,EAAyBX,EAC3BY,EAAuD,CAAA,EAAE,CAFvD,KAAA,SAAAF,EACA,KAAA,MAAAC,EACF,KAAA,QAAAC,CAChB,CASH,IAAc,aAAW,CACv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AY,IAAI,CAE/C,CAQU,aAAa,gBACrBE,EACAZ,EACAM,EACAC,EACAC,EACAN,EAAgB,CAEhB,OAAA7B,EAAoB2B,EAAO,OAAO,EAClC3B,EAAoBiC,EAAY,YAAY,EAC5CjC,EAAoB6B,EAAU,UAAU,GACf,MAAM9B,EAC7B,IACEwC,EACG,QACC,eAAeZ,CAAK;qBACXE,CAAQ;wBACLA,CAAQ,SAASF,CAAK;uBACvBM,CAAU;;eAElB,EAEJ,KAAKC,EAAQC,CAAK,EAClB,IAAG,EACR,wBAAwBR,CAAK,EAAE,GAElB,MAA+B,SAAW,CAC3D,CAKU,WAAW,eAAa,CAChC,OAAO7B,CACT,EAMF,OAAS,uBAAAE,EAAqB,kBAAAE,MAAsB",
6
+ "names": ["UNMETERED_SUBREQUESTS", "SubrequestBudgetExhaustedError", "DatabaseError", "D1_RETRY_DEFAULTS", "executeWithRetry", "assertSqlIdentifier", "changesOf", "statementTable", "BaseDAO", "__name", "database", "meter", "options", "sql", "bindings", "make", "prepared", "next", "statements", "results", "failed", "result", "tracked", "entry", "billedRows", "accounted", "index", "one", "total", "requested", "remaining", "context", "table", "id", "idColumn", "columns", "column", "projection", "timeColumn", "cutoff", "limit", "extra", "changes", "port", "db"]
7
7
  }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * D1 Sessions bookmark round-trip, framework-free.
3
+ *
4
+ * Converged from Mail-Meow's `backend-runtime/src/base/D1SessionEnv.ts` and the
5
+ * `D1SessionUtil.ts` copies in AWS-AccessBridge, CalDAV-Bridge, Mail-Bee and
6
+ * Mail-Otter, plus the header handling in each repo's API worker.
7
+ *
8
+ * A session makes one request's reads and writes consistent with each other: a
9
+ * write followed by a read cannot observe a different replica. Across requests
10
+ * that holds only if the client sends back the bookmark the previous response
11
+ * carried — a new `env` arrives per request, and the bookmark is what carries
12
+ * the session. Without the round-trip, a read after a write can silently miss
13
+ * the write.
14
+ *
15
+ * ```ts
16
+ * const session = openSession(env.DB, readBookmark(request));
17
+ * const response = await app.fetch(request, { ...env, DB: session }, ctx);
18
+ * return withBookmark(response, session);
19
+ * ```
20
+ *
21
+ * `@rexezuge/http` owns the middleware form; these are the primitives, so a
22
+ * worker without a web framework (a Durable Object, a cron task) gets them too.
23
+ */
24
+ /**
25
+ The request and response header the bookmark travels in.
26
+ */
27
+ declare const D1_BOOKMARK_HEADER = "x-d1-bookmark";
28
+ /**
29
+ * The session constraints the platform accepts in place of a bookmark.
30
+ * `first-primary` (the default) is Cloudflare's recommendation for a read path
31
+ * that must observe the latest write; `first-unconstrained` trades that for
32
+ * the nearest replica.
33
+ */
34
+ type D1SessionConstraint = 'first-primary' | 'first-unconstrained';
35
+ /**
36
+ A session, structurally: a real `D1DatabaseSession` satisfies it.
37
+ */
38
+ interface D1SessionLike {
39
+ getBookmark(): string | null;
40
+ }
41
+ /**
42
+ A binding that can open sessions: a real `D1Database` satisfies it.
43
+ */
44
+ interface D1SessionSource<TSession> {
45
+ withSession(constraintOrBookmark?: string): TSession;
46
+ }
47
+ /**
48
+ * The trimmed bookmark a request carries, or `null` when it carries none (an
49
+ * empty header is none).
50
+ */
51
+ declare function readBookmark(request: Request): string | null;
52
+ /**
53
+ * Open a session that continues `bookmark`, or starts at `fallback` when there
54
+ * is none.
55
+ */
56
+ declare function openSession<TSession>(db: D1SessionSource<TSession>, bookmark: string | null, fallback?: D1SessionConstraint): TSession;
57
+ /**
58
+ * Stamp the session's latest bookmark onto a response, and expose the header
59
+ * to browsers (appending to any existing `Access-Control-Expose-Headers`).
60
+ *
61
+ * A response with immutable headers (one returned straight from `fetch`) is
62
+ * copied rather than mutated, so this never throws on the response path. A
63
+ * session with no bookmark yet leaves the bookmark header unset.
64
+ */
65
+ declare function withBookmark(response: Response, session: D1SessionLike): Response;
66
+ export { D1_BOOKMARK_HEADER, openSession, readBookmark, withBookmark };
67
+ export type { D1SessionConstraint, D1SessionLike, D1SessionSource };
68
+ //# sourceMappingURL=D1Session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"D1Session.d.ts","sourceRoot":"","sources":["../src/D1Session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;EAEE;AACF,QAAA,MAAM,kBAAkB,kBAAkB,CAAC;AAE3C;;;;;GAKG;AACH,KAAK,mBAAmB,GAAG,eAAe,GAAG,qBAAqB,CAAC;AAEnE;;EAEE;AACF,UAAU,aAAa;IACrB,WAAW,IAAI,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED;;EAEE;AACF,UAAU,eAAe,CAAC,QAAQ;IAChC,WAAW,CAAC,oBAAoB,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;CACtD;AAED;;;GAGG;AACH,iBAAS,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAGrD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAAC,QAAQ,EAC3B,EAAE,EAAE,eAAe,CAAC,QAAQ,CAAC,EAC7B,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,QAAQ,GAAE,mBAAqC,GAC9C,QAAQ,CAEV;AAED;;;;;;;GAOG;AACH,iBAAS,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,aAAa,GAAG,QAAQ,CAc1E;AAaD,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC;AACvE,YAAY,EAAE,mBAAmB,EAAE,aAAa,EAAE,eAAe,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var n=(t,e)=>c(t,"name",{value:e,configurable:!0});const a="x-d1-bookmark";function u(t){const e=t.headers.get(a)?.trim()??"";return e===""?null:e}n(u,"readBookmark");function d(t,e,o="first-primary"){return t.withSession(e??o)}n(d,"openSession");function l(t,e){const o=e.getBookmark();try{return i(t.headers,o),t}catch{const s=new Response(t.body,{status:t.status,statusText:t.statusText,headers:new Headers(t.headers)});return i(s.headers,o),s}}n(l,"withBookmark");function i(t,e){e!==null&&e!==""&&t.set(a,e);const s=(t.get("Access-Control-Expose-Headers")??"").split(",").map(r=>r.trim()).filter(r=>r!=="");s.every(r=>r.toLowerCase()!==a)&&s.push(a),t.set("Access-Control-Expose-Headers",s.join(", "))}n(i,"stamp");export{a as D1_BOOKMARK_HEADER,d as openSession,u as readBookmark,l as withBookmark};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/D1Session.ts"],
4
+ "sourcesContent": ["/**\n * D1 Sessions bookmark round-trip, framework-free.\n *\n * Converged from Mail-Meow's `backend-runtime/src/base/D1SessionEnv.ts` and the\n * `D1SessionUtil.ts` copies in AWS-AccessBridge, CalDAV-Bridge, Mail-Bee and\n * Mail-Otter, plus the header handling in each repo's API worker.\n *\n * A session makes one request's reads and writes consistent with each other: a\n * write followed by a read cannot observe a different replica. Across requests\n * that holds only if the client sends back the bookmark the previous response\n * carried — a new `env` arrives per request, and the bookmark is what carries\n * the session. Without the round-trip, a read after a write can silently miss\n * the write.\n *\n * ```ts\n * const session = openSession(env.DB, readBookmark(request));\n * const response = await app.fetch(request, { ...env, DB: session }, ctx);\n * return withBookmark(response, session);\n * ```\n *\n * `@rexezuge/http` owns the middleware form; these are the primitives, so a\n * worker without a web framework (a Durable Object, a cron task) gets them too.\n */\n\n/**\nThe request and response header the bookmark travels in.\n*/\nconst D1_BOOKMARK_HEADER = 'x-d1-bookmark';\n\n/**\n * The session constraints the platform accepts in place of a bookmark.\n * `first-primary` (the default) is Cloudflare's recommendation for a read path\n * that must observe the latest write; `first-unconstrained` trades that for\n * the nearest replica.\n */\ntype D1SessionConstraint = 'first-primary' | 'first-unconstrained';\n\n/**\nA session, structurally: a real `D1DatabaseSession` satisfies it.\n*/\ninterface D1SessionLike {\n getBookmark(): string | null;\n}\n\n/**\nA binding that can open sessions: a real `D1Database` satisfies it.\n*/\ninterface D1SessionSource<TSession> {\n withSession(constraintOrBookmark?: string): TSession;\n}\n\n/**\n * The trimmed bookmark a request carries, or `null` when it carries none (an\n * empty header is none).\n */\nfunction readBookmark(request: Request): string | null {\n const value = request.headers.get(D1_BOOKMARK_HEADER)?.trim() ?? '';\n return value === '' ? null : value;\n}\n\n/**\n * Open a session that continues `bookmark`, or starts at `fallback` when there\n * is none.\n */\nfunction openSession<TSession>(\n db: D1SessionSource<TSession>,\n bookmark: string | null,\n fallback: D1SessionConstraint = 'first-primary',\n): TSession {\n return db.withSession(bookmark ?? fallback);\n}\n\n/**\n * Stamp the session's latest bookmark onto a response, and expose the header\n * to browsers (appending to any existing `Access-Control-Expose-Headers`).\n *\n * A response with immutable headers (one returned straight from `fetch`) is\n * copied rather than mutated, so this never throws on the response path. A\n * session with no bookmark yet leaves the bookmark header unset.\n */\nfunction withBookmark(response: Response, session: D1SessionLike): Response {\n const bookmark = session.getBookmark();\n try {\n stamp(response.headers, bookmark);\n return response;\n } catch {\n const copy = new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: new Headers(response.headers),\n });\n stamp(copy.headers, bookmark);\n return copy;\n }\n}\n\nfunction stamp(headers: Headers, bookmark: string | null): void {\n if (bookmark !== null && bookmark !== '') headers.set(D1_BOOKMARK_HEADER, bookmark);\n const exposed = headers.get('Access-Control-Expose-Headers');\n const list = (exposed ?? '')\n .split(',')\n .map((name) => name.trim())\n .filter((name) => name !== '');\n if (list.every((name) => name.toLowerCase() !== D1_BOOKMARK_HEADER)) list.push(D1_BOOKMARK_HEADER);\n headers.set('Access-Control-Expose-Headers', list.join(', '));\n}\n\nexport { D1_BOOKMARK_HEADER, openSession, readBookmark, withBookmark };\nexport type { D1SessionConstraint, D1SessionLike, D1SessionSource };\n"],
5
+ "mappings": "+EA2BA,MAAMA,EAAqB,gBA4B3B,SAASC,EAAaC,EAAgB,CACpC,MAAMC,EAAQD,EAAQ,QAAQ,IAAIF,CAAkB,GAAG,KAAI,GAAM,GACjE,OAAOG,IAAU,GAAK,KAAOA,CAC/B,CAHSC,EAAAH,EAAA,gBAST,SAASI,EACPC,EACAC,EACAC,EAAgC,gBAAe,CAE/C,OAAOF,EAAG,YAAYC,GAAYC,CAAQ,CAC5C,CANSJ,EAAAC,EAAA,eAgBT,SAASI,EAAaC,EAAoBC,EAAsB,CAC9D,MAAMJ,EAAWI,EAAQ,YAAW,EACpC,GAAI,CACF,OAAAC,EAAMF,EAAS,QAASH,CAAQ,EACzBG,CACT,MAAQ,CACN,MAAMG,EAAO,IAAI,SAASH,EAAS,KAAM,CACvC,OAAQA,EAAS,OACjB,WAAYA,EAAS,WACrB,QAAS,IAAI,QAAQA,EAAS,OAAO,EACtC,EACD,OAAAE,EAAMC,EAAK,QAASN,CAAQ,EACrBM,CACT,CACF,CAdST,EAAAK,EAAA,gBAgBT,SAASG,EAAME,EAAkBP,EAAuB,CAClDA,IAAa,MAAQA,IAAa,IAAIO,EAAQ,IAAId,EAAoBO,CAAQ,EAElF,MAAMQ,GADUD,EAAQ,IAAI,+BAA+B,GAClC,IACtB,MAAM,GAAG,EACT,IAAKE,GAASA,EAAK,KAAI,CAAE,EACzB,OAAQA,GAASA,IAAS,EAAE,EAC3BD,EAAK,MAAOC,GAASA,EAAK,YAAW,IAAOhB,CAAkB,GAAGe,EAAK,KAAKf,CAAkB,EACjGc,EAAQ,IAAI,gCAAiCC,EAAK,KAAK,IAAI,CAAC,CAC9D,CATSX,EAAAQ,EAAA",
6
+ "names": ["D1_BOOKMARK_HEADER", "readBookmark", "request", "value", "__name", "openSession", "db", "bookmark", "fallback", "withBookmark", "response", "session", "stamp", "copy", "headers", "list", "name"]
7
+ }
@@ -0,0 +1,76 @@
1
+ import type { SubrequestMeter } from '@rexezuge/shared';
2
+ import type { EncryptedEnvelope } from './aes-gcm.ts';
3
+ import { BaseDAO } from './BaseDAO.ts';
4
+ import type { BilledRowsForTable } from './BaseDAO.ts';
5
+ import type { D1Queryable } from './D1Types.ts';
6
+ /**
7
+ * The key port an {@link EncryptedDAO} is constructed with.
8
+ *
9
+ * Either one base64 key (the Mail-*, CalDAV-Bridge, ChordDHT-Tracker shape),
10
+ * or the keys to try in preference order (Edge-Git's): `keys[0]` is the only
11
+ * key new ciphertext is written under, and the rest are decrypt-only fallbacks
12
+ * for rows written before a rotation.
13
+ *
14
+ * The composition root resolves it once (from a secret binding, a KMS, a test
15
+ * fixture); the DAO never reads `env`, so it cannot use a key it was not wired
16
+ * with and is testable without a real secret.
17
+ */
18
+ type EncryptionKeys = string | readonly string[];
19
+ /**
20
+ * A DAO whose rows carry AES-GCM envelopes.
21
+ *
22
+ * Converged from the `EncryptedDAO` copies in Mail-Bee, Mail-Meow, Mail-Otter,
23
+ * CalDAV-Bridge and ChordDHT-Tracker (`masterKey: string`), AWS-AccessBridge and
24
+ * Edge-Git (`encryptionKeys` with a meter). Both constructor shapes are accepted,
25
+ * `masterKey` stays readable for subclasses that call `encryptSecret`
26
+ * themselves, and the envelope work moves into {@link seal} / {@link open} so a
27
+ * subclass stops repeating the key handling:
28
+ *
29
+ * - {@link seal} always encrypts under the first key.
30
+ * - {@link open} tries each key in order and fails closed with the
31
+ * `AesGcmKeyError` of the last attempt — never plaintext, never `null`.
32
+ *
33
+ * ## Extending
34
+ *
35
+ * Subclass it like `BaseDAO`; the SQL is yours, the cipher and key policy are
36
+ * the kit's. Override {@link open} only to add telemetry — the fail-closed
37
+ * contract is the point.
38
+ */
39
+ declare abstract class EncryptedDAO extends BaseDAO {
40
+ /**
41
+ The keys, in preference order. Never empty: the constructor refuses that.
42
+ */
43
+ protected readonly encryptionKeys: readonly string[];
44
+ /**
45
+ * @param database The binding.
46
+ * @param keys The key port — see {@link EncryptionKeys}.
47
+ * @param meter The invocation's subrequest counter.
48
+ * @param options Forwarded to `BaseDAO`.
49
+ */
50
+ constructor(database: D1Queryable, keys: EncryptionKeys, meter?: SubrequestMeter, options?: {
51
+ billedRowsForTable?: BilledRowsForTable;
52
+ });
53
+ /**
54
+ The key new ciphertext is written under (`keys[0]`).
55
+ */
56
+ protected get masterKey(): string;
57
+ /**
58
+ Encrypt one value under {@link masterKey}.
59
+ */
60
+ protected seal(plaintext: string): Promise<EncryptedEnvelope>;
61
+ /**
62
+ Decrypt one envelope, trying each key in order. Fails closed.
63
+ */
64
+ protected open(envelope: EncryptedEnvelope): Promise<string>;
65
+ /**
66
+ {@link seal} for a JSON-serialisable value.
67
+ */
68
+ protected sealJson(value: unknown): Promise<EncryptedEnvelope>;
69
+ /**
70
+ {@link open} and `JSON.parse`. The cast is the caller's claim about the row.
71
+ */
72
+ protected openJson<T>(envelope: EncryptedEnvelope): Promise<T>;
73
+ }
74
+ export { EncryptedDAO };
75
+ export type { EncryptionKeys };
76
+ //# sourceMappingURL=EncryptedDAO.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EncryptedDAO.d.ts","sourceRoot":"","sources":["../src/EncryptedDAO.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD;;;;;;;;;;;GAWG;AACH,KAAK,cAAc,GAAG,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,uBAAe,YAAa,SAAQ,OAAO;IACzC;;MAEE;IACF,SAAS,CAAC,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAErD;;;;;OAKG;gBAED,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,cAAc,EACpB,KAAK,GAAE,eAAuC,EAC9C,OAAO,GAAE;QAAE,kBAAkB,CAAC,EAAE,kBAAkB,CAAA;KAAO;IAU3D;;MAEE;IACF,SAAS,KAAK,SAAS,IAAI,MAAM,CAEhC;IAED;;MAEE;IACF,SAAS,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAI7D;;MAEE;cACc,IAAI,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC;IAYlE;;MAEE;IACF,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAI9D;;MAEE;cACc,QAAQ,CAAC,CAAC,EAAE,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,CAAC,CAAC;CAGrE;AAED,OAAO,EAAE,YAAY,EAAE,CAAC;AACxB,YAAY,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var i=(s,r)=>c(s,"name",{value:r,configurable:!0});import{UNMETERED_SUBREQUESTS as y}from"@rexezuge/shared";import{AesGcmKeyError as p,decryptSecret as a,encryptSecret as h}from"./aes-gcm.js";import{BaseDAO as f}from"./BaseDAO.js";class l extends f{static{i(this,"EncryptedDAO")}encryptionKeys;constructor(r,t,e=y,n={}){super(r,e,n);const o=typeof t=="string"?[t]:[...t];if(o.length===0)throw new p("No encryption key is configured for this DAO");this.encryptionKeys=o}get masterKey(){return this.encryptionKeys[0]}seal(r){return h(r,this.masterKey)}async open(r){let t=null;for(const e of this.encryptionKeys)try{return await a(r,e)}catch(n){t=n}throw t}sealJson(r){return this.seal(JSON.stringify(r))}async openJson(r){return JSON.parse(await this.open(r))}}export{l as EncryptedDAO};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/EncryptedDAO.ts"],
4
+ "sourcesContent": ["import { UNMETERED_SUBREQUESTS } from '@rexezuge/shared';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { AesGcmKeyError, decryptSecret, encryptSecret } from './aes-gcm.ts';\nimport type { EncryptedEnvelope } from './aes-gcm.ts';\nimport { BaseDAO } from './BaseDAO.ts';\nimport type { BilledRowsForTable } from './BaseDAO.ts';\nimport type { D1Queryable } from './D1Types.ts';\n\n/**\n * The key port an {@link EncryptedDAO} is constructed with.\n *\n * Either one base64 key (the Mail-*, CalDAV-Bridge, ChordDHT-Tracker shape),\n * or the keys to try in preference order (Edge-Git's): `keys[0]` is the only\n * key new ciphertext is written under, and the rest are decrypt-only fallbacks\n * for rows written before a rotation.\n *\n * The composition root resolves it once (from a secret binding, a KMS, a test\n * fixture); the DAO never reads `env`, so it cannot use a key it was not wired\n * with and is testable without a real secret.\n */\ntype EncryptionKeys = string | readonly string[];\n\n/**\n * A DAO whose rows carry AES-GCM envelopes.\n *\n * Converged from the `EncryptedDAO` copies in Mail-Bee, Mail-Meow, Mail-Otter,\n * CalDAV-Bridge and ChordDHT-Tracker (`masterKey: string`), AWS-AccessBridge and\n * Edge-Git (`encryptionKeys` with a meter). Both constructor shapes are accepted,\n * `masterKey` stays readable for subclasses that call `encryptSecret`\n * themselves, and the envelope work moves into {@link seal} / {@link open} so a\n * subclass stops repeating the key handling:\n *\n * - {@link seal} always encrypts under the first key.\n * - {@link open} tries each key in order and fails closed with the\n * `AesGcmKeyError` of the last attempt — never plaintext, never `null`.\n *\n * ## Extending\n *\n * Subclass it like `BaseDAO`; the SQL is yours, the cipher and key policy are\n * the kit's. Override {@link open} only to add telemetry — the fail-closed\n * contract is the point.\n */\nabstract class EncryptedDAO extends BaseDAO {\n /**\n The keys, in preference order. Never empty: the constructor refuses that.\n */\n protected readonly encryptionKeys: readonly string[];\n\n /**\n * @param database The binding.\n * @param keys The key port — see {@link EncryptionKeys}.\n * @param meter The invocation's subrequest counter.\n * @param options Forwarded to `BaseDAO`.\n */\n public constructor(\n database: D1Queryable,\n keys: EncryptionKeys,\n meter: SubrequestMeter = UNMETERED_SUBREQUESTS,\n options: { billedRowsForTable?: BilledRowsForTable } = {},\n ) {\n super(database, meter, options);\n const list = typeof keys === 'string' ? [keys] : [...keys];\n if (list.length === 0) {\n throw new AesGcmKeyError('No encryption key is configured for this DAO');\n }\n this.encryptionKeys = list;\n }\n\n /**\n The key new ciphertext is written under (`keys[0]`).\n */\n protected get masterKey(): string {\n return this.encryptionKeys[0];\n }\n\n /**\n Encrypt one value under {@link masterKey}.\n */\n protected seal(plaintext: string): Promise<EncryptedEnvelope> {\n return encryptSecret(plaintext, this.masterKey);\n }\n\n /**\n Decrypt one envelope, trying each key in order. Fails closed.\n */\n protected async open(envelope: EncryptedEnvelope): Promise<string> {\n let lastError: unknown = null;\n for (const key of this.encryptionKeys) {\n try {\n return await decryptSecret(envelope, key);\n } catch (error: unknown) {\n lastError = error;\n }\n }\n throw lastError;\n }\n\n /**\n {@link seal} for a JSON-serialisable value.\n */\n protected sealJson(value: unknown): Promise<EncryptedEnvelope> {\n return this.seal(JSON.stringify(value));\n }\n\n /**\n {@link open} and `JSON.parse`. The cast is the caller's claim about the row.\n */\n protected async openJson<T>(envelope: EncryptedEnvelope): Promise<T> {\n return JSON.parse(await this.open(envelope)) as T;\n }\n}\n\nexport { EncryptedDAO };\nexport type { EncryptionKeys };\n"],
5
+ "mappings": "+EAAA,OAAS,yBAAAA,MAA6B,mBAEtC,OAAS,kBAAAC,EAAgB,iBAAAC,EAAe,iBAAAC,MAAqB,eAE7D,OAAS,WAAAC,MAAe,eAsCxB,MAAeC,UAAqBD,CAAO,CA1C3C,MA0C2C,CAAAE,EAAA,qBAItB,eAQnB,YACEC,EACAC,EACAC,EAAyBT,EACzBU,EAAuD,CAAA,EAAE,CAEzD,MAAMH,EAAUE,EAAOC,CAAO,EAC9B,MAAMC,EAAO,OAAOH,GAAS,SAAW,CAACA,CAAI,EAAI,CAAC,GAAGA,CAAI,EACzD,GAAIG,EAAK,SAAW,EAClB,MAAM,IAAIV,EAAe,8CAA8C,EAEzE,KAAK,eAAiBU,CACxB,CAKA,IAAc,WAAS,CACrB,OAAO,KAAK,eAAe,CAAC,CAC9B,CAKU,KAAKC,EAAiB,CAC9B,OAAOT,EAAcS,EAAW,KAAK,SAAS,CAChD,CAKU,MAAM,KAAKC,EAA2B,CAC9C,IAAIC,EAAqB,KACzB,UAAWC,KAAO,KAAK,eACrB,GAAI,CACF,OAAO,MAAMb,EAAcW,EAAUE,CAAG,CAC1C,OAASC,EAAgB,CACvBF,EAAYE,CACd,CAEF,MAAMF,CACR,CAKU,SAASG,EAAc,CAC/B,OAAO,KAAK,KAAK,KAAK,UAAUA,CAAK,CAAC,CACxC,CAKU,MAAM,SAAYJ,EAA2B,CACrD,OAAO,KAAK,MAAM,MAAM,KAAK,KAAKA,CAAQ,CAAC,CAC7C",
6
+ "names": ["UNMETERED_SUBREQUESTS", "AesGcmKeyError", "decryptSecret", "encryptSecret", "BaseDAO", "EncryptedDAO", "__name", "database", "keys", "meter", "options", "list", "plaintext", "envelope", "lastError", "key", "error", "value"]
7
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The `background_task_runs` table: its SQL, its row, and the DAO's I/O types.
3
+ *
4
+ * Converged from the four copies of the table (AWS-AccessBridge
5
+ * `0030_squash.sql`, Mail-Bee `0001_initial.sql`, Mail-Meow
6
+ * `0008_background_task_runs.sql`, Mail-Otter `0023_background_task_runs.sql`).
7
+ * The canonical form is the Mail-* one — `application_id` included, both
8
+ * indexes — **without** the `REFERENCES connected_applications(...)` clause,
9
+ * which names a table the kit does not own. A repo that wants the cascade keeps
10
+ * its own migration; the column shape is identical, so this DAO works on both.
11
+ */
12
+ declare const BACKGROUND_TASK_RUNS_TABLE = "background_task_runs";
13
+ /**
14
+ * The fresh-install DDL. Idempotent (`IF NOT EXISTS`), so a repo whose table
15
+ * already exists can apply it unchanged; split and run it through
16
+ * `executableStatements`, or paste it into a migration file.
17
+ */
18
+ declare const BACKGROUND_TASK_RUNS_SCHEMA = "CREATE TABLE IF NOT EXISTS background_task_runs (\n run_id TEXT PRIMARY KEY,\n task_type TEXT NOT NULL,\n application_id TEXT,\n status TEXT NOT NULL DEFAULT 'running',\n items_processed INTEGER NOT NULL DEFAULT 0,\n items_failed INTEGER NOT NULL DEFAULT 0,\n summary TEXT,\n details TEXT,\n error_message TEXT,\n started_at INTEGER NOT NULL,\n completed_at INTEGER,\n created_at INTEGER NOT NULL,\n CHECK (status IN ('running', 'success', 'partial_success', 'error', 'skipped'))\n);\n\nCREATE INDEX IF NOT EXISTS idx_btr_app_started\n ON background_task_runs (application_id, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_btr_type_started\n ON background_task_runs (task_type, started_at DESC);\n";
19
+ /**
20
+ * The migration this package ships, in the `{ name, sql }` shape
21
+ * `@rexezuge/identity`'s `IDENTITY_MIGRATIONS` uses. The name is a suggestion;
22
+ * number it into the repo's own sequence.
23
+ */
24
+ declare const BACKGROUND_TASK_RUNS_MIGRATION: Readonly<{
25
+ name: string;
26
+ sql: string;
27
+ }>;
28
+ /**
29
+ * The upgrade for a table that predates `application_id` (AWS-AccessBridge's
30
+ * `0030_squash.sql`). **Not idempotent** — SQLite has no `ADD COLUMN IF NOT
31
+ * EXISTS` — so it goes into one numbered migration, applied once.
32
+ */
33
+ declare const BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID = "ALTER TABLE background_task_runs ADD COLUMN application_id TEXT;\n\nCREATE INDEX IF NOT EXISTS idx_btr_app_started\n ON background_task_runs (application_id, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_btr_type_started\n ON background_task_runs (task_type, started_at DESC);\n";
34
+ type BackgroundTaskRunStatus = 'running' | 'success' | 'partial_success' | 'error' | 'skipped';
35
+ /**
36
+ One stored row.
37
+ */
38
+ interface BackgroundTaskRunRow {
39
+ run_id: string;
40
+ task_type: string;
41
+ application_id: string | null;
42
+ status: BackgroundTaskRunStatus;
43
+ items_processed: number;
44
+ items_failed: number;
45
+ summary: string | null;
46
+ details: string | null;
47
+ error_message: string | null;
48
+ started_at: number;
49
+ completed_at: number | null;
50
+ created_at: number;
51
+ }
52
+ /**
53
+ One run, as a service reads it.
54
+ */
55
+ interface BackgroundTaskRun {
56
+ runId: string;
57
+ taskType: string;
58
+ applicationId: string | null;
59
+ status: BackgroundTaskRunStatus;
60
+ itemsProcessed: number;
61
+ itemsFailed: number;
62
+ summary: string | null;
63
+ details: unknown;
64
+ errorMessage: string | null;
65
+ startedAt: number;
66
+ completedAt: number | null;
67
+ createdAt: number;
68
+ }
69
+ /**
70
+ One page. `nextCursor` is omitted on the last page.
71
+ */
72
+ interface BackgroundTaskRunList {
73
+ runs: BackgroundTaskRun[];
74
+ nextCursor?: string;
75
+ }
76
+ /**
77
+ `TaskRunRecorder.startRun`'s argument.
78
+ */
79
+ interface StartTaskRunInput {
80
+ taskType: string;
81
+ applicationId?: string;
82
+ }
83
+ /**
84
+ `TaskRunRecorder.succeedRun`'s argument (runtime's `TaskRunSummary`).
85
+ */
86
+ interface CompleteTaskRunInput {
87
+ itemsProcessed: number;
88
+ itemsFailed: number;
89
+ summary?: string;
90
+ details?: unknown;
91
+ }
92
+ interface ListTaskRunsOptions {
93
+ taskType?: string;
94
+ applicationId?: string;
95
+ status?: BackgroundTaskRunStatus;
96
+ cursor?: string;
97
+ limit?: number;
98
+ }
99
+ export { BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID, BACKGROUND_TASK_RUNS_MIGRATION, BACKGROUND_TASK_RUNS_SCHEMA, BACKGROUND_TASK_RUNS_TABLE };
100
+ export type { BackgroundTaskRun, BackgroundTaskRunList, BackgroundTaskRunRow, BackgroundTaskRunStatus, CompleteTaskRunInput, ListTaskRunsOptions, StartTaskRunInput, };
101
+ //# sourceMappingURL=backgroundTaskRunsSchema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backgroundTaskRunsSchema.d.ts","sourceRoot":"","sources":["../src/backgroundTaskRunsSchema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,QAAA,MAAM,0BAA0B,yBAAyB,CAAC;AAE1D;;;;GAIG;AACH,QAAA,MAAM,2BAA2B,mtBAqBhC,CAAC;AAEF;;;;GAIG;AACH,QAAA,MAAM,8BAA8B,EAAE,QAA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AAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;EAEE;AACF,UAAU,iBAAiB;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;EAEE;AACF,UAAU,oBAAoB;IAC5B,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,uBAAuB,CAAC;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,OAAO,EAAE,uCAAuC,EAAE,8BAA8B,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,CAAC;AAC5I,YAAY,EACV,iBAAiB,EACjB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,CAAC"}
@@ -0,0 +1,29 @@
1
+ const _="background_task_runs",t=`CREATE TABLE IF NOT EXISTS background_task_runs (
2
+ run_id TEXT PRIMARY KEY,
3
+ task_type TEXT NOT NULL,
4
+ application_id TEXT,
5
+ status TEXT NOT NULL DEFAULT 'running',
6
+ items_processed INTEGER NOT NULL DEFAULT 0,
7
+ items_failed INTEGER NOT NULL DEFAULT 0,
8
+ summary TEXT,
9
+ details TEXT,
10
+ error_message TEXT,
11
+ started_at INTEGER NOT NULL,
12
+ completed_at INTEGER,
13
+ created_at INTEGER NOT NULL,
14
+ CHECK (status IN ('running', 'success', 'partial_success', 'error', 'skipped'))
15
+ );
16
+
17
+ CREATE INDEX IF NOT EXISTS idx_btr_app_started
18
+ ON background_task_runs (application_id, started_at DESC);
19
+
20
+ CREATE INDEX IF NOT EXISTS idx_btr_type_started
21
+ ON background_task_runs (task_type, started_at DESC);
22
+ `,a={name:"background_task_runs.sql",sql:t},T=`ALTER TABLE background_task_runs ADD COLUMN application_id TEXT;
23
+
24
+ CREATE INDEX IF NOT EXISTS idx_btr_app_started
25
+ ON background_task_runs (application_id, started_at DESC);
26
+
27
+ CREATE INDEX IF NOT EXISTS idx_btr_type_started
28
+ ON background_task_runs (task_type, started_at DESC);
29
+ `;export{T as BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID,a as BACKGROUND_TASK_RUNS_MIGRATION,t as BACKGROUND_TASK_RUNS_SCHEMA,_ as BACKGROUND_TASK_RUNS_TABLE};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/backgroundTaskRunsSchema.ts"],
4
+ "sourcesContent": ["/**\n * The `background_task_runs` table: its SQL, its row, and the DAO's I/O types.\n *\n * Converged from the four copies of the table (AWS-AccessBridge\n * `0030_squash.sql`, Mail-Bee `0001_initial.sql`, Mail-Meow\n * `0008_background_task_runs.sql`, Mail-Otter `0023_background_task_runs.sql`).\n * The canonical form is the Mail-* one — `application_id` included, both\n * indexes — **without** the `REFERENCES connected_applications(...)` clause,\n * which names a table the kit does not own. A repo that wants the cascade keeps\n * its own migration; the column shape is identical, so this DAO works on both.\n */\n\nconst BACKGROUND_TASK_RUNS_TABLE = 'background_task_runs';\n\n/**\n * The fresh-install DDL. Idempotent (`IF NOT EXISTS`), so a repo whose table\n * already exists can apply it unchanged; split and run it through\n * `executableStatements`, or paste it into a migration file.\n */\nconst BACKGROUND_TASK_RUNS_SCHEMA = `CREATE TABLE IF NOT EXISTS background_task_runs (\n run_id TEXT PRIMARY KEY,\n task_type TEXT NOT NULL,\n application_id TEXT,\n status TEXT NOT NULL DEFAULT 'running',\n items_processed INTEGER NOT NULL DEFAULT 0,\n items_failed INTEGER NOT NULL DEFAULT 0,\n summary TEXT,\n details TEXT,\n error_message TEXT,\n started_at INTEGER NOT NULL,\n completed_at INTEGER,\n created_at INTEGER NOT NULL,\n CHECK (status IN ('running', 'success', 'partial_success', 'error', 'skipped'))\n);\n\nCREATE INDEX IF NOT EXISTS idx_btr_app_started\n ON background_task_runs (application_id, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_btr_type_started\n ON background_task_runs (task_type, started_at DESC);\n`;\n\n/**\n * The migration this package ships, in the `{ name, sql }` shape\n * `@rexezuge/identity`'s `IDENTITY_MIGRATIONS` uses. The name is a suggestion;\n * number it into the repo's own sequence.\n */\nconst BACKGROUND_TASK_RUNS_MIGRATION: Readonly<{ name: string; sql: string }> = {\n name: 'background_task_runs.sql',\n sql: BACKGROUND_TASK_RUNS_SCHEMA,\n};\n\n/**\n * The upgrade for a table that predates `application_id` (AWS-AccessBridge's\n * `0030_squash.sql`). **Not idempotent** — SQLite has no `ADD COLUMN IF NOT\n * EXISTS` — so it goes into one numbered migration, applied once.\n */\nconst BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID = `ALTER TABLE background_task_runs ADD COLUMN application_id TEXT;\n\nCREATE INDEX IF NOT EXISTS idx_btr_app_started\n ON background_task_runs (application_id, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_btr_type_started\n ON background_task_runs (task_type, started_at DESC);\n`;\n\ntype BackgroundTaskRunStatus = 'running' | 'success' | 'partial_success' | 'error' | 'skipped';\n\n/**\nOne stored row.\n*/\ninterface BackgroundTaskRunRow {\n run_id: string;\n task_type: string;\n application_id: string | null;\n status: BackgroundTaskRunStatus;\n items_processed: number;\n items_failed: number;\n summary: string | null;\n details: string | null;\n error_message: string | null;\n started_at: number;\n completed_at: number | null;\n created_at: number;\n}\n\n/**\nOne run, as a service reads it.\n*/\ninterface BackgroundTaskRun {\n runId: string;\n taskType: string;\n applicationId: string | null;\n status: BackgroundTaskRunStatus;\n itemsProcessed: number;\n itemsFailed: number;\n summary: string | null;\n details: unknown;\n errorMessage: string | null;\n startedAt: number;\n completedAt: number | null;\n createdAt: number;\n}\n\n/**\nOne page. `nextCursor` is omitted on the last page.\n*/\ninterface BackgroundTaskRunList {\n runs: BackgroundTaskRun[];\n nextCursor?: string;\n}\n\n/**\n`TaskRunRecorder.startRun`'s argument.\n*/\ninterface StartTaskRunInput {\n taskType: string;\n applicationId?: string;\n}\n\n/**\n`TaskRunRecorder.succeedRun`'s argument (runtime's `TaskRunSummary`).\n*/\ninterface CompleteTaskRunInput {\n itemsProcessed: number;\n itemsFailed: number;\n summary?: string;\n details?: unknown;\n}\n\ninterface ListTaskRunsOptions {\n taskType?: string;\n applicationId?: string;\n status?: BackgroundTaskRunStatus;\n cursor?: string;\n limit?: number;\n}\n\nexport { BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID, BACKGROUND_TASK_RUNS_MIGRATION, BACKGROUND_TASK_RUNS_SCHEMA, BACKGROUND_TASK_RUNS_TABLE };\nexport type {\n BackgroundTaskRun,\n BackgroundTaskRunList,\n BackgroundTaskRunRow,\n BackgroundTaskRunStatus,\n CompleteTaskRunInput,\n ListTaskRunsOptions,\n StartTaskRunInput,\n};\n"],
5
+ "mappings": "AAYA,MAAMA,EAA6B,uBAO7BC,EAA8B;;;;;;;;;;;;;;;;;;;;;EA4B9BC,EAA0E,CAC9E,KAAM,2BACN,IAAKD,GAQDE,EAA0C;;;;;;;",
6
+ "names": ["BACKGROUND_TASK_RUNS_TABLE", "BACKGROUND_TASK_RUNS_SCHEMA", "BACKGROUND_TASK_RUNS_MIGRATION", "BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID"]
7
+ }
package/dist/index.d.ts CHANGED
@@ -9,4 +9,12 @@ export type { D1RetryOptions } from './D1Retry.ts';
9
9
  export type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';
10
10
  export { AesGcmKeyError, decryptSecret, encryptSecret, roundTripSecret, IV_BYTES, KEY_BYTES } from './aes-gcm.ts';
11
11
  export type { EncryptedEnvelope } from './aes-gcm.ts';
12
+ export { EncryptedDAO } from './EncryptedDAO.ts';
13
+ export type { EncryptionKeys } from './EncryptedDAO.ts';
14
+ export { BackgroundTaskRunDAO } from './BackgroundTaskRunDAO.ts';
15
+ export type { BackgroundTaskRunDAOOptions } from './BackgroundTaskRunDAO.ts';
16
+ export { BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID, BACKGROUND_TASK_RUNS_MIGRATION, BACKGROUND_TASK_RUNS_SCHEMA, BACKGROUND_TASK_RUNS_TABLE, } from './backgroundTaskRunsSchema.ts';
17
+ export type { BackgroundTaskRun, BackgroundTaskRunList, BackgroundTaskRunRow, BackgroundTaskRunStatus, CompleteTaskRunInput, ListTaskRunsOptions, StartTaskRunInput, } from './backgroundTaskRunsSchema.ts';
18
+ export { D1_BOOKMARK_HEADER, openSession, readBookmark, withBookmark } from './D1Session.ts';
19
+ export type { D1SessionConstraint, D1SessionLike, D1SessionSource } from './D1Session.ts';
12
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC5E,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACtF,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrF,YAAY,EAAE,cAAc,EAAE,M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jD,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,YAAY,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EACL,uCAAuC,EACvC,8BAA8B,EAC9B,2BAA2B,EAC3B,0BAA0B,GAC3B,MAAM,+BAA+B,CAAC;AACvC,YAAY,EACV,iBAAiB,EACjB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC7F,YAAY,EAAE,mBAAmB,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{BaseDAO as t,assertSqlIdentifier as E,statementTable as T}from"./BaseDAO.js";import{BIND_CEILING_PATTERN as i,DAILY_LIMIT_PATTERN as s,isD1DailyLimitError as S,isD1ErrorRetryable as R,nextMidnightUtc as _,RETRYABLE_PATTERNS as c,NON_RETRYABLE_PATTERNS as A}from"./D1ErrorClassifier.js";import{isMissingSchemaError as m,MISSING_SCHEMA_PATTERN as p}from"./isMissingSchemaError.js";import{executableStatements as I,isExecutable as N,splitSql as f}from"./splitSql.js";import{backoffMs as n,D1_RETRY_DEFAULTS as D,executeWithRetry as L,sleep as Y}from"./D1Retry.js";import{AesGcmKeyError as B,decryptSecret as M,encryptSecret as b,roundTripSecret as P,IV_BYTES as d,KEY_BYTES as u}from"./aes-gcm.js";export{B as AesGcmKeyError,i as BIND_CEILING_PATTERN,t as BaseDAO,D as D1_RETRY_DEFAULTS,s as DAILY_LIMIT_PATTERN,d as IV_BYTES,u as KEY_BYTES,p as MISSING_SCHEMA_PATTERN,A as NON_RETRYABLE_PATTERNS,c as RETRYABLE_PATTERNS,E as assertSqlIdentifier,n as backoffMs,M as decryptSecret,b as encryptSecret,I as executableStatements,L as executeWithRetry,S as isD1DailyLimitError,R as isD1ErrorRetryable,N as isExecutable,m as isMissingSchemaError,_ as nextMidnightUtc,P as roundTripSecret,Y as sleep,f as splitSql,T as statementTable};
1
+ import{BaseDAO as t,assertSqlIdentifier as o,statementTable as A}from"./BaseDAO.js";import{BIND_CEILING_PATTERN as T,DAILY_LIMIT_PATTERN as E,isD1DailyLimitError as R,isD1ErrorRetryable as S,nextMidnightUtc as N,RETRYABLE_PATTERNS as D,NON_RETRYABLE_PATTERNS as i}from"./D1ErrorClassifier.js";import{isMissingSchemaError as m,MISSING_SCHEMA_PATTERN as p}from"./isMissingSchemaError.js";import{executableStatements as B,isExecutable as I,splitSql as c}from"./splitSql.js";import{backoffMs as f,D1_RETRY_DEFAULTS as n,executeWithRetry as K,sleep as O}from"./D1Retry.js";import{AesGcmKeyError as l,decryptSecret as L,encryptSecret as M,roundTripSecret as C,IV_BYTES as G,KEY_BYTES as d}from"./aes-gcm.js";import{EncryptedDAO as y}from"./EncryptedDAO.js";import{BackgroundTaskRunDAO as Y}from"./BackgroundTaskRunDAO.js";import{BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID as b,BACKGROUND_TASK_RUNS_MIGRATION as h,BACKGROUND_TASK_RUNS_SCHEMA as g,BACKGROUND_TASK_RUNS_TABLE as H}from"./backgroundTaskRunsSchema.js";import{D1_BOOKMARK_HEADER as w,openSession as F,readBookmark as V,withBookmark as W}from"./D1Session.js";export{l as AesGcmKeyError,b as BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID,h as BACKGROUND_TASK_RUNS_MIGRATION,g as BACKGROUND_TASK_RUNS_SCHEMA,H as BACKGROUND_TASK_RUNS_TABLE,T as BIND_CEILING_PATTERN,Y as BackgroundTaskRunDAO,t as BaseDAO,w as D1_BOOKMARK_HEADER,n as D1_RETRY_DEFAULTS,E as DAILY_LIMIT_PATTERN,y as EncryptedDAO,G as IV_BYTES,d as KEY_BYTES,p as MISSING_SCHEMA_PATTERN,i as NON_RETRYABLE_PATTERNS,D as RETRYABLE_PATTERNS,o as assertSqlIdentifier,f as backoffMs,L as decryptSecret,M as encryptSecret,B as executableStatements,K as executeWithRetry,R as isD1DailyLimitError,S as isD1ErrorRetryable,I as isExecutable,m as isMissingSchemaError,N as nextMidnightUtc,F as openSession,V as readBookmark,C as roundTripSecret,O as sleep,c as splitSql,A as statementTable,W as withBookmark};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["export { BaseDAO, assertSqlIdentifier, statementTable } from './BaseDAO.ts';\nexport type { BilledRowsForTable, TrackedStatement, WriteResult } from './BaseDAO.ts';\nexport {\n BIND_CEILING_PATTERN,\n DAILY_LIMIT_PATTERN,\n isD1DailyLimitError,\n isD1ErrorRetryable,\n nextMidnightUtc,\n RETRYABLE_PATTERNS,\n NON_RETRYABLE_PATTERNS,\n} from './D1ErrorClassifier.ts';\nexport type { D1DailyLimit } from './D1ErrorClassifier.ts';\nexport { isMissingSchemaError, MISSING_SCHEMA_PATTERN } from './isMissingSchemaError.ts';\nexport { executableStatements, isExecutable, splitSql } from './splitSql.ts';\nexport { backoffMs, D1_RETRY_DEFAULTS, executeWithRetry, sleep } from './D1Retry.ts';\nexport type { D1RetryOptions } from './D1Retry.ts';\nexport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\nexport { AesGcmKeyError, decryptSecret, encryptSecret, roundTripSecret, IV_BYTES, KEY_BYTES } from './aes-gcm.ts';\nexport type { EncryptedEnvelope } from './aes-gcm.ts';\n"],
5
- "mappings": "AAAA,OAAS,WAAAA,EAAS,uBAAAC,EAAqB,kBAAAC,MAAsB,eAE7D,OACE,wBAAAC,EACA,uBAAAC,EACA,uBAAAC,EACA,sBAAAC,EACA,mBAAAC,EACA,sBAAAC,EACA,0BAAAC,MACK,yBAEP,OAAS,wBAAAC,EAAsB,0BAAAC,MAA8B,4BAC7D,OAAS,wBAAAC,EAAsB,gBAAAC,EAAc,YAAAC,MAAgB,gBAC7D,OAAS,aAAAC,EAAW,qBAAAC,EAAmB,oBAAAC,EAAkB,SAAAC,MAAa,eAGtE,OAAS,kBAAAC,EAAgB,iBAAAC,EAAe,iBAAAC,EAAe,mBAAAC,EAAiB,YAAAC,EAAU,aAAAC,MAAiB",
6
- "names": ["BaseDAO", "assertSqlIdentifier", "statementTable", "BIND_CEILING_PATTERN", "DAILY_LIMIT_PATTERN", "isD1DailyLimitError", "isD1ErrorRetryable", "nextMidnightUtc", "RETRYABLE_PATTERNS", "NON_RETRYABLE_PATTERNS", "isMissingSchemaError", "MISSING_SCHEMA_PATTERN", "executableStatements", "isExecutable", "splitSql", "backoffMs", "D1_RETRY_DEFAULTS", "executeWithRetry", "sleep", "AesGcmKeyError", "decryptSecret", "encryptSecret", "roundTripSecret", "IV_BYTES", "KEY_BYTES"]
4
+ "sourcesContent": ["export { BaseDAO, assertSqlIdentifier, statementTable } from './BaseDAO.ts';\nexport type { BilledRowsForTable, TrackedStatement, WriteResult } from './BaseDAO.ts';\nexport {\n BIND_CEILING_PATTERN,\n DAILY_LIMIT_PATTERN,\n isD1DailyLimitError,\n isD1ErrorRetryable,\n nextMidnightUtc,\n RETRYABLE_PATTERNS,\n NON_RETRYABLE_PATTERNS,\n} from './D1ErrorClassifier.ts';\nexport type { D1DailyLimit } from './D1ErrorClassifier.ts';\nexport { isMissingSchemaError, MISSING_SCHEMA_PATTERN } from './isMissingSchemaError.ts';\nexport { executableStatements, isExecutable, splitSql } from './splitSql.ts';\nexport { backoffMs, D1_RETRY_DEFAULTS, executeWithRetry, sleep } from './D1Retry.ts';\nexport type { D1RetryOptions } from './D1Retry.ts';\nexport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\nexport { AesGcmKeyError, decryptSecret, encryptSecret, roundTripSecret, IV_BYTES, KEY_BYTES } from './aes-gcm.ts';\nexport type { EncryptedEnvelope } from './aes-gcm.ts';\nexport { EncryptedDAO } from './EncryptedDAO.ts';\nexport type { EncryptionKeys } from './EncryptedDAO.ts';\nexport { BackgroundTaskRunDAO } from './BackgroundTaskRunDAO.ts';\nexport type { BackgroundTaskRunDAOOptions } from './BackgroundTaskRunDAO.ts';\nexport {\n BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID,\n BACKGROUND_TASK_RUNS_MIGRATION,\n BACKGROUND_TASK_RUNS_SCHEMA,\n BACKGROUND_TASK_RUNS_TABLE,\n} from './backgroundTaskRunsSchema.ts';\nexport type {\n BackgroundTaskRun,\n BackgroundTaskRunList,\n BackgroundTaskRunRow,\n BackgroundTaskRunStatus,\n CompleteTaskRunInput,\n ListTaskRunsOptions,\n StartTaskRunInput,\n} from './backgroundTaskRunsSchema.ts';\nexport { D1_BOOKMARK_HEADER, openSession, readBookmark, withBookmark } from './D1Session.ts';\nexport type { D1SessionConstraint, D1SessionLike, D1SessionSource } from './D1Session.ts';\n"],
5
+ "mappings": "AAAA,OAAS,WAAAA,EAAS,uBAAAC,EAAqB,kBAAAC,MAAsB,eAE7D,OACE,wBAAAC,EACA,uBAAAC,EACA,uBAAAC,EACA,sBAAAC,EACA,mBAAAC,EACA,sBAAAC,EACA,0BAAAC,MACK,yBAEP,OAAS,wBAAAC,EAAsB,0BAAAC,MAA8B,4BAC7D,OAAS,wBAAAC,EAAsB,gBAAAC,EAAc,YAAAC,MAAgB,gBAC7D,OAAS,aAAAC,EAAW,qBAAAC,EAAmB,oBAAAC,EAAkB,SAAAC,MAAa,eAGtE,OAAS,kBAAAC,EAAgB,iBAAAC,EAAe,iBAAAC,EAAe,mBAAAC,EAAiB,YAAAC,EAAU,aAAAC,MAAiB,eAEnG,OAAS,gBAAAC,MAAoB,oBAE7B,OAAS,wBAAAC,MAA4B,4BAErC,OACE,2CAAAC,EACA,kCAAAC,EACA,+BAAAC,EACA,8BAAAC,MACK,gCAUP,OAAS,sBAAAC,EAAoB,eAAAC,EAAa,gBAAAC,EAAc,gBAAAC,MAAoB",
6
+ "names": ["BaseDAO", "assertSqlIdentifier", "statementTable", "BIND_CEILING_PATTERN", "DAILY_LIMIT_PATTERN", "isD1DailyLimitError", "isD1ErrorRetryable", "nextMidnightUtc", "RETRYABLE_PATTERNS", "NON_RETRYABLE_PATTERNS", "isMissingSchemaError", "MISSING_SCHEMA_PATTERN", "executableStatements", "isExecutable", "splitSql", "backoffMs", "D1_RETRY_DEFAULTS", "executeWithRetry", "sleep", "AesGcmKeyError", "decryptSecret", "encryptSecret", "roundTripSecret", "IV_BYTES", "KEY_BYTES", "EncryptedDAO", "BackgroundTaskRunDAO", "BACKGROUND_TASK_RUNS_ADD_APPLICATION_ID", "BACKGROUND_TASK_RUNS_MIGRATION", "BACKGROUND_TASK_RUNS_SCHEMA", "BACKGROUND_TASK_RUNS_TABLE", "D1_BOOKMARK_HEADER", "openSession", "readBookmark", "withBookmark"]
7
7
  }
@@ -0,0 +1,22 @@
1
+ import type { D1Result } from './D1Types.ts';
2
+ /**
3
+ * Allow-list one SQL identifier segment. Values never go through this — they
4
+ * are always bound; this exists purely for the table/column names that
5
+ * parameter binding cannot express.
6
+ */
7
+ declare function assertSqlIdentifier(value: string, label: string): void;
8
+ declare function changesOf(result: D1Result): number;
9
+ /**
10
+ * The write verb's table name, or `null` when the SQL does not name one.
11
+ *
12
+ * The verb is anchored at the **start** of the statement, after leading
13
+ * whitespace and comments — a bare `/\bINSERT\s+INTO\s+(\w+)/` also matches a
14
+ * verb quoted inside a string literal, and a table read out of a `SELECT`'s
15
+ * projection is worse than no answer at all. An unreadable statement returns
16
+ * `null` for the caller to charge the worst case against, rather than throwing:
17
+ * accounting must not be the thing that turns a failed write into a crashed
18
+ * request.
19
+ */
20
+ declare function statementTable(sql: string): string | null;
21
+ export { assertSqlIdentifier, changesOf, statementTable };
22
+ //# sourceMappingURL=sqlStatement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlStatement.d.ts","sourceRoot":"","sources":["../src/sqlStatement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAE7C;;;;GAIG;AACH,iBAAS,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAI/D;AAED,iBAAS,SAAS,CAAC,MAAM,EAAE,QAAQ,GAAG,MAAM,CAE3C;AAED;;;;;;;;;;GAUG;AACH,iBAAS,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAqBlD;AAUD,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ var c=Object.defineProperty;var t=(n,e)=>c(n,"name",{value:e,configurable:!0});function l(n,e){if(!/^[A-Z_]\w*$/i.test(n))throw new Error(`Unsafe SQL identifier for ${e}: ${JSON.stringify(n)}`)}t(l,"assertSqlIdentifier");function f(n){return n.meta?.changes??0}t(f,"changesOf");function u(n){if(typeof n!="string")return null;let e=n.replace(/^\s+/,"");for(;e.startsWith("--");){const s=e.indexOf(`
2
+ `);if(s===-1)return null;e=e.slice(s+1).replace(/^\s+/,"")}const r=/^(?:INSERT|REPLACE|UPDATE|DELETE)\b/i.exec(e);return r?(e=i(e.slice(r[0].length)),e=i(e,/^(?:OR\s+[A-Z_]+\s+)?/i),e=i(e,/^(?:INTO\s+|FROM\s+)?/i),/^["`[]?([A-Z_]\w*)/i.exec(e)?.[1]??null):null}t(u,"statementTable");function i(n,e){const r=e?.exec(n)?.[0]??"";return n.slice(r.length).replace(/^\s+/,"")}t(i,"consume");export{l as assertSqlIdentifier,f as changesOf,u as statementTable};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/sqlStatement.ts"],
4
+ "sourcesContent": ["import type { D1Result } from './D1Types.ts';\n\n/**\n * Allow-list one SQL identifier segment. Values never go through this — they\n * are always bound; this exists purely for the table/column names that\n * parameter binding cannot express.\n */\nfunction assertSqlIdentifier(value: string, label: string): void {\n if (!/^[A-Z_]\\w*$/i.test(value)) {\n throw new Error(`Unsafe SQL identifier for ${label}: ${JSON.stringify(value)}`);\n }\n}\n\nfunction changesOf(result: D1Result): number {\n return (result.meta as { changes?: number })?.changes ?? 0;\n}\n\n/**\n * The write verb's table name, or `null` when the SQL does not name one.\n *\n * The verb is anchored at the **start** of the statement, after leading\n * whitespace and comments — a bare `/\\bINSERT\\s+INTO\\s+(\\w+)/` also matches a\n * verb quoted inside a string literal, and a table read out of a `SELECT`'s\n * projection is worse than no answer at all. An unreadable statement returns\n * `null` for the caller to charge the worst case against, rather than throwing:\n * accounting must not be the thing that turns a failed write into a crashed\n * request.\n */\nfunction statementTable(sql: string): string | null {\n if (typeof sql !== 'string') return null;\n let rest = sql.replace(/^\\s+/, '');\n // A `while` rather than a repeated strip: comments are the only noise, and a\n // bounded loop cannot be made quadratic by a statement full of them.\n while (rest.startsWith('--')) {\n const newline = rest.indexOf('\\n');\n if (newline === -1) return null;\n rest = rest.slice(newline + 1).replace(/^\\s+/, '');\n }\n const verb = /^(?:INSERT|REPLACE|UPDATE|DELETE)\\b/i.exec(rest);\n if (!verb) return null;\n rest = consume(rest.slice(verb[0].length));\n\n // `INSERT OR REPLACE`, `UPDATE OR IGNORE` — a conflict clause between the verb and\n // the table. This is why the parse is stepwise rather than one anchored pattern:\n // a single pattern either grows a nested quantifier the complexity gate rejects,\n // or drops the clause and reads `REPLACE` as a table name.\n rest = consume(rest, /^(?:OR\\s+[A-Z_]+\\s+)?/i);\n rest = consume(rest, /^(?:INTO\\s+|FROM\\s+)?/i);\n return /^[\"`[]?([A-Z_]\\w*)/i.exec(rest)?.[1] ?? null;\n}\n\n/**\n * Drop a leading match and the whitespace after it.\n */\nfunction consume(sql: string, pattern?: RegExp): string {\n const matched = pattern?.exec(sql)?.[0] ?? '';\n return sql.slice(matched.length).replace(/^\\s+/, '');\n}\n\nexport { assertSqlIdentifier, changesOf, statementTable };\n"],
5
+ "mappings": "+EAOA,SAASA,EAAoBC,EAAeC,EAAa,CACvD,GAAI,CAAC,eAAe,KAAKD,CAAK,EAC5B,MAAM,IAAI,MAAM,6BAA6BC,CAAK,KAAK,KAAK,UAAUD,CAAK,CAAC,EAAE,CAElF,CAJSE,EAAAH,EAAA,uBAMT,SAASI,EAAUC,EAAgB,CACjC,OAAQA,EAAO,MAA+B,SAAW,CAC3D,CAFSF,EAAAC,EAAA,aAeT,SAASE,EAAeC,EAAW,CACjC,GAAI,OAAOA,GAAQ,SAAU,OAAO,KACpC,IAAIC,EAAOD,EAAI,QAAQ,OAAQ,EAAE,EAGjC,KAAOC,EAAK,WAAW,IAAI,GAAG,CAC5B,MAAMC,EAAUD,EAAK,QAAQ;CAAI,EACjC,GAAIC,IAAY,GAAI,OAAO,KAC3BD,EAAOA,EAAK,MAAMC,EAAU,CAAC,EAAE,QAAQ,OAAQ,EAAE,CACnD,CACA,MAAMC,EAAO,uCAAuC,KAAKF,CAAI,EAC7D,OAAKE,GACLF,EAAOG,EAAQH,EAAK,MAAME,EAAK,CAAC,EAAE,MAAM,CAAC,EAMzCF,EAAOG,EAAQH,EAAM,wBAAwB,EAC7CA,EAAOG,EAAQH,EAAM,wBAAwB,EACtC,sBAAsB,KAAKA,CAAI,IAAI,CAAC,GAAK,MAT9B,IAUpB,CArBSL,EAAAG,EAAA,kBA0BT,SAASK,EAAQJ,EAAaK,EAAgB,CAC5C,MAAMC,EAAUD,GAAS,KAAKL,CAAG,IAAI,CAAC,GAAK,GAC3C,OAAOA,EAAI,MAAMM,EAAQ,MAAM,EAAE,QAAQ,OAAQ,EAAE,CACrD,CAHSV,EAAAQ,EAAA",
6
+ "names": ["assertSqlIdentifier", "value", "label", "__name", "changesOf", "result", "statementTable", "sql", "rest", "newline", "verb", "consume", "pattern", "matched"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/d1",
3
- "version": "1.9.4",
3
+ "version": "1.11.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,8 +25,8 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@rexezuge/errors": "1.9.4",
29
- "@rexezuge/shared": "1.9.4"
28
+ "@rexezuge/errors": "1.11.0",
29
+ "@rexezuge/shared": "1.11.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "26.6.4",
@@ -37,6 +37,7 @@
37
37
  "scripts": {
38
38
  "build": "tsc -p tsconfig.json && node ../../scripts/minify-dist.mjs",
39
39
  "typecheck": "tsc -p tsconfig.test.json --noEmit",
40
- "test": "vitest run"
40
+ "test": "vitest run",
41
+ "test:coverage": "vitest run --coverage"
41
42
  }
42
43
  }