cloudrop 0.2.0 → 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.
- package/CHANGELOG.md +55 -0
- package/README.md +29 -1
- package/dist/adapters/sql.d.ts +3 -0
- package/dist/adapters/sql.js +7 -0
- package/dist/adapters/sql.js.map +1 -1
- package/dist/cli.js +2045 -0
- package/dist/{client-ePVHwvMv.js → client-DxP3uv8V.js} +47 -5
- package/dist/client-DxP3uv8V.js.map +1 -0
- package/dist/client.js +1 -1
- package/dist/index.d.ts +25 -1
- package/dist/index.js +86 -45
- package/dist/index.js.map +1 -1
- package/dist/react.js +1 -1
- package/dist/testing.d.ts +81 -0
- package/dist/testing.js +1243 -0
- package/dist/testing.js.map +1 -0
- package/docs/README.md +30 -0
- package/docs/bucket-setup.md +226 -0
- package/docs/client.md +386 -0
- package/docs/command.md +129 -0
- package/docs/deployment.md +169 -0
- package/docs/errors.md +150 -0
- package/docs/hono.md +276 -0
- package/docs/react.md +508 -0
- package/docs/resume.md +253 -0
- package/docs/server.md +603 -0
- package/docs/store.md +804 -0
- package/docs/testing-your-app.md +328 -0
- package/docs/troubleshooting.md +176 -0
- package/package.json +10 -2
- package/dist/client-ePVHwvMv.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,61 @@ 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
|
+
|
|
9
64
|
## 0.2.0 - 2026-11-20
|
|
10
65
|
|
|
11
66
|
### Added
|
package/README.md
CHANGED
|
@@ -82,12 +82,35 @@ erasure of a user's files (`api.eraseOwner`) and a sweep for abandoned uploads,
|
|
|
82
82
|
crash, a throw or a run longer than its lease; only its writes through `tx` on Postgres with `transaction: true` commit
|
|
83
83
|
exactly once: [Database store](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/store.md#what-it-guarantees).
|
|
84
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
|
+
|
|
85
105
|
## Bucket setup
|
|
86
106
|
|
|
87
107
|
The browser uploads to the bucket directly, so the bucket needs a CORS rule that allows `PUT` from your page's origin
|
|
88
108
|
with the headers cloudrop signs (`content-type`, `content-disposition`, `if-none-match`, `x-amz-meta-cloudrop-id`) and
|
|
89
109
|
exposes `ETag` and `Retry-After`, plus a lifecycle rule that aborts incomplete multipart uploads. Both rules, with the
|
|
90
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).
|
|
91
114
|
|
|
92
115
|
## Documentation
|
|
93
116
|
|
|
@@ -98,9 +121,14 @@ Wrangler and AWS CLI commands: [Bucket setup](https://github.com/vcode-sh/cloudr
|
|
|
98
121
|
[Database store](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/store.md) ·
|
|
99
122
|
[Deployment](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/deployment.md) ·
|
|
100
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) ·
|
|
101
125
|
[Hono guide](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/hono.md) ·
|
|
102
126
|
[Errors](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/errors.md) ·
|
|
103
|
-
[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.
|
|
104
132
|
|
|
105
133
|
Runs on Node.js 24+, Bun, Deno and Cloudflare Workers, with zero runtime dependencies. `cloudrop/react` needs React 18
|
|
106
134
|
or 19, an optional peer dependency.
|
package/dist/adapters/sql.d.ts
CHANGED
|
@@ -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 {
|
package/dist/adapters/sql.js
CHANGED
|
@@ -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
|
}
|
package/dist/adapters/sql.js.map
CHANGED
|
@@ -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,OAAO,MAAM,UAAU,CAAC,CAA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AU,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;CACzE;AACF;;ACjDA,MAA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