cloudrop 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +34 -4
  3. package/dist/adapters/drizzle.d.ts +1 -1
  4. package/dist/adapters/drizzle.js +3 -3
  5. package/dist/adapters/drizzle.js.map +1 -1
  6. package/dist/adapters/prisma.d.ts +1 -1
  7. package/dist/adapters/prisma.js +1 -1
  8. package/dist/adapters/sql.d.ts +4 -1
  9. package/dist/adapters/sql.js +8 -1
  10. package/dist/adapters/sql.js.map +1 -1
  11. package/dist/cli.js +2045 -0
  12. package/dist/{client-Dj6ON4MN.d.ts → client-CP_ajLF4.d.ts} +43 -25
  13. package/dist/{client-Y1zUEbCj.js → client-DxP3uv8V.js} +172 -44
  14. package/dist/client-DxP3uv8V.js.map +1 -0
  15. package/dist/client.d.ts +3 -3
  16. package/dist/client.js +1 -1
  17. package/dist/errors-CUxMmFAe.js.map +1 -1
  18. package/dist/index.d.ts +92 -7
  19. package/dist/index.js +432 -152
  20. package/dist/index.js.map +1 -1
  21. package/dist/next.d.ts +1 -1
  22. package/dist/node.d.ts +1 -1
  23. package/dist/react.d.ts +18 -4
  24. package/dist/react.js +23 -3
  25. package/dist/react.js.map +1 -1
  26. package/dist/{route-CspI1Ypt.js → route-C8-YjzdY.js} +3 -2
  27. package/dist/{route-CspI1Ypt.js.map → route-C8-YjzdY.js.map} +1 -1
  28. package/dist/{store-BfCJejGh.d.ts → store-B539nY3J.d.ts} +41 -3
  29. package/dist/testing.d.ts +81 -0
  30. package/dist/testing.js +1243 -0
  31. package/dist/testing.js.map +1 -0
  32. package/dist/{transactional-DnvnGsVH.js → transactional-CiNwMiDb.js} +215 -105
  33. package/dist/transactional-CiNwMiDb.js.map +1 -0
  34. package/dist/{types-BrAx3dA4.d.ts → types-CFfMw-n_.d.ts} +1 -1
  35. package/docs/README.md +30 -0
  36. package/docs/bucket-setup.md +226 -0
  37. package/docs/client.md +386 -0
  38. package/docs/command.md +129 -0
  39. package/docs/deployment.md +169 -0
  40. package/docs/errors.md +150 -0
  41. package/docs/hono.md +276 -0
  42. package/docs/react.md +508 -0
  43. package/docs/resume.md +253 -0
  44. package/docs/server.md +603 -0
  45. package/docs/store.md +804 -0
  46. package/docs/testing-your-app.md +328 -0
  47. package/docs/troubleshooting.md +176 -0
  48. package/package.json +16 -8
  49. package/dist/client-Y1zUEbCj.js.map +0 -1
  50. package/dist/transactional-DnvnGsVH.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -6,6 +6,121 @@ Every notable change to the `cloudrop` package. The format follows
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.3.0 - 2026-11-21
10
+
11
+ In short: you can now test your upload routes without a bucket (`cloudrop/testing`), and one command checks and sets
12
+ up your bucket (`cloudrop doctor`, `cloudrop setup`). Everything was then tested against a real R2 bucket and a real
13
+ database, and the problems found there are fixed below. The guides now ship inside the package (`docs/`).
14
+
15
+ ### Added
16
+
17
+ - **`cloudrop/testing`:** `testBucket()`, `testClient()` and `memoryStore()` let an app test its routes, `authorize`,
18
+ metadata, quotas, `onComplete` and whole uploads in Vitest, Bun or `node:test`, with no bucket, browser or network.
19
+ The test client is the real client, wired to `cloudrop.handler` in-process; the test bucket is the in-process fake
20
+ of R2 that cloudrop's own tests use. Guide: [Testing your app](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/testing-your-app.md) (`M9-T1` to
21
+ `M9-T9`).
22
+ - **The `cloudrop` command** (Node 24+ and Bun): `cloudrop doctor --origin <origin>` checks the storage settings,
23
+ `CLOUDROP_SECRET`, the bucket and its CORS and lifecycle rules in plain words (exit 0, 1 or 2).
24
+ `cloudrop setup --origin <origin>` prints the rules and the Wrangler and AWS CLI commands; with `--apply` it adds
25
+ cloudrop's rules through the S3 API and keeps every other rule (`--dry-run`, `--replace`). It never prints a
26
+ setting's value. Guide: [The cloudrop command](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/command.md) (`M9-C1` to `M9-C9`).
27
+ - `StorageDriver` gains optional `putBucketCors` and `putBucketLifecycle`. `BucketCorsRule` gains `id` and
28
+ `maxAgeSeconds`, and `BucketLifecycleRule` gains `sourceXml`.
29
+ - **The guides ship in the package:** `node_modules/cloudrop/docs/` holds the user guides of this exact version, with
30
+ an index in `docs/README.md`; links to the project's history point at GitHub.
31
+
32
+ ### Changed
33
+
34
+ - Reading bucket settings refuses a configuration with CDATA, comments or namespace prefixes, with a non-retryable
35
+ `STORAGE_ERROR`, and reads an empty self-closing configuration as no rules.
36
+ - **Upload URLs end at least 15 minutes before their token**, so a `PUT` started near the deadline can still be
37
+ completed: `/sign` answers `UPLOAD_EXPIRED` in a token's last 15 minutes, and the client gets a new ticket or starts
38
+ over there (`M9-H3`). Measured on R2: a URL's expiry is checked when the request starts, not when its body ends.
39
+ - The `cloudrop` command names the setting to fix when the bucket does not answer, suggests the exact origin for one
40
+ that is not, refuses a pattern such as `https://*.example.com`, notes a misspelt `CLOUDROP_*` name, offers
41
+ `--replace` only after a refused read, and ends a dry run by pointing at `--apply` (`M9-H100` to `M9-H104`,
42
+ `M9-H107`). `setup --apply` was measured on R2: both writes accepted, other rules kept, rule IDs kept.
43
+
44
+ ### Fixed
45
+
46
+ Found by testing against a real R2 bucket and as a new user before this release (`M9-H`):
47
+
48
+ - A file whose type has parameters (`text/csv;charset=utf-8`, and every `text/plain` `File` under `bun test`) was
49
+ refused as "not a valid MIME type"; it is stored with its essence type (`M9-H1`).
50
+ - A storage `HEAD` refused because the server's clock is more than 15 minutes off says so, instead of pointing at the
51
+ credentials (`M9-H2`); a `401` (R2's answer to an unknown access key) points at the access key ID and secret instead
52
+ of the object key (`M9-H5`).
53
+ - A part sent to a multipart upload aborted elsewhere fails as `NO_SUCH_UPLOAD`, not `UPLOAD_REJECTED` (`M9-H4`).
54
+ - Two `resume()` calls of one upload in the same page could let the second one win when the first one's file check
55
+ was slower; the first call now always decides (`M9-H7`).
56
+ - `api.deletePrefix` refused a folder whose name has accents when R2 listed a key in the other Unicode form, so the
57
+ folder could never be deleted (`M9-H6`).
58
+ - With `transaction: true`, a node-postgres connection that dies while `onComplete` runs no longer stops the process;
59
+ the completion answers a retryable error (`M9-H50`). The store guide now asks for `pool.on("error")` and gives a
60
+ workaround for drizzle-orm 0.45.
61
+ - Owners, file ids and cursors containing NUL, and cursor times after the year 9999, are refused with `INVALID_INPUT`
62
+ instead of a retryable `SERVER_ERROR` on Postgres; an `owner()` that returns NUL is the route's bug (`M9-H51`).
63
+
64
+ ## 0.2.0 - 2026-11-20
65
+
66
+ ### Added
67
+
68
+ - **`client.close()`** stops a client: every running and queued upload of every route stops, and `start()`,
69
+ `upload()` and `resume()` answer the new error code `CLIENT_CLOSED` afterwards. Without options it acts like closing
70
+ the tab: a multipart upload keeps its record and its parts, so the same user can resume it. `close({ abort: true })`
71
+ cancels on the server too, for sign-out: `await close({ abort: true })`, then `forget()`, then your auth library's
72
+ sign-out. A file whose `/complete` may have finished is always kept. `createUploadHooks()` returns the same `close()`
73
+ (`M8-L1` to `M8-L4`, `M8-L7`).
74
+ - **`headers` client option** for requests to the upload server only (`/upload`, `/sign`, `/complete`, `/abort`),
75
+ never for bucket `PUT`s: an object, or a function (possibly async) called before each request, so a bearer token is
76
+ fresh on each. A function that fails or hangs fails that request unsent with `NETWORK_ERROR` (`M8-L5`, `M8-L6`).
77
+ - **`useResumable().discarding`**: the ids being discarded, to disable a second press of Discard (`M8-L8`).
78
+ - **`api.files({ owner, route?, limit?, cursor? })`**: an owner's completed files, newest first, a page at a time
79
+ (`M8-A1`).
80
+ - **`api.eraseOwner(owner, { graceMs?, signal? })`** removes everything an owner uploaded without needing your key
81
+ layout: it revokes unfinished uploads, deletes completed files and reports `done` once nothing can still land. Run it
82
+ until it reports `done` (`M8-A5`).
83
+ - **Route option `replace: true`** (needs a store and `owner`): one file per owner on the route, such as an avatar. The
84
+ previous file is deleted in the same write that records the next one's completion, and of two completions at once
85
+ exactly one file survives. Read the kept file with `api.files({ owner, route, limit: 1 })` (`M8-A6`).
86
+ - **`api.sweep({ all: true, signal? })`** runs every page in one call and sums the reports; the store guide has cron
87
+ recipes for Node and Cloudflare Workers (`M8-A7`).
88
+ - Exported types `FilesOptions`, `FilesPage`, `EraseOptions`, `EraseReport` and `Completion`.
89
+
90
+ ### Changed
91
+
92
+ - **Type-level breaks:** `CloudropErrorCode` and `ClientErrorCode` gain `CLIENT_CLOSED`, which breaks an exhaustive
93
+ `switch` over them. New members break a hand-written mock: `CloudropClient.close()`, `UploadHooks.close()`,
94
+ `UseResumable.discarding`, and `FileApi`/`StoreFileApi`'s `files()` and `eraseOwner()`.
95
+ - **A store written by hand** must implement the new `CloudropStore.list()`, and `complete()` takes `{ replace }` and
96
+ answers `Completion` with `replaced`. Every shipped adapter does (`M8-A3`).
97
+ - `api.deleteFile` deletes the object at once and marks the row cleaned only once a late `PUT` can no longer land
98
+ (about 1 h 15 min after completion); until then the sweep checks the key again. The sweep follows the same rule: it
99
+ marks an ended row cleaned, and counts it in `cleaned`, only once no upload URL of the row can still put an object
100
+ back, and stamps `cleaned_at` with the time its check started (`M8-A4`).
101
+ - The React "Signed-in users" recipe, the guides and the Vite example use `close()` instead of each route's `abort`.
102
+ "Send a bearer token" uses `headers`.
103
+
104
+ ### Fixed
105
+
106
+ - A bearer token no longer needs a custom `fetch`, which moved bucket `PUT`s off `XMLHttpRequest` and its byte-by-byte
107
+ progress.
108
+ - A file still waiting for its ticket can no longer ask `/upload` after sign-out.
109
+ - The sweep could mark a row cleaned up to 15 minutes before its last upload URL ran out when the row ended soon after
110
+ it left `pending` (an `/abort` or a revoke right after `/upload`), so a slow `PUT` landing then stayed in the bucket
111
+ (`M8-A4`).
112
+ - Without a store, `/complete` sends `data: null` when `onComplete` returns a value JSON cannot carry (a function, a
113
+ Symbol); the answer used to have no `data`, which the client refused (`M8-Q34`).
114
+
115
+ ### Migration
116
+
117
+ - **Database store:** the owner index becomes `(owner, status, created_at)`, which `api.files` and `eraseOwner` read:
118
+ `CREATE INDEX "cloudrop_files_owner_status_created_at_idx" ON "cloudrop_files" (owner, status, created_at); DROP
119
+ INDEX "cloudrop_files_owner_status_idx";` (`CONCURRENTLY` on a large Postgres table). Drizzle and Prisma users
120
+ generate a migration; when drizzle-kit asks whether the new index renames the old one, answer that it is created.
121
+ With `tables.schema` or your own table names, use those names. Without the migration the store works, only slower
122
+ for owners with many files (`M8-A2`).
123
+
9
124
  ## 0.1.1 - 2026-11-20
10
125
 
11
126
  ### Fixed
package/README.md CHANGED
@@ -70,22 +70,47 @@ export function AvatarPicker() {
70
70
 
71
71
  Without React, `createCloudropClient` from `cloudrop/client` gives you `upload()`, which resolves to `{ data, error }`.
72
72
 
73
- When users sign in, give each user a client of their own and cancel their uploads before `forget()` at sign-out:
74
- [Signed-in users](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/react.md#signed-in-users).
73
+ When users sign in, give each user a client of their own, and at sign-out `await close({ abort: true })` before
74
+ `forget()`: [Signed-in users](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/react.md#signed-in-users). A
75
+ bearer token for your API goes in the client's `headers` option, which never reaches the bucket.
75
76
 
76
77
  `onComplete` runs at least once per file: a client that lost the answer to `/complete` asks again, so make it
77
78
  idempotent before it sends an email or calls a webhook. To keep a row per upload in your own database, with a quota per
78
- user, revocation and a sweep for abandoned uploads, pass a store from `cloudrop/adapters/sql`,
79
+ user, revocation, a listing of each user's files, one file per user on routes such as avatars (`replace: true`),
80
+ erasure of a user's files (`api.eraseOwner`) and a sweep for abandoned uploads, pass a store from `cloudrop/adapters/sql`,
79
81
  `cloudrop/adapters/drizzle` or `cloudrop/adapters/prisma`. With a store, `onComplete` runs once per file, except after a
80
82
  crash, a throw or a run longer than its lease; only its writes through `tx` on Postgres with `transaction: true` commit
81
83
  exactly once: [Database store](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/store.md#what-it-guarantees).
82
84
 
85
+ ## Testing your app
86
+
87
+ `cloudrop/testing` runs your server and the real client in one process, in Vitest, Bun or `node:test`, with no bucket,
88
+ browser or network:
89
+
90
+ ```ts
91
+ import { createCloudrop } from "cloudrop";
92
+ import { testBucket, testClient } from "cloudrop/testing";
93
+
94
+ const bucket = testBucket();
95
+ const cloudrop = createCloudrop({ storage: bucket.storage, secret, routes: { avatar } });
96
+ const client = testClient(cloudrop, { bucket, headers: { cookie: "session=alice" } });
97
+
98
+ const { data, error } = await client.upload("avatar", new File([png], "me.png", { type: "image/png" }));
99
+ expect(bucket.object(data!.file.key)?.size).toBe(png.byteLength);
100
+ ```
101
+
102
+ `memoryStore()` stands in for a database store. Examples for `authorize`, metadata, quotas, `onComplete` and multipart
103
+ files: [Testing your app](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/testing-your-app.md).
104
+
83
105
  ## Bucket setup
84
106
 
85
107
  The browser uploads to the bucket directly, so the bucket needs a CORS rule that allows `PUT` from your page's origin
86
108
  with the headers cloudrop signs (`content-type`, `content-disposition`, `if-none-match`, `x-amz-meta-cloudrop-id`) and
87
109
  exposes `ETag` and `Retry-After`, plus a lifecycle rule that aborts incomplete multipart uploads. Both rules, with the
88
110
  Wrangler and AWS CLI commands: [Bucket setup](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/bucket-setup.md).
111
+ `npx cloudrop setup --origin <origin> --apply` adds both and keeps the bucket's other rules, and `npx cloudrop doctor
112
+ --origin <origin>` checks the settings, the bucket and its rules:
113
+ [The cloudrop command](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/command.md).
89
114
 
90
115
  ## Documentation
91
116
 
@@ -96,9 +121,14 @@ Wrangler and AWS CLI commands: [Bucket setup](https://github.com/vcode-sh/cloudr
96
121
  [Database store](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/store.md) ·
97
122
  [Deployment](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/deployment.md) ·
98
123
  [Resume after reload](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/resume.md) ·
124
+ [Testing your app](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/testing-your-app.md) ·
99
125
  [Hono guide](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/hono.md) ·
100
126
  [Errors](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/errors.md) ·
101
- [Troubleshooting](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/troubleshooting.md)
127
+ [Troubleshooting](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/troubleshooting.md) ·
128
+ [The cloudrop command](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/command.md)
129
+
130
+ The same guides ship inside the package, for this exact version: `node_modules/cloudrop/docs/README.md` lists them, so
131
+ your editor and your coding agent can read them offline.
102
132
 
103
133
  Runs on Node.js 24+, Bun, Deno and Cloudflare Workers, with zero runtime dependencies. `cloudrop/react` needs React 18
104
134
  or 19, an optional peer dependency.
@@ -1,4 +1,4 @@
1
- import { a as FileStatus, c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
1
+ import { l as TransactionalStore, n as CloudropStore, o as FileStatus } from "../store-B539nY3J.js";
2
2
  import { t as StoreTables } from "../tables-DZnw2sPK.js";
3
3
  import { r as SqlRow } from "../executor-CEA7WV2W.js";
4
4
  import { SQL } from "drizzle-orm";
@@ -1,5 +1,5 @@
1
1
  import { n as configError } from "../errors-CUxMmFAe.js";
2
- import { i as sequential, n as sqlStore, r as tableNames, t as withRoute } from "../transactional-DnvnGsVH.js";
2
+ import { i as sequential, n as sqlStore, r as tableNames, t as withRoute } from "../transactional-CiNwMiDb.js";
3
3
  import { t as d1Executor } from "../d1-BY2c5bcL.js";
4
4
  import { sql } from "drizzle-orm";
5
5
  import { PgSchema, bigint, check, index, integer, pgTable, text, timestamp } from "drizzle-orm/pg-core";
@@ -135,7 +135,7 @@ function cloudropPgTables(options = {}) {
135
135
  index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),
136
136
  index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),
137
137
  index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),
138
- index(`${names.files}_owner_status_idx`).on(t.owner, t.status),
138
+ index(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),
139
139
  index(`${names.files}_key_idx`).on(t.key),
140
140
  index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey)
141
141
  ]),
@@ -184,7 +184,7 @@ function cloudropSqliteTables(options = {}) {
184
184
  index$1(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),
185
185
  index$1(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),
186
186
  index$1(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),
187
- index$1(`${names.files}_owner_status_idx`).on(t.owner, t.status),
187
+ index$1(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),
188
188
  index$1(`${names.files}_key_idx`).on(t.key),
189
189
  index$1(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey)
190
190
  ]),
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle.js","names":["time","count","text","integer","index"],"sources":["../../src/adapters/drizzle/statement.ts","../../src/adapters/drizzle/postgres.ts","../../src/adapters/drizzle/sqlite.ts","../../src/adapters/drizzle/postgres-tables.ts","../../src/adapters/drizzle/sqlite-tables.ts","../../src/adapters/drizzle.ts"],"sourcesContent":["// A core statement as Drizzle SQL. Drizzle's `sql.raw` takes no parameters, so the text is cut at each placeholder the\n// core's binder wrote (store/sql/bind.ts) and every placeholder becomes a Drizzle parameter; Drizzle numbers them\n// again as it renders, `$1`, `$2`… on Postgres and `?` on SQLite, and the `::type` casts after them stay in the text.\n\nimport { type SQL, type SQLChunk, sql } from \"drizzle-orm\";\nimport type { SqlDialect, SqlStatement } from \"../../store/sql/executor.ts\";\n\nconst PLACEHOLDER: Record<SqlDialect, RegExp> = { postgres: /\\$(\\d+)/g, sqlite: /\\?/g };\n\nexport function drizzleSql(dialect: SqlDialect, { sql: text, params }: SqlStatement): SQL {\n const chunks: SQLChunk[] = [];\n let end = 0;\n for (const [position, match] of [...text.matchAll(PLACEHOLDER[dialect])].entries()) {\n // `$n` names its parameter; SQLite's `?` takes the next one.\n const value = params[match[1] === undefined ? position : Number(match[1]) - 1];\n chunks.push(sql.raw(text.slice(end, match.index)), sql.param(value));\n end = match.index + match[0].length;\n }\n chunks.push(sql.raw(text.slice(end)));\n return sql.join(chunks);\n}\n","// Drizzle on Postgres: statements through `execute`, batches and transactions through `db.transaction`. The database is\n// described by the two members used here, so any Drizzle Postgres driver fits and the library needs no Drizzle types\n// beyond `SQL`; drizzle.db.integration.test.ts runs it on node-postgres and postgres.js.\n\nimport type { SQL } from \"drizzle-orm\";\nimport { configError } from \"../../errors.ts\";\nimport { type SqlRow, type SqlStatement, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a Drizzle Postgres database or transaction. */\nexport interface DrizzlePostgresQueryable {\n execute(query: SQL): PromiseLike<unknown>;\n}\n\n/** A Drizzle Postgres database: `drizzle(pool)` from `drizzle-orm/node-postgres`, `drizzle-orm/postgres-js`, … */\nexport interface DrizzlePostgres extends DrizzlePostgresQueryable {\n transaction<T>(run: (tx: DrizzlePostgresQueryable) => Promise<T>): Promise<T>;\n}\n\n/** The `tx` Drizzle hands to `db.transaction`'s callback, for this database's driver and schema. */\nexport type DrizzleTransaction<TDb extends DrizzlePostgres> = Parameters<Parameters<TDb[\"transaction\"]>[0]>[0];\n\n/** How a result looked, for the message: its keys, never its values. */\nconst shapeOf = (result: unknown): string =>\n typeof result === \"object\" && result !== null ? `{ ${Object.keys(result).join(\", \")} }` : typeof result;\n\n/** node-postgres answers `{ rows }`, postgres.js the rows themselves. */\nasync function rowsOf(target: DrizzlePostgresQueryable, statement: SqlStatement): Promise<SqlRow[]> {\n const result = await target.execute(drizzleSql(\"postgres\", statement));\n if (Array.isArray(result)) return result;\n const { rows } = (result ?? {}) as { rows?: unknown };\n if (Array.isArray(rows)) return rows;\n throw configError(\n `This Drizzle driver's execute() answered ${shapeOf(result)}, not rows or { rows }. Use drizzleStore with node-postgres or postgres.js, or build an executor for cloudrop/adapters/sql.`,\n );\n}\n\n/** The executor's statements on the database or a transaction, in order when batched. */\nconst on = (target: DrizzlePostgresQueryable) =>\n sequential(\"postgres\", (sql, params) => rowsOf(target, { sql, params }));\n\n/**\n * True for a node-postgres client that is not a pool: Drizzle's node-postgres driver checks out a connection for a\n * transaction only from a pool (its own test: the constructor's name contains \"Pool\"), and otherwise runs BEGIN on the\n * client's one connection, which every other request is using too.\n */\nfunction isSingleConnection(db: DrizzlePostgres): boolean {\n const client: unknown = (db as { $client?: unknown }).$client;\n if (typeof client !== \"object\" || client === null) return false;\n const { query, connect } = client as { query?: unknown; connect?: unknown };\n return typeof query === \"function\" && typeof connect === \"function\" && !client.constructor.name.includes(\"Pool\");\n}\n\n/** The executor; its `transaction` runs `onComplete` in a Drizzle transaction whose `tx` the route gets. */\nexport function postgresExecutor(db: DrizzlePostgres): TransactionalSqlExecutor<DrizzlePostgresQueryable> {\n if (isSingleConnection(db)) {\n throw configError(\n \"drizzleStore needs a pg Pool, not a single pg Client: a transaction on the one shared connection would take every other request's statements with it. Pass drizzle(new Pool({ connectionString })), or use postgres.js.\",\n );\n }\n return {\n ...on(db),\n batch: (statements) => db.transaction((tx) => on(tx).batch(statements)),\n transaction: (run) => db.transaction((tx) => run(on(tx), tx)),\n };\n}\n","// Drizzle on SQLite, through `all` and `run`. A synchronous driver (better-sqlite3) runs a batch in\n// `db.transaction(…, { behavior: \"immediate\" })`, which ends before any other call can start. An asynchronous one with\n// an atomic batch (libsql/Turso) runs it through `db.batch`, ordered and all-or-nothing. D1 runs through the binding\n// Drizzle keeps as `db.$client`, as `d1Executor` does: drizzle-orm 0.45's D1 `batch` cannot take a raw statement with\n// parameters (it reads a `stmt` that `db.run(sql)` never prepares; measured in the Wrangler lane). None has transaction\n// mode: an interactive transaction would hold the only writer across `onComplete`'s awaits.\n\nimport type { SQL } from \"drizzle-orm\";\nimport type { BatchItem } from \"drizzle-orm/batch\";\nimport type { SqlExecutor, SqlRow, SqlStatement } from \"../../store/sql/executor.ts\";\nimport { type D1Database, d1Executor } from \"../sql/d1.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a synchronous Drizzle SQLite database or transaction. */\nexport interface DrizzleSqliteQueryable {\n all<T = unknown>(query: SQL): T[];\n run(query: SQL): unknown;\n}\n\n/**\n * A Drizzle SQLite database over a synchronous driver: `drizzle(new Database(path))` from `drizzle-orm/better-sqlite3`.\n * `transaction` is not generic here: drizzle-orm 0.45 types its answer as the callback's, 1.0 through a conditional type\n * that refuses async callbacks, and both fit this shape.\n */\nexport interface DrizzleSqlite extends DrizzleSqliteQueryable {\n transaction(run: (tx: DrizzleSqliteQueryable) => SqlRow[][], config?: { behavior?: \"immediate\" }): unknown;\n}\n\n/**\n * A Drizzle SQLite database over an asynchronous driver with an atomic batch: `drizzle-orm/libsql` (Turso) or\n * `drizzle-orm/d1`. `all` and `run` build a statement that runs when awaited, or as part of `batch`.\n */\nexport interface DrizzleAsyncSqlite {\n all<T = unknown>(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<T[]>;\n run(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<unknown>;\n batch(statements: readonly [BatchItem<\"sqlite\">, ...BatchItem<\"sqlite\">[]]): PromiseLike<readonly unknown[]>;\n}\n\n/**\n * Whether the statement answers rows: better-sqlite3 refuses `all` for one that does not. Every statement the core\n * writes either starts with SELECT or ends its write with a RETURNING clause when it needs rows back. A table named\n * `returning` is quoted, so the word is followed by `\"`, never by whitespace.\n */\nconst ANSWERS_ROWS = /^\\s*SELECT\\b|\\bRETURNING\\s/i;\nconst answersRows = ({ sql }: SqlStatement) => ANSWERS_ROWS.test(sql);\n\nfunction synchronousExecutor(db: DrizzleSqlite): SqlExecutor {\n const rowsOf = (target: DrizzleSqliteQueryable, statement: SqlStatement): SqlRow[] => {\n const query = drizzleSql(\"sqlite\", statement);\n if (answersRows(statement)) return target.all<SqlRow>(query);\n target.run(query);\n return [];\n };\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsOf(db, { sql, params }),\n // The transaction answers what its callback returned.\n batch: async (statements) =>\n db.transaction((tx) => statements.map((statement) => rowsOf(tx, statement)), {\n behavior: \"immediate\",\n }) as SqlRow[][],\n };\n}\n\nfunction batchingExecutor(db: DrizzleAsyncSqlite): SqlExecutor {\n const built = (statement: SqlStatement) => {\n const query = drizzleSql(\"sqlite\", statement);\n return answersRows(statement) ? db.all<SqlRow>(query) : db.run(query);\n };\n // A write's answer (libsql's ResultSet, D1's meta) is not rows.\n const rowsFrom = (statement: SqlStatement, answer: unknown) => (answersRows(statement) ? (answer as SqlRow[]) : []);\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsFrom({ sql, params }, await built({ sql, params })),\n async batch(statements) {\n const [first, ...rest] = statements;\n if (!first) return [];\n const answers = await db.batch([built(first), ...rest.map(built)]);\n return statements.map((statement, index) => rowsFrom(statement, answers[index]));\n },\n };\n}\n\n/** The D1 binding of a `drizzle-orm/d1` database, which Drizzle keeps as `$client`; null for any other driver. */\nfunction d1Binding(db: object): D1Database | null {\n const client: unknown = \"$client\" in db ? db.$client : null;\n const isD1 =\n typeof client === \"object\" &&\n client !== null &&\n \"prepare\" in client &&\n typeof client.prepare === \"function\" &&\n \"batch\" in client &&\n typeof client.batch === \"function\";\n return isD1 ? (client as D1Database) : null;\n}\n\nexport function sqliteExecutor(db: DrizzleSqlite | DrizzleAsyncSqlite): SqlExecutor {\n const d1 = d1Binding(db);\n if (d1) return d1Executor(d1);\n return \"batch\" in db && typeof db.batch === \"function\"\n ? batchingExecutor(db as DrizzleAsyncSqlite)\n : synchronousExecutor(db as DrizzleSqlite);\n}\n","// The store's tables as Drizzle `pg-core` tables (spec M5 §3). The package emits declarations without inference\n// (isolatedDeclarations), so the table types are spelled out, but only through what drizzle-orm 0.45 and 1.0 both\n// export: the builder functions' return types, their `this`-typed methods and the table function type `PgTableFn`, the\n// one type name both lines share. The names of the builder types differ between the two lines and are never written\n// here. The compiler checks the builders below against these types, and drizzle.test.ts pins the row types they give\n// on both lines. With `tables.schema` the tables come from that schema's `table`, so drizzle-kit creates them in it and\n// queries name it.\n\nimport { sql } from \"drizzle-orm\";\nimport { bigint, check, index, integer, PgSchema, type PgTableFn, pgTable, text, timestamp } from \"drizzle-orm/pg-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// Each builder function's last overload names the column; `timestamp`'s mode defaults to Dates, and `bigint`'s answer\n// is a union by mode, of which the number one is taken.\ntype Text = ReturnType<typeof text>;\ntype Time = ReturnType<typeof timestamp>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\ntype Count = NotNull<Extract<ReturnType<typeof bigint>, { _: { data: number } }>>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n// A type-only table function whose tables may or may not carry a schema: `pgTable` and a schema's `table` both fit it.\ndeclare const tableStandIn: PgTableFn<string | undefined>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: NotNull<ReturnType<typeof integer>>;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropPgTables()`: the files and usage tables as Drizzle `pg-core` tables, in a schema with `tables.schema`. */\nexport interface CloudropPgTables {\n files: ReturnType<typeof tableStandIn<string, FileColumns>>;\n usage: ReturnType<typeof tableStandIn<string, UsageColumns>>;\n}\n\n/** The tables' names and, on Postgres, their schema: pass the same `tables` as to `drizzleStore`. */\nexport interface CloudropTablesOptions {\n tables?: StoreTables;\n}\n\n// The constructor, not `pgSchema()`, which refuses \"public\" although the store accepts it: the constructor is what\n// `pgSchema()` calls for every other name. 1.0 declares a required `casing` (undefined is what `pgSchema()` passes);\n// 0.45 takes the name alone.\nconst Schema: new (name: string, casing: undefined) => { table: PgTableFn<string> } = PgSchema;\n\nconst time = (name: string) => timestamp(name, { withTimezone: true, precision: 3, mode: \"date\" });\nconst count = (name: string) => bigint(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `pg-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropPgTables();\n * const inApp = cloudropPgTables({ tables: { schema: \"app\" } });\n * ```\n */\nexport function cloudropPgTables(options: CloudropTablesOptions = {}): CloudropPgTables {\n const names = tableNames(options.tables, \"postgres\");\n const table: PgTableFn<string | undefined> =\n names.schema === undefined ? pgTable : new Schema(names.schema, undefined).table;\n const files = table(\n names.files,\n {\n id: text(\"id\").primaryKey(),\n route: text(\"route\").notNull(),\n key: text(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: text(\"owner\"),\n status: text(\"status\").$type<FileStatus>().notNull(),\n name: text(\"name\").notNull(),\n type: text(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: text(\"upload_id\"),\n metadata: text(\"metadata\"),\n result: text(\"result\"),\n claim: text(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: text(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_idx`).on(t.owner, t.status),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = table(\n names.usage,\n {\n owner: text(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: integer(\"files\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n },\n // Named as Postgres names an unnamed column CHECK, so the plain DDL and these tables agree.\n (t) => [\n check(`${names.usage}_reserved_bytes_check`, sql`${t.reservedBytes} >= 0`),\n check(`${names.usage}_active_bytes_check`, sql`${t.activeBytes} >= 0`),\n check(`${names.usage}_files_check`, sql`${t.files} >= 0`),\n ],\n );\n return { files, usage };\n}\n","// The store's tables as Drizzle `sqlite-core` tables (spec M5 §3): sizes and counters as integers read as numbers,\n// times as integer milliseconds read as Dates. The types are spelled out from what drizzle-orm 0.45 and 1.0 both export,\n// as on Postgres (postgres-tables.ts).\n\nimport { index, integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// drizzle-orm 0.45 and 1.0 share no builder type names, and `text`'s overload that takes a name erases to `any` on both,\n// so each builder type comes from an overload both lines have. `text`'s third type argument is the length in 0.45 and\n// the mode in 1.0; `never` satisfies both and selects the plain text builder. An integer's mode defaults to a number.\ntype Text = ReturnType<typeof text<string, [string, ...string[]], never>>;\ntype Time = ReturnType<typeof integer<\"timestamp_ms\">>;\ntype Count = NotNull<ReturnType<typeof integer>>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: Count;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropSqliteTables()`: the files and usage tables as Drizzle `sqlite-core` tables. */\nexport interface CloudropSqliteTables {\n files: ReturnType<typeof sqliteTable<string, FileColumns>>;\n usage: ReturnType<typeof sqliteTable<string, UsageColumns>>;\n}\n\n// The overloads above are the ones without a column name, which 0.45 types as `\"\"` (and then names after the property)\n// and 1.0 does not type at all. The builders below take the real SQL name, so on 0.45 their types differ from those\n// overloads in the name and the text length only: cast here, and pinned by the row-type tests and the catalogue test.\nconst textColumn = (name: string) => text(name) as unknown as Text;\nconst time = (name: string) => integer(name, { mode: \"timestamp_ms\" }) as unknown as Time;\nconst count = (name: string) => integer(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `sqlite-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropSqliteTables();\n * ```\n */\nexport function cloudropSqliteTables(options: { tables?: Omit<StoreTables, \"schema\"> } = {}): CloudropSqliteTables {\n const names = tableNames(options.tables, \"sqlite\");\n const files = sqliteTable(\n names.files,\n {\n id: textColumn(\"id\").primaryKey(),\n route: textColumn(\"route\").notNull(),\n key: textColumn(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: textColumn(\"owner\"),\n status: textColumn(\"status\").$type<FileStatus>().notNull(),\n name: textColumn(\"name\").notNull(),\n type: textColumn(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: textColumn(\"upload_id\"),\n metadata: textColumn(\"metadata\"),\n result: textColumn(\"result\"),\n claim: textColumn(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: textColumn(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_idx`).on(t.owner, t.status),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = sqliteTable(names.usage, {\n owner: textColumn(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: count(\"files\"),\n updatedAt: time(\"updated_at\").notNull(),\n });\n return { files, usage };\n}\n","// cloudrop/adapters/drizzle: the database store over an app's Drizzle database (spec M5 §7). The SQL core writes every\n// statement; this entry runs them through Drizzle and exports the tables for the app's own schema. `drizzle-orm` is an\n// optional peer: only this entry imports it.\n\nimport { configError } from \"../errors.ts\";\nimport type { CloudropStore, TransactionalStore } from \"../server/store.ts\";\nimport { sqlStore } from \"../store/sql/store.ts\";\nimport type { StoreTables } from \"../store/sql/tables.ts\";\nimport { type DrizzlePostgres, type DrizzleTransaction, postgresExecutor } from \"./drizzle/postgres.ts\";\nimport { type DrizzleAsyncSqlite, type DrizzleSqlite, sqliteExecutor } from \"./drizzle/sqlite.ts\";\nimport { withRoute } from \"./transactional.ts\";\n\nexport type { StoreTables } from \"../store/sql/tables.ts\";\nexport type { DrizzlePostgres, DrizzlePostgresQueryable, DrizzleTransaction } from \"./drizzle/postgres.ts\";\nexport type { CloudropPgTables, CloudropTablesOptions } from \"./drizzle/postgres-tables.ts\";\nexport { cloudropPgTables } from \"./drizzle/postgres-tables.ts\";\nexport type { DrizzleAsyncSqlite, DrizzleSqlite, DrizzleSqliteQueryable } from \"./drizzle/sqlite.ts\";\nexport type { CloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\nexport { cloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\n\n/** What the overloads below take; each one names its dialect as a literal. */\ninterface DrizzleStoreOptions {\n dialect: \"postgres\" | \"sqlite\";\n tables?: StoreTables;\n transaction?: boolean;\n}\n\n/**\n * A cloudrop store over a Drizzle database: Postgres (node-postgres over a `Pool`, postgres.js) or SQLite\n * (better-sqlite3, libsql/Turso, D1). Create the tables first, from `cloudropPgTables` or `cloudropSqliteTables` in\n * your Drizzle schema or from the documented DDL; the store checks them on its first call. `tables` names them,\n * defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres `tables.schema` names their schema (pass the same\n * `tables` to `cloudropPgTables`). A single node-postgres `Client` is refused: every request would share its one\n * connection, and a transaction on it would take the others' statements with it.\n *\n * With `transaction: true` (Postgres only), `onComplete` runs inside the completion's transaction with Drizzle's `tx`:\n * an app row written through `tx` commits with the upload or not at all, and routes must come from `store.route`.\n * Postgres waits at most 2 s for the row lock, so a second `/complete` of the same file answers busy. Keep storage and\n * other network calls out of that `onComplete`; they belong in `afterComplete`.\n *\n * Usage:\n * ```ts\n * const db = drizzle(new Pool({ connectionString }));\n * const store = drizzleStore(db, { dialect: \"postgres\", transaction: true });\n * const avatars = store.route({ accept: \"image/*\", maxSize: \"5MB\", authorize }, {\n * owner: ({ userId }) => userId,\n * onComplete: async ({ tx, userId, file }) => {\n * await tx.update(users).set({ avatar: file.key }).where(eq(users.id, userId));\n * },\n * });\n * export const cloudrop = createCloudrop({ storage, secret, store, routes: { avatars } });\n * ```\n */\nexport function drizzleStore<TDb extends DrizzlePostgres>(\n db: TDb,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction: true },\n): TransactionalStore<DrizzleTransaction<TDb>>;\nexport function drizzleStore(\n db: DrizzlePostgres,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction?: false },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzleSqlite | DrizzleAsyncSqlite,\n options: { dialect: \"sqlite\"; tables?: Omit<StoreTables, \"schema\"> },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzlePostgres | DrizzleSqlite | DrizzleAsyncSqlite,\n options: DrizzleStoreOptions,\n): CloudropStore<unknown> {\n const { dialect, tables, transaction = false } = options;\n if (dialect === \"sqlite\") {\n // The core refuses transaction: true on SQLite, with the same message for every adapter.\n return sqlStore(sqliteExecutor(db as DrizzleSqlite | DrizzleAsyncSqlite), { tables, transaction });\n }\n if (dialect !== \"postgres\") {\n throw configError(\n `drizzleStore's dialect ${JSON.stringify(dialect)} is not supported. Use \"postgres\" or \"sqlite\".`,\n );\n }\n const store = sqlStore(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statement.ts","../../src/adapters/drizzle/postgres.ts","../../src/adapters/drizzle/sqlite.ts","../../src/adapters/drizzle/postgres-tables.ts","../../src/adapters/drizzle/sqlite-tables.ts","../../src/adapters/drizzle.ts"],"sourcesContent":["// A core statement as Drizzle SQL. Drizzle's `sql.raw` takes no parameters, so the text is cut at each placeholder the\n// core's binder wrote (store/sql/bind.ts) and every placeholder becomes a Drizzle parameter; Drizzle numbers them\n// again as it renders, `$1`, `$2`… on Postgres and `?` on SQLite, and the `::type` casts after them stay in the text.\n\nimport { type SQL, type SQLChunk, sql } from \"drizzle-orm\";\nimport type { SqlDialect, SqlStatement } from \"../../store/sql/executor.ts\";\n\nconst PLACEHOLDER: Record<SqlDialect, RegExp> = { postgres: /\\$(\\d+)/g, sqlite: /\\?/g };\n\nexport function drizzleSql(dialect: SqlDialect, { sql: text, params }: SqlStatement): SQL {\n const chunks: SQLChunk[] = [];\n let end = 0;\n for (const [position, match] of [...text.matchAll(PLACEHOLDER[dialect])].entries()) {\n // `$n` names its parameter; SQLite's `?` takes the next one.\n const value = params[match[1] === undefined ? position : Number(match[1]) - 1];\n chunks.push(sql.raw(text.slice(end, match.index)), sql.param(value));\n end = match.index + match[0].length;\n }\n chunks.push(sql.raw(text.slice(end)));\n return sql.join(chunks);\n}\n","// Drizzle on Postgres: statements through `execute`, batches and transactions through `db.transaction`. The database is\n// described by the two members used here, so any Drizzle Postgres driver fits and the library needs no Drizzle types\n// beyond `SQL`; drizzle.db.integration.test.ts runs it on node-postgres and postgres.js.\n\nimport type { SQL } from \"drizzle-orm\";\nimport { configError } from \"../../errors.ts\";\nimport { type SqlRow, type SqlStatement, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a Drizzle Postgres database or transaction. */\nexport interface DrizzlePostgresQueryable {\n execute(query: SQL): PromiseLike<unknown>;\n}\n\n/** A Drizzle Postgres database: `drizzle(pool)` from `drizzle-orm/node-postgres`, `drizzle-orm/postgres-js`, … */\nexport interface DrizzlePostgres extends DrizzlePostgresQueryable {\n transaction<T>(run: (tx: DrizzlePostgresQueryable) => Promise<T>): Promise<T>;\n}\n\n/** The `tx` Drizzle hands to `db.transaction`'s callback, for this database's driver and schema. */\nexport type DrizzleTransaction<TDb extends DrizzlePostgres> = Parameters<Parameters<TDb[\"transaction\"]>[0]>[0];\n\n/** How a result looked, for the message: its keys, never its values. */\nconst shapeOf = (result: unknown): string =>\n typeof result === \"object\" && result !== null ? `{ ${Object.keys(result).join(\", \")} }` : typeof result;\n\n/** node-postgres answers `{ rows }`, postgres.js the rows themselves. */\nasync function rowsOf(target: DrizzlePostgresQueryable, statement: SqlStatement): Promise<SqlRow[]> {\n const result = await target.execute(drizzleSql(\"postgres\", statement));\n if (Array.isArray(result)) return result;\n const { rows } = (result ?? {}) as { rows?: unknown };\n if (Array.isArray(rows)) return rows;\n throw configError(\n `This Drizzle driver's execute() answered ${shapeOf(result)}, not rows or { rows }. Use drizzleStore with node-postgres or postgres.js, or build an executor for cloudrop/adapters/sql.`,\n );\n}\n\n/** The executor's statements on the database or a transaction, in order when batched. */\nconst on = (target: DrizzlePostgresQueryable) =>\n sequential(\"postgres\", (sql, params) => rowsOf(target, { sql, params }));\n\n/**\n * True for a node-postgres client that is not a pool: Drizzle's node-postgres driver checks out a connection for a\n * transaction only from a pool (its own test: the constructor's name contains \"Pool\"), and otherwise runs BEGIN on the\n * client's one connection, which every other request is using too.\n */\nfunction isSingleConnection(db: DrizzlePostgres): boolean {\n const client: unknown = (db as { $client?: unknown }).$client;\n if (typeof client !== \"object\" || client === null) return false;\n const { query, connect } = client as { query?: unknown; connect?: unknown };\n return typeof query === \"function\" && typeof connect === \"function\" && !client.constructor.name.includes(\"Pool\");\n}\n\n/** The executor; its `transaction` runs `onComplete` in a Drizzle transaction whose `tx` the route gets. */\nexport function postgresExecutor(db: DrizzlePostgres): TransactionalSqlExecutor<DrizzlePostgresQueryable> {\n if (isSingleConnection(db)) {\n throw configError(\n \"drizzleStore needs a pg Pool, not a single pg Client: a transaction on the one shared connection would take every other request's statements with it. Pass drizzle(new Pool({ connectionString })), or use postgres.js.\",\n );\n }\n return {\n ...on(db),\n batch: (statements) => db.transaction((tx) => on(tx).batch(statements)),\n transaction: (run) => db.transaction((tx) => run(on(tx), tx)),\n };\n}\n","// Drizzle on SQLite, through `all` and `run`. A synchronous driver (better-sqlite3) runs a batch in\n// `db.transaction(…, { behavior: \"immediate\" })`, which ends before any other call can start. An asynchronous one with\n// an atomic batch (libsql/Turso) runs it through `db.batch`, ordered and all-or-nothing. D1 runs through the binding\n// Drizzle keeps as `db.$client`, as `d1Executor` does: drizzle-orm 0.45's D1 `batch` cannot take a raw statement with\n// parameters (it reads a `stmt` that `db.run(sql)` never prepares; measured in the Wrangler lane). None has transaction\n// mode: an interactive transaction would hold the only writer across `onComplete`'s awaits.\n\nimport type { SQL } from \"drizzle-orm\";\nimport type { BatchItem } from \"drizzle-orm/batch\";\nimport type { SqlExecutor, SqlRow, SqlStatement } from \"../../store/sql/executor.ts\";\nimport { type D1Database, d1Executor } from \"../sql/d1.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a synchronous Drizzle SQLite database or transaction. */\nexport interface DrizzleSqliteQueryable {\n all<T = unknown>(query: SQL): T[];\n run(query: SQL): unknown;\n}\n\n/**\n * A Drizzle SQLite database over a synchronous driver: `drizzle(new Database(path))` from `drizzle-orm/better-sqlite3`.\n * `transaction` is not generic here: drizzle-orm 0.45 types its answer as the callback's, 1.0 through a conditional type\n * that refuses async callbacks, and both fit this shape.\n */\nexport interface DrizzleSqlite extends DrizzleSqliteQueryable {\n transaction(run: (tx: DrizzleSqliteQueryable) => SqlRow[][], config?: { behavior?: \"immediate\" }): unknown;\n}\n\n/**\n * A Drizzle SQLite database over an asynchronous driver with an atomic batch: `drizzle-orm/libsql` (Turso) or\n * `drizzle-orm/d1`. `all` and `run` build a statement that runs when awaited, or as part of `batch`.\n */\nexport interface DrizzleAsyncSqlite {\n all<T = unknown>(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<T[]>;\n run(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<unknown>;\n batch(statements: readonly [BatchItem<\"sqlite\">, ...BatchItem<\"sqlite\">[]]): PromiseLike<readonly unknown[]>;\n}\n\n/**\n * Whether the statement answers rows: better-sqlite3 refuses `all` for one that does not. Every statement the core\n * writes either starts with SELECT or ends its write with a RETURNING clause when it needs rows back. A table named\n * `returning` is quoted, so the word is followed by `\"`, never by whitespace.\n */\nconst ANSWERS_ROWS = /^\\s*SELECT\\b|\\bRETURNING\\s/i;\nconst answersRows = ({ sql }: SqlStatement) => ANSWERS_ROWS.test(sql);\n\nfunction synchronousExecutor(db: DrizzleSqlite): SqlExecutor {\n const rowsOf = (target: DrizzleSqliteQueryable, statement: SqlStatement): SqlRow[] => {\n const query = drizzleSql(\"sqlite\", statement);\n if (answersRows(statement)) return target.all<SqlRow>(query);\n target.run(query);\n return [];\n };\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsOf(db, { sql, params }),\n // The transaction answers what its callback returned.\n batch: async (statements) =>\n db.transaction((tx) => statements.map((statement) => rowsOf(tx, statement)), {\n behavior: \"immediate\",\n }) as SqlRow[][],\n };\n}\n\nfunction batchingExecutor(db: DrizzleAsyncSqlite): SqlExecutor {\n const built = (statement: SqlStatement) => {\n const query = drizzleSql(\"sqlite\", statement);\n return answersRows(statement) ? db.all<SqlRow>(query) : db.run(query);\n };\n // A write's answer (libsql's ResultSet, D1's meta) is not rows.\n const rowsFrom = (statement: SqlStatement, answer: unknown) => (answersRows(statement) ? (answer as SqlRow[]) : []);\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsFrom({ sql, params }, await built({ sql, params })),\n async batch(statements) {\n const [first, ...rest] = statements;\n if (!first) return [];\n const answers = await db.batch([built(first), ...rest.map(built)]);\n return statements.map((statement, index) => rowsFrom(statement, answers[index]));\n },\n };\n}\n\n/** The D1 binding of a `drizzle-orm/d1` database, which Drizzle keeps as `$client`; null for any other driver. */\nfunction d1Binding(db: object): D1Database | null {\n const client: unknown = \"$client\" in db ? db.$client : null;\n const isD1 =\n typeof client === \"object\" &&\n client !== null &&\n \"prepare\" in client &&\n typeof client.prepare === \"function\" &&\n \"batch\" in client &&\n typeof client.batch === \"function\";\n return isD1 ? (client as D1Database) : null;\n}\n\nexport function sqliteExecutor(db: DrizzleSqlite | DrizzleAsyncSqlite): SqlExecutor {\n const d1 = d1Binding(db);\n if (d1) return d1Executor(d1);\n return \"batch\" in db && typeof db.batch === \"function\"\n ? batchingExecutor(db as DrizzleAsyncSqlite)\n : synchronousExecutor(db as DrizzleSqlite);\n}\n","// The store's tables as Drizzle `pg-core` tables (spec M5 §3). The package emits declarations without inference\n// (isolatedDeclarations), so the table types are spelled out, but only through what drizzle-orm 0.45 and 1.0 both\n// export: the builder functions' return types, their `this`-typed methods and the table function type `PgTableFn`, the\n// one type name both lines share. The names of the builder types differ between the two lines and are never written\n// here. The compiler checks the builders below against these types, and drizzle.test.ts pins the row types they give\n// on both lines. With `tables.schema` the tables come from that schema's `table`, so drizzle-kit creates them in it and\n// queries name it.\n\nimport { sql } from \"drizzle-orm\";\nimport { bigint, check, index, integer, PgSchema, type PgTableFn, pgTable, text, timestamp } from \"drizzle-orm/pg-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// Each builder function's last overload names the column; `timestamp`'s mode defaults to Dates, and `bigint`'s answer\n// is a union by mode, of which the number one is taken.\ntype Text = ReturnType<typeof text>;\ntype Time = ReturnType<typeof timestamp>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\ntype Count = NotNull<Extract<ReturnType<typeof bigint>, { _: { data: number } }>>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n// A type-only table function whose tables may or may not carry a schema: `pgTable` and a schema's `table` both fit it.\ndeclare const tableStandIn: PgTableFn<string | undefined>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: NotNull<ReturnType<typeof integer>>;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropPgTables()`: the files and usage tables as Drizzle `pg-core` tables, in a schema with `tables.schema`. */\nexport interface CloudropPgTables {\n files: ReturnType<typeof tableStandIn<string, FileColumns>>;\n usage: ReturnType<typeof tableStandIn<string, UsageColumns>>;\n}\n\n/** The tables' names and, on Postgres, their schema: pass the same `tables` as to `drizzleStore`. */\nexport interface CloudropTablesOptions {\n tables?: StoreTables;\n}\n\n// The constructor, not `pgSchema()`, which refuses \"public\" although the store accepts it: the constructor is what\n// `pgSchema()` calls for every other name. 1.0 declares a required `casing` (undefined is what `pgSchema()` passes);\n// 0.45 takes the name alone.\nconst Schema: new (name: string, casing: undefined) => { table: PgTableFn<string> } = PgSchema;\n\nconst time = (name: string) => timestamp(name, { withTimezone: true, precision: 3, mode: \"date\" });\nconst count = (name: string) => bigint(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `pg-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropPgTables();\n * const inApp = cloudropPgTables({ tables: { schema: \"app\" } });\n * ```\n */\nexport function cloudropPgTables(options: CloudropTablesOptions = {}): CloudropPgTables {\n const names = tableNames(options.tables, \"postgres\");\n const table: PgTableFn<string | undefined> =\n names.schema === undefined ? pgTable : new Schema(names.schema, undefined).table;\n const files = table(\n names.files,\n {\n id: text(\"id\").primaryKey(),\n route: text(\"route\").notNull(),\n key: text(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: text(\"owner\"),\n status: text(\"status\").$type<FileStatus>().notNull(),\n name: text(\"name\").notNull(),\n type: text(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: text(\"upload_id\"),\n metadata: text(\"metadata\"),\n result: text(\"result\"),\n claim: text(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: text(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = table(\n names.usage,\n {\n owner: text(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: integer(\"files\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n },\n // Named as Postgres names an unnamed column CHECK, so the plain DDL and these tables agree.\n (t) => [\n check(`${names.usage}_reserved_bytes_check`, sql`${t.reservedBytes} >= 0`),\n check(`${names.usage}_active_bytes_check`, sql`${t.activeBytes} >= 0`),\n check(`${names.usage}_files_check`, sql`${t.files} >= 0`),\n ],\n );\n return { files, usage };\n}\n","// The store's tables as Drizzle `sqlite-core` tables (spec M5 §3): sizes and counters as integers read as numbers,\n// times as integer milliseconds read as Dates. The types are spelled out from what drizzle-orm 0.45 and 1.0 both export,\n// as on Postgres (postgres-tables.ts).\n\nimport { index, integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// drizzle-orm 0.45 and 1.0 share no builder type names, and `text`'s overload that takes a name erases to `any` on both,\n// so each builder type comes from an overload both lines have. `text`'s third type argument is the length in 0.45 and\n// the mode in 1.0; `never` satisfies both and selects the plain text builder. An integer's mode defaults to a number.\ntype Text = ReturnType<typeof text<string, [string, ...string[]], never>>;\ntype Time = ReturnType<typeof integer<\"timestamp_ms\">>;\ntype Count = NotNull<ReturnType<typeof integer>>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: Count;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropSqliteTables()`: the files and usage tables as Drizzle `sqlite-core` tables. */\nexport interface CloudropSqliteTables {\n files: ReturnType<typeof sqliteTable<string, FileColumns>>;\n usage: ReturnType<typeof sqliteTable<string, UsageColumns>>;\n}\n\n// The overloads above are the ones without a column name, which 0.45 types as `\"\"` (and then names after the property)\n// and 1.0 does not type at all. The builders below take the real SQL name, so on 0.45 their types differ from those\n// overloads in the name and the text length only: cast here, and pinned by the row-type tests and the catalogue test.\nconst textColumn = (name: string) => text(name) as unknown as Text;\nconst time = (name: string) => integer(name, { mode: \"timestamp_ms\" }) as unknown as Time;\nconst count = (name: string) => integer(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `sqlite-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropSqliteTables();\n * ```\n */\nexport function cloudropSqliteTables(options: { tables?: Omit<StoreTables, \"schema\"> } = {}): CloudropSqliteTables {\n const names = tableNames(options.tables, \"sqlite\");\n const files = sqliteTable(\n names.files,\n {\n id: textColumn(\"id\").primaryKey(),\n route: textColumn(\"route\").notNull(),\n key: textColumn(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: textColumn(\"owner\"),\n status: textColumn(\"status\").$type<FileStatus>().notNull(),\n name: textColumn(\"name\").notNull(),\n type: textColumn(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: textColumn(\"upload_id\"),\n metadata: textColumn(\"metadata\"),\n result: textColumn(\"result\"),\n claim: textColumn(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: textColumn(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = sqliteTable(names.usage, {\n owner: textColumn(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: count(\"files\"),\n updatedAt: time(\"updated_at\").notNull(),\n });\n return { files, usage };\n}\n","// cloudrop/adapters/drizzle: the database store over an app's Drizzle database (spec M5 §7). The SQL core writes every\n// statement; this entry runs them through Drizzle and exports the tables for the app's own schema. `drizzle-orm` is an\n// optional peer: only this entry imports it.\n\nimport { configError } from \"../errors.ts\";\nimport type { CloudropStore, TransactionalStore } from \"../server/store.ts\";\nimport { sqlStore } from \"../store/sql/store.ts\";\nimport type { StoreTables } from \"../store/sql/tables.ts\";\nimport { type DrizzlePostgres, type DrizzleTransaction, postgresExecutor } from \"./drizzle/postgres.ts\";\nimport { type DrizzleAsyncSqlite, type DrizzleSqlite, sqliteExecutor } from \"./drizzle/sqlite.ts\";\nimport { withRoute } from \"./transactional.ts\";\n\nexport type { StoreTables } from \"../store/sql/tables.ts\";\nexport type { DrizzlePostgres, DrizzlePostgresQueryable, DrizzleTransaction } from \"./drizzle/postgres.ts\";\nexport type { CloudropPgTables, CloudropTablesOptions } from \"./drizzle/postgres-tables.ts\";\nexport { cloudropPgTables } from \"./drizzle/postgres-tables.ts\";\nexport type { DrizzleAsyncSqlite, DrizzleSqlite, DrizzleSqliteQueryable } from \"./drizzle/sqlite.ts\";\nexport type { CloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\nexport { cloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\n\n/** What the overloads below take; each one names its dialect as a literal. */\ninterface DrizzleStoreOptions {\n dialect: \"postgres\" | \"sqlite\";\n tables?: StoreTables;\n transaction?: boolean;\n}\n\n/**\n * A cloudrop store over a Drizzle database: Postgres (node-postgres over a `Pool`, postgres.js) or SQLite\n * (better-sqlite3, libsql/Turso, D1). Create the tables first, from `cloudropPgTables` or `cloudropSqliteTables` in\n * your Drizzle schema or from the documented DDL; the store checks them on its first call. `tables` names them,\n * defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres `tables.schema` names their schema (pass the same\n * `tables` to `cloudropPgTables`). A single node-postgres `Client` is refused: every request would share its one\n * connection, and a transaction on it would take the others' statements with it.\n *\n * With `transaction: true` (Postgres only), `onComplete` runs inside the completion's transaction with Drizzle's `tx`:\n * an app row written through `tx` commits with the upload or not at all, and routes must come from `store.route`.\n * Postgres waits at most 2 s for the row lock, so a second `/complete` of the same file answers busy. Keep storage and\n * other network calls out of that `onComplete`; they belong in `afterComplete`.\n *\n * Usage:\n * ```ts\n * const db = drizzle(new Pool({ connectionString }));\n * const store = drizzleStore(db, { dialect: \"postgres\", transaction: true });\n * const avatars = store.route({ accept: \"image/*\", maxSize: \"5MB\", authorize }, {\n * owner: ({ userId }) => userId,\n * onComplete: async ({ tx, userId, file }) => {\n * await tx.update(users).set({ avatar: file.key }).where(eq(users.id, userId));\n * },\n * });\n * export const cloudrop = createCloudrop({ storage, secret, store, routes: { avatars } });\n * ```\n */\nexport function drizzleStore<TDb extends DrizzlePostgres>(\n db: TDb,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction: true },\n): TransactionalStore<DrizzleTransaction<TDb>>;\nexport function drizzleStore(\n db: DrizzlePostgres,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction?: false },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzleSqlite | DrizzleAsyncSqlite,\n options: { dialect: \"sqlite\"; tables?: Omit<StoreTables, \"schema\"> },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzlePostgres | DrizzleSqlite | DrizzleAsyncSqlite,\n options: DrizzleStoreOptions,\n): CloudropStore<unknown> {\n const { dialect, tables, transaction = false } = options;\n if (dialect === \"sqlite\") {\n // The core refuses transaction: true on SQLite, with the same message for every adapter.\n return sqlStore(sqliteExecutor(db as DrizzleSqlite | DrizzleAsyncSqlite), { tables, transaction });\n }\n if (dialect !== \"postgres\") {\n throw configError(\n `drizzleStore's dialect ${JSON.stringify(dialect)} is not supported. Use \"postgres\" or \"sqlite\".`,\n );\n }\n const store = sqlStore(postgresExecutor(db as DrizzlePostgres), { tables, transaction });\n return transaction ? withRoute(store) : store;\n}\n"],"mappings":";;;;;;;AAOA,MAAM,cAA0C;CAAE,UAAU;CAAY,QAAQ;AAAM;AAEtF,SAAgB,WAAW,SAAqB,EAAE,KAAK,MAAM,UAA6B;CACxF,MAAM,SAAqB,CAAC;CAC5B,IAAI,MAAM;CACV,KAAK,MAAM,CAAC,UAAU,UAAU,CAAC,GAAG,KAAK,SAAS,YAAY,QAAQ,CAAC,CAAC,CAAC,QAAQ,GAAG;EAElF,MAAM,QAAQ,OAAO,MAAM,OAAO,KAAA,IAAY,WAAW,OAAO,MAAM,EAAE,IAAI;EAC5E,OAAO,KAAK,IAAI,IAAI,KAAK,MAAM,KAAK,MAAM,KAAK,CAAC,GAAG,IAAI,MAAM,KAAK,CAAC;EACnE,MAAM,MAAM,QAAQ,MAAM,EAAE,CAAC;CAC/B;CACA,OAAO,KAAK,IAAI,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC;CACpC,OAAO,IAAI,KAAK,MAAM;AACxB;;ACGA,MAAM,WAAW,WACf,OAAO,WAAW,YAAY,WAAW,OAAO,KAAK,OAAO,KAAK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gB;GACrC,aAAa,MAAM,cAAc;GACjC,OAAO,MAAM,OAAO;GACpB,WAAW,KAAK,YAAY,CAAC,CAAC,QAAQ;EACxC,CACoB;CAAE;AACxB;;ACrDA,SAAgB,aACd,IACA,SACwB;CACxB,MAAM,EAAE,SAAS,QAAQ,cAAc,UAAU;CACjD,IAAI,YAAY,UAEd,OAAO,SAAS,eAAe,EAAwC,GAAG;EAAE;EAAQ;CAAY,CAAC;CAEnG,IAAI,YAAY,YACd,MAAM,YACJ,0BAA0B,KAAK,UAAU,OAAO,EAAE,+CACpD;CAEF,MAAM,QAAQ,SAAS,iBAAiB,EAAqB,GAAG;EAAE;EAAQ;CAAY,CAAC;CACvF,OAAO,cAAc,UAAU,KAAK,IAAI;AAC1C"}
@@ -1,4 +1,4 @@
1
- import { c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
1
+ import { l as TransactionalStore, n as CloudropStore } from "../store-B539nY3J.js";
2
2
  import { t as StoreTables } from "../tables-DZnw2sPK.js";
3
3
  /** What the store calls on a Prisma client, or on the client of an interactive transaction. */
4
4
  export interface PrismaQueryable {
@@ -1,5 +1,5 @@
1
1
  import { n as configError } from "../errors-CUxMmFAe.js";
2
- import { i as sequential, n as sqlStore, t as withRoute } from "../transactional-DnvnGsVH.js";
2
+ import { i as sequential, n as sqlStore, t as withRoute } from "../transactional-CiNwMiDb.js";
3
3
  // src/adapters/prisma.ts
4
4
  const on = (client, dialect) => sequential(dialect, async (sql, params) => await client.$queryRawUnsafe(sql, ...params));
5
5
  function checkOptions(options) {
@@ -1,4 +1,4 @@
1
- import { c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
1
+ import { l as TransactionalStore, n as CloudropStore } from "../store-B539nY3J.js";
2
2
  import { a as TransactionalSqlExecutor, i as SqlStatement, n as SqlExecutor, r as SqlRow, t as SqlDialect } from "../executor-CEA7WV2W.js";
3
3
  import { t as StoreTables } from "../tables-DZnw2sPK.js";
4
4
  interface SqlStoreOptions {
@@ -40,6 +40,9 @@ interface PgQueryable {
40
40
  /** A client checked out of the pool. */
41
41
  interface PgPoolClient extends PgQueryable {
42
42
  release(destroy?: boolean | Error): void;
43
+ /** node-postgres reports a connection that fails between statements as an `error` event of the client. */
44
+ on?(event: "error", listener: (error: Error) => void): unknown;
45
+ removeListener?(event: "error", listener: (error: Error) => void): unknown;
43
46
  }
44
47
  /** A node-postgres `Pool`. Size it for your concurrency; transaction mode holds a client while `onComplete` runs. */
45
48
  interface PgPool extends PgQueryable {
@@ -1,4 +1,4 @@
1
- import { i as sequential, n as sqlStore$1, t as withRoute } from "../transactional-DnvnGsVH.js";
1
+ import { i as sequential, n as sqlStore$1, t as withRoute } from "../transactional-CiNwMiDb.js";
2
2
  import { t as d1Executor } from "../d1-BY2c5bcL.js";
3
3
  // src/adapters/sql/pg.ts
4
4
  const on$1 = (client) => sequential("postgres", async (sql, params) => (await client.query(sql, [...params])).rows);
@@ -6,6 +6,12 @@ function pgExecutor(pool) {
6
6
  async function inTransaction(work) {
7
7
  const client = await pool.connect();
8
8
  let broken = false;
9
+ const onError = () => {
10
+ broken = true;
11
+ };
12
+ const { on, removeListener } = client;
13
+ const listening = on !== void 0 && removeListener !== void 0;
14
+ if (listening) on.call(client, "error", onError);
9
15
  try {
10
16
  await client.query("BEGIN");
11
17
  const result = await work(client);
@@ -17,6 +23,7 @@ function pgExecutor(pool) {
17
23
  });
18
24
  throw error;
19
25
  } finally {
26
+ if (listening) removeListener.call(client, "error", onError);
20
27
  client.release(broken);
21
28
  }
22
29
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sql.js","names":["on","storeOverSql"],"sources":["../../src/adapters/sql/pg.ts","../../src/adapters/sql/postgres-js.ts","../../src/adapters/sql/sqlite.ts","../../src/adapters/sql.ts"],"sourcesContent":["// node-postgres (`pg`): a Pool, with batches and transactions on one checked-out client. The pool's shape is described\n// by the members used here, so the library needs neither pg nor its types; sql.db.integration.test.ts passes a real\n// pg.Pool.\n\nimport { type SqlRow, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\n\n/** What the executor calls on a node-postgres pool or client; `onComplete` gets the transaction's client as `tx`. */\nexport interface PgQueryable {\n query(text: string, values?: unknown[]): Promise<{ rows: SqlRow[] }>;\n}\n\n/** A client checked out of the pool. */\nexport interface PgPoolClient extends PgQueryable {\n release(destroy?: boolean | Error): void;\n}\n\n/** A node-postgres `Pool`. Size it for your concurrency; transaction mode holds a client while `onComplete` runs. */\nexport interface PgPool extends PgQueryable {\n connect(): Promise<PgPoolClient>;\n}\n\n/** The executor's statements on one pool or client, in order when batched. */\nconst on = (client: PgQueryable) =>\n sequential(\"postgres\", async (sql, params) => (await client.query(sql, [...params])).rows);\n\n/**\n * An executor over a node-postgres pool: `sqlStore(pgExecutor(new Pool({ connectionString })))`. Leave the\n * connections at Postgres's default isolation, READ COMMITTED: the store's guarantees rely on it (set no\n * `default_transaction_isolation`).\n */\nexport function pgExecutor(pool: PgPool): TransactionalSqlExecutor<PgQueryable> {\n /** Runs `work` between BEGIN and COMMIT on one client; a throw rolls back and is rethrown. */\n async function inTransaction<T>(work: (client: PgPoolClient) => Promise<T>): Promise<T> {\n const client = await pool.connect();\n let broken = false;\n try {\n await client.query(\"BEGIN\");\n const result = await work(client);\n await client.query(\"COMMIT\");\n return result;\n } catch (error) {\n // A client that cannot even roll back is in an unknown state: the pool discards it instead of reusing it.\n await client.query(\"ROLLBACK\").catch(() => {\n broken = true;\n });\n throw error;\n } finally {\n client.release(broken);\n }\n }\n\n return {\n ...on(pool),\n // Outside a transaction, a batch gets one of its own on one client.\n batch: (statements) => inTransaction((client) => on(client).batch(statements)),\n transaction: (run) => inTransaction((client) => run(on(client), client)),\n };\n}\n","// postgres.js (`postgres`): statements through `sql.unsafe`, batches and transactions through `sql.begin`. Its shape is\n// described by the members used here, so the library needs neither postgres.js nor its types;\n// sql.db.integration.test.ts passes a real `postgres()` instance.\n\nimport { type SqlRow, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\n\n/** What the executor calls on postgres.js's `sql` or a transaction's `sql`. */\nexport interface PostgresJsQueryable {\n unsafe(query: string, parameters?: unknown[]): PromiseLike<readonly SqlRow[]>;\n}\n\n/**\n * A postgres.js instance, `postgres(url)`. `TTx` is its transaction's `sql`, which `onComplete` receives as `tx`; it is\n * inferred from the instance, so `tx` keeps postgres.js's own type.\n */\nexport interface PostgresJsSql<TTx extends PostgresJsQueryable = PostgresJsQueryable> extends PostgresJsQueryable {\n begin(run: (sql: TTx) => Promise<unknown>): Promise<unknown>;\n // postgres.js declares both forms of begin; TypeScript infers TTx from the last one, so the shape mirrors both.\n begin(options: string, run: (sql: TTx) => Promise<unknown>): Promise<unknown>;\n}\n\n/** The executor's statements on `sql` or a transaction's `sql`, in order when batched. */\nconst on = (sql: PostgresJsQueryable) =>\n sequential(\"postgres\", async (query, params): Promise<SqlRow[]> => [...(await sql.unsafe(query, [...params]))]);\n\n/**\n * An executor over postgres.js: `sqlStore(postgresJsExecutor(postgres(url)))`. Leave the connections at Postgres's\n * default isolation, READ COMMITTED: the store's guarantees rely on it (set no `default_transaction_isolation`).\n */\nexport function postgresJsExecutor<TTx extends PostgresJsQueryable>(\n sql: PostgresJsSql<TTx>,\n): TransactionalSqlExecutor<TTx> {\n /** `sql.begin` commits when `work` resolves and rolls back when it throws; its answer is `work`'s. */\n const inTransaction = async <T>(work: (tx: TTx) => Promise<T>): Promise<T> =>\n // postgres.js types its answer from the callback, which the structural shape above cannot express.\n (await sql.begin(work)) as T;\n return {\n ...on(sql),\n // Outside a transaction, a batch gets one of its own.\n batch: (statements) => inTransaction((tx) => on(tx).batch(statements)),\n transaction: (run) => inTransaction((tx) => run(on(tx), tx)),\n };\n}\n","// node:sqlite (`DatabaseSync`): synchronous, so a batch between BEGIN IMMEDIATE and COMMIT runs to its end before any\n// other call can start, and no transaction mode is offered (an interactive one would hold the only connection across\n// `onComplete`'s awaits). The database is described by the members used here; sql.db.integration.test.ts passes a real\n// DatabaseSync.\n\nimport type { SqlExecutor, SqlRow, SqlStatement } from \"../../store/sql/executor.ts\";\n\n/** What the executor calls on a node:sqlite `DatabaseSync`. */\nexport interface SqliteDatabase {\n exec(sql: string): unknown;\n prepare(sql: string): { all(...params: unknown[]): SqlRow[] };\n}\n\n/**\n * An executor over node:sqlite: `sqlStore(sqliteExecutor(new DatabaseSync(path)))`. Do not share the connection with\n * code that holds its own transaction open across awaits: a batch's BEGIN would then fail. When another connection or\n * process writes the same file, open it with a busy timeout, `new DatabaseSync(path, { timeout: 5000 })`: the default\n * of 0 fails a batch at once with \"database is locked\" while the other writer holds the file.\n */\nexport function sqliteExecutor(db: SqliteDatabase): SqlExecutor {\n const rowsOf = ({ sql, params }: SqlStatement) => db.prepare(sql).all(...params);\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsOf({ sql, params }),\n async batch(statements) {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n const results = statements.map(rowsOf);\n db.exec(\"COMMIT\");\n return results;\n } catch (error) {\n // Some errors (a full disk) end the transaction themselves, and ROLLBACK then fails; the statement's error is\n // the one worth reporting.\n try {\n db.exec(\"ROLLBACK\");\n } catch {}\n throw error;\n }\n },\n };\n}\n","// cloudrop/adapters/sql: the database store over plain SQL drivers. `sqlStore(executor)` takes an executor for\n// Postgres or SQLite; the four shipped here cover node-postgres, postgres.js, node:sqlite and Cloudflare D1, and any\n// other driver needs only `query` and an atomic `batch` (spec M5 §7).\n\nimport type { CloudropStore, TransactionalStore } from \"../server/store.ts\";\nimport type { SqlExecutor, TransactionalSqlExecutor } from \"../store/sql/executor.ts\";\nimport { type SqlStoreOptions, sqlStore as storeOverSql } from \"../store/sql/store.ts\";\nimport { withRoute } from \"./transactional.ts\";\n\nexport type {\n SqlDialect,\n SqlExecutor,\n SqlRow,\n SqlStatement,\n TransactionalSqlExecutor,\n} from \"../store/sql/executor.ts\";\nexport type { SqlStoreOptions } from \"../store/sql/store.ts\";\nexport type { StoreTables } from \"../store/sql/tables.ts\";\nexport type { D1Database, D1Statement } from \"./sql/d1.ts\";\nexport { d1Executor } from \"./sql/d1.ts\";\nexport type { PgPool, PgPoolClient, PgQueryable } from \"./sql/pg.ts\";\nexport { pgExecutor } from \"./sql/pg.ts\";\nexport type { PostgresJsQueryable, PostgresJsSql } from \"./sql/postgres-js.ts\";\nexport { postgresJsExecutor } from \"./sql/postgres-js.ts\";\nexport type { SqliteDatabase } from \"./sql/sqlite.ts\";\nexport { sqliteExecutor } from \"./sql/sqlite.ts\";\n\n/**\n * The database store over SQL tables, for Postgres or SQLite. Each method is one atomic unit (one statement on\n * Postgres, one batch on SQLite); the tables are checked on the first call. Postgres must run at its default isolation,\n * READ COMMITTED: the claim, quota and reconcile guarantees rely on its re-reading of a row it waited for. With\n * `transaction: true` and an executor that can hold a transaction (`pgExecutor`, `postgresJsExecutor`), completions\n * run in a transaction and the store gets `route`; without it, completions use a lease.\n */\nexport function sqlStore<TTx>(\n executor: TransactionalSqlExecutor<TTx>,\n options: SqlStoreOptions & { transaction: true },\n): TransactionalStore<TTx>;\nexport function sqlStore(\n executor: SqlExecutor<unknown>,\n options?: SqlStoreOptions & { transaction?: false },\n): CloudropStore;\nexport function sqlStore<TTx>(executor: SqlExecutor<TTx>, options: SqlStoreOptions = {}): CloudropStore<TTx> {\n const store = storeOverSql(executor, options);\n return options.transaction ? withRoute(store) : store;\n}\n"],"mappings":";;;AAsBA,MAAMA,QAAM,WACV,WAAW,YAAY,OAAO,KAAK,YAAY,MAAM,OAAO,MAAM,KAAK,CAAC,GAAG,MAAM,CAAC,EAAA,CAAG,IAAI;AAO3F,SAAgB,WAAW,MAAqD;CAE9E,eAAe,cAAiB,MAAwD;EACtF,MAAM,SAAS,MAAM,KAAK,QAAQ;EAClC,IAAI,SAAS;EACb,IAAI;GACF,MAAM,OAAO,MAAM,OAAO;GAC1B,MAAM,SAAS,MAAM,KAAK,MAAM;GAChC,MAAM,OAAO,MAAM,QAAQ;GAC3B,OAAO;EACT,SAAS,OAAO;GAEd,MAAM,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AC5C,OAAO,QAAQ,cAAc,UAAU,KAAK,IAAI;AAClD"}
1
+ {"version":3,"file":"sql.js","names":["on","storeOverSql"],"sources":["../../src/adapters/sql/pg.ts","../../src/adapters/sql/postgres-js.ts","../../src/adapters/sql/sqlite.ts","../../src/adapters/sql.ts"],"sourcesContent":["// node-postgres (`pg`): a Pool, with batches and transactions on one checked-out client. The pool's shape is described\n// by the members used here, so the library needs neither pg nor its types; sql.db.integration.test.ts passes a real\n// pg.Pool.\n\nimport { type SqlRow, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\n\n/** What the executor calls on a node-postgres pool or client; `onComplete` gets the transaction's client as `tx`. */\nexport interface PgQueryable {\n query(text: string, values?: unknown[]): Promise<{ rows: SqlRow[] }>;\n}\n\n/** A client checked out of the pool. */\nexport interface PgPoolClient extends PgQueryable {\n release(destroy?: boolean | Error): void;\n /** node-postgres reports a connection that fails between statements as an `error` event of the client. */\n on?(event: \"error\", listener: (error: Error) => void): unknown;\n removeListener?(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** A node-postgres `Pool`. Size it for your concurrency; transaction mode holds a client while `onComplete` runs. */\nexport interface PgPool extends PgQueryable {\n connect(): Promise<PgPoolClient>;\n}\n\n/** The executor's statements on one pool or client, in order when batched. */\nconst on = (client: PgQueryable) =>\n sequential(\"postgres\", async (sql, params) => (await client.query(sql, [...params])).rows);\n\n/**\n * An executor over a node-postgres pool: `sqlStore(pgExecutor(new Pool({ connectionString })))`. Leave the\n * connections at Postgres's default isolation, READ COMMITTED: the store's guarantees rely on it (set no\n * `default_transaction_isolation`).\n */\nexport function pgExecutor(pool: PgPool): TransactionalSqlExecutor<PgQueryable> {\n /** Runs `work` between BEGIN and COMMIT on one client; a throw rolls back and is rethrown. */\n async function inTransaction<T>(work: (client: PgPoolClient) => Promise<T>): Promise<T> {\n const client = await pool.connect();\n let broken = false;\n // A connection that fails while it is checked out but idle, such as while onComplete runs, is an 'error' event of\n // the client, which the pool listens for only while the client is idle in it: without a listener, Node throws it\n // and the process stops. The next statement fails with that error, so the listener only marks the client broken.\n const onError = () => {\n broken = true;\n };\n // Only a client that can also drop the listener gets one: otherwise each checkout would add another.\n const { on, removeListener } = client;\n const listening = on !== undefined && removeListener !== undefined;\n if (listening) on.call(client, \"error\", onError);\n try {\n await client.query(\"BEGIN\");\n const result = await work(client);\n await client.query(\"COMMIT\");\n return result;\n } catch (error) {\n // A client that cannot even roll back is in an unknown state: the pool discards it instead of reusing it.\n await client.query(\"ROLLBACK\").catch(() => {\n broken = true;\n });\n throw error;\n } finally {\n if (listening) removeListener.call(client, \"error\", onError);\n client.release(broken);\n }\n }\n\n return {\n ...on(pool),\n // Outside a transaction, a batch gets one of its own on one client.\n batch: (statements) => inTransaction((client) => on(client).batch(statements)),\n transaction: (run) => inTransaction((client) => run(on(client), client)),\n };\n}\n","// postgres.js (`postgres`): statements through `sql.unsafe`, batches and transactions through `sql.begin`. Its shape is\n// described by the members used here, so the library needs neither postgres.js nor its types;\n// sql.db.integration.test.ts passes a real `postgres()` instance.\n\nimport { type SqlRow, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\n\n/** What the executor calls on postgres.js's `sql` or a transaction's `sql`. */\nexport interface PostgresJsQueryable {\n unsafe(query: string, parameters?: unknown[]): PromiseLike<readonly SqlRow[]>;\n}\n\n/**\n * A postgres.js instance, `postgres(url)`. `TTx` is its transaction's `sql`, which `onComplete` receives as `tx`; it is\n * inferred from the instance, so `tx` keeps postgres.js's own type.\n */\nexport interface PostgresJsSql<TTx extends PostgresJsQueryable = PostgresJsQueryable> extends PostgresJsQueryable {\n begin(run: (sql: TTx) => Promise<unknown>): Promise<unknown>;\n // postgres.js declares both forms of begin; TypeScript infers TTx from the last one, so the shape mirrors both.\n begin(options: string, run: (sql: TTx) => Promise<unknown>): Promise<unknown>;\n}\n\n/** The executor's statements on `sql` or a transaction's `sql`, in order when batched. */\nconst on = (sql: PostgresJsQueryable) =>\n sequential(\"postgres\", async (query, params): Promise<SqlRow[]> => [...(await sql.unsafe(query, [...params]))]);\n\n/**\n * An executor over postgres.js: `sqlStore(postgresJsExecutor(postgres(url)))`. Leave the connections at Postgres's\n * default isolation, READ COMMITTED: the store's guarantees rely on it (set no `default_transaction_isolation`).\n */\nexport function postgresJsExecutor<TTx extends PostgresJsQueryable>(\n sql: PostgresJsSql<TTx>,\n): TransactionalSqlExecutor<TTx> {\n /** `sql.begin` commits when `work` resolves and rolls back when it throws; its answer is `work`'s. */\n const inTransaction = async <T>(work: (tx: TTx) => Promise<T>): Promise<T> =>\n // postgres.js types its answer from the callback, which the structural shape above cannot express.\n (await sql.begin(work)) as T;\n return {\n ...on(sql),\n // Outside a transaction, a batch gets one of its own.\n batch: (statements) => inTransaction((tx) => on(tx).batch(statements)),\n transaction: (run) => inTransaction((tx) => run(on(tx), tx)),\n };\n}\n","// node:sqlite (`DatabaseSync`): synchronous, so a batch between BEGIN IMMEDIATE and COMMIT runs to its end before any\n// other call can start, and no transaction mode is offered (an interactive one would hold the only connection across\n// `onComplete`'s awaits). The database is described by the members used here; sql.db.integration.test.ts passes a real\n// DatabaseSync.\n\nimport type { SqlExecutor, SqlRow, SqlStatement } from \"../../store/sql/executor.ts\";\n\n/** What the executor calls on a node:sqlite `DatabaseSync`. */\nexport interface SqliteDatabase {\n exec(sql: string): unknown;\n prepare(sql: string): { all(...params: unknown[]): SqlRow[] };\n}\n\n/**\n * An executor over node:sqlite: `sqlStore(sqliteExecutor(new DatabaseSync(path)))`. Do not share the connection with\n * code that holds its own transaction open across awaits: a batch's BEGIN would then fail. When another connection or\n * process writes the same file, open it with a busy timeout, `new DatabaseSync(path, { timeout: 5000 })`: the default\n * of 0 fails a batch at once with \"database is locked\" while the other writer holds the file.\n */\nexport function sqliteExecutor(db: SqliteDatabase): SqlExecutor {\n const rowsOf = ({ sql, params }: SqlStatement) => db.prepare(sql).all(...params);\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsOf({ sql, params }),\n async batch(statements) {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n const results = statements.map(rowsOf);\n db.exec(\"COMMIT\");\n return results;\n } catch (error) {\n // Some errors (a full disk) end the transaction themselves, and ROLLBACK then fails; the statement's error is\n // the one worth reporting.\n try {\n db.exec(\"ROLLBACK\");\n } catch {}\n throw error;\n }\n },\n };\n}\n","// cloudrop/adapters/sql: the database store over plain SQL drivers. `sqlStore(executor)` takes an executor for\n// Postgres or SQLite; the four shipped here cover node-postgres, postgres.js, node:sqlite and Cloudflare D1, and any\n// other driver needs only `query` and an atomic `batch` (spec M5 §7).\n\nimport type { CloudropStore, TransactionalStore } from \"../server/store.ts\";\nimport type { SqlExecutor, TransactionalSqlExecutor } from \"../store/sql/executor.ts\";\nimport { type SqlStoreOptions, sqlStore as storeOverSql } from \"../store/sql/store.ts\";\nimport { withRoute } from \"./transactional.ts\";\n\nexport type {\n SqlDialect,\n SqlExecutor,\n SqlRow,\n SqlStatement,\n TransactionalSqlExecutor,\n} from \"../store/sql/executor.ts\";\nexport type { SqlStoreOptions } from \"../store/sql/store.ts\";\nexport type { StoreTables } from \"../store/sql/tables.ts\";\nexport type { D1Database, D1Statement } from \"./sql/d1.ts\";\nexport { d1Executor } from \"./sql/d1.ts\";\nexport type { PgPool, PgPoolClient, PgQueryable } from \"./sql/pg.ts\";\nexport { pgExecutor } from \"./sql/pg.ts\";\nexport type { PostgresJsQueryable, PostgresJsSql } from \"./sql/postgres-js.ts\";\nexport { postgresJsExecutor } from \"./sql/postgres-js.ts\";\nexport type { SqliteDatabase } from \"./sql/sqlite.ts\";\nexport { sqliteExecutor } from \"./sql/sqlite.ts\";\n\n/**\n * The database store over SQL tables, for Postgres or SQLite. Each method is one atomic unit (one statement on\n * Postgres, one batch on SQLite); the tables are checked on the first call. Postgres must run at its default isolation,\n * READ COMMITTED: the claim, quota and reconcile guarantees rely on its re-reading of a row it waited for. With\n * `transaction: true` and an executor that can hold a transaction (`pgExecutor`, `postgresJsExecutor`), completions\n * run in a transaction and the store gets `route`; without it, completions use a lease.\n */\nexport function sqlStore<TTx>(\n executor: TransactionalSqlExecutor<TTx>,\n options: SqlStoreOptions & { transaction: true },\n): TransactionalStore<TTx>;\nexport function sqlStore(\n executor: SqlExecutor<unknown>,\n options?: SqlStoreOptions & { transaction?: false },\n): CloudropStore;\nexport function sqlStore<TTx>(executor: SqlExecutor<TTx>, options: SqlStoreOptions = {}): CloudropStore<TTx> {\n const store = storeOverSql(executor, options);\n return options.transaction ? withRoute(store) : store;\n}\n"],"mappings":";;;AAyBA,MAAMA,QAAM,WACV,WAAW,YAAY,OAAO,KAAK,YAAY,MAAM,OAAO,MAAM,KAAK,CAAC,GAAG,MAAM,CAAC,EAAA,CAAG,IAAI;AAO3F,SAAgB,WAAW,MAAqD;CAE9E,eAAe,cAAiB,MAAwD;EACtF,MAAM,SAAS,MAAM,KAAK,QAAQ;EAClC,IAAI,SAAS;EAIb,MAAM,gBAAgB;GACpB,SAAS;EACX;EAEA,MAAM,EAAE,IAAI,mBAAmB;EAC/B,MAAM,YAAY,OAAO,KAAA,KAAa,mBAAmB,KAAA;EACzD,IAAI,WAAW,GAAG,KAAK,QAAQ,SAAS,OAAO;EAC/C,IAAI;GACF,MAAM,OAAO,MAAM,OAAO;GAC1B,MAAM,SAAS,MAAM,KAAK,MAAM;GAChC,MAAM,OAAO,MAAM,QAAQ;GAC3B,OAAO;EACT,SAAS,OAAO;GAEd,MAAM,OAAO,MAAM,UAAU,CAAC,CAAC,YAAY;IACzC,SAAS;GACX,CAAC;GACD,MAAM;EACR,UAAU;GACR,IAAI,WAAW,eAAe,KAAK,QAAQ,SAAS,OAAO;GAC3D,OAAO,QAAQ,MAAM;EACvB;CACF;CAEA,OAAO;EACL,GAAGA,KAAG,IAAI;EAEV,QAAQ,eAAe,eAAe,WAAWA,KAAG,MAAM,CAAC,CAAC,MAAM,UAAU,CAAC;EAC7E,cAAc,QAAQ,eAAe,WAAW,IAAIA,KAAG,MAAM,GAAG,MAAM,CAAC;CAC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