cloudrop 0.0.0 → 0.1.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 +56 -0
- package/LICENSE +21 -0
- package/README.md +98 -3
- package/dist/adapters/drizzle.d.ts +204 -0
- package/dist/adapters/drizzle.js +216 -0
- package/dist/adapters/drizzle.js.map +1 -0
- package/dist/adapters/prisma.d.ts +81 -0
- package/dist/adapters/prisma.js +32 -0
- package/dist/adapters/prisma.js.map +1 -0
- package/dist/adapters/sql.d.ts +98 -0
- package/dist/adapters/sql.js +70 -0
- package/dist/adapters/sql.js.map +1 -0
- package/dist/client-Dj6ON4MN.d.ts +214 -0
- package/dist/client-Y1zUEbCj.js +1561 -0
- package/dist/client-Y1zUEbCj.js.map +1 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +3 -0
- package/dist/d1-BY2c5bcL.js +16 -0
- package/dist/d1-BY2c5bcL.js.map +1 -0
- package/dist/errors-CUxMmFAe.js +40 -0
- package/dist/errors-CUxMmFAe.js.map +1 -0
- package/dist/executor-CEA7WV2W.d.ts +27 -0
- package/dist/index.d.ts +421 -0
- package/dist/index.js +3007 -0
- package/dist/index.js.map +1 -0
- package/dist/input-DTC476_I.js +13 -0
- package/dist/input-DTC476_I.js.map +1 -0
- package/dist/next.d.ts +9 -0
- package/dist/next.js +14 -0
- package/dist/next.js.map +1 -0
- package/dist/node.d.ts +32 -0
- package/dist/node.js +100 -0
- package/dist/node.js.map +1 -0
- package/dist/part-size-CvMoobfC.js +9 -0
- package/dist/part-size-CvMoobfC.js.map +1 -0
- package/dist/react.d.ts +123 -0
- package/dist/react.js +355 -0
- package/dist/react.js.map +1 -0
- package/dist/route-CspI1Ypt.js +72 -0
- package/dist/route-CspI1Ypt.js.map +1 -0
- package/dist/store-BfCJejGh.d.ts +382 -0
- package/dist/tables-DZnw2sPK.d.ts +11 -0
- package/dist/transactional-DnvnGsVH.js +672 -0
- package/dist/transactional-DnvnGsVH.js.map +1 -0
- package/dist/types-BZUOaz_B.js +5 -0
- package/dist/types-BZUOaz_B.js.map +1 -0
- package/dist/types-BrAx3dA4.d.ts +185 -0
- package/package.json +108 -4
|
@@ -0,0 +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(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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,MAAM,MAAM,uBAAuB,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,UAAU;EACxE,CASW;EAAG,OAPF,YAAY,MAAM,OAAO;GACrC,OAAO,WAAW,OAAO,CAAC,CAAC,WAAW;GACtC,eAAe,MAAM,gBAAgB;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"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
|
|
2
|
+
import { t as StoreTables } from "../tables-DZnw2sPK.js";
|
|
3
|
+
/** What the store calls on a Prisma client, or on the client of an interactive transaction. */
|
|
4
|
+
export interface PrismaQueryable {
|
|
5
|
+
$queryRawUnsafe(query: string, ...values: unknown[]): PromiseLike<unknown>;
|
|
6
|
+
}
|
|
7
|
+
/** Prisma's options for an interactive transaction, both in milliseconds. */
|
|
8
|
+
export interface PrismaTransactionOptions {
|
|
9
|
+
/** How long to wait for a connection from the pool. Prisma's default is 2000. */
|
|
10
|
+
maxWait?: number;
|
|
11
|
+
/**
|
|
12
|
+
* How long the whole transaction, `onComplete` included, may run before Prisma rolls it back. Prisma's default is
|
|
13
|
+
* 5000; a completion that runs out answers a retryable error and nothing of it is kept.
|
|
14
|
+
*/
|
|
15
|
+
timeout?: number;
|
|
16
|
+
}
|
|
17
|
+
/** A Prisma 7 client, `new PrismaClient({ adapter })`, or one made with `$extends`. */
|
|
18
|
+
export interface PrismaClientLike extends PrismaQueryable {
|
|
19
|
+
$transaction(queries: PromiseLike<unknown>[]): Promise<unknown[]>;
|
|
20
|
+
$transaction<T>(run: (tx: PrismaQueryable) => Promise<T>, options?: PrismaTransactionOptions): Promise<T>;
|
|
21
|
+
}
|
|
22
|
+
/** The client Prisma hands an interactive transaction's callback, as `TClient`'s own type declares it. */
|
|
23
|
+
export type PrismaTransactionClient<TClient> = TClient extends {
|
|
24
|
+
$transaction(run: (tx: infer TTx) => Promise<unknown>, ...rest: never[]): unknown;
|
|
25
|
+
} ? TTx : never;
|
|
26
|
+
interface StoreOptionsBase {
|
|
27
|
+
/** The provider of the Prisma schema's datasource: `"postgres"` (`postgresql`) or `"sqlite"`. */
|
|
28
|
+
dialect: "postgres" | "sqlite";
|
|
29
|
+
/**
|
|
30
|
+
* The two tables' names, defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres their schema; letters,
|
|
31
|
+
* digits and `_`.
|
|
32
|
+
*/
|
|
33
|
+
tables?: StoreTables;
|
|
34
|
+
}
|
|
35
|
+
export interface PrismaStoreOptions extends StoreOptionsBase {
|
|
36
|
+
/** Off: each `/complete` holds its file with a lease while `onComplete` runs, and `onComplete` gets no `tx`. */
|
|
37
|
+
transaction?: false;
|
|
38
|
+
}
|
|
39
|
+
export interface PrismaTransactionalStoreOptions extends StoreOptionsBase {
|
|
40
|
+
dialect: "postgres";
|
|
41
|
+
/**
|
|
42
|
+
* Runs each completion's claim, `onComplete` and completion in one Prisma interactive transaction, and passes its
|
|
43
|
+
* client to `onComplete` as `tx`: what `onComplete` writes through `tx` commits with the completion or not at all.
|
|
44
|
+
*/
|
|
45
|
+
transaction: true;
|
|
46
|
+
/** Raise `timeout` when `onComplete` may take longer than Prisma's 5 seconds. */
|
|
47
|
+
transactionOptions?: PrismaTransactionOptions;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A cloudrop store over a Prisma 7 client, in two tables you add to your Prisma schema (the store guide links the
|
|
51
|
+
* models). Without `transaction`, a `/complete` holds its file with a lease while `onComplete` runs. With
|
|
52
|
+
* `transaction: true` (Postgres only), the claim, `onComplete` and the completion share one interactive transaction:
|
|
53
|
+
* build routes with `store.route` so `onComplete` gets Prisma's transaction client as `tx`, and keep network calls out
|
|
54
|
+
* of it (they belong in `afterComplete`).
|
|
55
|
+
*
|
|
56
|
+
* On Postgres, tables outside `public` take `tables: { schema: "app" }`, with both models declared `@@schema("app")`
|
|
57
|
+
* and `schemas = ["public", "app"]` in the datasource; every model then needs its `@@schema`. PrismaPg's `schema`
|
|
58
|
+
* option does not reach the store, whose raw SQL uses only `tables`. Without `tables.schema` the store's SQL finds its
|
|
59
|
+
* tables through the connection's search path, set once for the role with `ALTER ROLE <user> SET search_path = app`
|
|
60
|
+
* (this also works behind a connection pooler) or per connection with `?options=-c%20search_path%3Dapp` in the
|
|
61
|
+
* connection string (some poolers drop or refuse that startup option).
|
|
62
|
+
*
|
|
63
|
+
* Usage
|
|
64
|
+
* ```ts
|
|
65
|
+
* const store = prismaStore(prisma, { dialect: "postgres", transaction: true });
|
|
66
|
+
* const avatar = store.route(
|
|
67
|
+
* { accept: "image/*", maxSize: "5MB", authorize: async ({ request }) => ({ userId: await userIdOf(request) }) },
|
|
68
|
+
* {
|
|
69
|
+
* owner: ({ userId }) => userId,
|
|
70
|
+
* onComplete: async ({ tx, userId, file }) => {
|
|
71
|
+
* await tx.avatar.create({ data: { userId, key: file.key } });
|
|
72
|
+
* return { key: file.key };
|
|
73
|
+
* },
|
|
74
|
+
* },
|
|
75
|
+
* );
|
|
76
|
+
* export const cloudrop = createCloudrop({ storage: r2(), store, routes: { avatar } });
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export declare function prismaStore<TClient extends PrismaClientLike>(prisma: TClient, options: PrismaTransactionalStoreOptions): TransactionalStore<PrismaTransactionClient<TClient>>;
|
|
80
|
+
export declare function prismaStore(prisma: PrismaClientLike, options: PrismaStoreOptions): CloudropStore;
|
|
81
|
+
export type { StoreTables };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { n as configError } from "../errors-CUxMmFAe.js";
|
|
2
|
+
import { i as sequential, n as sqlStore, t as withRoute } from "../transactional-DnvnGsVH.js";
|
|
3
|
+
// src/adapters/prisma.ts
|
|
4
|
+
const on = (client, dialect) => sequential(dialect, async (sql, params) => await client.$queryRawUnsafe(sql, ...params));
|
|
5
|
+
function checkOptions(options) {
|
|
6
|
+
const { dialect, transaction } = options;
|
|
7
|
+
if (dialect !== "postgres" && dialect !== "sqlite") throw configError(`prismaStore() got dialect ${JSON.stringify(dialect)}. Pass { dialect: "postgres" } or { dialect: "sqlite" }, matching your Prisma datasource.`);
|
|
8
|
+
if (!transaction && "transactionOptions" in options && options.transactionOptions) throw configError("prismaStore(): transactionOptions applies only with transaction: true. Add transaction: true, or remove transactionOptions.");
|
|
9
|
+
}
|
|
10
|
+
function prismaExecutor(prisma, { dialect, transactionOptions }) {
|
|
11
|
+
return {
|
|
12
|
+
...on(prisma, dialect),
|
|
13
|
+
batch: async (statements) => await prisma.$transaction(statements.map(({ sql, params }) => prisma.$queryRawUnsafe(sql, ...params))),
|
|
14
|
+
transaction: (run) => prisma.$transaction((tx) => run(on(tx, dialect), tx), transactionOptions)
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function prismaStore(prisma, options) {
|
|
18
|
+
checkOptions(options);
|
|
19
|
+
const { tables, transaction = false } = options;
|
|
20
|
+
const transactionOptions = options.transaction ? options.transactionOptions : void 0;
|
|
21
|
+
const store = sqlStore(prismaExecutor(prisma, {
|
|
22
|
+
dialect: options.dialect,
|
|
23
|
+
transactionOptions
|
|
24
|
+
}), {
|
|
25
|
+
tables,
|
|
26
|
+
transaction
|
|
27
|
+
});
|
|
28
|
+
return transaction ? withRoute(store) : store;
|
|
29
|
+
}
|
|
30
|
+
export { prismaStore };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=prisma.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prisma.js","names":[],"sources":["../../src/adapters/prisma.ts"],"sourcesContent":["// cloudrop/adapters/prisma: the database store over a Prisma 7 client, on Postgres or SQLite (spec M5 §7, M5-T14). The\n// SQL core writes every statement; this file runs them through `$queryRawUnsafe` and `$transaction`. The client is\n// described by the members called here, so the library imports nothing from Prisma.\n\nimport { configError } from \"../errors.ts\";\nimport type { CloudropStore, TransactionalStore } from \"../server/store.ts\";\nimport { type SqlRow, sequential, type TransactionalSqlExecutor } from \"../store/sql/executor.ts\";\nimport { sqlStore } from \"../store/sql/store.ts\";\nimport type { StoreTables } from \"../store/sql/tables.ts\";\nimport { withRoute } from \"./transactional.ts\";\n\nexport type { StoreTables } from \"../store/sql/tables.ts\";\n\n/** What the store calls on a Prisma client, or on the client of an interactive transaction. */\nexport interface PrismaQueryable {\n $queryRawUnsafe(query: string, ...values: unknown[]): PromiseLike<unknown>;\n}\n\n/** Prisma's options for an interactive transaction, both in milliseconds. */\nexport interface PrismaTransactionOptions {\n /** How long to wait for a connection from the pool. Prisma's default is 2000. */\n maxWait?: number;\n /**\n * How long the whole transaction, `onComplete` included, may run before Prisma rolls it back. Prisma's default is\n * 5000; a completion that runs out answers a retryable error and nothing of it is kept.\n */\n timeout?: number;\n}\n\n/** A Prisma 7 client, `new PrismaClient({ adapter })`, or one made with `$extends`. */\nexport interface PrismaClientLike extends PrismaQueryable {\n $transaction(queries: PromiseLike<unknown>[]): Promise<unknown[]>;\n $transaction<T>(run: (tx: PrismaQueryable) => Promise<T>, options?: PrismaTransactionOptions): Promise<T>;\n}\n\n/** The client Prisma hands an interactive transaction's callback, as `TClient`'s own type declares it. */\nexport type PrismaTransactionClient<TClient> = TClient extends {\n // Prisma declares the callback form last, and inference reads the last overload.\n $transaction(run: (tx: infer TTx) => Promise<unknown>, ...rest: never[]): unknown;\n}\n ? TTx\n : never;\n\ninterface StoreOptionsBase {\n /** The provider of the Prisma schema's datasource: `\"postgres\"` (`postgresql`) or `\"sqlite\"`. */\n dialect: \"postgres\" | \"sqlite\";\n /**\n * The two tables' names, defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres their schema; letters,\n * digits and `_`.\n */\n tables?: StoreTables;\n}\n\nexport interface PrismaStoreOptions extends StoreOptionsBase {\n /** Off: each `/complete` holds its file with a lease while `onComplete` runs, and `onComplete` gets no `tx`. */\n transaction?: false;\n}\n\nexport interface PrismaTransactionalStoreOptions extends StoreOptionsBase {\n dialect: \"postgres\";\n /**\n * Runs each completion's claim, `onComplete` and completion in one Prisma interactive transaction, and passes its\n * client to `onComplete` as `tx`: what `onComplete` writes through `tx` commits with the completion or not at all.\n */\n transaction: true;\n /** Raise `timeout` when `onComplete` may take longer than Prisma's 5 seconds. */\n transactionOptions?: PrismaTransactionOptions;\n}\n\n/** The executor's statements on the client or a transaction's client, in order when batched. */\nconst on = (client: PrismaQueryable, dialect: \"postgres\" | \"sqlite\") =>\n sequential(\n dialect,\n // Prisma answers the rows of a raw query as plain objects, and an empty array for a statement without RETURNING.\n async (sql, params) => (await client.$queryRawUnsafe(sql, ...params)) as SqlRow[],\n );\n\nfunction checkOptions(options: PrismaStoreOptions | PrismaTransactionalStoreOptions): void {\n const { dialect, transaction } = options;\n if (dialect !== \"postgres\" && dialect !== \"sqlite\") {\n throw configError(\n `prismaStore() got dialect ${JSON.stringify(dialect)}. Pass { dialect: \"postgres\" } or { dialect: \"sqlite\" }, matching your Prisma datasource.`,\n );\n }\n if (!transaction && \"transactionOptions\" in options && options.transactionOptions) {\n throw configError(\n \"prismaStore(): transactionOptions applies only with transaction: true. Add transaction: true, or remove transactionOptions.\",\n );\n }\n}\n\nfunction prismaExecutor(\n prisma: PrismaClientLike,\n { dialect, transactionOptions }: { dialect: \"postgres\" | \"sqlite\"; transactionOptions?: PrismaTransactionOptions },\n): TransactionalSqlExecutor<PrismaQueryable> {\n return {\n ...on(prisma, dialect),\n // The array form: Prisma runs the queries in order in one transaction, and a failure rolls back all of them.\n batch: async (statements) =>\n (await prisma.$transaction(\n statements.map(({ sql, params }) => prisma.$queryRawUnsafe(sql, ...params)),\n )) as SqlRow[][],\n // The store uses it only with transaction: true, which the core refuses on SQLite.\n transaction: (run) => prisma.$transaction((tx) => run(on(tx, dialect), tx), transactionOptions),\n };\n}\n\n/**\n * A cloudrop store over a Prisma 7 client, in two tables you add to your Prisma schema (the store guide links the\n * models). Without `transaction`, a `/complete` holds its file with a lease while `onComplete` runs. With\n * `transaction: true` (Postgres only), the claim, `onComplete` and the completion share one interactive transaction:\n * build routes with `store.route` so `onComplete` gets Prisma's transaction client as `tx`, and keep network calls out\n * of it (they belong in `afterComplete`).\n *\n * On Postgres, tables outside `public` take `tables: { schema: \"app\" }`, with both models declared `@@schema(\"app\")`\n * and `schemas = [\"public\", \"app\"]` in the datasource; every model then needs its `@@schema`. PrismaPg's `schema`\n * option does not reach the store, whose raw SQL uses only `tables`. Without `tables.schema` the store's SQL finds its\n * tables through the connection's search path, set once for the role with `ALTER ROLE <user> SET search_path = app`\n * (this also works behind a connection pooler) or per connection with `?options=-c%20search_path%3Dapp` in the\n * connection string (some poolers drop or refuse that startup option).\n *\n * Usage\n * ```ts\n * const store = prismaStore(prisma, { dialect: \"postgres\", transaction: true });\n * const avatar = store.route(\n * { accept: \"image/*\", maxSize: \"5MB\", authorize: async ({ request }) => ({ userId: await userIdOf(request) }) },\n * {\n * owner: ({ userId }) => userId,\n * onComplete: async ({ tx, userId, file }) => {\n * await tx.avatar.create({ data: { userId, key: file.key } });\n * return { key: file.key };\n * },\n * },\n * );\n * export const cloudrop = createCloudrop({ storage: r2(), store, routes: { avatar } });\n * ```\n */\nexport function prismaStore<TClient extends PrismaClientLike>(\n prisma: TClient,\n options: PrismaTransactionalStoreOptions,\n): TransactionalStore<PrismaTransactionClient<TClient>>;\nexport function prismaStore(prisma: PrismaClientLike, options: PrismaStoreOptions): CloudropStore;\nexport function prismaStore(\n prisma: PrismaClientLike,\n options: PrismaStoreOptions | PrismaTransactionalStoreOptions,\n): CloudropStore<unknown> {\n checkOptions(options);\n const { tables, transaction = false } = options;\n const transactionOptions = options.transaction ? options.transactionOptions : undefined;\n const store = sqlStore(prismaExecutor(prisma, { dialect: options.dialect, transactionOptions }), {\n tables,\n transaction,\n });\n return transaction ? withRoute(store) : store;\n}\n"],"mappings":";;;AAsEA,MAAM,MAAM,QAAyB,YACnC,WACE,SAEA,OAAO,KAAK,WAAY,MAAM,OAAO,gBAAgB,KAAK,GAAG,MAAM,CACrE;AAEF,SAAS,aAAa,SAAqE;CACzF,MAAM,EAAE,SAAS,gBAAgB;CACjC,IAAI,YAAY,cAAc,YAAY,UACxC,MAAM,YACJ,6BAA6B,KAAK,UAAU,OAAO,EAAE,0FACvD;CAEF,IAAI,CAAC,eAAe,wBAAwB,WAAW,QAAQ,oBAC7D,MAAM,YACJ,6HACF;AAEJ;AAEA,SAAS,eACP,QACA,EAAE,SAAS,sBACgC;CAC3C,OAAO;EACL,GAAG,GAAG,QAAQ,OAAO;EAErB,OAAO,OAAO,eACX,MAAM,OAAO,aACZ,WAAW,KAAK,EAAE,KAAK,aAAa,OAAO,gBAAgB,KAAK,GAAG,MAAM,CAAC,CAC5E;EAEF,cAAc,QAAQ,OAAO,cAAc,OAAO,IAAI,GAAG,IAAI,OAAO,GAAG,EAAE,GAAG,kBAAkB;CAChG;AACF;AAqCA,SAAgB,YACd,QACA,SACwB;CACxB,aAAa,OAAO;CACpB,MAAM,EAAE,QAAQ,cAAc,UAAU;CACxC,MAAM,qBAAqB,QAAQ,cAAc,QAAQ,qBAAqB,KAAA;CAC9E,MAAM,QAAQ,SAAS,eAAe,QAAQ;EAAE,SAAS,QAAQ;EAAS;CAAmB,CAAC,GAAG;EAC/F;EACA;CACF,CAAC;CACD,OAAO,cAAc,UAAU,KAAK,IAAI;AAC1C"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
|
|
2
|
+
import { a as TransactionalSqlExecutor, i as SqlStatement, n as SqlExecutor, r as SqlRow, t as SqlDialect } from "../executor-CEA7WV2W.js";
|
|
3
|
+
import { t as StoreTables } from "../tables-DZnw2sPK.js";
|
|
4
|
+
interface SqlStoreOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The two tables' names, defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres their schema; letters,
|
|
7
|
+
* digits and `_`.
|
|
8
|
+
*/
|
|
9
|
+
tables?: StoreTables;
|
|
10
|
+
/**
|
|
11
|
+
* Postgres only, with an executor that has `transaction()`. On: each completion's claim, `onComplete` and record
|
|
12
|
+
* share one transaction, and the store gets `route` for routes whose `onComplete` receives it as `tx`; a completion
|
|
13
|
+
* holds a connection and the row lock while `onComplete` runs. Off (the default): a completion holds its file with
|
|
14
|
+
* a lease and no connection.
|
|
15
|
+
*/
|
|
16
|
+
transaction?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** A D1 prepared statement. */
|
|
19
|
+
interface D1Statement {
|
|
20
|
+
bind(...values: unknown[]): D1Statement;
|
|
21
|
+
all(): Promise<{
|
|
22
|
+
results: SqlRow[];
|
|
23
|
+
}>;
|
|
24
|
+
}
|
|
25
|
+
/** A D1 database binding, `env.DB`. */
|
|
26
|
+
interface D1Database {
|
|
27
|
+
prepare(query: string): D1Statement;
|
|
28
|
+
batch(statements: D1Statement[]): Promise<{
|
|
29
|
+
results: SqlRow[];
|
|
30
|
+
}[]>;
|
|
31
|
+
}
|
|
32
|
+
/** An executor over a D1 binding: `sqlStore(d1Executor(env.DB))`. */
|
|
33
|
+
export declare function d1Executor(d1: D1Database): SqlExecutor;
|
|
34
|
+
/** What the executor calls on a node-postgres pool or client; `onComplete` gets the transaction's client as `tx`. */
|
|
35
|
+
interface PgQueryable {
|
|
36
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
37
|
+
rows: SqlRow[];
|
|
38
|
+
}>;
|
|
39
|
+
}
|
|
40
|
+
/** A client checked out of the pool. */
|
|
41
|
+
interface PgPoolClient extends PgQueryable {
|
|
42
|
+
release(destroy?: boolean | Error): void;
|
|
43
|
+
}
|
|
44
|
+
/** A node-postgres `Pool`. Size it for your concurrency; transaction mode holds a client while `onComplete` runs. */
|
|
45
|
+
interface PgPool extends PgQueryable {
|
|
46
|
+
connect(): Promise<PgPoolClient>;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* An executor over a node-postgres pool: `sqlStore(pgExecutor(new Pool({ connectionString })))`. Leave the
|
|
50
|
+
* connections at Postgres's default isolation, READ COMMITTED: the store's guarantees rely on it (set no
|
|
51
|
+
* `default_transaction_isolation`).
|
|
52
|
+
*/
|
|
53
|
+
export declare function pgExecutor(pool: PgPool): TransactionalSqlExecutor<PgQueryable>;
|
|
54
|
+
/** What the executor calls on postgres.js's `sql` or a transaction's `sql`. */
|
|
55
|
+
interface PostgresJsQueryable {
|
|
56
|
+
unsafe(query: string, parameters?: unknown[]): PromiseLike<readonly SqlRow[]>;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* A postgres.js instance, `postgres(url)`. `TTx` is its transaction's `sql`, which `onComplete` receives as `tx`; it is
|
|
60
|
+
* inferred from the instance, so `tx` keeps postgres.js's own type.
|
|
61
|
+
*/
|
|
62
|
+
interface PostgresJsSql<TTx extends PostgresJsQueryable = PostgresJsQueryable> extends PostgresJsQueryable {
|
|
63
|
+
begin(run: (sql: TTx) => Promise<unknown>): Promise<unknown>;
|
|
64
|
+
begin(options: string, run: (sql: TTx) => Promise<unknown>): Promise<unknown>;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* An executor over postgres.js: `sqlStore(postgresJsExecutor(postgres(url)))`. Leave the connections at Postgres's
|
|
68
|
+
* default isolation, READ COMMITTED: the store's guarantees rely on it (set no `default_transaction_isolation`).
|
|
69
|
+
*/
|
|
70
|
+
export declare function postgresJsExecutor<TTx extends PostgresJsQueryable>(sql: PostgresJsSql<TTx>): TransactionalSqlExecutor<TTx>;
|
|
71
|
+
/** What the executor calls on a node:sqlite `DatabaseSync`. */
|
|
72
|
+
interface SqliteDatabase {
|
|
73
|
+
exec(sql: string): unknown;
|
|
74
|
+
prepare(sql: string): {
|
|
75
|
+
all(...params: unknown[]): SqlRow[];
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* An executor over node:sqlite: `sqlStore(sqliteExecutor(new DatabaseSync(path)))`. Do not share the connection with
|
|
80
|
+
* code that holds its own transaction open across awaits: a batch's BEGIN would then fail. When another connection or
|
|
81
|
+
* process writes the same file, open it with a busy timeout, `new DatabaseSync(path, { timeout: 5000 })`: the default
|
|
82
|
+
* of 0 fails a batch at once with "database is locked" while the other writer holds the file.
|
|
83
|
+
*/
|
|
84
|
+
export declare function sqliteExecutor(db: SqliteDatabase): SqlExecutor;
|
|
85
|
+
/**
|
|
86
|
+
* The database store over SQL tables, for Postgres or SQLite. Each method is one atomic unit (one statement on
|
|
87
|
+
* Postgres, one batch on SQLite); the tables are checked on the first call. Postgres must run at its default isolation,
|
|
88
|
+
* READ COMMITTED: the claim, quota and reconcile guarantees rely on its re-reading of a row it waited for. With
|
|
89
|
+
* `transaction: true` and an executor that can hold a transaction (`pgExecutor`, `postgresJsExecutor`), completions
|
|
90
|
+
* run in a transaction and the store gets `route`; without it, completions use a lease.
|
|
91
|
+
*/
|
|
92
|
+
export declare function sqlStore<TTx>(executor: TransactionalSqlExecutor<TTx>, options: SqlStoreOptions & {
|
|
93
|
+
transaction: true;
|
|
94
|
+
}): TransactionalStore<TTx>;
|
|
95
|
+
export declare function sqlStore(executor: SqlExecutor<unknown>, options?: SqlStoreOptions & {
|
|
96
|
+
transaction?: false;
|
|
97
|
+
}): CloudropStore;
|
|
98
|
+
export type { D1Database, D1Statement, PgPool, PgPoolClient, PgQueryable, PostgresJsQueryable, PostgresJsSql, SqlDialect, SqlExecutor, SqlRow, SqlStatement, SqlStoreOptions, SqliteDatabase, StoreTables, TransactionalSqlExecutor };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { i as sequential, n as sqlStore$1, t as withRoute } from "../transactional-DnvnGsVH.js";
|
|
2
|
+
import { t as d1Executor } from "../d1-BY2c5bcL.js";
|
|
3
|
+
// src/adapters/sql/pg.ts
|
|
4
|
+
const on$1 = (client) => sequential("postgres", async (sql, params) => (await client.query(sql, [...params])).rows);
|
|
5
|
+
function pgExecutor(pool) {
|
|
6
|
+
async function inTransaction(work) {
|
|
7
|
+
const client = await pool.connect();
|
|
8
|
+
let broken = false;
|
|
9
|
+
try {
|
|
10
|
+
await client.query("BEGIN");
|
|
11
|
+
const result = await work(client);
|
|
12
|
+
await client.query("COMMIT");
|
|
13
|
+
return result;
|
|
14
|
+
} catch (error) {
|
|
15
|
+
await client.query("ROLLBACK").catch(() => {
|
|
16
|
+
broken = true;
|
|
17
|
+
});
|
|
18
|
+
throw error;
|
|
19
|
+
} finally {
|
|
20
|
+
client.release(broken);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
...on$1(pool),
|
|
25
|
+
batch: (statements) => inTransaction((client) => on$1(client).batch(statements)),
|
|
26
|
+
transaction: (run) => inTransaction((client) => run(on$1(client), client))
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
// src/adapters/sql/postgres-js.ts
|
|
30
|
+
const on = (sql) => sequential("postgres", async (query, params) => [...await sql.unsafe(query, [...params])]);
|
|
31
|
+
function postgresJsExecutor(sql) {
|
|
32
|
+
const inTransaction = async (work) => await sql.begin(work);
|
|
33
|
+
return {
|
|
34
|
+
...on(sql),
|
|
35
|
+
batch: (statements) => inTransaction((tx) => on(tx).batch(statements)),
|
|
36
|
+
transaction: (run) => inTransaction((tx) => run(on(tx), tx))
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
// src/adapters/sql/sqlite.ts
|
|
40
|
+
function sqliteExecutor(db) {
|
|
41
|
+
const rowsOf = ({ sql, params }) => db.prepare(sql).all(...params);
|
|
42
|
+
return {
|
|
43
|
+
dialect: "sqlite",
|
|
44
|
+
query: async (sql, params) => rowsOf({
|
|
45
|
+
sql,
|
|
46
|
+
params
|
|
47
|
+
}),
|
|
48
|
+
async batch(statements) {
|
|
49
|
+
db.exec("BEGIN IMMEDIATE");
|
|
50
|
+
try {
|
|
51
|
+
const results = statements.map(rowsOf);
|
|
52
|
+
db.exec("COMMIT");
|
|
53
|
+
return results;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
try {
|
|
56
|
+
db.exec("ROLLBACK");
|
|
57
|
+
} catch {}
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
// src/adapters/sql.ts
|
|
64
|
+
function sqlStore(executor, options = {}) {
|
|
65
|
+
const store = sqlStore$1(executor, options);
|
|
66
|
+
return options.transaction ? withRoute(store) : store;
|
|
67
|
+
}
|
|
68
|
+
export { d1Executor, pgExecutor, postgresJsExecutor, sqlStore, sqliteExecutor };
|
|
69
|
+
|
|
70
|
+
//# sourceMappingURL=sql.js.map
|
|
@@ -0,0 +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,CAAC,YAAY;IACzC,SAAS;GACX,CAAC;GACD,MAAM;EACR,UAAU;GACR,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;;ACnCA,MAAM,MAAM,QACV,WAAW,YAAY,OAAO,OAAO,WAA8B,CAAC,GAAI,MAAM,IAAI,OAAO,OAAO,CAAC,GAAG,MAAM,CAAC,CAAE,CAAC;AAMhH,SAAgB,mBACd,KAC+B;CAE/B,MAAM,gBAAgB,OAAU,SAE7B,MAAM,IAAI,MAAM,IAAI;CACvB,OAAO;EACL,GAAG,GAAG,GAAG;EAET,QAAQ,eAAe,eAAe,OAAO,GAAG,EAAE,CAAC,CAAC,MAAM,UAAU,CAAC;EACrE,cAAc,QAAQ,eAAe,OAAO,IAAI,GAAG,EAAE,GAAG,EAAE,CAAC;CAC7D;AACF;;ACvBA,SAAgB,eAAe,IAAiC;CAC9D,MAAM,UAAU,EAAE,KAAK,aAA2B,GAAG,QAAQ,GAAG,CAAC,CAAC,IAAI,GAAG,MAAM;CAC/E,OAAO;EACL,SAAS;EACT,OAAO,OAAO,KAAK,WAAW,OAAO;GAAE;GAAK;EAAO,CAAC;EACpD,MAAM,MAAM,YAAY;GACtB,GAAG,KAAK,iBAAiB;GACzB,IAAI;IACF,MAAM,UAAU,WAAW,IAAI,MAAM;IACrC,GAAG,KAAK,QAAQ;IAChB,OAAO;GACT,SAAS,OAAO;IAGd,IAAI;KACF,GAAG,KAAK,UAAU;IACpB,QAAQ,CAAC;IACT,MAAM;GACR;EACF;CACF;AACF;;ACEA,SAAgB,SAAc,UAA4B,UAA2B,CAAC,GAAuB;CAC3G,MAAM,QAAQC,WAAa,UAAU,OAAO;CAC5C,OAAO,QAAQ,cAAc,UAAU,KAAK,IAAI;AAClD"}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { E as CloudropError, _ as RouteResult, g as RouteName, h as RouteMetadata, i as CompleteResponse, k as Result, u as InferableCloudrop } from "./types-BrAx3dA4.js";
|
|
2
|
+
/** How the client sends every request: the endpoints' POSTs and the bucket's PUTs. */
|
|
3
|
+
type ClientFetch = (url: string, init: RequestInit) => Promise<Response>;
|
|
4
|
+
/** Where one file of a job stands. `done`, `failed` and `aborted` are final. */
|
|
5
|
+
type FileStatus = "queued" | "uploading" | "paused" | "completing" | "done" | "failed" | "aborted";
|
|
6
|
+
/** One file as a page renders it (spec §2.1). */
|
|
7
|
+
interface FileSnapshot<R> {
|
|
8
|
+
/** The same id as the file's handle. */
|
|
9
|
+
id: string;
|
|
10
|
+
name: string;
|
|
11
|
+
size: number;
|
|
12
|
+
type: string;
|
|
13
|
+
status: FileStatus;
|
|
14
|
+
/**
|
|
15
|
+
* Bytes sent, never decreasing while the file keeps its ticket: a re-sent part counts once it passes its earlier
|
|
16
|
+
* attempt (spec §4.2). A retry() that starts a new upload starts again from 0.
|
|
17
|
+
*/
|
|
18
|
+
bytes: number;
|
|
19
|
+
/** `bytes / size`; for an empty file, 1 once done and 0 before. */
|
|
20
|
+
progress: number;
|
|
21
|
+
/** Bytes per second, averaged over about 3 s (spec §4.3); 0 unless uploading. */
|
|
22
|
+
speed: number;
|
|
23
|
+
/** Seconds left at the current speed; null while the speed is 0. */
|
|
24
|
+
eta: number | null;
|
|
25
|
+
error: CloudropError | null;
|
|
26
|
+
result: CompleteResponse<R> | null;
|
|
27
|
+
}
|
|
28
|
+
/** The whole job as a page renders it. A new object only when something changed (spec §2.1). */
|
|
29
|
+
interface JobSnapshot<R> {
|
|
30
|
+
/** In the order the files were passed. */
|
|
31
|
+
files: readonly FileSnapshot<R>[];
|
|
32
|
+
/**
|
|
33
|
+
* `bytes`, `size`, `progress`, `speed` and `eta` count only the files that did not fail or abort, so a failed file
|
|
34
|
+
* never holds the job below 1; `done`, `failed` and `aborted` count files, and `count` is every file of the job.
|
|
35
|
+
*/
|
|
36
|
+
totals: {
|
|
37
|
+
bytes: number;
|
|
38
|
+
size: number;
|
|
39
|
+
progress: number;
|
|
40
|
+
speed: number;
|
|
41
|
+
eta: number | null;
|
|
42
|
+
done: number;
|
|
43
|
+
failed: number;
|
|
44
|
+
aborted: number;
|
|
45
|
+
count: number;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** How one file of a job ended. */
|
|
49
|
+
type FileOutcome<R> = {
|
|
50
|
+
id: string;
|
|
51
|
+
name: string;
|
|
52
|
+
status: "done";
|
|
53
|
+
result: CompleteResponse<R>;
|
|
54
|
+
} | {
|
|
55
|
+
id: string;
|
|
56
|
+
name: string;
|
|
57
|
+
status: "failed" | "aborted";
|
|
58
|
+
error: CloudropError;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* A job's result. Unlike `Result`, `data` stays when some files failed, so the files that succeeded are not hidden;
|
|
62
|
+
* `error` is then the error of the first file, in the order passed, that did not end done. `data` is null only when
|
|
63
|
+
* nothing started: the server refused the whole job, or the arguments were wrong.
|
|
64
|
+
*/
|
|
65
|
+
type UploadResult<R> = {
|
|
66
|
+
data: {
|
|
67
|
+
files: FileOutcome<R>[];
|
|
68
|
+
};
|
|
69
|
+
error: null;
|
|
70
|
+
} | {
|
|
71
|
+
data: {
|
|
72
|
+
files: FileOutcome<R>[];
|
|
73
|
+
};
|
|
74
|
+
error: CloudropError;
|
|
75
|
+
} | {
|
|
76
|
+
data: null;
|
|
77
|
+
error: CloudropError;
|
|
78
|
+
};
|
|
79
|
+
/** One file of a job. */
|
|
80
|
+
interface FileHandle<R = unknown> {
|
|
81
|
+
/** The client's sequence number as text ("1", "2", …): unique per client, stable for the job's life. */
|
|
82
|
+
readonly id: string;
|
|
83
|
+
readonly name: string;
|
|
84
|
+
/**
|
|
85
|
+
* Stops a queued or uploading file's requests and keeps what it sent: the parts that landed stay, and its bytes stay
|
|
86
|
+
* as counted. A file that is completing or has settled ignores it.
|
|
87
|
+
*/
|
|
88
|
+
pause(): void;
|
|
89
|
+
/** Sends a paused file's parts that have not landed; a single PUT starts again. Other files ignore it. */
|
|
90
|
+
resume(): void;
|
|
91
|
+
/**
|
|
92
|
+
* Cancels this file only, paused or not: its requests stop, it ends aborted at once, and the server is told of the
|
|
93
|
+
* ticket it holds. A failed file ends aborted too, and the server is told to drop what it kept for retry(), unless a
|
|
94
|
+
* /complete may have finished the file or the page already gave its ticket up (pagehide). A done file ignores it.
|
|
95
|
+
*/
|
|
96
|
+
abort(): void;
|
|
97
|
+
/**
|
|
98
|
+
* Sends a failed file again: with its ticket, only the parts that have not landed; when that ticket cannot succeed
|
|
99
|
+
* (expired, refused, or a failure only a new upload fixes), as a new upload with a new key. Resolves with the file's
|
|
100
|
+
* outcome once it settles. A file still sending is waited for, a paused one until it is resumed, and a done or
|
|
101
|
+
* aborted one resolves as it is.
|
|
102
|
+
*/
|
|
103
|
+
retry(): Promise<FileOutcome<R>>;
|
|
104
|
+
}
|
|
105
|
+
/** Several files sent through one /upload and one connection pool. */
|
|
106
|
+
interface UploadJob<R> {
|
|
107
|
+
/** The files in the order they were passed. */
|
|
108
|
+
readonly files: readonly FileHandle<R>[];
|
|
109
|
+
/**
|
|
110
|
+
* Settles once, when every file has first settled, with those outcomes: a later retry() never changes it. Never
|
|
111
|
+
* rejects.
|
|
112
|
+
*/
|
|
113
|
+
readonly done: Promise<UploadResult<R>>;
|
|
114
|
+
/** Cancels every file that has not ended done, as the signal does. */
|
|
115
|
+
abort(): void;
|
|
116
|
+
/** Pauses every file that is queued or uploading, as FileHandle.pause does. */
|
|
117
|
+
pause(): void;
|
|
118
|
+
/** Resumes every paused file. */
|
|
119
|
+
resume(): void;
|
|
120
|
+
/**
|
|
121
|
+
* Retries every failed file, as FileHandle.retry does, with one /upload for all that need a new ticket. Resolves
|
|
122
|
+
* with every file's current outcome once all have settled, or with `data` null and the error when that /upload asked
|
|
123
|
+
* for every file of the job and was refused or cancelled; never rejects.
|
|
124
|
+
*/
|
|
125
|
+
retry(): Promise<UploadResult<R>>;
|
|
126
|
+
/**
|
|
127
|
+
* Calls `listener` when the snapshot changes: at once on a status change, at most every 100 ms while bytes flow, and
|
|
128
|
+
* every second while a file uploads. Returns the unsubscribe. Needs no `this`, as `useSyncExternalStore` calls it.
|
|
129
|
+
*/
|
|
130
|
+
subscribe(listener: () => void): () => void;
|
|
131
|
+
/** The current snapshot: the same object until something changes. */
|
|
132
|
+
getSnapshot(): JobSnapshot<R>;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* An unfinished upload this browser keeps, as `resumable()` lists it: enough to ask the user for the file again. A
|
|
136
|
+
* plain, JSON-safe object; never the upload's token, key or metadata (resume spec §2).
|
|
137
|
+
*/
|
|
138
|
+
interface ResumableUpload<TName extends string = string> {
|
|
139
|
+
/** The upload's id, stable across page loads: the ticket's `id`. */
|
|
140
|
+
id: string;
|
|
141
|
+
route: TName;
|
|
142
|
+
name: string;
|
|
143
|
+
size: number;
|
|
144
|
+
type: string;
|
|
145
|
+
lastModified: number;
|
|
146
|
+
/** ISO 8601: when its token expires. A minute before that it is no longer listed. */
|
|
147
|
+
expiresAt: string;
|
|
148
|
+
}
|
|
149
|
+
interface ClientOptions {
|
|
150
|
+
/** Where the server's handler is mounted: a path on this page's origin or an absolute URL. Default "/api/cloudrop". */
|
|
151
|
+
basePath?: string;
|
|
152
|
+
/** Replaces the global fetch, for tests and runtimes that bring their own. */
|
|
153
|
+
fetch?: ClientFetch;
|
|
154
|
+
/**
|
|
155
|
+
* How many bucket PUTs this client sends at once, across all its uploads: 1 to 16, or "auto" (the default), which
|
|
156
|
+
* starts at 4, adds one while the bytes sent keep rising, up to 8, and halves on a network error or a busy bucket.
|
|
157
|
+
*/
|
|
158
|
+
concurrency?: number | "auto";
|
|
159
|
+
/** Which PUTs go first when they wait for a connection: "added" (the default) or "smallest-first" by file size. */
|
|
160
|
+
order?: "added" | "smallest-first";
|
|
161
|
+
/**
|
|
162
|
+
* Keeps each unfinished multipart upload in the browser's IndexedDB, with its upload token, until the file ends, so
|
|
163
|
+
* that it can resume after a reload. Default true; false keeps nothing on disk.
|
|
164
|
+
*/
|
|
165
|
+
persist?: boolean;
|
|
166
|
+
/**
|
|
167
|
+
* Keeps one signed-in user's unfinished uploads apart from another's in the same browser: pass the user's id. At most
|
|
168
|
+
* 256 characters; default "".
|
|
169
|
+
*/
|
|
170
|
+
namespace?: string;
|
|
171
|
+
}
|
|
172
|
+
interface UploadOptions<TMetadata = unknown> {
|
|
173
|
+
/** Validated by the route's schema on the server. */
|
|
174
|
+
metadata?: TMetadata;
|
|
175
|
+
/** Cancels the upload: requests stop, the server is told, and the result is ABORTED. */
|
|
176
|
+
signal?: AbortSignal;
|
|
177
|
+
}
|
|
178
|
+
/** The options argument is required when the route's metadata is. */
|
|
179
|
+
type UploadArguments<TMetadata> = undefined extends TMetadata ? [options?: UploadOptions<TMetadata>] : [options: UploadOptions<TMetadata> & {
|
|
180
|
+
metadata: TMetadata;
|
|
181
|
+
}];
|
|
182
|
+
interface CloudropClient<TCloudrop extends InferableCloudrop = InferableCloudrop> {
|
|
183
|
+
/** Sends one file or several through one /upload; each file then runs on its own through the client's pool. */
|
|
184
|
+
start<TName extends RouteName<TCloudrop>>(route: TName, files: File | ArrayLike<File>, ...options: UploadArguments<RouteMetadata<TCloudrop, TName>>): UploadJob<RouteResult<TCloudrop, TName>>;
|
|
185
|
+
/** Uploads several files, such as input.files, and resolves with an outcome per file once all have settled. */
|
|
186
|
+
upload<TName extends RouteName<TCloudrop>>(route: TName, files: ArrayLike<File>, ...options: UploadArguments<RouteMetadata<TCloudrop, TName>>): Promise<UploadResult<RouteResult<TCloudrop, TName>>>;
|
|
187
|
+
/** Uploads one file and resolves with the route's result or the error. */
|
|
188
|
+
upload<TName extends RouteName<TCloudrop>>(route: TName, file: File, ...options: UploadArguments<RouteMetadata<TCloudrop, TName>>): Promise<Result<CompleteResponse<RouteResult<TCloudrop, TName>>>>;
|
|
189
|
+
/** The unfinished uploads this browser keeps for the client's namespace, newest first: of `route`, or of all. */
|
|
190
|
+
resumable<TName extends RouteName<TCloudrop> = RouteName<TCloudrop>>(route?: TName): Promise<Result<ResumableUpload<TName>[]>>;
|
|
191
|
+
/**
|
|
192
|
+
* Continues an unfinished upload with the file the user picked again: the server is asked first which parts the
|
|
193
|
+
* bucket lacks, and only those are sent. The route and the metadata are the upload's own.
|
|
194
|
+
*/
|
|
195
|
+
resume<TName extends RouteName<TCloudrop>>(upload: ResumableUpload<TName>, file: File, options?: {
|
|
196
|
+
signal?: AbortSignal;
|
|
197
|
+
}): UploadJob<RouteResult<TCloudrop, TName>>;
|
|
198
|
+
/**
|
|
199
|
+
* Drops one unfinished upload from resumable() without its file: the server is told to abort it, and its record is
|
|
200
|
+
* deleted. `aborted` is true once the server accepted the /abort, which keeps a file whose /complete finished; false
|
|
201
|
+
* when the token could no longer abort anything (the bucket's lifecycle rule cleans up).
|
|
202
|
+
*/
|
|
203
|
+
discard(upload: ResumableUpload<RouteName<TCloudrop>>): Promise<Result<{
|
|
204
|
+
aborted: boolean;
|
|
205
|
+
}>>;
|
|
206
|
+
/** Deletes the namespace's unfinished uploads, which sign-out should do, or every one in this browser with `all`. */
|
|
207
|
+
forget(options?: {
|
|
208
|
+
all: true;
|
|
209
|
+
}): Promise<Result<{
|
|
210
|
+
forgotten: number;
|
|
211
|
+
}>>;
|
|
212
|
+
}
|
|
213
|
+
declare function createCloudropClient<TCloudrop extends InferableCloudrop = InferableCloudrop>(options?: ClientOptions): CloudropClient<TCloudrop>;
|
|
214
|
+
export { createCloudropClient as a, FileSnapshot as c, ResumableUpload as d, UploadJob as f, UploadOptions as i, FileStatus as l, CloudropClient as n, FileHandle as o, UploadResult as p, UploadArguments as r, FileOutcome as s, ClientOptions as t, JobSnapshot as u };
|