@tapedb/tapedb 0.0.0-stage → 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/API.md +301 -0
- package/LICENSE +21 -0
- package/LIMITATIONS.md +34 -0
- package/PRIVACY.md +119 -0
- package/README.md +720 -2
- package/RELEASING.md +117 -0
- package/SECURITY.md +121 -0
- package/dist/chunk-3AL32Q4K.js +241 -0
- package/dist/chunk-3AL32Q4K.js.map +1 -0
- package/dist/chunk-CYDXFAEB.js +33 -0
- package/dist/chunk-CYDXFAEB.js.map +1 -0
- package/dist/chunk-UYZJAMBR.js +27 -0
- package/dist/chunk-UYZJAMBR.js.map +1 -0
- package/dist/chunk-VWW5OS5B.js +841 -0
- package/dist/chunk-VWW5OS5B.js.map +1 -0
- package/dist/cli.d.ts +44 -0
- package/dist/cli.js +1501 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-DgSnn9BE.d.ts +646 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +3007 -0
- package/dist/index.js.map +1 -0
- package/dist/react.d.ts +41 -0
- package/dist/react.js +59 -0
- package/dist/react.js.map +1 -0
- package/dist/schema-CVcGZJfR.d.ts +691 -0
- package/dist/schema-entry-CpO_IGFv.d.ts +522 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +22 -0
- package/dist/schema.js.map +1 -0
- package/dist/worker.d.ts +437 -0
- package/dist/worker.js +9270 -0
- package/dist/worker.js.map +1 -0
- package/package.json +93 -4
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/index.ts","../src/cli/migrate.ts","../src/cli/studio.ts","../src/cli/move.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * tapedb CLI.\n *\n * `init` writes the files a Worker needs, and nothing else:\n * tapedb.schema.ts the models\n * worker.ts the Worker entry (two exports)\n * wrangler.jsonc one Durable Object class, two R2 buckets\n * .dev.vars the claim secret, so dev works with no configuration\n * tapedb/ the first migration, its snapshot and the bundle\n *\n * Existing files are kept, never overwritten, so `init` is safe to re-run.\n * `migrate` keeps tapedb/ in step with the schema; `deploy` refuses to ship a\n * development configuration or an unmigrated schema.\n */\n\nimport { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport { spawnSync } from \"node:child_process\";\nimport { basename, dirname, extname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport type { TapeDBSchema } from \"../schema\";\nimport { migrateCheck, migrateDev, migrateRollback, readMigrations, readSnapshot } from \"./migrate\";\nimport { mintToken, startStudio } from \"./studio\";\nimport { moveWorkspaces } from \"./move\";\n\nlet schemaLoads = 0;\n\n/** Loads the schema module: its default export, or an export named `schema`. */\nasync function loadSchema(root: string, flags: Record<string, string | boolean>): Promise<TapeDBSchema> {\n const path = resolve(root, typeof flags.schema === \"string\" ? flags.schema : \"tapedb.schema.ts\");\n if (!existsSync(path)) throw new Error(`No schema at ${path}. Pass --schema <file>.`);\n let loaded: Record<string, unknown>;\n try {\n // Import a fresh copy beside the original, so its relative imports still\n // resolve and no runtime's module cache can hand back an older schema.\n // (Node keys its cache on the URL; Bun ignores the query string.)\n // A counter, not the clock: two loads within one millisecond must still\n // get different files.\n schemaLoads += 1;\n // TapeDB's TypeScript schema is ESM even when the host application is\n // CommonJS. An explicit .mts copy avoids inheriting its package type;\n // leave explicit .cts and JavaScript module formats alone.\n const extension = extname(path) === \".ts\" ? \".mts\" : extname(path);\n const copy = join(dirname(path), `.${basename(path, extname(path))}.${process.pid}.${schemaLoads}${extension}`);\n copyFileSync(path, copy);\n try {\n loaded = (await import(pathToFileURL(copy).href)) as Record<string, unknown>;\n } finally {\n rmSync(copy, { force: true });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION/.test(message)) {\n throw new Error(\n `This Node cannot load TypeScript directly. Use Node 22.18 or newer, or run the CLI through tsx: npx tsx node_modules/@tapedb/tapedb/dist/cli.js ...`\n );\n }\n throw error;\n }\n const schema = (loaded.default ?? loaded.schema) as TapeDBSchema | undefined;\n if (!schema || !schema.registry || !Array.isArray(schema.migrations)) {\n throw new Error(`${path} must export a schema() as its default export (or as \"schema\").`);\n }\n return schema;\n}\n\nfunction listFlag(argv: string[], name: string): string[] {\n const values: string[] = [];\n for (let index = 0; index < argv.length; index += 1) {\n if (argv[index] === `--${name}` && argv[index + 1] !== undefined) values.push(argv[index + 1]);\n }\n return values;\n}\n\nasync function migrate(argv: string[]): Promise<number> {\n const action = argv[0];\n const flags = parseFlags(argv.slice(1));\n const root = resolve(typeof flags.dir === \"string\" ? flags.dir : \".\");\n\n if (action === \"status\") {\n const migrations = readMigrations(root);\n if (migrations.length === 0) {\n console.log(\"No migrations yet. Run `tapedb migrate dev --name init`.\");\n return 0;\n }\n for (const migration of migrations) {\n console.log(` ${migration.id}${migration.changes.length > 0 ? ` (${migration.changes.map((change) => change.kind).join(\", \")})` : \"\"}`);\n }\n const result = migrateCheck(root, await loadSchema(root, flags));\n console.log(result.ok ? \"\\nUp to date.\" : `\\n${result.problems.join(\"\\n\")}`);\n return 0;\n }\n\n if (action === \"check\") {\n const result = migrateCheck(root, await loadSchema(root, flags));\n if (result.ok) {\n console.log(\"Migrations match the schema.\");\n return 0;\n }\n console.error(result.problems.join(\"\\n\"));\n return 1;\n }\n\n if (action === \"dev\") {\n const name = typeof flags.name === \"string\" ? flags.name : readSnapshot(root) === null ? \"entities\" : \"\";\n if (!name) {\n console.error(\"Name the migration: tapedb migrate dev --name <what changed>\");\n return 1;\n }\n const result = migrateDev(root, await loadSchema(root, flags), name, {\n renames: listFlag(argv, \"rename\"),\n acceptDataLoss: flags[\"accept-data-loss\"] === true,\n });\n if (result.status === \"refused\") {\n console.error(`No migration written:\\n\\n ${result.reasons.join(\"\\n \")}`);\n return 1;\n }\n if (result.status === \"unchanged\") {\n console.log(\"The schema matches the last migration. Nothing to write.\");\n return 0;\n }\n console.log(`Created tapedb/migrations/${result.id}.sql (${result.statements} statements).`);\n if (result.changes.length > 0) {\n console.log(`Declared: ${result.changes.map((change) => change.kind).join(\", \")}.`);\n }\n console.log(\"Review it, commit it, and deploy: each workspace applies it on its next wake.\");\n return 0;\n }\n\n if (action === \"rollback\") {\n const result = migrateRollback(root, {\n ...(typeof flags.to === \"string\" ? { to: flags.to } : {}),\n acceptDataLoss: flags[\"accept-data-loss\"] === true,\n });\n if (result.status === \"refused\") {\n console.error(`No migration written:\\n\\n ${result.reasons.join(\"\\n \")}`);\n return 1;\n }\n console.log(`Created tapedb/migrations/${result.id}.sql (${result.statements} statements): the schema after ${result.to}.`);\n if (result.schemaEdits.length > 0) {\n console.log(`\\nChange the schema to match, then \\`tapedb migrate check\\` passes:\\n ${result.schemaEdits.join(\"\\n \")}`);\n }\n console.log(\"\\nReview it, commit it, and deploy: each workspace applies it on its next wake.\");\n return 0;\n }\n\n console.error(\"Usage: tapedb migrate dev --name <name> | rollback [--to <id>] | status | check\");\n return 1;\n}\n\n/** JSON with comments, without mangling \"//\" inside strings. */\nfunction parseJsonc(text: string): unknown {\n let out = \"\";\n let inString = false;\n for (let index = 0; index < text.length; index += 1) {\n const char = text[index];\n if (inString) {\n out += char;\n if (char === \"\\\\\") {\n out += text[index + 1] ?? \"\";\n index += 1;\n } else if (char === '\"') inString = false;\n continue;\n }\n if (char === '\"') {\n inString = true;\n out += char;\n } else if (char === \"/\" && text[index + 1] === \"/\") {\n while (index < text.length && text[index] !== \"\\n\") index += 1;\n out += \"\\n\";\n } else if (char === \"/\" && text[index + 1] === \"*\") {\n index = text.indexOf(\"*/\", index + 2) + 1;\n if (index === 0) break;\n } else out += char;\n }\n return JSON.parse(out.replace(/,(\\s*[}\\]])/g, \"$1\"));\n}\n\nasync function deploy(argv: string[]): Promise<number> {\n const flags = parseFlags(argv);\n const root = resolve(typeof flags.dir === \"string\" ? flags.dir : \".\");\n const env = typeof flags.env === \"string\" ? flags.env : undefined;\n\n const configPath = join(root, \"wrangler.jsonc\");\n if (!existsSync(configPath)) {\n console.error(`No wrangler.jsonc in ${root}.`);\n return 1;\n }\n const config = parseJsonc(readFileSync(configPath, \"utf8\")) as {\n vars?: Record<string, string>;\n r2_buckets?: Array<{ binding?: string; bucket_name?: string; jurisdiction?: string }>;\n env?: Record<string, { vars?: Record<string, string>; r2_buckets?: Array<{ binding?: string; bucket_name?: string; jurisdiction?: string }> }>;\n };\n const vars = env === undefined ? config.vars : config.env?.[env]?.vars;\n if (vars?.ENVIRONMENT !== \"production\") {\n console.error(\n `Refusing to deploy: ENVIRONMENT is ${JSON.stringify(vars?.ENVIRONMENT ?? null)}${env ? ` in env \"${env}\"` : \"\"}, not \"production\". Dev claims are only refused when it is \"production\". Set it in wrangler.jsonc${env ? ` under env.${env}.vars` : \" (or add an env and pass --env)\"}.`\n );\n return 1;\n }\n if (vars.TAPEDB_DEV_CLAIMS !== undefined) {\n console.error(\"Refusing to deploy: TAPEDB_DEV_CLAIMS is set. It must never reach production.\");\n return 1;\n }\n const residency = checkJurisdiction(vars, (env === undefined ? undefined : config.env?.[env]?.r2_buckets) ?? config.r2_buckets ?? []);\n if (residency !== null) {\n console.error(`Refusing to deploy: ${residency}`);\n return 1;\n }\n\n const check = migrateCheck(root, await loadSchema(root, flags));\n if (!check.ok) {\n console.error(`Refusing to deploy:\\n${check.problems.join(\"\\n\")}`);\n return 1;\n }\n\n const run = spawnSync(\"npx\", [\"--no-install\", \"wrangler\", \"deploy\", ...(env ? [\"--env\", env] : [])], {\n cwd: root,\n stdio: \"inherit\",\n });\n return run.status ?? 1;\n}\n\nconst JURISDICTIONS = [\"eu\", \"fedramp\"];\n\n/**\n * Data residency is all or nothing: the Durable Objects (TAPEDB_JURISDICTION)\n * and every R2 bucket in the same jurisdiction, or none restricted.\n */\nexport function checkJurisdiction(\n vars: Record<string, string>,\n buckets: Array<{ binding?: string; bucket_name?: string; jurisdiction?: string }>\n): string | null {\n const wanted = vars.TAPEDB_JURISDICTION;\n if (wanted !== undefined && !JURISDICTIONS.includes(wanted)) {\n return `TAPEDB_JURISDICTION is ${JSON.stringify(wanted)}; Cloudflare's jurisdictions are ${JURISDICTIONS.join(\" and \")}.`;\n }\n const from = vars.TAPEDB_MOVE_FROM === \"none\" || vars.TAPEDB_MOVE_FROM === \"\" ? undefined : vars.TAPEDB_MOVE_FROM;\n if (vars.TAPEDB_MOVE_FROM !== undefined && from !== undefined && !JURISDICTIONS.includes(from)) return \"TAPEDB_MOVE_FROM must be eu, fedramp or none.\";\n if (vars.TAPEDB_MOVE_FROM !== undefined && !buckets.some(bucket => bucket.binding === \"DATA_FROM\")) return \"A move requires the original DATA_FROM bucket.\";\n const outside = buckets.filter(bucket => bucket.jurisdiction !== (bucket.binding?.endsWith(\"_FROM\") ? from : wanted));\n if (outside.length === 0) return null;\n const names = outside.map((bucket) => `${bucket.binding ?? \"?\"} (${bucket.bucket_name ?? \"?\"}: ${bucket.jurisdiction ?? \"no jurisdiction\"})`).join(\", \");\n return wanted === undefined\n ? `R2 buckets ${names} are restricted to a jurisdiction but TAPEDB_JURISDICTION is not set, so the Durable Objects holding the same data are not. Set TAPEDB_JURISDICTION and use tapedb move for existing workspaces.`\n : `TAPEDB_JURISDICTION is \"${wanted}\" but R2 buckets ${names} are not. Create them with \\`wrangler r2 bucket create <name> --jurisdiction ${wanted}\\` and add \"jurisdiction\": \"${wanted}\" to each r2_buckets entry.`;\n}\n\nconst SCHEMA_FILE = `import { model, schema, t } from \"@tapedb/tapedb/schema\";\n\n/**\n * The whole database: tables, relations, indexes and access rules. Change it,\n * then run \\`npx @tapedb/tapedb migrate dev --name <what changed>\\`.\n */\nexport default schema({\n board: model({\n name: t.string(),\n columns: t.hasMany(\"column\"),\n }),\n column: model({\n name: t.string(),\n position: t.number().default(0).index(),\n board: t.belongsTo(\"board\", { onDelete: \"cascade\" }),\n tasks: t.hasMany(\"task\"),\n }),\n task: model({\n title: t.string(),\n done: t.boolean().default(false),\n column: t.belongsTo(\"column\").optional(),\n }),\n});\n`;\n\nconst WORKER_FILE = `import { defineTapeDB } from \"@tapedb/tapedb/worker\";\n\nimport schema from \"./tapedb.schema\";\nimport { migrations } from \"./tapedb/migrations.gen\";\n\nconst tapedb = defineTapeDB({\n schema,\n migrations,\n // Development only: serves POST /_tapedb/claim so the client works with no\n // session. defineTapeDB refuses that route when ENVIRONMENT is \"production\".\n devClaims: true,\n});\n\n// Cloudflare requires the Durable Object class to be exported by the Worker\n// that declares the binding.\nexport const WorkspaceRoom = tapedb.WorkspaceRoom;\n\nexport default tapedb.worker;\n`;\n\nfunction wrangler(name: string, jurisdiction?: string): string {\n const vars = jurisdiction ? `{ \"ENVIRONMENT\": \"development\", \"TAPEDB_JURISDICTION\": \"${jurisdiction}\" }` : `{ \"ENVIRONMENT\": \"development\" }`;\n const where = jurisdiction ? `, \"jurisdiction\": \"${jurisdiction}\"` : \"\";\n return `{\n \"$schema\": \"node_modules/wrangler/config-schema.json\",\n \"name\": \"${name}\",\n \"main\": \"worker.ts\",\n \"compatibility_date\": \"${new Date().toISOString().slice(0, 10)}\",\n \"compatibility_flags\": [\"nodejs_compat\"],\n \"workers_dev\": true,\n \"observability\": { \"enabled\": true, \"traces\": { \"enabled\": true } },\n \"vars\": ${vars},\n \"durable_objects\": {\n \"bindings\": [{ \"name\": \"WORKSPACE\", \"class_name\": \"WorkspaceRoom\" }]\n },\n \"migrations\": [{ \"tag\": \"v1\", \"new_sqlite_classes\": [\"WorkspaceRoom\"] }],\n \"r2_buckets\": [\n { \"binding\": \"DATA\", \"bucket_name\": \"${name}-data\"${where} },\n { \"binding\": \"FILES\", \"bucket_name\": \"${name}-files\"${where} }\n ]\n}\n`;\n}\n\nfunction write(path: string, contents: string, force: boolean): \"written\" | \"kept\" {\n if (existsSync(path) && !force) return \"kept\";\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n return \"written\";\n}\n\nfunction parseFlags(argv: string[]): Record<string, string | boolean> {\n const flags: Record<string, string | boolean> = {};\n for (let index = 0; index < argv.length; index += 1) {\n const token = argv[index];\n if (!token.startsWith(\"--\")) continue;\n const key = token.slice(2);\n const next = argv[index + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n flags[key] = next;\n index += 1;\n } else {\n flags[key] = true;\n }\n }\n return flags;\n}\n\nasync function init(argv: string[]): Promise<number> {\n const flags = parseFlags(argv);\n const target = resolve(typeof flags.dir === \"string\" ? flags.dir : \".\");\n const name = typeof flags.name === \"string\" ? flags.name : \"tapedb-app\";\n const force = flags.force === true;\n const jurisdiction = typeof flags.jurisdiction === \"string\" ? flags.jurisdiction : undefined;\n if (jurisdiction !== undefined && !JURISDICTIONS.includes(jurisdiction)) {\n console.error(`--jurisdiction must be one of ${JURISDICTIONS.join(\", \")}.`);\n return 1;\n }\n\n mkdirSync(target, { recursive: true });\n\n const devVarsPath = join(target, \".dev.vars\");\n const secret = existsSync(devVarsPath)\n ? (readFileSync(devVarsPath, \"utf8\").match(/^TAPEDB_CLAIM_SECRET=(.*)$/m)?.[1] ??\n randomBytes(32).toString(\"base64url\"))\n : randomBytes(32).toString(\"base64url\");\n\n const results: Array<[string, string]> = [\n [\"tapedb.schema.ts\", write(join(target, \"tapedb.schema.ts\"), SCHEMA_FILE, force)],\n [\"worker.ts\", write(join(target, \"worker.ts\"), WORKER_FILE, force)],\n [\"wrangler.jsonc\", write(join(target, \"wrangler.jsonc\"), wrangler(name, jurisdiction), force)],\n [\n \".dev.vars\",\n write(devVarsPath, `TAPEDB_CLAIM_SECRET=${secret}\\nTAPEDB_KEY_SECRET=${randomBytes(32).toString(\"base64url\")}\\n`, force),\n ],\n ];\n\n console.log(`tapedb init in ${target}\\n`);\n for (const [file, status] of results) {\n console.log(` ${status === \"written\" ? \"created\" : \"kept \"} ${file}`);\n }\n\n try {\n if (readSnapshot(target) === null) {\n const schema = await loadSchema(target, {});\n const result = migrateDev(target, schema, \"entities\");\n if (result.status === \"created\") console.log(` created tapedb/migrations/${result.id}.sql`);\n }\n } catch (error) {\n console.error(\n `\\n Could not generate the first migration (${error instanceof Error ? error.message : String(error)}).\\n Fix the schema and run \\`npx @tapedb/tapedb init\\` again; existing files are kept.`\n );\n return 1;\n }\n\n console.log(`\nNext:\n\n npx wrangler r2 bucket create ${name}-data${jurisdiction ? ` --jurisdiction ${jurisdiction}` : \"\"}\n npx wrangler r2 bucket create ${name}-files${jurisdiction ? ` --jurisdiction ${jurisdiction}` : \"\"}\n npx wrangler secret put TAPEDB_CLAIM_SECRET\n npx wrangler secret put TAPEDB_KEY_SECRET\n npx @tapedb/tapedb dev # local database\n npx @tapedb/tapedb deploy # once ENVIRONMENT is \"production\"\n\nThat is the whole footprint: one Durable Object class, two R2 buckets.\n`);\n return 0;\n}\n\nfunction usage(): number {\n console.log(`tapedb — a typed database for Cloudflare: models in, Durable Objects and R2 out\n\nUsage:\n tapedb init [--dir <path>] [--name <worker-name>] [--jurisdiction eu] [--force]\n tapedb migrate dev|rollback|status|check [--dir <path>] [--schema <file>]\n tapedb deploy [--dir <path>] [--env <name>]\n tapedb dev [--dir <path>] [--port <port>]\n tapedb studio [--url <worker-url>] [--workspace <uuid>] [--port <port>]\n tapedb export --workspace <uuid> [--url <worker-url>] [--out <file>]\n tapedb erase --workspace <uuid> --confirm <uuid> [--url <worker-url>]\n tapedb move --to eu|fedramp|none --workspaces <file> [--url <worker-url>]\n\nCommands:\n init Write tapedb.schema.ts, worker.ts, wrangler.jsonc and .dev.vars,\n and the first migration. Existing files are kept unless --force.\n --jurisdiction eu keeps Durable Objects and R2 buckets in the EU.\n migrate dev --name <name> [--rename old=new] [--accept-data-loss]\n Diff the schema against the last migration and write the next one.\n migrate rollback [--to <id>] [--accept-data-loss]\n Write the migration that takes the database back to the schema\n after <id> (default: the one before the last).\n migrate status | check\n List migrations; check fails if the schema has unmigrated changes.\n deploy [--env <name>] Check ENVIRONMENT, dev claims, data residency and migrations, then wrangler deploy.\n dev Run the local database with wrangler dev on port 8787.\n studio Open a local table browser against a running Worker.\n export Stream every row the claim may read as NDJSON (TAPEDB_TOKEN, or a dev claim).\n erase Delete a workspace for good: its data, history and files (owner claim).\n --confirm must repeat the workspace id. The id answers 410 afterwards.\n`);\n return 0;\n}\n\nfunction dev(argv: string[]): number {\n const flags = parseFlags(argv);\n const target = resolve(typeof flags.dir === \"string\" ? flags.dir : \".\");\n const port = typeof flags.port === \"string\" ? flags.port : \"8787\";\n\n if (!existsSync(join(target, \".dev.vars\"))) {\n console.error(`No .dev.vars in ${target}. Run \\`tapedb init\\` first.`);\n return 1;\n }\n\n const probe = spawnSync(\"npx\", [\"--no-install\", \"wrangler\", \"--version\"], {\n cwd: target,\n encoding: \"utf8\",\n });\n if (probe.status !== 0) {\n console.error(\n \"wrangler is required to run the local database.\\n\\n npm i -D wrangler\\n\"\n );\n return 1;\n }\n\n const run = spawnSync(\n \"npx\",\n [\n \"--no-install\",\n \"wrangler\",\n \"dev\",\n \"--port\",\n port,\n // Passed here, never written to wrangler.jsonc: a plain `wrangler deploy`\n // therefore has no dev claim route even if ENVIRONMENT is the default.\n \"--var\",\n \"TAPEDB_DEV_CLAIMS:true\",\n // workerd has no jurisdictions: locally every object is unrestricted.\n // Deployed, TAPEDB_JURISDICTION from wrangler.jsonc applies.\n \"--var\",\n \"TAPEDB_JURISDICTION:\",\n ],\n { cwd: target, stdio: \"inherit\" }\n );\n return run.status ?? 1;\n}\n\n/**\n * Streams a workspace export to a file or stdout. Uses TAPEDB_TOKEN when set,\n * otherwise mints a dev claim (which only `tapedb dev` serves).\n */\nexport async function exportWorkspace(argv: string[]): Promise<number> {\n const flags = parseFlags(argv);\n const url = (typeof flags.url === \"string\" ? flags.url : \"http://localhost:8787\").replace(/\\/+$/, \"\");\n const workspace = typeof flags.workspace === \"string\" ? flags.workspace : process.env.TAPEDB_WORKSPACE ?? \"\";\n if (!workspace) {\n console.error(\"Name the workspace: tapedb export --workspace <uuid> [--url <worker>] [--out <file>]\");\n return 1;\n }\n\n let response: Response;\n try {\n const token = process.env.TAPEDB_TOKEN || (await mintToken(url, workspace));\n response = await fetch(`${url}/engine/workspaces/${workspace}/export`, {\n headers: { authorization: `Bearer ${token}` },\n });\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n return 1;\n }\n if (!response.ok || !response.body) {\n console.error(`Export failed with HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);\n return 1;\n }\n\n const out = typeof flags.out === \"string\" ? resolve(flags.out) : null;\n if (out) writeFileSync(out, \"\");\n const write = (text: string) => (out ? appendFileSync(out, text) : process.stdout.write(text));\n\n const decoder = new TextDecoder();\n let tail = \"\";\n const reader = response.body.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n const text = decoder.decode(value, { stream: true });\n write(text);\n tail = (tail + text).slice(-65_536);\n }\n const last = tail.trim().split(\"\\n\").at(-1) ?? \"\";\n let end: { type?: string; rows?: number; consistent?: boolean; seq?: number; message?: string } = {};\n try {\n end = JSON.parse(last);\n } catch {\n // Reported below as an incomplete export.\n }\n if (end.type !== \"end\") {\n console.error(`Export incomplete: ${end.type === \"error\" ? end.message : \"the stream ended without an end line\"}.`);\n return 1;\n }\n console.error(\n `Exported ${end.rows} rows at seq ${end.seq}${end.consistent ? \"\" : \" (writes landed during the export; it is not a single point in time)\"}${out ? ` to ${out}` : \"\"}.`\n );\n return 0;\n}\n\nasync function studio(argv: string[]): Promise<number> {\n const flags = parseFlags(argv);\n\n const url = typeof flags.url === \"string\" ? flags.url : \"http://localhost:8787\";\n const workspace =\n typeof flags.workspace === \"string\"\n ? flags.workspace\n : process.env.TAPEDB_WORKSPACE ?? \"\";\n const port = Number(typeof flags.port === \"string\" ? flags.port : \"4400\");\n\n let server: { url: string; close: () => void };\n try {\n server = await startStudio({ url, workspace, port });\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n return 1;\n }\n console.log(`tapedb studio on ${server.url} -> ${url}`);\n console.log(\"Press Ctrl+C to stop.\");\n\n await new Promise<void>((resolve) => {\n process.on(\"SIGINT\", () => {\n server.close();\n resolve();\n });\n });\n return 0;\n}\n\n/**\n * Erases a workspace: DELETE /engine/workspaces/:id with an owner claim\n * (TAPEDB_TOKEN, or a dev claim). Irreversible, so the id is typed twice.\n */\nexport async function eraseWorkspace(argv: string[]): Promise<number> {\n const flags = parseFlags(argv);\n const url = (typeof flags.url === \"string\" ? flags.url : \"http://localhost:8787\").replace(/\\/+$/, \"\");\n const workspace = typeof flags.workspace === \"string\" ? flags.workspace : \"\";\n if (!workspace || flags.confirm !== workspace) {\n console.error(\"Erasing cannot be undone. Name the workspace twice: tapedb erase --workspace <uuid> --confirm <uuid> [--url <worker>]\");\n return 1;\n }\n\n let response: Response;\n try {\n const token = process.env.TAPEDB_TOKEN || (await mintToken(url, workspace));\n response = await fetch(`${url}/engine/workspaces/${workspace}`, {\n method: \"DELETE\",\n headers: { authorization: `Bearer ${token}` },\n });\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n return 1;\n }\n const body = (await response.json().catch(() => null)) as { erased?: { historyObjects: number; files: number }; error?: { message?: string } } | null;\n if (response.status === 410) {\n console.log(`Workspace ${workspace} was already erased.`);\n return 0;\n }\n if (!response.ok || !body?.erased) {\n console.error(`Erase failed with HTTP ${response.status}: ${body?.error?.message ?? \"no details\"}. It is safe to run again.`);\n return 1;\n }\n console.log(`Erased workspace ${workspace}: ${body.erased.historyObjects} history objects and ${body.erased.files} files deleted, Durable Object storage cleared.`);\n return 0;\n}\n\n/** Runs the CLI and returns its exit code. Importable without side effects. */\nexport async function run(argv: string[]): Promise<number> {\n const command = argv[0];\n\n if (command === \"init\") return init(argv.slice(1));\n if (command === \"migrate\") return migrate(argv.slice(1));\n if (command === \"deploy\") return deploy(argv.slice(1));\n if (command === \"dev\") return dev(argv.slice(1));\n if (command === \"studio\") return studio(argv.slice(1));\n if (command === \"export\") return exportWorkspace(argv.slice(1));\n if (command === \"erase\") return eraseWorkspace(argv.slice(1));\n if (command === \"move\") return moveWorkspaces(argv.slice(1));\n if (command === undefined || command === \"--help\" || command === \"-h\") {\n return usage();\n }\n\n console.error(`Unknown command \"${command}\".`);\n return usage();\n}\n\n/**\n * True when this module is the process entry point. `npx @tapedb/tapedb` runs it\n * through the node_modules/.bin symlink: argv[1] is the link, while\n * import.meta.url is the resolved file, so both are compared after resolving.\n */\nexport function isEntryPoint(entry: string | undefined, moduleUrl: string): boolean {\n if (entry === undefined) return false;\n try {\n return realpathSync(entry) === realpathSync(fileURLToPath(moduleUrl));\n } catch {\n return false;\n }\n}\n\n// Only execute when invoked as the binary, never when imported.\nif (isEntryPoint(process.argv[1], import.meta.url)) {\n void run(process.argv.slice(2)).then((code) => process.exit(code));\n}\n","/**\n * `tapedb migrate`: committed migrations from schema diffs.\n *\n * The schema as of the last migration is kept in `tapedb/schema.snapshot.json`.\n * `migrate dev` compares the current schema with it, writes the SQL that gets\n * one to the other as the next numbered file, updates the snapshot, and\n * regenerates `tapedb/migrations.gen.ts`, the bundle the Worker imports.\n *\n * Each migration also declares what it changed (dropped, renamed, retyped\n * fields and models) in a `-- tapedb:changes` line, so recovery can read data\n * written before it. The declarations are part of the committed file, and the\n * checksum, like the SQL.\n *\n * The schema after each migration is kept too, in `tapedb/snapshots/<id>.json`,\n * so `migrate rollback` can write the migration that takes the database back\n * to an earlier one.\n *\n * The very first migration is the full CREATE script for the schema, under\n * the id `0002_entities`: exactly what `defineSchema` has always generated, so\n * workspaces deployed before migrations were files keep a matching checksum.\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { AttributeDefinition, NamespaceDefinition } from \"../engine/registry\";\nimport type { SchemaChange } from \"../engine/schema-evolution\";\nimport { entityDdl, SQL_TYPE, sqlLiteral, type TapeDBSchema } from \"../schema\";\n\nexport const FIRST_MIGRATION_ID = \"0002_entities\";\nconst CHANGES_PREFIX = \"-- tapedb:changes \";\n\nexport interface SnapshotAttribute {\n type: AttributeDefinition[\"type\"];\n optional: boolean;\n indexed: boolean;\n unique: boolean;\n default?: string | number | null;\n references?: { table: string; column: string; onDelete: string };\n}\n\nexport interface SchemaSnapshot {\n version: 1;\n /** Keyed by model (namespace) name. */\n models: Record<string, { table: string; attributes: Record<string, SnapshotAttribute> }>;\n}\n\nexport function snapshotOf(schema: TapeDBSchema): SchemaSnapshot {\n const models: SchemaSnapshot[\"models\"] = {};\n for (const namespace of schema.registry.namespaces) {\n const attributes: Record<string, SnapshotAttribute> = {};\n for (const [name, attribute] of Object.entries(namespace.attributes)) {\n attributes[name] = {\n type: attribute.type,\n optional: attribute.optional === true,\n indexed: attribute.indexed === true,\n unique: attribute.unique === true,\n ...(attribute.default === undefined ? {} : { default: attribute.default }),\n ...(attribute.references\n ? {\n references: {\n table: attribute.references.table,\n column: attribute.references.column,\n onDelete: attribute.references.onDelete ?? \"SET NULL\",\n },\n }\n : {}),\n };\n }\n models[namespace.apiName] = { table: namespace.table, attributes };\n }\n return { version: 1, models };\n}\n\n// ---- Diff -------------------------------------------------------------------\n\nexport interface DiffOptions {\n /** \"old=new\" for a model, \"model.old=new\" for a field. */\n renames?: string[];\n acceptDataLoss?: boolean;\n}\n\nexport interface MigrationPlan {\n statements: string[];\n changes: SchemaChange[];\n /** Steps that discard data; refused unless acceptDataLoss. */\n destructive: string[];\n /** Steps that cannot be done; the plan must not be written. */\n refused: string[];\n}\n\nfunction column(attribute: string): string {\n return attribute.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n\nfunction indexName(table: string, columnName: string): string {\n return `${table}_${columnName}_idx`;\n}\n\nfunction columnDefinition(name: string, attribute: SnapshotAttribute): string {\n let sql = `\"${column(name)}\" ${SQL_TYPE[attribute.type] ?? \"TEXT\"}`;\n if (attribute.default !== undefined) sql += ` DEFAULT ${sqlLiteral(attribute.default)}`;\n if (attribute.references) {\n sql += ` REFERENCES \"${attribute.references.table}\"(\"${attribute.references.column}\") ON DELETE ${attribute.references.onDelete}`;\n }\n return sql;\n}\n\nfunction createTable(model: string, table: string, attributes: Record<string, SnapshotAttribute>): string[] {\n const namespace: NamespaceDefinition = { apiName: model, table, attributes: {} };\n const entity: Record<string, AttributeDefinition> = {};\n for (const [name, attribute] of Object.entries(attributes)) {\n entity[name] = {\n type: attribute.type,\n optional: attribute.optional,\n indexed: attribute.indexed,\n unique: attribute.unique,\n ...(attribute.default === undefined ? {} : { default: attribute.default }),\n ...(attribute.references\n ? {\n references: {\n table: attribute.references.table,\n column: attribute.references.column,\n onDelete: attribute.references.onDelete as \"CASCADE\" | \"SET NULL\" | \"RESTRICT\",\n },\n }\n : {}),\n };\n }\n return entityDdl(namespace, entity);\n}\n\nfunction indexStatements(table: string, name: string, before: SnapshotAttribute | undefined, after: SnapshotAttribute | undefined): string[] {\n const index = indexName(table, column(name));\n const had = before !== undefined && (before.indexed || before.unique);\n const has = after !== undefined && (after.indexed || after.unique);\n const same = had && has && before!.unique === after!.unique;\n if (same || (!had && !has)) return [];\n const statements: string[] = [];\n if (had) statements.push(`DROP INDEX IF EXISTS \"${index}\";`);\n if (has) {\n statements.push(\n `CREATE ${after!.unique ? \"UNIQUE \" : \"\"}INDEX IF NOT EXISTS \"${index}\" ON \"${table}\" (\"${column(name)}\");`\n );\n }\n return statements;\n}\n\nfunction parseRenames(renames: string[]): {\n models: Map<string, string>;\n fields: Map<string, Map<string, string>>;\n} {\n const models = new Map<string, string>();\n const fields = new Map<string, Map<string, string>>();\n for (const entry of renames) {\n const match = /^([A-Za-z][A-Za-z0-9]*)(?:\\.([A-Za-z][A-Za-z0-9]*))?=([A-Za-z][A-Za-z0-9]*)$/.exec(entry);\n if (!match) throw new Error(`--rename \"${entry}\" must be old=new or model.old=new.`);\n const [, first, second, target] = match;\n if (second === undefined) models.set(first, target);\n else {\n const map = fields.get(first) ?? new Map<string, string>();\n map.set(second, target);\n fields.set(first, map);\n }\n }\n return { models, fields };\n}\n\n/** Plans the SQL and declarations that take `before` to `after`. */\nexport function diffSnapshots(\n before: SchemaSnapshot,\n after: SchemaSnapshot,\n options: DiffOptions = {}\n): MigrationPlan {\n const plan: MigrationPlan = { statements: [], changes: [], destructive: [], refused: [] };\n const renames = parseRenames(options.renames ?? []);\n\n // Models: renames first, so field diffs compare the right pair.\n const pairs: Array<[string | null, string | null]> = [];\n const matchedOld = new Set<string>();\n for (const name of Object.keys(after.models)) {\n const previous = [...renames.models.entries()].find(([, to]) => to === name)?.[0];\n if (previous !== undefined) {\n if (!(previous in before.models)) plan.refused.push(`--rename ${previous}=${name}: there is no model \"${previous}\".`);\n else {\n pairs.push([previous, name]);\n matchedOld.add(previous);\n }\n } else if (name in before.models) {\n pairs.push([name, name]);\n matchedOld.add(name);\n } else {\n pairs.push([null, name]);\n }\n }\n for (const name of Object.keys(before.models)) {\n if (!matchedOld.has(name)) pairs.push([name, null]);\n }\n\n for (const [oldName, newName] of pairs) {\n if (oldName === null) {\n const model = after.models[newName!];\n plan.statements.push(...createTable(newName!, model.table, model.attributes));\n continue;\n }\n const oldModel = before.models[oldName];\n if (newName === null) {\n plan.destructive.push(`drop model \"${oldName}\" and every row in \"${oldModel.table}\"`);\n plan.statements.push(`DROP TABLE IF EXISTS \"${oldModel.table}\";`);\n plan.changes.push({ kind: \"dropModel\", model: oldName, table: oldModel.table });\n continue;\n }\n const newModel = after.models[newName];\n if (oldName !== newName || oldModel.table !== newModel.table) {\n if (oldModel.table !== newModel.table) {\n plan.statements.push(`ALTER TABLE \"${oldModel.table}\" RENAME TO \"${newModel.table}\";`);\n }\n plan.changes.push({ kind: \"renameModel\", from: oldName, to: newName, fromTable: oldModel.table, toTable: newModel.table });\n }\n diffFields(plan, newName, newModel.table, oldModel.attributes, newModel.attributes, renames.fields.get(newName) ?? renames.fields.get(oldName) ?? new Map());\n }\n\n if (plan.destructive.length > 0 && !options.acceptDataLoss) {\n plan.refused.push(\n `This migration would ${plan.destructive.join(\"; \")}. Re-run with --accept-data-loss if that is intended, or --rename old=new if it is a rename.`\n );\n }\n return plan;\n}\n\nfunction diffFields(\n plan: MigrationPlan,\n model: string,\n table: string,\n before: Record<string, SnapshotAttribute>,\n after: Record<string, SnapshotAttribute>,\n renames: Map<string, string>\n): void {\n const handled = new Set<string>();\n for (const [from, to] of renames) {\n if (!(from in before)) {\n plan.refused.push(`--rename ${model}.${from}=${to}: \"${model}\" has no field \"${from}\".`);\n continue;\n }\n if (!(to in after)) {\n plan.refused.push(`--rename ${model}.${from}=${to}: the schema has no field \"${model}.${to}\".`);\n continue;\n }\n plan.statements.push(...indexStatements(table, from, before[from], undefined));\n plan.statements.push(`ALTER TABLE \"${table}\" RENAME COLUMN \"${column(from)}\" TO \"${column(to)}\";`);\n plan.statements.push(...indexStatements(table, to, undefined, after[to]));\n plan.changes.push({ kind: \"renameField\", model, table, from, to, fromColumn: column(from), toColumn: column(to) });\n handled.add(from);\n handled.add(to);\n compareField(plan, model, table, to, { ...before[from] }, after[to], true);\n }\n\n for (const [name, attribute] of Object.entries(after)) {\n if (handled.has(name)) continue;\n if (!(name in before)) {\n if (!attribute.optional && attribute.default === undefined) {\n plan.refused.push(\n `\"${model}.${name}\" is new and required with no default, so existing rows would have no value. Give it .default(...) or make it .optional().`\n );\n continue;\n }\n plan.statements.push(`ALTER TABLE \"${table}\" ADD COLUMN ${columnDefinition(name, attribute)};`);\n plan.statements.push(...indexStatements(table, name, undefined, attribute));\n continue;\n }\n compareField(plan, model, table, name, before[name], attribute, false);\n }\n\n for (const [name, attribute] of Object.entries(before)) {\n if (handled.has(name) || name in after) continue;\n plan.destructive.push(`drop \"${model}.${name}\" and its values`);\n plan.statements.push(...indexStatements(table, name, attribute, undefined));\n plan.statements.push(`ALTER TABLE \"${table}\" DROP COLUMN \"${column(name)}\";`);\n plan.changes.push({ kind: \"dropField\", model, table, field: name, column: column(name) });\n }\n}\n\nfunction compareField(\n plan: MigrationPlan,\n model: string,\n table: string,\n name: string,\n before: SnapshotAttribute,\n after: SnapshotAttribute,\n renamed: boolean\n): void {\n // A renamed field's index was dropped and recreated with the rename.\n if (!renamed) plan.statements.push(...indexStatements(table, name, before, after));\n\n const sqlTypeChanged = (SQL_TYPE[before.type] ?? \"TEXT\") !== (SQL_TYPE[after.type] ?? \"TEXT\");\n const referencesChanged =\n JSON.stringify(before.references ?? null) !== JSON.stringify(after.references ?? null);\n const defaultChanged = JSON.stringify(before.default ?? null) !== JSON.stringify(after.default ?? null);\n\n if (before.type !== after.type) {\n plan.changes.push({ kind: \"retypeField\", model, field: name });\n }\n if (sqlTypeChanged || referencesChanged || defaultChanged) {\n if (sqlTypeChanged) plan.destructive.push(`convert \"${model}.${name}\" from ${before.type} to ${after.type}; values that do not convert are lost`);\n plan.statements.push(`-- rebuild \"${table}\" for \"${model}.${name}\"`);\n plan.statements.push(`${REBUILD_MARKER}${table}:${name}`);\n }\n}\n\n/** Placeholder replaced once the whole table's final shape is known. */\nconst REBUILD_MARKER = \"-- tapedb:rebuild \";\n\n/** Expands rebuild markers into the create-copy-drop-rename sequence for each table. */\nfunction expandRebuilds(plan: MigrationPlan, after: SchemaSnapshot): void {\n const tables = new Set<string>();\n plan.statements = plan.statements.filter((statement) => {\n if (!statement.startsWith(REBUILD_MARKER)) return true;\n tables.add(statement.slice(REBUILD_MARKER.length).split(\":\")[0]);\n return false;\n });\n for (const table of tables) {\n const [model, definition] = Object.entries(after.models).find(([, entry]) => entry.table === table)!;\n const temporary = `${table}__rebuild`;\n const columns = [\"id\", \"created_at\", \"updated_at\", \"updated_seq\", ...Object.keys(definition.attributes).map(column)];\n const selected = [\"id\", \"created_at\", \"updated_at\", \"updated_seq\", ...Object.entries(definition.attributes).map(\n ([name, attribute]) => `CAST(\"${column(name)}\" AS ${SQL_TYPE[attribute.type] ?? \"TEXT\"})`\n )];\n const create = createTable(model, temporary, definition.attributes).map((statement) =>\n statement.replace(new RegExp(`\"${temporary}_`, \"g\"), `\"${table}_`)\n );\n plan.statements.push(\n create[0],\n `INSERT INTO \"${temporary}\" (${columns.map((name) => `\"${name}\"`).join(\", \")}) SELECT ${selected.join(\", \")} FROM \"${table}\";`,\n `DROP TABLE \"${table}\";`,\n `ALTER TABLE \"${temporary}\" RENAME TO \"${table}\";`,\n ...create.slice(1).map((statement) => statement.replace(`ON \"${temporary}\"`, `ON \"${table}\"`))\n );\n }\n}\n\n// ---- Files -------------------------------------------------------------------\n\nexport interface MigrationFile {\n id: string;\n sql: string;\n changes: SchemaChange[];\n}\n\nexport function migrationsDir(root: string): string {\n return join(root, \"tapedb\", \"migrations\");\n}\n\nfunction snapshotPath(root: string): string {\n return join(root, \"tapedb\", \"schema.snapshot.json\");\n}\n\nfunction historyPath(root: string, id: string): string {\n return join(root, \"tapedb\", \"snapshots\", `${id}.json`);\n}\n\nfunction writeHistory(root: string, id: string, snapshot: SchemaSnapshot): void {\n mkdirSync(join(root, \"tapedb\", \"snapshots\"), { recursive: true });\n writeFileSync(historyPath(root, id), `${JSON.stringify(snapshot, null, 2)}\\n`);\n}\n\n/** The schema as it was after migration `id`, when it was recorded. */\nexport function readHistory(root: string, id: string): SchemaSnapshot | null {\n const path = historyPath(root, id);\n return existsSync(path) ? (JSON.parse(readFileSync(path, \"utf8\")) as SchemaSnapshot) : null;\n}\n\nfunction bundlePath(root: string): string {\n return join(root, \"tapedb\", \"migrations.gen.ts\");\n}\n\nexport function readMigrations(root: string): MigrationFile[] {\n const dir = migrationsDir(root);\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((file) => /^\\d{4}_[a-z0-9_]+\\.sql$/.test(file))\n .sort()\n .map((file) => {\n const sql = readFileSync(join(dir, file), \"utf8\");\n const header = sql.split(\"\\n\").find((line) => line.startsWith(CHANGES_PREFIX));\n return {\n id: file.replace(/\\.sql$/, \"\"),\n sql,\n changes: header ? (JSON.parse(header.slice(CHANGES_PREFIX.length)) as SchemaChange[]) : [],\n };\n });\n}\n\nexport function readSnapshot(root: string): SchemaSnapshot | null {\n const path = snapshotPath(root);\n return existsSync(path) ? (JSON.parse(readFileSync(path, \"utf8\")) as SchemaSnapshot) : null;\n}\n\n/** The bundle the Worker imports: every app migration, inlined. */\nexport function renderBundle(migrations: MigrationFile[]): string {\n const entries = migrations\n .map(\n (migration) =>\n ` {\\n id: ${JSON.stringify(migration.id)},\\n sql: ${JSON.stringify(migration.sql)},${\n migration.changes.length > 0 ? `\\n changes: ${JSON.stringify(migration.changes)},` : \"\"\n }\\n },`\n )\n .join(\"\\n\");\n return `// Generated by \\`tapedb migrate\\`. Do not edit; edit the schema and run it again.\nimport type { AppMigration } from \"@tapedb/tapedb/worker\";\n\nexport const migrations: AppMigration[] = [\n${entries}\n];\n`;\n}\n\nfunction slug(name: string): string {\n const value = name.toLowerCase().replace(/[^a-z0-9]+/g, \"_\").replace(/^_+|_+$/g, \"\");\n if (!value) throw new Error(`Migration name \"${name}\" has no letters or digits.`);\n return value;\n}\n\nexport type DevResult =\n | { status: \"created\"; id: string; statements: number; changes: SchemaChange[] }\n | { status: \"unchanged\" }\n | { status: \"refused\"; reasons: string[] };\n\n/** `tapedb migrate dev`: diff, write the migration, the snapshot and the bundle. */\nexport function migrateDev(\n root: string,\n schema: TapeDBSchema,\n name: string,\n options: DiffOptions = {}\n): DevResult {\n const next = snapshotOf(schema);\n const previous = readSnapshot(root);\n const existing = readMigrations(root);\n mkdirSync(migrationsDir(root), { recursive: true });\n // A project from before the history was kept: the snapshot is the schema\n // after its last migration.\n const last = existing.at(-1);\n if (previous !== null && last && readHistory(root, last.id) === null) writeHistory(root, last.id, previous);\n\n let file: MigrationFile;\n if (previous === null) {\n if (existing.length > 0) {\n return { status: \"refused\", reasons: [\"tapedb/migrations has files but no schema.snapshot.json. Restore the snapshot from version control.\"] };\n }\n // The first migration is byte-for-byte what defineSchema always\n // generated: deployed workspaces hold its checksum.\n file = { id: FIRST_MIGRATION_ID, sql: schema.migrations.at(-1)!.sql, changes: [] };\n } else {\n const plan = diffSnapshots(previous, next, options);\n if (plan.refused.length > 0) return { status: \"refused\", reasons: plan.refused };\n expandRebuilds(plan, next);\n if (plan.statements.length === 0 && plan.changes.length === 0) {\n writeFileSync(snapshotPath(root), `${JSON.stringify(next, null, 2)}\\n`);\n writeFileSync(bundlePath(root), renderBundle(existing));\n return { status: \"unchanged\" };\n }\n const number = Math.max(2, ...existing.map((migration) => Number(migration.id.slice(0, 4)))) + 1;\n const id = `${String(number).padStart(4, \"0\")}_${slug(name)}`;\n const header = plan.changes.length > 0 ? `${CHANGES_PREFIX}${JSON.stringify(plan.changes)}\\n` : \"\";\n file = { id, sql: `${header}${plan.statements.join(\"\\n\")}\\n`, changes: plan.changes };\n }\n\n writeFileSync(join(migrationsDir(root), `${file.id}.sql`), file.sql);\n writeFileSync(snapshotPath(root), `${JSON.stringify(next, null, 2)}\\n`);\n writeHistory(root, file.id, next);\n writeFileSync(bundlePath(root), renderBundle([...existing, file]));\n return {\n status: \"created\",\n id: file.id,\n statements: countStatements(file.sql),\n changes: file.changes,\n };\n}\n\n// ---- Rollback ------------------------------------------------------------------\n\nexport type RollbackResult =\n | { status: \"created\"; id: string; to: string; statements: number; changes: SchemaChange[]; schemaEdits: string[] }\n | { status: \"refused\"; reasons: string[] };\n\n/**\n * The renames that take the current names back to the names at `target`:\n * each migration's renames after it, followed forward from the target names.\n */\nfunction renamesBack(target: SchemaSnapshot, undone: MigrationFile[]): string[] {\n const models = new Map(Object.keys(target.models).map((name) => [name, name]));\n const fields = new Map<string, { model: string; field: string; current: string }>();\n for (const [name, entry] of Object.entries(target.models)) {\n for (const field of Object.keys(entry.attributes)) fields.set(`${name}.${field}`, { model: name, field, current: field });\n }\n for (const migration of undone) {\n for (const change of migration.changes) {\n if (change.kind === \"renameModel\") {\n for (const [original, current] of models) if (current === change.from) models.set(original, change.to);\n } else if (change.kind === \"renameField\") {\n for (const entry of fields.values()) {\n if (models.get(entry.model) === change.model && entry.current === change.from) entry.current = change.to;\n }\n }\n }\n }\n const renames: string[] = [];\n for (const [original, current] of models) if (original !== current) renames.push(`${current}=${original}`);\n for (const entry of fields.values()) {\n if (entry.current !== entry.field) renames.push(`${models.get(entry.model)}.${entry.current}=${entry.field}`);\n }\n return renames;\n}\n\n/** What the schema code has to change to match `target`, in words. */\nfunction schemaEdits(current: SchemaSnapshot, target: SchemaSnapshot, renames: string[]): string[] {\n const modelBack = new Map<string, string>();\n const fieldBack = new Map<string, string>();\n for (const rename of renames) {\n const [from, to] = rename.split(\"=\");\n if (from.includes(\".\")) fieldBack.set(from, to);\n else modelBack.set(from, to);\n }\n const describe = (attribute: SnapshotAttribute) =>\n [attribute.type, attribute.optional ? \"optional\" : \"\", attribute.unique ? \"unique\" : attribute.indexed ? \"indexed\" : \"\",\n attribute.default === undefined ? \"\" : `default ${JSON.stringify(attribute.default)}`].filter(Boolean).join(\", \");\n const edits: string[] = [];\n const matched = new Set<string>();\n for (const [name, entry] of Object.entries(target.models)) {\n const was = [...modelBack.entries()].find(([, original]) => original === name)?.[0] ?? name;\n const now = current.models[was];\n if (!now) {\n edits.push(`add model \"${name}\"`);\n continue;\n }\n matched.add(was);\n if (was !== name) edits.push(`rename model \"${was}\" back to \"${name}\"`);\n const kept = new Set<string>();\n for (const [field, attribute] of Object.entries(entry.attributes)) {\n const from = [...fieldBack.entries()].find(([key, original]) => key.startsWith(`${was}.`) && original === field)?.[0].split(\".\")[1] ?? field;\n if (!(from in now.attributes)) {\n edits.push(`add \"${name}.${field}\" (${describe(attribute)})`);\n continue;\n }\n kept.add(from);\n if (from !== field) edits.push(`rename \"${name}.${from}\" back to \"${field}\"`);\n if (JSON.stringify(now.attributes[from]) !== JSON.stringify(attribute)) edits.push(`make \"${name}.${field}\" ${describe(attribute)} again`);\n }\n for (const field of Object.keys(now.attributes)) if (!kept.has(field)) edits.push(`remove \"${name}.${field}\"`);\n }\n for (const name of Object.keys(current.models)) if (!matched.has(name)) edits.push(`remove model \"${name}\"`);\n return edits;\n}\n\n/**\n * `tapedb migrate rollback [--to <id>]`: writes the migration that takes the\n * database back to the schema after `<id>` (by default, the one before the\n * last). It is a new forward migration, applied like any other.\n *\n * Refused when a migration being undone dropped data: those values are gone,\n * so the earlier schema cannot be restored. Undoing an addition discards the\n * values written since, and needs --accept-data-loss like any drop.\n */\nexport function migrateRollback(root: string, options: { to?: string; acceptDataLoss?: boolean } = {}): RollbackResult {\n const existing = readMigrations(root);\n const current = readSnapshot(root);\n if (current === null || existing.length === 0) return { status: \"refused\", reasons: [\"There are no migrations to roll back.\"] };\n const targetIndex = options.to === undefined ? existing.length - 2 : existing.findIndex((migration) => migration.id === options.to);\n if (options.to !== undefined && targetIndex === -1) {\n return { status: \"refused\", reasons: [`There is no migration \"${options.to}\".`] };\n }\n if (targetIndex < 0) return { status: \"refused\", reasons: [`${existing[0].id} creates the schema; there is nothing before it to go back to.`] };\n if (targetIndex === existing.length - 1) return { status: \"refused\", reasons: [`${options.to} is the last migration already.`] };\n const target = existing[targetIndex];\n const before = readHistory(root, target.id);\n if (before === null) {\n return {\n status: \"refused\",\n reasons: [\n `The schema after ${target.id} was not recorded (tapedb/snapshots/${target.id}.json): it predates rollback. Change the schema back and run \\`tapedb migrate dev\\`.`,\n ],\n };\n }\n const undone = existing.slice(targetIndex + 1);\n const dropped = undone.flatMap((migration) =>\n migration.changes\n .filter((change) => change.kind === \"dropField\" || change.kind === \"dropModel\")\n .map((change) =>\n change.kind === \"dropField\"\n ? `${migration.id} dropped \"${change.model}.${change.field}\"`\n : `${migration.id} dropped model \"${change.model}\"`\n )\n );\n if (dropped.length > 0) {\n return {\n status: \"refused\",\n reasons: [`${dropped.join(\"; \")}: those values are gone, so the schema after ${target.id} cannot be restored.`],\n };\n }\n\n const renames = renamesBack(before, undone);\n const plan = diffSnapshots(current, before, { renames, acceptDataLoss: options.acceptDataLoss });\n if (plan.refused.length > 0) return { status: \"refused\", reasons: plan.refused };\n expandRebuilds(plan, before);\n const number = Math.max(...existing.map((migration) => Number(migration.id.slice(0, 4)))) + 1;\n const id = `${String(number).padStart(4, \"0\")}_rollback_to_${target.id.slice(0, 4)}`;\n const header = plan.changes.length > 0 ? `${CHANGES_PREFIX}${JSON.stringify(plan.changes)}\\n` : \"\";\n const file: MigrationFile = { id, sql: `${header}${plan.statements.join(\"\\n\")}\\n`, changes: plan.changes };\n if (readHistory(root, existing.at(-1)!.id) === null) writeHistory(root, existing.at(-1)!.id, current);\n writeFileSync(join(migrationsDir(root), `${id}.sql`), file.sql);\n writeFileSync(snapshotPath(root), `${JSON.stringify(before, null, 2)}\\n`);\n writeHistory(root, id, before);\n writeFileSync(bundlePath(root), renderBundle([...existing, file]));\n return {\n status: \"created\",\n id,\n to: target.id,\n statements: countStatements(file.sql),\n changes: plan.changes,\n schemaEdits: schemaEdits(current, before, renames),\n };\n}\n\nfunction countStatements(sql: string): number {\n return sql\n .split(\"\\n\")\n .filter((line) => !line.startsWith(\"--\"))\n .join(\"\\n\")\n .split(\";\")\n .filter((statement) => statement.trim()).length;\n}\n\nexport interface CheckResult {\n ok: boolean;\n problems: string[];\n}\n\n/** `tapedb migrate check`: the schema, the snapshot and the bundle all agree. */\nexport function migrateCheck(root: string, schema: TapeDBSchema): CheckResult {\n const problems: string[] = [];\n const previous = readSnapshot(root);\n if (previous === null) {\n problems.push(\"No migrations yet. Run `tapedb migrate dev --name init`.\");\n return { ok: false, problems };\n }\n const plan = diffSnapshots(previous, snapshotOf(schema), { acceptDataLoss: true });\n if (plan.statements.length > 0 || plan.changes.length > 0 || plan.refused.length > 0) {\n problems.push(\"The schema has changes with no migration. Run `tapedb migrate dev --name <what changed>`.\");\n }\n const bundle = existsSync(bundlePath(root)) ? readFileSync(bundlePath(root), \"utf8\") : \"\";\n if (bundle !== renderBundle(readMigrations(root))) {\n problems.push(\"tapedb/migrations.gen.ts is out of date with tapedb/migrations. Run `tapedb migrate dev` to regenerate it.\");\n }\n return { ok: problems.length === 0, problems };\n}\n","/**\n * `tapedb studio`: a local table browser.\n *\n * A devtool that needs no build and no dependencies: it serves one HTML page\n * and proxies to the running Worker, minting a dev claim the same way the\n * client does. Nothing here ships to production, and it only talks to the\n * Worker you point it at.\n *\n * Two things make it usable against a real workspace: it remembers every\n * workspace you have opened (in the browser, never on disk) and it pages\n * through a namespace one cursor at a time instead of stopping at the first\n * fifty rows.\n */\n\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\n\nexport interface StudioOptions {\n /** Base URL of the running Worker, e.g. http://localhost:8787 */\n url: string;\n /** Workspace to open; prompted for in the page when empty. */\n workspace: string;\n /** Port to bind. `0` asks the OS for an ephemeral port. */\n port: number;\n}\n\ninterface StudioState {\n token: string | null;\n workspace: string;\n}\n\n/** A client mistake, reported as 400 rather than as a server error. */\nclass BadRequest extends Error {}\n\n/** Rows per page. Small enough to page quickly, large enough to be useful. */\nexport const PAGE_LIMIT = 50;\n\nfunction parseJsonBody<T>(body: string): T {\n try {\n return JSON.parse(body || \"{}\") as T;\n } catch {\n throw new BadRequest(\"Request body must be JSON.\");\n }\n}\n\nasync function readBody(request: IncomingMessage): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of request) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction sendJson(response: ServerResponse, status: number, body: unknown): void {\n const payload = JSON.stringify(body);\n response.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"content-length\": Buffer.byteLength(payload),\n });\n response.end(payload);\n}\n\n/**\n * Passes an upstream response through with its status intact.\n *\n * The engine answers JSON, but a misrouted request can come back as HTML or as\n * an empty body. Parsing unconditionally would turn that into a 500 here and\n * hide the real status, so a non-JSON body is forwarded verbatim.\n */\nasync function forward(response: ServerResponse, upstream: Response): Promise<void> {\n const text = await upstream.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n response.writeHead(upstream.status, {\n \"content-type\": upstream.headers.get(\"content-type\") ?? \"text/plain; charset=utf-8\",\n \"content-length\": Buffer.byteLength(text),\n });\n response.end(text);\n return;\n }\n sendJson(response, upstream.status, parsed);\n}\n\nexport async function mintToken(base: string, workspace: string): Promise<string> {\n const response = await fetch(`${base}/_tapedb/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ workspaceId: workspace }),\n });\n const text = await response.text();\n if (!response.ok) {\n throw new Error(\n `claim failed (${response.status}): ${text.slice(0, 200)}. ` +\n `Is the Worker running with \\`tapedb dev\\`?`\n );\n }\n const parsed = JSON.parse(text) as { token?: unknown };\n if (typeof parsed.token !== \"string\") throw new Error(\"claim returned no token\");\n return parsed.token;\n}\n\n/**\n * Points the studio at a workspace, dropping the cached claim when it changes.\n *\n * A claim is scoped to one workspace, so reusing it after a switch would make\n * every request fail as unauthorized.\n */\nfunction setWorkspace(state: StudioState, workspace: string): void {\n if (workspace === state.workspace) return;\n state.workspace = workspace;\n state.token = null;\n}\n\n/** Calls the engine with a claim, re-minting once on 401. */\nasync function engine(\n base: string,\n state: StudioState,\n path: string,\n init: RequestInit = {}\n): Promise<Response> {\n if (state.workspace.length === 0) {\n throw new Error(\"No workspace id. Enter one in the page.\");\n }\n if (state.token === null) state.token = await mintToken(base, state.workspace);\n\n const call = (token: string) =>\n fetch(`${base}/engine/workspaces/${state.workspace}${path}`, {\n ...init,\n headers: {\n ...(init.headers as Record<string, string> | undefined),\n authorization: `Bearer ${token}`,\n },\n });\n\n let response = await call(state.token);\n if (response.status === 401) {\n state.token = await mintToken(base, state.workspace);\n response = await call(state.token);\n }\n return response;\n}\n\n/**\n * One page of a namespace, in the shape `/api/query` expects.\n *\n * The order is fixed to `id asc` so the cursor the engine hands back stays\n * valid on the next request: a cursor is only meaningful against a total order,\n * and an unordered page would silently skip or repeat rows.\n */\nexport function pageQuery(\n namespace: string,\n cursor: string | null = null,\n limit: number = PAGE_LIMIT\n): Record<string, unknown> {\n const options: Record<string, unknown> = { limit, order: { id: \"asc\" } };\n if (cursor !== null && cursor.length > 0) options.after = cursor;\n return { [namespace]: { $: options } };\n}\n\nconst PAGE = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<title>tapedb studio</title>\n<style>\n :root { color-scheme: dark; }\n body { margin: 0; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;\n background: #0d1117; color: #e6edf3; }\n header { display: flex; gap: 8px; align-items: center; padding: 10px 14px;\n border-bottom: 1px solid #21262d; flex-wrap: wrap; }\n input, select, button, textarea { font: inherit; background: #161b22; color: #e6edf3;\n border: 1px solid #30363d; border-radius: 6px; padding: 6px 8px; }\n button { cursor: pointer; } button:hover { border-color: #8b949e; }\n main { padding: 14px; display: grid; gap: 14px; }\n table { border-collapse: collapse; width: 100%; }\n th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid #21262d;\n vertical-align: top; max-width: 360px; overflow: hidden; text-overflow: ellipsis; }\n th { color: #8b949e; font-weight: 600; }\n .muted { color: #8b949e; }\n .err { color: #ff7b72; white-space: pre-wrap; }\n textarea { width: 100%; min-height: 90px; }\n #more { margin-top: 8px; }\n</style>\n</head>\n<body>\n<header>\n <strong>tapedb</strong>\n <select id=\"workspaces\" title=\"workspaces opened before\"></select>\n <input id=\"workspace\" placeholder=\"workspace uuid\" size=\"38\" />\n <select id=\"namespace\"><option value=\"\">(connect)</option></select>\n <button id=\"refresh\">refresh</button>\n <span id=\"status\" class=\"muted\"></span>\n</header>\n<main>\n <div id=\"error\" class=\"err\"></div>\n <div id=\"table-wrap\" class=\"muted\">no data yet</div>\n <div>\n <button id=\"more\" style=\"display:none\">load more</button>\n </div>\n <div>\n <div class=\"muted\">transact (JSON ops, sent as one transaction)</div>\n <textarea id=\"ops\">[{\"op\":\"update\",\"namespace\":\"boards\",\"id\":\"board-1\",\"values\":{\"name\":\"Hello\"}}]</textarea>\n <button id=\"send\">send</button>\n </div>\n</main>\n<script>\nconst $ = (id) => document.getElementById(id);\nconst LIST_KEY = \"tapedb-workspaces\";\nconst CURRENT_KEY = \"tapedb-workspace\";\nconst PAGE_LIMIT = ${PAGE_LIMIT};\nconst MAX_REMEMBERED = 8;\n\n// The token lives on the server, keyed by workspace; the page only knows which\n// workspace is open, so switching one resets the other.\nconst state = { namespace: \"\", cursor: null, rows: [] };\n\nfunction showError(message) { $(\"error\").textContent = message || \"\"; }\n\nfunction readWorkspaces() {\n try {\n const parsed = JSON.parse(localStorage.getItem(LIST_KEY) || \"[]\");\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((id) => typeof id === \"string\" && id.length > 0);\n } catch { return []; }\n}\n\nfunction renderWorkspaces() {\n const select = $(\"workspaces\");\n const list = readWorkspaces();\n select.innerHTML = \"\";\n const placeholder = document.createElement(\"option\");\n placeholder.value = \"\";\n placeholder.textContent = list.length > 0 ? \"recent workspaces\" : \"no saved workspaces\";\n select.append(placeholder);\n for (const id of list) {\n const option = document.createElement(\"option\");\n option.value = id;\n option.textContent = id.length > 12 ? id.slice(0, 8) + \"…\" + id.slice(-3) : id;\n option.title = id;\n select.append(option);\n }\n select.value = \"\";\n}\n\nfunction rememberWorkspace(id) {\n if (!id) return;\n const next = [id].concat(readWorkspaces().filter((existing) => existing !== id)).slice(0, MAX_REMEMBERED);\n localStorage.setItem(LIST_KEY, JSON.stringify(next));\n localStorage.setItem(CURRENT_KEY, id);\n renderWorkspaces();\n}\n\nasync function api(path, body) {\n const response = await fetch(path, {\n method: body === undefined ? \"GET\" : \"POST\",\n headers: body === undefined ? {} : { \"content-type\": \"application/json\" },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const text = await response.text();\n let parsed; try { parsed = JSON.parse(text); } catch { parsed = { raw: text }; }\n if (!response.ok) throw new Error(parsed?.error?.message || text.slice(0, 300));\n return parsed;\n}\n\nfunction workspaceId() { return $(\"workspace\").value.trim(); }\n\nfunction cell(value) {\n const text = value === null || value === undefined\n ? \"\"\n : typeof value === \"object\" ? JSON.stringify(value) : String(value);\n const escaped = text.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/'/g, \"'\");\n return \"<td title='\" + escaped + \"'>\" + escaped + \"</td>\";\n}\n\n// Rebuilt from every row loaded so far, so a later page can add columns the\n// first one did not have and nothing already on screen is lost.\nfunction renderRows() {\n if (state.rows.length === 0) {\n $(\"table-wrap\").textContent = \"no rows in \" + state.namespace;\n return;\n }\n const columns = [...new Set(state.rows.flatMap((row) => Object.keys(row)))];\n const head = \"<tr>\" + columns.map((column) => \"<th>\" + column + \"</th>\").join(\"\") + \"</tr>\";\n const body = state.rows\n .map((row) => \"<tr>\" + columns.map((column) => cell(row[column])).join(\"\") + \"</tr>\")\n .join(\"\");\n $(\"table-wrap\").innerHTML = \"<table>\" + head + body + \"</table>\";\n}\n\nfunction applyPage(namespace, data, pageInfo, append) {\n const rows = data[namespace] || [];\n state.rows = append ? state.rows.concat(rows) : rows;\n const info = pageInfo?.[namespace];\n state.cursor = info && info.hasMore && info.nextCursor ? info.nextCursor : null;\n renderRows();\n $(\"more\").style.display = state.cursor ? \"\" : \"none\";\n $(\"status\").textContent = namespace + \": \" + state.rows.length + \" rows\" +\n (state.cursor ? \" (more available)\" : \"\");\n}\n\nasync function fetchPage(cursor) {\n return api(\"/api/query\", {\n workspaceId: workspaceId(),\n namespace: state.namespace,\n limit: PAGE_LIMIT,\n cursor: cursor || undefined,\n });\n}\n\nasync function loadSchema() {\n const workspace = workspaceId();\n if (!workspace) { showError(\"Enter a workspace id first.\"); return; }\n showError(\"\");\n const { data } = await api(\"/api/schema\", { workspaceId: workspace });\n const select = $(\"namespace\");\n select.innerHTML = \"\";\n for (const namespace of data.namespaces) {\n const option = document.createElement(\"option\");\n option.value = namespace.apiName;\n option.textContent = namespace.apiName + \" (\" + Object.keys(namespace.attributes).length + \" attrs)\";\n select.append(option);\n }\n $(\"status\").textContent = data.namespaces.length + \" namespaces\";\n state.namespace = select.value || \"\";\n state.cursor = null;\n state.rows = [];\n await loadRows();\n}\n\nasync function loadRows() {\n if (!state.namespace) { state.namespace = $(\"namespace\").value; }\n if (!state.namespace) return;\n const { data, pageInfo } = await fetchPage(null);\n applyPage(state.namespace, data, pageInfo, false);\n}\n\nasync function loadMore() {\n if (!state.cursor) return;\n const { data, pageInfo } = await fetchPage(state.cursor);\n applyPage(state.namespace, data, pageInfo, true);\n}\n\n// A workspace switch invalidates both the cached claim (server side) and the\n// rows on screen (here), so schema and first page are always fetched together.\nfunction connect(workspace) {\n $(\"workspace\").value = workspace;\n rememberWorkspace(workspace);\n state.cursor = null;\n state.rows = [];\n $(\"more\").style.display = \"none\";\n loadSchema().catch((error) => showError(error.message));\n}\n\n$(\"refresh\").addEventListener(\"click\", () => { loadSchema().catch((e) => showError(e.message)); });\n$(\"namespace\").addEventListener(\"change\", () => {\n state.namespace = $(\"namespace\").value;\n state.cursor = null;\n state.rows = [];\n loadRows().catch((e) => showError(e.message));\n});\n$(\"more\").addEventListener(\"click\", () => { loadMore().catch((e) => showError(e.message)); });\n$(\"workspaces\").addEventListener(\"change\", () => {\n const selected = $(\"workspaces\").value;\n if (selected) connect(selected);\n});\n$(\"workspace\").addEventListener(\"change\", () => {\n const entered = workspaceId();\n if (entered) connect(entered); else showError(\"Enter a workspace id first.\");\n});\n$(\"send\").addEventListener(\"click\", async () => {\n try {\n showError(\"\");\n const ops = JSON.parse($(\"ops\").value);\n const result = await api(\"/api/transact\", {\n workspaceId: workspaceId(),\n body: { txId: \"studio-\" + Date.now(), ops },\n });\n $(\"status\").textContent = \"applied seq \" + (result?.result?.seq ?? \"?\");\n state.cursor = null;\n state.rows = [];\n await loadRows();\n } catch (error) { showError(error.message); }\n});\n\nrenderWorkspaces();\n$(\"workspace\").value = localStorage.getItem(CURRENT_KEY) || \"\";\nloadSchema().catch((e) => showError(e.message));\n</script>\n</body>\n</html>`;\n\nexport function startStudio(options: StudioOptions): Promise<{ url: string; close: () => void }> {\n const base = options.url.replace(/\\/+$/, \"\");\n const state: StudioState = { token: null, workspace: options.workspace };\n\n const server = createServer(async (request, response) => {\n try {\n const url = new URL(request.url ?? \"/\", \"http://localhost\");\n\n if (url.pathname === \"/\") {\n response.writeHead(200, { \"content-type\": \"text/html; charset=utf-8\" });\n response.end(PAGE);\n return;\n }\n\n if (url.pathname === \"/api/health\") {\n sendJson(response, 200, { base, workspace: state.workspace });\n return;\n }\n\n const body = await readBody(request);\n\n if (url.pathname === \"/api/schema\") {\n const parsed = parseJsonBody<{ workspaceId?: string }>(body);\n if (typeof parsed.workspaceId === \"string\") setWorkspace(state, parsed.workspaceId);\n const upstream = await engine(base, state, \"/schema\");\n await forward(response, upstream);\n return;\n }\n\n if (url.pathname === \"/api/query\") {\n const parsed = parseJsonBody<{\n workspaceId?: string;\n query?: unknown;\n namespace?: string;\n cursor?: string | null;\n limit?: number;\n }>(body);\n if (typeof parsed.workspaceId === \"string\") setWorkspace(state, parsed.workspaceId);\n\n let query = parsed.query;\n if (query === undefined) {\n // The page sends a namespace plus the cursor it was handed, and the\n // studio composes the query, so `order` cannot drift between pages.\n if (typeof parsed.namespace !== \"string\" || parsed.namespace.length === 0) {\n throw new BadRequest(\"Send either a `query` document or a `namespace` to page through.\");\n }\n const cursor = typeof parsed.cursor === \"string\" ? parsed.cursor : null;\n const limit = typeof parsed.limit === \"number\" ? parsed.limit : PAGE_LIMIT;\n query = pageQuery(parsed.namespace, cursor, limit);\n }\n\n const upstream = await engine(base, state, \"/query\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ query }),\n });\n await forward(response, upstream);\n return;\n }\n\n if (url.pathname === \"/api/transact\") {\n const parsed = parseJsonBody<{ workspaceId?: string; body?: unknown }>(body);\n if (typeof parsed.workspaceId === \"string\") setWorkspace(state, parsed.workspaceId);\n const upstream = await engine(base, state, \"/transact\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(parsed.body),\n });\n await forward(response, upstream);\n return;\n }\n\n sendJson(response, 404, { error: { message: `No studio route for ${url.pathname}` } });\n } catch (error) {\n const status = error instanceof BadRequest ? 400 : 500;\n sendJson(response, status, {\n error: { message: error instanceof Error ? error.message : String(error) },\n });\n }\n });\n\n return new Promise((resolve, reject) => {\n server.once(\"error\", (error: NodeJS.ErrnoException) => {\n reject(\n error.code === \"EADDRINUSE\"\n ? new Error(\n `Port ${options.port} is already in use. Pass --port <port> to pick another.`\n )\n : error\n );\n });\n\n server.listen(options.port, \"127.0.0.1\", () => {\n // `port: 0` lets the OS choose, so the bound port is read back rather\n // than assumed: tests rely on it to avoid fixed ports entirely.\n const address = server.address();\n const bound = typeof address === \"object\" && address !== null ? address.port : options.port;\n resolve({\n url: `http://127.0.0.1:${bound}`,\n close: () => {\n server.close();\n // A browser (or a test client) holds keep-alive sockets open, and\n // `close` alone would wait for them before releasing the port.\n server.closeAllConnections();\n },\n });\n });\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport { mintToken } from \"./studio\";\n\nexport async function moveWorkspaces(argv: string[]): Promise<number> {\n const flag = (name: string) => { const i = argv.indexOf(`--${name}`); return i < 0 ? undefined : argv[i + 1]; };\n const to = flag(\"to\");\n if (!to || ![\"none\", \"eu\", \"fedramp\"].includes(to)) { console.error(\"Use tapedb move --to none|eu|fedramp --workspace <uuid> or --workspaces <file>.\"); return 1; }\n const url = (flag(\"url\") ?? \"http://localhost:8787\").replace(/\\/+$/, \"\");\n const ids = new Set<string>();\n if (flag(\"workspace\")) ids.add(flag(\"workspace\")!);\n if (flag(\"workspaces\")) for (const id of readFileSync(flag(\"workspaces\")!, \"utf8\").split(/\\s+/).filter(Boolean)) ids.add(id);\n if (!ids.size || argv.includes(\"--discover\")) {\n const account = flag(\"account\") ?? process.env.CLOUDFLARE_ACCOUNT_ID;\n const bucket = flag(\"source-bucket\");\n const token = process.env.CLOUDFLARE_API_TOKEN;\n if (!account || !bucket || !token) { console.error(\"Discovery needs --account, --source-bucket and CLOUDFLARE_API_TOKEN; alternatively pass workspace ids.\"); return 1; }\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ prefix: \"ws/\", delimiter: \"/\", per_page: \"1000\", ...(cursor ? { cursor } : {}) });\n const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(account)}/r2/buckets/${encodeURIComponent(bucket)}/objects?${params}`, {\n headers: { authorization: `Bearer ${token}`, \"cf-r2-jurisdiction\": !flag(\"from\") || flag(\"from\") === \"none\" ? \"default\" : flag(\"from\")! },\n });\n const body = await response.json() as { success: boolean; result: Array<{ key: string }>; result_info?: { delimited?: string[]; cursor?: string; is_truncated?: boolean } };\n if (!response.ok || !body.success) throw new Error(`Discovery failed (${response.status}).`);\n for (const key of [...body.result_info?.delimited ?? [], ...body.result.map(object => object.key)]) {\n const id = /^ws\\/([^/]+)\\//.exec(key)?.[1]; if (id) ids.add(id);\n }\n cursor = body.result_info?.is_truncated ? body.result_info.cursor : undefined;\n if (body.result_info?.is_truncated && !cursor) throw new Error(\"Discovery ended without its next cursor.\");\n } while (cursor);\n }\n const tokens: Record<string, string> = flag(\"tokens\") ? JSON.parse(readFileSync(flag(\"tokens\")!, \"utf8\")) : {};\n for (const id of ids) {\n const token = tokens[id] ?? process.env.TAPEDB_TOKEN ?? await mintToken(url, id);\n for (let attempt = 0;; attempt++) {\n const response = await fetch(`${url}/engine/workspaces/${encodeURIComponent(id)}/move`, {\n method: \"POST\", headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" }, body: JSON.stringify({ to }),\n });\n const body = await response.json() as { ok?: boolean; error?: { message?: string; code?: string } };\n if (response.ok && body.ok) { console.log(`Moved ${id} to ${to}; source data removed.`); break; }\n if (attempt >= 300 || (response.status < 500 && body.error?.code !== \"workspace_moving\")) {\n console.error(`Move ${id} did not finish: ${body.error?.message ?? response.status}. Run the command again to resume.`); return 1;\n }\n await new Promise(resolve => setTimeout(resolve, 2000));\n }\n }\n return 0;\n}\n"],"mappings":";;;;;;;;;AAgBA,SAAS,gBAAgB,cAAc,cAAAA,aAAY,aAAAC,YAAW,gBAAAC,eAAc,cAAc,QAAQ,iBAAAC,sBAAqB;AACvH,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;AAC1B,SAAS,UAAU,SAAS,SAAS,QAAAC,OAAM,eAAe;AAC1D,SAAS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I;AAC7C,SAAO,MAAM;AACf;AAOO,SAAS,aAAa,OAA2B,WAA4B;AAClF,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI;AACF,WAAO,aAAa,KAAK,MAAM,aAAa,cAAc,SAAS,CAAC;AAAA,EACtE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,IAAI,aAAa,QAAQ,KAAK,CAAC,GAAG,YAAY,GAAG,GAAG;AAClD,OAAK,IAAI,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,SAAS,QAAQ,KAAK,IAAI,CAAC;AACnE;","names":["existsSync","mkdirSync","readFileSync","writeFileSync","join","init","resolve","readFileSync","readFileSync","resolve","existsSync","join","readFileSync","run","mkdirSync","writeFileSync","write","resolve"]}
|