@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/dist/cli.js ADDED
@@ -0,0 +1,1501 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ SQL_TYPE,
4
+ entityDdl,
5
+ sqlLiteral
6
+ } from "./chunk-VWW5OS5B.js";
7
+ import "./chunk-3AL32Q4K.js";
8
+
9
+ // src/cli/index.ts
10
+ import { appendFileSync, copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
11
+ import { randomBytes } from "crypto";
12
+ import { spawnSync } from "child_process";
13
+ import { basename, dirname, extname, join as join2, resolve } from "path";
14
+ import { fileURLToPath, pathToFileURL } from "url";
15
+
16
+ // src/cli/migrate.ts
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "fs";
18
+ import { join } from "path";
19
+ var FIRST_MIGRATION_ID = "0002_entities";
20
+ var CHANGES_PREFIX = "-- tapedb:changes ";
21
+ function snapshotOf(schema) {
22
+ const models = {};
23
+ for (const namespace of schema.registry.namespaces) {
24
+ const attributes = {};
25
+ for (const [name, attribute] of Object.entries(namespace.attributes)) {
26
+ attributes[name] = {
27
+ type: attribute.type,
28
+ optional: attribute.optional === true,
29
+ indexed: attribute.indexed === true,
30
+ unique: attribute.unique === true,
31
+ ...attribute.default === void 0 ? {} : { default: attribute.default },
32
+ ...attribute.references ? {
33
+ references: {
34
+ table: attribute.references.table,
35
+ column: attribute.references.column,
36
+ onDelete: attribute.references.onDelete ?? "SET NULL"
37
+ }
38
+ } : {}
39
+ };
40
+ }
41
+ models[namespace.apiName] = { table: namespace.table, attributes };
42
+ }
43
+ return { version: 1, models };
44
+ }
45
+ function column(attribute) {
46
+ return attribute.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
47
+ }
48
+ function indexName(table, columnName) {
49
+ return `${table}_${columnName}_idx`;
50
+ }
51
+ function columnDefinition(name, attribute) {
52
+ let sql = `"${column(name)}" ${SQL_TYPE[attribute.type] ?? "TEXT"}`;
53
+ if (attribute.default !== void 0) sql += ` DEFAULT ${sqlLiteral(attribute.default)}`;
54
+ if (attribute.references) {
55
+ sql += ` REFERENCES "${attribute.references.table}"("${attribute.references.column}") ON DELETE ${attribute.references.onDelete}`;
56
+ }
57
+ return sql;
58
+ }
59
+ function createTable(model, table, attributes) {
60
+ const namespace = { apiName: model, table, attributes: {} };
61
+ const entity = {};
62
+ for (const [name, attribute] of Object.entries(attributes)) {
63
+ entity[name] = {
64
+ type: attribute.type,
65
+ optional: attribute.optional,
66
+ indexed: attribute.indexed,
67
+ unique: attribute.unique,
68
+ ...attribute.default === void 0 ? {} : { default: attribute.default },
69
+ ...attribute.references ? {
70
+ references: {
71
+ table: attribute.references.table,
72
+ column: attribute.references.column,
73
+ onDelete: attribute.references.onDelete
74
+ }
75
+ } : {}
76
+ };
77
+ }
78
+ return entityDdl(namespace, entity);
79
+ }
80
+ function indexStatements(table, name, before, after) {
81
+ const index = indexName(table, column(name));
82
+ const had = before !== void 0 && (before.indexed || before.unique);
83
+ const has = after !== void 0 && (after.indexed || after.unique);
84
+ const same = had && has && before.unique === after.unique;
85
+ if (same || !had && !has) return [];
86
+ const statements = [];
87
+ if (had) statements.push(`DROP INDEX IF EXISTS "${index}";`);
88
+ if (has) {
89
+ statements.push(
90
+ `CREATE ${after.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS "${index}" ON "${table}" ("${column(name)}");`
91
+ );
92
+ }
93
+ return statements;
94
+ }
95
+ function parseRenames(renames) {
96
+ const models = /* @__PURE__ */ new Map();
97
+ const fields = /* @__PURE__ */ new Map();
98
+ for (const entry of renames) {
99
+ 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);
100
+ if (!match) throw new Error(`--rename "${entry}" must be old=new or model.old=new.`);
101
+ const [, first, second, target] = match;
102
+ if (second === void 0) models.set(first, target);
103
+ else {
104
+ const map = fields.get(first) ?? /* @__PURE__ */ new Map();
105
+ map.set(second, target);
106
+ fields.set(first, map);
107
+ }
108
+ }
109
+ return { models, fields };
110
+ }
111
+ function diffSnapshots(before, after, options = {}) {
112
+ const plan = { statements: [], changes: [], destructive: [], refused: [] };
113
+ const renames = parseRenames(options.renames ?? []);
114
+ const pairs = [];
115
+ const matchedOld = /* @__PURE__ */ new Set();
116
+ for (const name of Object.keys(after.models)) {
117
+ const previous = [...renames.models.entries()].find(([, to]) => to === name)?.[0];
118
+ if (previous !== void 0) {
119
+ if (!(previous in before.models)) plan.refused.push(`--rename ${previous}=${name}: there is no model "${previous}".`);
120
+ else {
121
+ pairs.push([previous, name]);
122
+ matchedOld.add(previous);
123
+ }
124
+ } else if (name in before.models) {
125
+ pairs.push([name, name]);
126
+ matchedOld.add(name);
127
+ } else {
128
+ pairs.push([null, name]);
129
+ }
130
+ }
131
+ for (const name of Object.keys(before.models)) {
132
+ if (!matchedOld.has(name)) pairs.push([name, null]);
133
+ }
134
+ for (const [oldName, newName] of pairs) {
135
+ if (oldName === null) {
136
+ const model = after.models[newName];
137
+ plan.statements.push(...createTable(newName, model.table, model.attributes));
138
+ continue;
139
+ }
140
+ const oldModel = before.models[oldName];
141
+ if (newName === null) {
142
+ plan.destructive.push(`drop model "${oldName}" and every row in "${oldModel.table}"`);
143
+ plan.statements.push(`DROP TABLE IF EXISTS "${oldModel.table}";`);
144
+ plan.changes.push({ kind: "dropModel", model: oldName, table: oldModel.table });
145
+ continue;
146
+ }
147
+ const newModel = after.models[newName];
148
+ if (oldName !== newName || oldModel.table !== newModel.table) {
149
+ if (oldModel.table !== newModel.table) {
150
+ plan.statements.push(`ALTER TABLE "${oldModel.table}" RENAME TO "${newModel.table}";`);
151
+ }
152
+ plan.changes.push({ kind: "renameModel", from: oldName, to: newName, fromTable: oldModel.table, toTable: newModel.table });
153
+ }
154
+ diffFields(plan, newName, newModel.table, oldModel.attributes, newModel.attributes, renames.fields.get(newName) ?? renames.fields.get(oldName) ?? /* @__PURE__ */ new Map());
155
+ }
156
+ if (plan.destructive.length > 0 && !options.acceptDataLoss) {
157
+ plan.refused.push(
158
+ `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.`
159
+ );
160
+ }
161
+ return plan;
162
+ }
163
+ function diffFields(plan, model, table, before, after, renames) {
164
+ const handled = /* @__PURE__ */ new Set();
165
+ for (const [from, to] of renames) {
166
+ if (!(from in before)) {
167
+ plan.refused.push(`--rename ${model}.${from}=${to}: "${model}" has no field "${from}".`);
168
+ continue;
169
+ }
170
+ if (!(to in after)) {
171
+ plan.refused.push(`--rename ${model}.${from}=${to}: the schema has no field "${model}.${to}".`);
172
+ continue;
173
+ }
174
+ plan.statements.push(...indexStatements(table, from, before[from], void 0));
175
+ plan.statements.push(`ALTER TABLE "${table}" RENAME COLUMN "${column(from)}" TO "${column(to)}";`);
176
+ plan.statements.push(...indexStatements(table, to, void 0, after[to]));
177
+ plan.changes.push({ kind: "renameField", model, table, from, to, fromColumn: column(from), toColumn: column(to) });
178
+ handled.add(from);
179
+ handled.add(to);
180
+ compareField(plan, model, table, to, { ...before[from] }, after[to], true);
181
+ }
182
+ for (const [name, attribute] of Object.entries(after)) {
183
+ if (handled.has(name)) continue;
184
+ if (!(name in before)) {
185
+ if (!attribute.optional && attribute.default === void 0) {
186
+ plan.refused.push(
187
+ `"${model}.${name}" is new and required with no default, so existing rows would have no value. Give it .default(...) or make it .optional().`
188
+ );
189
+ continue;
190
+ }
191
+ plan.statements.push(`ALTER TABLE "${table}" ADD COLUMN ${columnDefinition(name, attribute)};`);
192
+ plan.statements.push(...indexStatements(table, name, void 0, attribute));
193
+ continue;
194
+ }
195
+ compareField(plan, model, table, name, before[name], attribute, false);
196
+ }
197
+ for (const [name, attribute] of Object.entries(before)) {
198
+ if (handled.has(name) || name in after) continue;
199
+ plan.destructive.push(`drop "${model}.${name}" and its values`);
200
+ plan.statements.push(...indexStatements(table, name, attribute, void 0));
201
+ plan.statements.push(`ALTER TABLE "${table}" DROP COLUMN "${column(name)}";`);
202
+ plan.changes.push({ kind: "dropField", model, table, field: name, column: column(name) });
203
+ }
204
+ }
205
+ function compareField(plan, model, table, name, before, after, renamed) {
206
+ if (!renamed) plan.statements.push(...indexStatements(table, name, before, after));
207
+ const sqlTypeChanged = (SQL_TYPE[before.type] ?? "TEXT") !== (SQL_TYPE[after.type] ?? "TEXT");
208
+ const referencesChanged = JSON.stringify(before.references ?? null) !== JSON.stringify(after.references ?? null);
209
+ const defaultChanged = JSON.stringify(before.default ?? null) !== JSON.stringify(after.default ?? null);
210
+ if (before.type !== after.type) {
211
+ plan.changes.push({ kind: "retypeField", model, field: name });
212
+ }
213
+ if (sqlTypeChanged || referencesChanged || defaultChanged) {
214
+ if (sqlTypeChanged) plan.destructive.push(`convert "${model}.${name}" from ${before.type} to ${after.type}; values that do not convert are lost`);
215
+ plan.statements.push(`-- rebuild "${table}" for "${model}.${name}"`);
216
+ plan.statements.push(`${REBUILD_MARKER}${table}:${name}`);
217
+ }
218
+ }
219
+ var REBUILD_MARKER = "-- tapedb:rebuild ";
220
+ function expandRebuilds(plan, after) {
221
+ const tables = /* @__PURE__ */ new Set();
222
+ plan.statements = plan.statements.filter((statement) => {
223
+ if (!statement.startsWith(REBUILD_MARKER)) return true;
224
+ tables.add(statement.slice(REBUILD_MARKER.length).split(":")[0]);
225
+ return false;
226
+ });
227
+ for (const table of tables) {
228
+ const [model, definition] = Object.entries(after.models).find(([, entry]) => entry.table === table);
229
+ const temporary = `${table}__rebuild`;
230
+ const columns = ["id", "created_at", "updated_at", "updated_seq", ...Object.keys(definition.attributes).map(column)];
231
+ const selected = ["id", "created_at", "updated_at", "updated_seq", ...Object.entries(definition.attributes).map(
232
+ ([name, attribute]) => `CAST("${column(name)}" AS ${SQL_TYPE[attribute.type] ?? "TEXT"})`
233
+ )];
234
+ const create = createTable(model, temporary, definition.attributes).map(
235
+ (statement) => statement.replace(new RegExp(`"${temporary}_`, "g"), `"${table}_`)
236
+ );
237
+ plan.statements.push(
238
+ create[0],
239
+ `INSERT INTO "${temporary}" (${columns.map((name) => `"${name}"`).join(", ")}) SELECT ${selected.join(", ")} FROM "${table}";`,
240
+ `DROP TABLE "${table}";`,
241
+ `ALTER TABLE "${temporary}" RENAME TO "${table}";`,
242
+ ...create.slice(1).map((statement) => statement.replace(`ON "${temporary}"`, `ON "${table}"`))
243
+ );
244
+ }
245
+ }
246
+ function migrationsDir(root) {
247
+ return join(root, "tapedb", "migrations");
248
+ }
249
+ function snapshotPath(root) {
250
+ return join(root, "tapedb", "schema.snapshot.json");
251
+ }
252
+ function historyPath(root, id) {
253
+ return join(root, "tapedb", "snapshots", `${id}.json`);
254
+ }
255
+ function writeHistory(root, id, snapshot) {
256
+ mkdirSync(join(root, "tapedb", "snapshots"), { recursive: true });
257
+ writeFileSync(historyPath(root, id), `${JSON.stringify(snapshot, null, 2)}
258
+ `);
259
+ }
260
+ function readHistory(root, id) {
261
+ const path = historyPath(root, id);
262
+ return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : null;
263
+ }
264
+ function bundlePath(root) {
265
+ return join(root, "tapedb", "migrations.gen.ts");
266
+ }
267
+ function readMigrations(root) {
268
+ const dir = migrationsDir(root);
269
+ if (!existsSync(dir)) return [];
270
+ return readdirSync(dir).filter((file) => /^\d{4}_[a-z0-9_]+\.sql$/.test(file)).sort().map((file) => {
271
+ const sql = readFileSync(join(dir, file), "utf8");
272
+ const header = sql.split("\n").find((line) => line.startsWith(CHANGES_PREFIX));
273
+ return {
274
+ id: file.replace(/\.sql$/, ""),
275
+ sql,
276
+ changes: header ? JSON.parse(header.slice(CHANGES_PREFIX.length)) : []
277
+ };
278
+ });
279
+ }
280
+ function readSnapshot(root) {
281
+ const path = snapshotPath(root);
282
+ return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : null;
283
+ }
284
+ function renderBundle(migrations) {
285
+ const entries = migrations.map(
286
+ (migration) => ` {
287
+ id: ${JSON.stringify(migration.id)},
288
+ sql: ${JSON.stringify(migration.sql)},${migration.changes.length > 0 ? `
289
+ changes: ${JSON.stringify(migration.changes)},` : ""}
290
+ },`
291
+ ).join("\n");
292
+ return `// Generated by \`tapedb migrate\`. Do not edit; edit the schema and run it again.
293
+ import type { AppMigration } from "@tapedb/tapedb/worker";
294
+
295
+ export const migrations: AppMigration[] = [
296
+ ${entries}
297
+ ];
298
+ `;
299
+ }
300
+ function slug(name) {
301
+ const value = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
302
+ if (!value) throw new Error(`Migration name "${name}" has no letters or digits.`);
303
+ return value;
304
+ }
305
+ function migrateDev(root, schema, name, options = {}) {
306
+ const next = snapshotOf(schema);
307
+ const previous = readSnapshot(root);
308
+ const existing = readMigrations(root);
309
+ mkdirSync(migrationsDir(root), { recursive: true });
310
+ const last = existing.at(-1);
311
+ if (previous !== null && last && readHistory(root, last.id) === null) writeHistory(root, last.id, previous);
312
+ let file;
313
+ if (previous === null) {
314
+ if (existing.length > 0) {
315
+ return { status: "refused", reasons: ["tapedb/migrations has files but no schema.snapshot.json. Restore the snapshot from version control."] };
316
+ }
317
+ file = { id: FIRST_MIGRATION_ID, sql: schema.migrations.at(-1).sql, changes: [] };
318
+ } else {
319
+ const plan = diffSnapshots(previous, next, options);
320
+ if (plan.refused.length > 0) return { status: "refused", reasons: plan.refused };
321
+ expandRebuilds(plan, next);
322
+ if (plan.statements.length === 0 && plan.changes.length === 0) {
323
+ writeFileSync(snapshotPath(root), `${JSON.stringify(next, null, 2)}
324
+ `);
325
+ writeFileSync(bundlePath(root), renderBundle(existing));
326
+ return { status: "unchanged" };
327
+ }
328
+ const number = Math.max(2, ...existing.map((migration) => Number(migration.id.slice(0, 4)))) + 1;
329
+ const id = `${String(number).padStart(4, "0")}_${slug(name)}`;
330
+ const header = plan.changes.length > 0 ? `${CHANGES_PREFIX}${JSON.stringify(plan.changes)}
331
+ ` : "";
332
+ file = { id, sql: `${header}${plan.statements.join("\n")}
333
+ `, changes: plan.changes };
334
+ }
335
+ writeFileSync(join(migrationsDir(root), `${file.id}.sql`), file.sql);
336
+ writeFileSync(snapshotPath(root), `${JSON.stringify(next, null, 2)}
337
+ `);
338
+ writeHistory(root, file.id, next);
339
+ writeFileSync(bundlePath(root), renderBundle([...existing, file]));
340
+ return {
341
+ status: "created",
342
+ id: file.id,
343
+ statements: countStatements(file.sql),
344
+ changes: file.changes
345
+ };
346
+ }
347
+ function renamesBack(target, undone) {
348
+ const models = new Map(Object.keys(target.models).map((name) => [name, name]));
349
+ const fields = /* @__PURE__ */ new Map();
350
+ for (const [name, entry] of Object.entries(target.models)) {
351
+ for (const field of Object.keys(entry.attributes)) fields.set(`${name}.${field}`, { model: name, field, current: field });
352
+ }
353
+ for (const migration of undone) {
354
+ for (const change of migration.changes) {
355
+ if (change.kind === "renameModel") {
356
+ for (const [original, current] of models) if (current === change.from) models.set(original, change.to);
357
+ } else if (change.kind === "renameField") {
358
+ for (const entry of fields.values()) {
359
+ if (models.get(entry.model) === change.model && entry.current === change.from) entry.current = change.to;
360
+ }
361
+ }
362
+ }
363
+ }
364
+ const renames = [];
365
+ for (const [original, current] of models) if (original !== current) renames.push(`${current}=${original}`);
366
+ for (const entry of fields.values()) {
367
+ if (entry.current !== entry.field) renames.push(`${models.get(entry.model)}.${entry.current}=${entry.field}`);
368
+ }
369
+ return renames;
370
+ }
371
+ function schemaEdits(current, target, renames) {
372
+ const modelBack = /* @__PURE__ */ new Map();
373
+ const fieldBack = /* @__PURE__ */ new Map();
374
+ for (const rename of renames) {
375
+ const [from, to] = rename.split("=");
376
+ if (from.includes(".")) fieldBack.set(from, to);
377
+ else modelBack.set(from, to);
378
+ }
379
+ const describe = (attribute) => [
380
+ attribute.type,
381
+ attribute.optional ? "optional" : "",
382
+ attribute.unique ? "unique" : attribute.indexed ? "indexed" : "",
383
+ attribute.default === void 0 ? "" : `default ${JSON.stringify(attribute.default)}`
384
+ ].filter(Boolean).join(", ");
385
+ const edits = [];
386
+ const matched = /* @__PURE__ */ new Set();
387
+ for (const [name, entry] of Object.entries(target.models)) {
388
+ const was = [...modelBack.entries()].find(([, original]) => original === name)?.[0] ?? name;
389
+ const now = current.models[was];
390
+ if (!now) {
391
+ edits.push(`add model "${name}"`);
392
+ continue;
393
+ }
394
+ matched.add(was);
395
+ if (was !== name) edits.push(`rename model "${was}" back to "${name}"`);
396
+ const kept = /* @__PURE__ */ new Set();
397
+ for (const [field, attribute] of Object.entries(entry.attributes)) {
398
+ const from = [...fieldBack.entries()].find(([key, original]) => key.startsWith(`${was}.`) && original === field)?.[0].split(".")[1] ?? field;
399
+ if (!(from in now.attributes)) {
400
+ edits.push(`add "${name}.${field}" (${describe(attribute)})`);
401
+ continue;
402
+ }
403
+ kept.add(from);
404
+ if (from !== field) edits.push(`rename "${name}.${from}" back to "${field}"`);
405
+ if (JSON.stringify(now.attributes[from]) !== JSON.stringify(attribute)) edits.push(`make "${name}.${field}" ${describe(attribute)} again`);
406
+ }
407
+ for (const field of Object.keys(now.attributes)) if (!kept.has(field)) edits.push(`remove "${name}.${field}"`);
408
+ }
409
+ for (const name of Object.keys(current.models)) if (!matched.has(name)) edits.push(`remove model "${name}"`);
410
+ return edits;
411
+ }
412
+ function migrateRollback(root, options = {}) {
413
+ const existing = readMigrations(root);
414
+ const current = readSnapshot(root);
415
+ if (current === null || existing.length === 0) return { status: "refused", reasons: ["There are no migrations to roll back."] };
416
+ const targetIndex = options.to === void 0 ? existing.length - 2 : existing.findIndex((migration) => migration.id === options.to);
417
+ if (options.to !== void 0 && targetIndex === -1) {
418
+ return { status: "refused", reasons: [`There is no migration "${options.to}".`] };
419
+ }
420
+ if (targetIndex < 0) return { status: "refused", reasons: [`${existing[0].id} creates the schema; there is nothing before it to go back to.`] };
421
+ if (targetIndex === existing.length - 1) return { status: "refused", reasons: [`${options.to} is the last migration already.`] };
422
+ const target = existing[targetIndex];
423
+ const before = readHistory(root, target.id);
424
+ if (before === null) {
425
+ return {
426
+ status: "refused",
427
+ reasons: [
428
+ `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\`.`
429
+ ]
430
+ };
431
+ }
432
+ const undone = existing.slice(targetIndex + 1);
433
+ const dropped = undone.flatMap(
434
+ (migration) => migration.changes.filter((change) => change.kind === "dropField" || change.kind === "dropModel").map(
435
+ (change) => change.kind === "dropField" ? `${migration.id} dropped "${change.model}.${change.field}"` : `${migration.id} dropped model "${change.model}"`
436
+ )
437
+ );
438
+ if (dropped.length > 0) {
439
+ return {
440
+ status: "refused",
441
+ reasons: [`${dropped.join("; ")}: those values are gone, so the schema after ${target.id} cannot be restored.`]
442
+ };
443
+ }
444
+ const renames = renamesBack(before, undone);
445
+ const plan = diffSnapshots(current, before, { renames, acceptDataLoss: options.acceptDataLoss });
446
+ if (plan.refused.length > 0) return { status: "refused", reasons: plan.refused };
447
+ expandRebuilds(plan, before);
448
+ const number = Math.max(...existing.map((migration) => Number(migration.id.slice(0, 4)))) + 1;
449
+ const id = `${String(number).padStart(4, "0")}_rollback_to_${target.id.slice(0, 4)}`;
450
+ const header = plan.changes.length > 0 ? `${CHANGES_PREFIX}${JSON.stringify(plan.changes)}
451
+ ` : "";
452
+ const file = { id, sql: `${header}${plan.statements.join("\n")}
453
+ `, changes: plan.changes };
454
+ if (readHistory(root, existing.at(-1).id) === null) writeHistory(root, existing.at(-1).id, current);
455
+ writeFileSync(join(migrationsDir(root), `${id}.sql`), file.sql);
456
+ writeFileSync(snapshotPath(root), `${JSON.stringify(before, null, 2)}
457
+ `);
458
+ writeHistory(root, id, before);
459
+ writeFileSync(bundlePath(root), renderBundle([...existing, file]));
460
+ return {
461
+ status: "created",
462
+ id,
463
+ to: target.id,
464
+ statements: countStatements(file.sql),
465
+ changes: plan.changes,
466
+ schemaEdits: schemaEdits(current, before, renames)
467
+ };
468
+ }
469
+ function countStatements(sql) {
470
+ return sql.split("\n").filter((line) => !line.startsWith("--")).join("\n").split(";").filter((statement) => statement.trim()).length;
471
+ }
472
+ function migrateCheck(root, schema) {
473
+ const problems = [];
474
+ const previous = readSnapshot(root);
475
+ if (previous === null) {
476
+ problems.push("No migrations yet. Run `tapedb migrate dev --name init`.");
477
+ return { ok: false, problems };
478
+ }
479
+ const plan = diffSnapshots(previous, snapshotOf(schema), { acceptDataLoss: true });
480
+ if (plan.statements.length > 0 || plan.changes.length > 0 || plan.refused.length > 0) {
481
+ problems.push("The schema has changes with no migration. Run `tapedb migrate dev --name <what changed>`.");
482
+ }
483
+ const bundle = existsSync(bundlePath(root)) ? readFileSync(bundlePath(root), "utf8") : "";
484
+ if (bundle !== renderBundle(readMigrations(root))) {
485
+ problems.push("tapedb/migrations.gen.ts is out of date with tapedb/migrations. Run `tapedb migrate dev` to regenerate it.");
486
+ }
487
+ return { ok: problems.length === 0, problems };
488
+ }
489
+
490
+ // src/cli/studio.ts
491
+ import { createServer } from "http";
492
+ var BadRequest = class extends Error {
493
+ };
494
+ var PAGE_LIMIT = 50;
495
+ function parseJsonBody(body) {
496
+ try {
497
+ return JSON.parse(body || "{}");
498
+ } catch {
499
+ throw new BadRequest("Request body must be JSON.");
500
+ }
501
+ }
502
+ async function readBody(request) {
503
+ const chunks = [];
504
+ for await (const chunk of request) chunks.push(chunk);
505
+ return Buffer.concat(chunks).toString("utf8");
506
+ }
507
+ function sendJson(response, status, body) {
508
+ const payload = JSON.stringify(body);
509
+ response.writeHead(status, {
510
+ "content-type": "application/json; charset=utf-8",
511
+ "content-length": Buffer.byteLength(payload)
512
+ });
513
+ response.end(payload);
514
+ }
515
+ async function forward(response, upstream) {
516
+ const text = await upstream.text();
517
+ let parsed;
518
+ try {
519
+ parsed = JSON.parse(text);
520
+ } catch {
521
+ response.writeHead(upstream.status, {
522
+ "content-type": upstream.headers.get("content-type") ?? "text/plain; charset=utf-8",
523
+ "content-length": Buffer.byteLength(text)
524
+ });
525
+ response.end(text);
526
+ return;
527
+ }
528
+ sendJson(response, upstream.status, parsed);
529
+ }
530
+ async function mintToken(base, workspace) {
531
+ const response = await fetch(`${base}/_tapedb/claim`, {
532
+ method: "POST",
533
+ headers: { "content-type": "application/json" },
534
+ body: JSON.stringify({ workspaceId: workspace })
535
+ });
536
+ const text = await response.text();
537
+ if (!response.ok) {
538
+ throw new Error(
539
+ `claim failed (${response.status}): ${text.slice(0, 200)}. Is the Worker running with \`tapedb dev\`?`
540
+ );
541
+ }
542
+ const parsed = JSON.parse(text);
543
+ if (typeof parsed.token !== "string") throw new Error("claim returned no token");
544
+ return parsed.token;
545
+ }
546
+ function setWorkspace(state, workspace) {
547
+ if (workspace === state.workspace) return;
548
+ state.workspace = workspace;
549
+ state.token = null;
550
+ }
551
+ async function engine(base, state, path, init2 = {}) {
552
+ if (state.workspace.length === 0) {
553
+ throw new Error("No workspace id. Enter one in the page.");
554
+ }
555
+ if (state.token === null) state.token = await mintToken(base, state.workspace);
556
+ const call = (token) => fetch(`${base}/engine/workspaces/${state.workspace}${path}`, {
557
+ ...init2,
558
+ headers: {
559
+ ...init2.headers,
560
+ authorization: `Bearer ${token}`
561
+ }
562
+ });
563
+ let response = await call(state.token);
564
+ if (response.status === 401) {
565
+ state.token = await mintToken(base, state.workspace);
566
+ response = await call(state.token);
567
+ }
568
+ return response;
569
+ }
570
+ function pageQuery(namespace, cursor = null, limit = PAGE_LIMIT) {
571
+ const options = { limit, order: { id: "asc" } };
572
+ if (cursor !== null && cursor.length > 0) options.after = cursor;
573
+ return { [namespace]: { $: options } };
574
+ }
575
+ var PAGE = `<!doctype html>
576
+ <html lang="en">
577
+ <head>
578
+ <meta charset="utf-8" />
579
+ <title>tapedb studio</title>
580
+ <style>
581
+ :root { color-scheme: dark; }
582
+ body { margin: 0; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
583
+ background: #0d1117; color: #e6edf3; }
584
+ header { display: flex; gap: 8px; align-items: center; padding: 10px 14px;
585
+ border-bottom: 1px solid #21262d; flex-wrap: wrap; }
586
+ input, select, button, textarea { font: inherit; background: #161b22; color: #e6edf3;
587
+ border: 1px solid #30363d; border-radius: 6px; padding: 6px 8px; }
588
+ button { cursor: pointer; } button:hover { border-color: #8b949e; }
589
+ main { padding: 14px; display: grid; gap: 14px; }
590
+ table { border-collapse: collapse; width: 100%; }
591
+ th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid #21262d;
592
+ vertical-align: top; max-width: 360px; overflow: hidden; text-overflow: ellipsis; }
593
+ th { color: #8b949e; font-weight: 600; }
594
+ .muted { color: #8b949e; }
595
+ .err { color: #ff7b72; white-space: pre-wrap; }
596
+ textarea { width: 100%; min-height: 90px; }
597
+ #more { margin-top: 8px; }
598
+ </style>
599
+ </head>
600
+ <body>
601
+ <header>
602
+ <strong>tapedb</strong>
603
+ <select id="workspaces" title="workspaces opened before"></select>
604
+ <input id="workspace" placeholder="workspace uuid" size="38" />
605
+ <select id="namespace"><option value="">(connect)</option></select>
606
+ <button id="refresh">refresh</button>
607
+ <span id="status" class="muted"></span>
608
+ </header>
609
+ <main>
610
+ <div id="error" class="err"></div>
611
+ <div id="table-wrap" class="muted">no data yet</div>
612
+ <div>
613
+ <button id="more" style="display:none">load more</button>
614
+ </div>
615
+ <div>
616
+ <div class="muted">transact (JSON ops, sent as one transaction)</div>
617
+ <textarea id="ops">[{"op":"update","namespace":"boards","id":"board-1","values":{"name":"Hello"}}]</textarea>
618
+ <button id="send">send</button>
619
+ </div>
620
+ </main>
621
+ <script>
622
+ const $ = (id) => document.getElementById(id);
623
+ const LIST_KEY = "tapedb-workspaces";
624
+ const CURRENT_KEY = "tapedb-workspace";
625
+ const PAGE_LIMIT = ${PAGE_LIMIT};
626
+ const MAX_REMEMBERED = 8;
627
+
628
+ // The token lives on the server, keyed by workspace; the page only knows which
629
+ // workspace is open, so switching one resets the other.
630
+ const state = { namespace: "", cursor: null, rows: [] };
631
+
632
+ function showError(message) { $("error").textContent = message || ""; }
633
+
634
+ function readWorkspaces() {
635
+ try {
636
+ const parsed = JSON.parse(localStorage.getItem(LIST_KEY) || "[]");
637
+ if (!Array.isArray(parsed)) return [];
638
+ return parsed.filter((id) => typeof id === "string" && id.length > 0);
639
+ } catch { return []; }
640
+ }
641
+
642
+ function renderWorkspaces() {
643
+ const select = $("workspaces");
644
+ const list = readWorkspaces();
645
+ select.innerHTML = "";
646
+ const placeholder = document.createElement("option");
647
+ placeholder.value = "";
648
+ placeholder.textContent = list.length > 0 ? "recent workspaces" : "no saved workspaces";
649
+ select.append(placeholder);
650
+ for (const id of list) {
651
+ const option = document.createElement("option");
652
+ option.value = id;
653
+ option.textContent = id.length > 12 ? id.slice(0, 8) + "\u2026" + id.slice(-3) : id;
654
+ option.title = id;
655
+ select.append(option);
656
+ }
657
+ select.value = "";
658
+ }
659
+
660
+ function rememberWorkspace(id) {
661
+ if (!id) return;
662
+ const next = [id].concat(readWorkspaces().filter((existing) => existing !== id)).slice(0, MAX_REMEMBERED);
663
+ localStorage.setItem(LIST_KEY, JSON.stringify(next));
664
+ localStorage.setItem(CURRENT_KEY, id);
665
+ renderWorkspaces();
666
+ }
667
+
668
+ async function api(path, body) {
669
+ const response = await fetch(path, {
670
+ method: body === undefined ? "GET" : "POST",
671
+ headers: body === undefined ? {} : { "content-type": "application/json" },
672
+ body: body === undefined ? undefined : JSON.stringify(body),
673
+ });
674
+ const text = await response.text();
675
+ let parsed; try { parsed = JSON.parse(text); } catch { parsed = { raw: text }; }
676
+ if (!response.ok) throw new Error(parsed?.error?.message || text.slice(0, 300));
677
+ return parsed;
678
+ }
679
+
680
+ function workspaceId() { return $("workspace").value.trim(); }
681
+
682
+ function cell(value) {
683
+ const text = value === null || value === undefined
684
+ ? ""
685
+ : typeof value === "object" ? JSON.stringify(value) : String(value);
686
+ const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/'/g, "&#39;");
687
+ return "<td title='" + escaped + "'>" + escaped + "</td>";
688
+ }
689
+
690
+ // Rebuilt from every row loaded so far, so a later page can add columns the
691
+ // first one did not have and nothing already on screen is lost.
692
+ function renderRows() {
693
+ if (state.rows.length === 0) {
694
+ $("table-wrap").textContent = "no rows in " + state.namespace;
695
+ return;
696
+ }
697
+ const columns = [...new Set(state.rows.flatMap((row) => Object.keys(row)))];
698
+ const head = "<tr>" + columns.map((column) => "<th>" + column + "</th>").join("") + "</tr>";
699
+ const body = state.rows
700
+ .map((row) => "<tr>" + columns.map((column) => cell(row[column])).join("") + "</tr>")
701
+ .join("");
702
+ $("table-wrap").innerHTML = "<table>" + head + body + "</table>";
703
+ }
704
+
705
+ function applyPage(namespace, data, pageInfo, append) {
706
+ const rows = data[namespace] || [];
707
+ state.rows = append ? state.rows.concat(rows) : rows;
708
+ const info = pageInfo?.[namespace];
709
+ state.cursor = info && info.hasMore && info.nextCursor ? info.nextCursor : null;
710
+ renderRows();
711
+ $("more").style.display = state.cursor ? "" : "none";
712
+ $("status").textContent = namespace + ": " + state.rows.length + " rows" +
713
+ (state.cursor ? " (more available)" : "");
714
+ }
715
+
716
+ async function fetchPage(cursor) {
717
+ return api("/api/query", {
718
+ workspaceId: workspaceId(),
719
+ namespace: state.namespace,
720
+ limit: PAGE_LIMIT,
721
+ cursor: cursor || undefined,
722
+ });
723
+ }
724
+
725
+ async function loadSchema() {
726
+ const workspace = workspaceId();
727
+ if (!workspace) { showError("Enter a workspace id first."); return; }
728
+ showError("");
729
+ const { data } = await api("/api/schema", { workspaceId: workspace });
730
+ const select = $("namespace");
731
+ select.innerHTML = "";
732
+ for (const namespace of data.namespaces) {
733
+ const option = document.createElement("option");
734
+ option.value = namespace.apiName;
735
+ option.textContent = namespace.apiName + " (" + Object.keys(namespace.attributes).length + " attrs)";
736
+ select.append(option);
737
+ }
738
+ $("status").textContent = data.namespaces.length + " namespaces";
739
+ state.namespace = select.value || "";
740
+ state.cursor = null;
741
+ state.rows = [];
742
+ await loadRows();
743
+ }
744
+
745
+ async function loadRows() {
746
+ if (!state.namespace) { state.namespace = $("namespace").value; }
747
+ if (!state.namespace) return;
748
+ const { data, pageInfo } = await fetchPage(null);
749
+ applyPage(state.namespace, data, pageInfo, false);
750
+ }
751
+
752
+ async function loadMore() {
753
+ if (!state.cursor) return;
754
+ const { data, pageInfo } = await fetchPage(state.cursor);
755
+ applyPage(state.namespace, data, pageInfo, true);
756
+ }
757
+
758
+ // A workspace switch invalidates both the cached claim (server side) and the
759
+ // rows on screen (here), so schema and first page are always fetched together.
760
+ function connect(workspace) {
761
+ $("workspace").value = workspace;
762
+ rememberWorkspace(workspace);
763
+ state.cursor = null;
764
+ state.rows = [];
765
+ $("more").style.display = "none";
766
+ loadSchema().catch((error) => showError(error.message));
767
+ }
768
+
769
+ $("refresh").addEventListener("click", () => { loadSchema().catch((e) => showError(e.message)); });
770
+ $("namespace").addEventListener("change", () => {
771
+ state.namespace = $("namespace").value;
772
+ state.cursor = null;
773
+ state.rows = [];
774
+ loadRows().catch((e) => showError(e.message));
775
+ });
776
+ $("more").addEventListener("click", () => { loadMore().catch((e) => showError(e.message)); });
777
+ $("workspaces").addEventListener("change", () => {
778
+ const selected = $("workspaces").value;
779
+ if (selected) connect(selected);
780
+ });
781
+ $("workspace").addEventListener("change", () => {
782
+ const entered = workspaceId();
783
+ if (entered) connect(entered); else showError("Enter a workspace id first.");
784
+ });
785
+ $("send").addEventListener("click", async () => {
786
+ try {
787
+ showError("");
788
+ const ops = JSON.parse($("ops").value);
789
+ const result = await api("/api/transact", {
790
+ workspaceId: workspaceId(),
791
+ body: { txId: "studio-" + Date.now(), ops },
792
+ });
793
+ $("status").textContent = "applied seq " + (result?.result?.seq ?? "?");
794
+ state.cursor = null;
795
+ state.rows = [];
796
+ await loadRows();
797
+ } catch (error) { showError(error.message); }
798
+ });
799
+
800
+ renderWorkspaces();
801
+ $("workspace").value = localStorage.getItem(CURRENT_KEY) || "";
802
+ loadSchema().catch((e) => showError(e.message));
803
+ </script>
804
+ </body>
805
+ </html>`;
806
+ function startStudio(options) {
807
+ const base = options.url.replace(/\/+$/, "");
808
+ const state = { token: null, workspace: options.workspace };
809
+ const server = createServer(async (request, response) => {
810
+ try {
811
+ const url = new URL(request.url ?? "/", "http://localhost");
812
+ if (url.pathname === "/") {
813
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
814
+ response.end(PAGE);
815
+ return;
816
+ }
817
+ if (url.pathname === "/api/health") {
818
+ sendJson(response, 200, { base, workspace: state.workspace });
819
+ return;
820
+ }
821
+ const body = await readBody(request);
822
+ if (url.pathname === "/api/schema") {
823
+ const parsed = parseJsonBody(body);
824
+ if (typeof parsed.workspaceId === "string") setWorkspace(state, parsed.workspaceId);
825
+ const upstream = await engine(base, state, "/schema");
826
+ await forward(response, upstream);
827
+ return;
828
+ }
829
+ if (url.pathname === "/api/query") {
830
+ const parsed = parseJsonBody(body);
831
+ if (typeof parsed.workspaceId === "string") setWorkspace(state, parsed.workspaceId);
832
+ let query = parsed.query;
833
+ if (query === void 0) {
834
+ if (typeof parsed.namespace !== "string" || parsed.namespace.length === 0) {
835
+ throw new BadRequest("Send either a `query` document or a `namespace` to page through.");
836
+ }
837
+ const cursor = typeof parsed.cursor === "string" ? parsed.cursor : null;
838
+ const limit = typeof parsed.limit === "number" ? parsed.limit : PAGE_LIMIT;
839
+ query = pageQuery(parsed.namespace, cursor, limit);
840
+ }
841
+ const upstream = await engine(base, state, "/query", {
842
+ method: "POST",
843
+ headers: { "content-type": "application/json" },
844
+ body: JSON.stringify({ query })
845
+ });
846
+ await forward(response, upstream);
847
+ return;
848
+ }
849
+ if (url.pathname === "/api/transact") {
850
+ const parsed = parseJsonBody(body);
851
+ if (typeof parsed.workspaceId === "string") setWorkspace(state, parsed.workspaceId);
852
+ const upstream = await engine(base, state, "/transact", {
853
+ method: "POST",
854
+ headers: { "content-type": "application/json" },
855
+ body: JSON.stringify(parsed.body)
856
+ });
857
+ await forward(response, upstream);
858
+ return;
859
+ }
860
+ sendJson(response, 404, { error: { message: `No studio route for ${url.pathname}` } });
861
+ } catch (error) {
862
+ const status = error instanceof BadRequest ? 400 : 500;
863
+ sendJson(response, status, {
864
+ error: { message: error instanceof Error ? error.message : String(error) }
865
+ });
866
+ }
867
+ });
868
+ return new Promise((resolve2, reject) => {
869
+ server.once("error", (error) => {
870
+ reject(
871
+ error.code === "EADDRINUSE" ? new Error(
872
+ `Port ${options.port} is already in use. Pass --port <port> to pick another.`
873
+ ) : error
874
+ );
875
+ });
876
+ server.listen(options.port, "127.0.0.1", () => {
877
+ const address = server.address();
878
+ const bound = typeof address === "object" && address !== null ? address.port : options.port;
879
+ resolve2({
880
+ url: `http://127.0.0.1:${bound}`,
881
+ close: () => {
882
+ server.close();
883
+ server.closeAllConnections();
884
+ }
885
+ });
886
+ });
887
+ });
888
+ }
889
+
890
+ // src/cli/move.ts
891
+ import { readFileSync as readFileSync2 } from "fs";
892
+ async function moveWorkspaces(argv) {
893
+ const flag = (name) => {
894
+ const i = argv.indexOf(`--${name}`);
895
+ return i < 0 ? void 0 : argv[i + 1];
896
+ };
897
+ const to = flag("to");
898
+ if (!to || !["none", "eu", "fedramp"].includes(to)) {
899
+ console.error("Use tapedb move --to none|eu|fedramp --workspace <uuid> or --workspaces <file>.");
900
+ return 1;
901
+ }
902
+ const url = (flag("url") ?? "http://localhost:8787").replace(/\/+$/, "");
903
+ const ids = /* @__PURE__ */ new Set();
904
+ if (flag("workspace")) ids.add(flag("workspace"));
905
+ if (flag("workspaces")) for (const id of readFileSync2(flag("workspaces"), "utf8").split(/\s+/).filter(Boolean)) ids.add(id);
906
+ if (!ids.size || argv.includes("--discover")) {
907
+ const account = flag("account") ?? process.env.CLOUDFLARE_ACCOUNT_ID;
908
+ const bucket = flag("source-bucket");
909
+ const token = process.env.CLOUDFLARE_API_TOKEN;
910
+ if (!account || !bucket || !token) {
911
+ console.error("Discovery needs --account, --source-bucket and CLOUDFLARE_API_TOKEN; alternatively pass workspace ids.");
912
+ return 1;
913
+ }
914
+ let cursor;
915
+ do {
916
+ const params = new URLSearchParams({ prefix: "ws/", delimiter: "/", per_page: "1000", ...cursor ? { cursor } : {} });
917
+ const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(account)}/r2/buckets/${encodeURIComponent(bucket)}/objects?${params}`, {
918
+ headers: { authorization: `Bearer ${token}`, "cf-r2-jurisdiction": !flag("from") || flag("from") === "none" ? "default" : flag("from") }
919
+ });
920
+ const body = await response.json();
921
+ if (!response.ok || !body.success) throw new Error(`Discovery failed (${response.status}).`);
922
+ for (const key of [...body.result_info?.delimited ?? [], ...body.result.map((object) => object.key)]) {
923
+ const id = /^ws\/([^/]+)\//.exec(key)?.[1];
924
+ if (id) ids.add(id);
925
+ }
926
+ cursor = body.result_info?.is_truncated ? body.result_info.cursor : void 0;
927
+ if (body.result_info?.is_truncated && !cursor) throw new Error("Discovery ended without its next cursor.");
928
+ } while (cursor);
929
+ }
930
+ const tokens = flag("tokens") ? JSON.parse(readFileSync2(flag("tokens"), "utf8")) : {};
931
+ for (const id of ids) {
932
+ const token = tokens[id] ?? process.env.TAPEDB_TOKEN ?? await mintToken(url, id);
933
+ for (let attempt = 0; ; attempt++) {
934
+ const response = await fetch(`${url}/engine/workspaces/${encodeURIComponent(id)}/move`, {
935
+ method: "POST",
936
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
937
+ body: JSON.stringify({ to })
938
+ });
939
+ const body = await response.json();
940
+ if (response.ok && body.ok) {
941
+ console.log(`Moved ${id} to ${to}; source data removed.`);
942
+ break;
943
+ }
944
+ if (attempt >= 300 || response.status < 500 && body.error?.code !== "workspace_moving") {
945
+ console.error(`Move ${id} did not finish: ${body.error?.message ?? response.status}. Run the command again to resume.`);
946
+ return 1;
947
+ }
948
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
949
+ }
950
+ }
951
+ return 0;
952
+ }
953
+
954
+ // src/cli/index.ts
955
+ var schemaLoads = 0;
956
+ async function loadSchema(root, flags) {
957
+ const path = resolve(root, typeof flags.schema === "string" ? flags.schema : "tapedb.schema.ts");
958
+ if (!existsSync2(path)) throw new Error(`No schema at ${path}. Pass --schema <file>.`);
959
+ let loaded;
960
+ try {
961
+ schemaLoads += 1;
962
+ const extension = extname(path) === ".ts" ? ".mts" : extname(path);
963
+ const copy = join2(dirname(path), `.${basename(path, extname(path))}.${process.pid}.${schemaLoads}${extension}`);
964
+ copyFileSync(path, copy);
965
+ try {
966
+ loaded = await import(pathToFileURL(copy).href);
967
+ } finally {
968
+ rmSync(copy, { force: true });
969
+ }
970
+ } catch (error) {
971
+ const message = error instanceof Error ? error.message : String(error);
972
+ if (/Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION/.test(message)) {
973
+ throw new Error(
974
+ `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 ...`
975
+ );
976
+ }
977
+ throw error;
978
+ }
979
+ const schema = loaded.default ?? loaded.schema;
980
+ if (!schema || !schema.registry || !Array.isArray(schema.migrations)) {
981
+ throw new Error(`${path} must export a schema() as its default export (or as "schema").`);
982
+ }
983
+ return schema;
984
+ }
985
+ function listFlag(argv, name) {
986
+ const values = [];
987
+ for (let index = 0; index < argv.length; index += 1) {
988
+ if (argv[index] === `--${name}` && argv[index + 1] !== void 0) values.push(argv[index + 1]);
989
+ }
990
+ return values;
991
+ }
992
+ async function migrate(argv) {
993
+ const action = argv[0];
994
+ const flags = parseFlags(argv.slice(1));
995
+ const root = resolve(typeof flags.dir === "string" ? flags.dir : ".");
996
+ if (action === "status") {
997
+ const migrations = readMigrations(root);
998
+ if (migrations.length === 0) {
999
+ console.log("No migrations yet. Run `tapedb migrate dev --name init`.");
1000
+ return 0;
1001
+ }
1002
+ for (const migration of migrations) {
1003
+ console.log(` ${migration.id}${migration.changes.length > 0 ? ` (${migration.changes.map((change) => change.kind).join(", ")})` : ""}`);
1004
+ }
1005
+ const result = migrateCheck(root, await loadSchema(root, flags));
1006
+ console.log(result.ok ? "\nUp to date." : `
1007
+ ${result.problems.join("\n")}`);
1008
+ return 0;
1009
+ }
1010
+ if (action === "check") {
1011
+ const result = migrateCheck(root, await loadSchema(root, flags));
1012
+ if (result.ok) {
1013
+ console.log("Migrations match the schema.");
1014
+ return 0;
1015
+ }
1016
+ console.error(result.problems.join("\n"));
1017
+ return 1;
1018
+ }
1019
+ if (action === "dev") {
1020
+ const name = typeof flags.name === "string" ? flags.name : readSnapshot(root) === null ? "entities" : "";
1021
+ if (!name) {
1022
+ console.error("Name the migration: tapedb migrate dev --name <what changed>");
1023
+ return 1;
1024
+ }
1025
+ const result = migrateDev(root, await loadSchema(root, flags), name, {
1026
+ renames: listFlag(argv, "rename"),
1027
+ acceptDataLoss: flags["accept-data-loss"] === true
1028
+ });
1029
+ if (result.status === "refused") {
1030
+ console.error(`No migration written:
1031
+
1032
+ ${result.reasons.join("\n ")}`);
1033
+ return 1;
1034
+ }
1035
+ if (result.status === "unchanged") {
1036
+ console.log("The schema matches the last migration. Nothing to write.");
1037
+ return 0;
1038
+ }
1039
+ console.log(`Created tapedb/migrations/${result.id}.sql (${result.statements} statements).`);
1040
+ if (result.changes.length > 0) {
1041
+ console.log(`Declared: ${result.changes.map((change) => change.kind).join(", ")}.`);
1042
+ }
1043
+ console.log("Review it, commit it, and deploy: each workspace applies it on its next wake.");
1044
+ return 0;
1045
+ }
1046
+ if (action === "rollback") {
1047
+ const result = migrateRollback(root, {
1048
+ ...typeof flags.to === "string" ? { to: flags.to } : {},
1049
+ acceptDataLoss: flags["accept-data-loss"] === true
1050
+ });
1051
+ if (result.status === "refused") {
1052
+ console.error(`No migration written:
1053
+
1054
+ ${result.reasons.join("\n ")}`);
1055
+ return 1;
1056
+ }
1057
+ console.log(`Created tapedb/migrations/${result.id}.sql (${result.statements} statements): the schema after ${result.to}.`);
1058
+ if (result.schemaEdits.length > 0) {
1059
+ console.log(`
1060
+ Change the schema to match, then \`tapedb migrate check\` passes:
1061
+ ${result.schemaEdits.join("\n ")}`);
1062
+ }
1063
+ console.log("\nReview it, commit it, and deploy: each workspace applies it on its next wake.");
1064
+ return 0;
1065
+ }
1066
+ console.error("Usage: tapedb migrate dev --name <name> | rollback [--to <id>] | status | check");
1067
+ return 1;
1068
+ }
1069
+ function parseJsonc(text) {
1070
+ let out = "";
1071
+ let inString = false;
1072
+ for (let index = 0; index < text.length; index += 1) {
1073
+ const char = text[index];
1074
+ if (inString) {
1075
+ out += char;
1076
+ if (char === "\\") {
1077
+ out += text[index + 1] ?? "";
1078
+ index += 1;
1079
+ } else if (char === '"') inString = false;
1080
+ continue;
1081
+ }
1082
+ if (char === '"') {
1083
+ inString = true;
1084
+ out += char;
1085
+ } else if (char === "/" && text[index + 1] === "/") {
1086
+ while (index < text.length && text[index] !== "\n") index += 1;
1087
+ out += "\n";
1088
+ } else if (char === "/" && text[index + 1] === "*") {
1089
+ index = text.indexOf("*/", index + 2) + 1;
1090
+ if (index === 0) break;
1091
+ } else out += char;
1092
+ }
1093
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
1094
+ }
1095
+ async function deploy(argv) {
1096
+ const flags = parseFlags(argv);
1097
+ const root = resolve(typeof flags.dir === "string" ? flags.dir : ".");
1098
+ const env = typeof flags.env === "string" ? flags.env : void 0;
1099
+ const configPath = join2(root, "wrangler.jsonc");
1100
+ if (!existsSync2(configPath)) {
1101
+ console.error(`No wrangler.jsonc in ${root}.`);
1102
+ return 1;
1103
+ }
1104
+ const config = parseJsonc(readFileSync3(configPath, "utf8"));
1105
+ const vars = env === void 0 ? config.vars : config.env?.[env]?.vars;
1106
+ if (vars?.ENVIRONMENT !== "production") {
1107
+ console.error(
1108
+ `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)"}.`
1109
+ );
1110
+ return 1;
1111
+ }
1112
+ if (vars.TAPEDB_DEV_CLAIMS !== void 0) {
1113
+ console.error("Refusing to deploy: TAPEDB_DEV_CLAIMS is set. It must never reach production.");
1114
+ return 1;
1115
+ }
1116
+ const residency = checkJurisdiction(vars, (env === void 0 ? void 0 : config.env?.[env]?.r2_buckets) ?? config.r2_buckets ?? []);
1117
+ if (residency !== null) {
1118
+ console.error(`Refusing to deploy: ${residency}`);
1119
+ return 1;
1120
+ }
1121
+ const check = migrateCheck(root, await loadSchema(root, flags));
1122
+ if (!check.ok) {
1123
+ console.error(`Refusing to deploy:
1124
+ ${check.problems.join("\n")}`);
1125
+ return 1;
1126
+ }
1127
+ const run2 = spawnSync("npx", ["--no-install", "wrangler", "deploy", ...env ? ["--env", env] : []], {
1128
+ cwd: root,
1129
+ stdio: "inherit"
1130
+ });
1131
+ return run2.status ?? 1;
1132
+ }
1133
+ var JURISDICTIONS = ["eu", "fedramp"];
1134
+ function checkJurisdiction(vars, buckets) {
1135
+ const wanted = vars.TAPEDB_JURISDICTION;
1136
+ if (wanted !== void 0 && !JURISDICTIONS.includes(wanted)) {
1137
+ return `TAPEDB_JURISDICTION is ${JSON.stringify(wanted)}; Cloudflare's jurisdictions are ${JURISDICTIONS.join(" and ")}.`;
1138
+ }
1139
+ const from = vars.TAPEDB_MOVE_FROM === "none" || vars.TAPEDB_MOVE_FROM === "" ? void 0 : vars.TAPEDB_MOVE_FROM;
1140
+ if (vars.TAPEDB_MOVE_FROM !== void 0 && from !== void 0 && !JURISDICTIONS.includes(from)) return "TAPEDB_MOVE_FROM must be eu, fedramp or none.";
1141
+ if (vars.TAPEDB_MOVE_FROM !== void 0 && !buckets.some((bucket) => bucket.binding === "DATA_FROM")) return "A move requires the original DATA_FROM bucket.";
1142
+ const outside = buckets.filter((bucket) => bucket.jurisdiction !== (bucket.binding?.endsWith("_FROM") ? from : wanted));
1143
+ if (outside.length === 0) return null;
1144
+ const names = outside.map((bucket) => `${bucket.binding ?? "?"} (${bucket.bucket_name ?? "?"}: ${bucket.jurisdiction ?? "no jurisdiction"})`).join(", ");
1145
+ return wanted === void 0 ? `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.` : `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.`;
1146
+ }
1147
+ var SCHEMA_FILE = `import { model, schema, t } from "@tapedb/tapedb/schema";
1148
+
1149
+ /**
1150
+ * The whole database: tables, relations, indexes and access rules. Change it,
1151
+ * then run \`npx @tapedb/tapedb migrate dev --name <what changed>\`.
1152
+ */
1153
+ export default schema({
1154
+ board: model({
1155
+ name: t.string(),
1156
+ columns: t.hasMany("column"),
1157
+ }),
1158
+ column: model({
1159
+ name: t.string(),
1160
+ position: t.number().default(0).index(),
1161
+ board: t.belongsTo("board", { onDelete: "cascade" }),
1162
+ tasks: t.hasMany("task"),
1163
+ }),
1164
+ task: model({
1165
+ title: t.string(),
1166
+ done: t.boolean().default(false),
1167
+ column: t.belongsTo("column").optional(),
1168
+ }),
1169
+ });
1170
+ `;
1171
+ var WORKER_FILE = `import { defineTapeDB } from "@tapedb/tapedb/worker";
1172
+
1173
+ import schema from "./tapedb.schema";
1174
+ import { migrations } from "./tapedb/migrations.gen";
1175
+
1176
+ const tapedb = defineTapeDB({
1177
+ schema,
1178
+ migrations,
1179
+ // Development only: serves POST /_tapedb/claim so the client works with no
1180
+ // session. defineTapeDB refuses that route when ENVIRONMENT is "production".
1181
+ devClaims: true,
1182
+ });
1183
+
1184
+ // Cloudflare requires the Durable Object class to be exported by the Worker
1185
+ // that declares the binding.
1186
+ export const WorkspaceRoom = tapedb.WorkspaceRoom;
1187
+
1188
+ export default tapedb.worker;
1189
+ `;
1190
+ function wrangler(name, jurisdiction) {
1191
+ const vars = jurisdiction ? `{ "ENVIRONMENT": "development", "TAPEDB_JURISDICTION": "${jurisdiction}" }` : `{ "ENVIRONMENT": "development" }`;
1192
+ const where = jurisdiction ? `, "jurisdiction": "${jurisdiction}"` : "";
1193
+ return `{
1194
+ "$schema": "node_modules/wrangler/config-schema.json",
1195
+ "name": "${name}",
1196
+ "main": "worker.ts",
1197
+ "compatibility_date": "${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}",
1198
+ "compatibility_flags": ["nodejs_compat"],
1199
+ "workers_dev": true,
1200
+ "observability": { "enabled": true, "traces": { "enabled": true } },
1201
+ "vars": ${vars},
1202
+ "durable_objects": {
1203
+ "bindings": [{ "name": "WORKSPACE", "class_name": "WorkspaceRoom" }]
1204
+ },
1205
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["WorkspaceRoom"] }],
1206
+ "r2_buckets": [
1207
+ { "binding": "DATA", "bucket_name": "${name}-data"${where} },
1208
+ { "binding": "FILES", "bucket_name": "${name}-files"${where} }
1209
+ ]
1210
+ }
1211
+ `;
1212
+ }
1213
+ function write(path, contents, force) {
1214
+ if (existsSync2(path) && !force) return "kept";
1215
+ mkdirSync2(dirname(path), { recursive: true });
1216
+ writeFileSync2(path, contents);
1217
+ return "written";
1218
+ }
1219
+ function parseFlags(argv) {
1220
+ const flags = {};
1221
+ for (let index = 0; index < argv.length; index += 1) {
1222
+ const token = argv[index];
1223
+ if (!token.startsWith("--")) continue;
1224
+ const key = token.slice(2);
1225
+ const next = argv[index + 1];
1226
+ if (next !== void 0 && !next.startsWith("--")) {
1227
+ flags[key] = next;
1228
+ index += 1;
1229
+ } else {
1230
+ flags[key] = true;
1231
+ }
1232
+ }
1233
+ return flags;
1234
+ }
1235
+ async function init(argv) {
1236
+ const flags = parseFlags(argv);
1237
+ const target = resolve(typeof flags.dir === "string" ? flags.dir : ".");
1238
+ const name = typeof flags.name === "string" ? flags.name : "tapedb-app";
1239
+ const force = flags.force === true;
1240
+ const jurisdiction = typeof flags.jurisdiction === "string" ? flags.jurisdiction : void 0;
1241
+ if (jurisdiction !== void 0 && !JURISDICTIONS.includes(jurisdiction)) {
1242
+ console.error(`--jurisdiction must be one of ${JURISDICTIONS.join(", ")}.`);
1243
+ return 1;
1244
+ }
1245
+ mkdirSync2(target, { recursive: true });
1246
+ const devVarsPath = join2(target, ".dev.vars");
1247
+ const secret = existsSync2(devVarsPath) ? readFileSync3(devVarsPath, "utf8").match(/^TAPEDB_CLAIM_SECRET=(.*)$/m)?.[1] ?? randomBytes(32).toString("base64url") : randomBytes(32).toString("base64url");
1248
+ const results = [
1249
+ ["tapedb.schema.ts", write(join2(target, "tapedb.schema.ts"), SCHEMA_FILE, force)],
1250
+ ["worker.ts", write(join2(target, "worker.ts"), WORKER_FILE, force)],
1251
+ ["wrangler.jsonc", write(join2(target, "wrangler.jsonc"), wrangler(name, jurisdiction), force)],
1252
+ [
1253
+ ".dev.vars",
1254
+ write(devVarsPath, `TAPEDB_CLAIM_SECRET=${secret}
1255
+ TAPEDB_KEY_SECRET=${randomBytes(32).toString("base64url")}
1256
+ `, force)
1257
+ ]
1258
+ ];
1259
+ console.log(`tapedb init in ${target}
1260
+ `);
1261
+ for (const [file, status] of results) {
1262
+ console.log(` ${status === "written" ? "created" : "kept "} ${file}`);
1263
+ }
1264
+ try {
1265
+ if (readSnapshot(target) === null) {
1266
+ const schema = await loadSchema(target, {});
1267
+ const result = migrateDev(target, schema, "entities");
1268
+ if (result.status === "created") console.log(` created tapedb/migrations/${result.id}.sql`);
1269
+ }
1270
+ } catch (error) {
1271
+ console.error(
1272
+ `
1273
+ Could not generate the first migration (${error instanceof Error ? error.message : String(error)}).
1274
+ Fix the schema and run \`npx @tapedb/tapedb init\` again; existing files are kept.`
1275
+ );
1276
+ return 1;
1277
+ }
1278
+ console.log(`
1279
+ Next:
1280
+
1281
+ npx wrangler r2 bucket create ${name}-data${jurisdiction ? ` --jurisdiction ${jurisdiction}` : ""}
1282
+ npx wrangler r2 bucket create ${name}-files${jurisdiction ? ` --jurisdiction ${jurisdiction}` : ""}
1283
+ npx wrangler secret put TAPEDB_CLAIM_SECRET
1284
+ npx wrangler secret put TAPEDB_KEY_SECRET
1285
+ npx @tapedb/tapedb dev # local database
1286
+ npx @tapedb/tapedb deploy # once ENVIRONMENT is "production"
1287
+
1288
+ That is the whole footprint: one Durable Object class, two R2 buckets.
1289
+ `);
1290
+ return 0;
1291
+ }
1292
+ function usage() {
1293
+ console.log(`tapedb \u2014 a typed database for Cloudflare: models in, Durable Objects and R2 out
1294
+
1295
+ Usage:
1296
+ tapedb init [--dir <path>] [--name <worker-name>] [--jurisdiction eu] [--force]
1297
+ tapedb migrate dev|rollback|status|check [--dir <path>] [--schema <file>]
1298
+ tapedb deploy [--dir <path>] [--env <name>]
1299
+ tapedb dev [--dir <path>] [--port <port>]
1300
+ tapedb studio [--url <worker-url>] [--workspace <uuid>] [--port <port>]
1301
+ tapedb export --workspace <uuid> [--url <worker-url>] [--out <file>]
1302
+ tapedb erase --workspace <uuid> --confirm <uuid> [--url <worker-url>]
1303
+ tapedb move --to eu|fedramp|none --workspaces <file> [--url <worker-url>]
1304
+
1305
+ Commands:
1306
+ init Write tapedb.schema.ts, worker.ts, wrangler.jsonc and .dev.vars,
1307
+ and the first migration. Existing files are kept unless --force.
1308
+ --jurisdiction eu keeps Durable Objects and R2 buckets in the EU.
1309
+ migrate dev --name <name> [--rename old=new] [--accept-data-loss]
1310
+ Diff the schema against the last migration and write the next one.
1311
+ migrate rollback [--to <id>] [--accept-data-loss]
1312
+ Write the migration that takes the database back to the schema
1313
+ after <id> (default: the one before the last).
1314
+ migrate status | check
1315
+ List migrations; check fails if the schema has unmigrated changes.
1316
+ deploy [--env <name>] Check ENVIRONMENT, dev claims, data residency and migrations, then wrangler deploy.
1317
+ dev Run the local database with wrangler dev on port 8787.
1318
+ studio Open a local table browser against a running Worker.
1319
+ export Stream every row the claim may read as NDJSON (TAPEDB_TOKEN, or a dev claim).
1320
+ erase Delete a workspace for good: its data, history and files (owner claim).
1321
+ --confirm must repeat the workspace id. The id answers 410 afterwards.
1322
+ `);
1323
+ return 0;
1324
+ }
1325
+ function dev(argv) {
1326
+ const flags = parseFlags(argv);
1327
+ const target = resolve(typeof flags.dir === "string" ? flags.dir : ".");
1328
+ const port = typeof flags.port === "string" ? flags.port : "8787";
1329
+ if (!existsSync2(join2(target, ".dev.vars"))) {
1330
+ console.error(`No .dev.vars in ${target}. Run \`tapedb init\` first.`);
1331
+ return 1;
1332
+ }
1333
+ const probe = spawnSync("npx", ["--no-install", "wrangler", "--version"], {
1334
+ cwd: target,
1335
+ encoding: "utf8"
1336
+ });
1337
+ if (probe.status !== 0) {
1338
+ console.error(
1339
+ "wrangler is required to run the local database.\n\n npm i -D wrangler\n"
1340
+ );
1341
+ return 1;
1342
+ }
1343
+ const run2 = spawnSync(
1344
+ "npx",
1345
+ [
1346
+ "--no-install",
1347
+ "wrangler",
1348
+ "dev",
1349
+ "--port",
1350
+ port,
1351
+ // Passed here, never written to wrangler.jsonc: a plain `wrangler deploy`
1352
+ // therefore has no dev claim route even if ENVIRONMENT is the default.
1353
+ "--var",
1354
+ "TAPEDB_DEV_CLAIMS:true",
1355
+ // workerd has no jurisdictions: locally every object is unrestricted.
1356
+ // Deployed, TAPEDB_JURISDICTION from wrangler.jsonc applies.
1357
+ "--var",
1358
+ "TAPEDB_JURISDICTION:"
1359
+ ],
1360
+ { cwd: target, stdio: "inherit" }
1361
+ );
1362
+ return run2.status ?? 1;
1363
+ }
1364
+ async function exportWorkspace(argv) {
1365
+ const flags = parseFlags(argv);
1366
+ const url = (typeof flags.url === "string" ? flags.url : "http://localhost:8787").replace(/\/+$/, "");
1367
+ const workspace = typeof flags.workspace === "string" ? flags.workspace : process.env.TAPEDB_WORKSPACE ?? "";
1368
+ if (!workspace) {
1369
+ console.error("Name the workspace: tapedb export --workspace <uuid> [--url <worker>] [--out <file>]");
1370
+ return 1;
1371
+ }
1372
+ let response;
1373
+ try {
1374
+ const token = process.env.TAPEDB_TOKEN || await mintToken(url, workspace);
1375
+ response = await fetch(`${url}/engine/workspaces/${workspace}/export`, {
1376
+ headers: { authorization: `Bearer ${token}` }
1377
+ });
1378
+ } catch (error) {
1379
+ console.error(error instanceof Error ? error.message : String(error));
1380
+ return 1;
1381
+ }
1382
+ if (!response.ok || !response.body) {
1383
+ console.error(`Export failed with HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
1384
+ return 1;
1385
+ }
1386
+ const out = typeof flags.out === "string" ? resolve(flags.out) : null;
1387
+ if (out) writeFileSync2(out, "");
1388
+ const write2 = (text) => out ? appendFileSync(out, text) : process.stdout.write(text);
1389
+ const decoder = new TextDecoder();
1390
+ let tail = "";
1391
+ const reader = response.body.getReader();
1392
+ for (; ; ) {
1393
+ const { value, done } = await reader.read();
1394
+ if (done) break;
1395
+ const text = decoder.decode(value, { stream: true });
1396
+ write2(text);
1397
+ tail = (tail + text).slice(-65536);
1398
+ }
1399
+ const last = tail.trim().split("\n").at(-1) ?? "";
1400
+ let end = {};
1401
+ try {
1402
+ end = JSON.parse(last);
1403
+ } catch {
1404
+ }
1405
+ if (end.type !== "end") {
1406
+ console.error(`Export incomplete: ${end.type === "error" ? end.message : "the stream ended without an end line"}.`);
1407
+ return 1;
1408
+ }
1409
+ console.error(
1410
+ `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}` : ""}.`
1411
+ );
1412
+ return 0;
1413
+ }
1414
+ async function studio(argv) {
1415
+ const flags = parseFlags(argv);
1416
+ const url = typeof flags.url === "string" ? flags.url : "http://localhost:8787";
1417
+ const workspace = typeof flags.workspace === "string" ? flags.workspace : process.env.TAPEDB_WORKSPACE ?? "";
1418
+ const port = Number(typeof flags.port === "string" ? flags.port : "4400");
1419
+ let server;
1420
+ try {
1421
+ server = await startStudio({ url, workspace, port });
1422
+ } catch (error) {
1423
+ console.error(error instanceof Error ? error.message : String(error));
1424
+ return 1;
1425
+ }
1426
+ console.log(`tapedb studio on ${server.url} -> ${url}`);
1427
+ console.log("Press Ctrl+C to stop.");
1428
+ await new Promise((resolve2) => {
1429
+ process.on("SIGINT", () => {
1430
+ server.close();
1431
+ resolve2();
1432
+ });
1433
+ });
1434
+ return 0;
1435
+ }
1436
+ async function eraseWorkspace(argv) {
1437
+ const flags = parseFlags(argv);
1438
+ const url = (typeof flags.url === "string" ? flags.url : "http://localhost:8787").replace(/\/+$/, "");
1439
+ const workspace = typeof flags.workspace === "string" ? flags.workspace : "";
1440
+ if (!workspace || flags.confirm !== workspace) {
1441
+ console.error("Erasing cannot be undone. Name the workspace twice: tapedb erase --workspace <uuid> --confirm <uuid> [--url <worker>]");
1442
+ return 1;
1443
+ }
1444
+ let response;
1445
+ try {
1446
+ const token = process.env.TAPEDB_TOKEN || await mintToken(url, workspace);
1447
+ response = await fetch(`${url}/engine/workspaces/${workspace}`, {
1448
+ method: "DELETE",
1449
+ headers: { authorization: `Bearer ${token}` }
1450
+ });
1451
+ } catch (error) {
1452
+ console.error(error instanceof Error ? error.message : String(error));
1453
+ return 1;
1454
+ }
1455
+ const body = await response.json().catch(() => null);
1456
+ if (response.status === 410) {
1457
+ console.log(`Workspace ${workspace} was already erased.`);
1458
+ return 0;
1459
+ }
1460
+ if (!response.ok || !body?.erased) {
1461
+ console.error(`Erase failed with HTTP ${response.status}: ${body?.error?.message ?? "no details"}. It is safe to run again.`);
1462
+ return 1;
1463
+ }
1464
+ console.log(`Erased workspace ${workspace}: ${body.erased.historyObjects} history objects and ${body.erased.files} files deleted, Durable Object storage cleared.`);
1465
+ return 0;
1466
+ }
1467
+ async function run(argv) {
1468
+ const command = argv[0];
1469
+ if (command === "init") return init(argv.slice(1));
1470
+ if (command === "migrate") return migrate(argv.slice(1));
1471
+ if (command === "deploy") return deploy(argv.slice(1));
1472
+ if (command === "dev") return dev(argv.slice(1));
1473
+ if (command === "studio") return studio(argv.slice(1));
1474
+ if (command === "export") return exportWorkspace(argv.slice(1));
1475
+ if (command === "erase") return eraseWorkspace(argv.slice(1));
1476
+ if (command === "move") return moveWorkspaces(argv.slice(1));
1477
+ if (command === void 0 || command === "--help" || command === "-h") {
1478
+ return usage();
1479
+ }
1480
+ console.error(`Unknown command "${command}".`);
1481
+ return usage();
1482
+ }
1483
+ function isEntryPoint(entry, moduleUrl) {
1484
+ if (entry === void 0) return false;
1485
+ try {
1486
+ return realpathSync(entry) === realpathSync(fileURLToPath(moduleUrl));
1487
+ } catch {
1488
+ return false;
1489
+ }
1490
+ }
1491
+ if (isEntryPoint(process.argv[1], import.meta.url)) {
1492
+ void run(process.argv.slice(2)).then((code) => process.exit(code));
1493
+ }
1494
+ export {
1495
+ checkJurisdiction,
1496
+ eraseWorkspace,
1497
+ exportWorkspace,
1498
+ isEntryPoint,
1499
+ run
1500
+ };
1501
+ //# sourceMappingURL=cli.js.map