durable-db 0.1.10 → 0.1.12

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/bin.js CHANGED
@@ -5,7 +5,7 @@ import "../snapshot-DMW6j2Ix.js";
5
5
  import "../generator-KHBZaOI1.js";
6
6
  import "../parser-CL3Nlmsy.js";
7
7
  import "../push-DiHH52-G.js";
8
- import { n as registerDbCommands } from "../cli-BCgiaUy_.js";
8
+ import { n as registerDbCommands } from "../cli-m2H7mQpa.js";
9
9
  import { Command } from "commander";
10
10
 
11
11
  //#region src/cli/bin.ts
package/dist/cli/index.js CHANGED
@@ -4,6 +4,6 @@ import "../snapshot-DMW6j2Ix.js";
4
4
  import "../generator-KHBZaOI1.js";
5
5
  import "../parser-CL3Nlmsy.js";
6
6
  import { a as loadSchema, i as discoverDatabases, n as pushOne, o as reportCliError, r as diffSchema, t as push } from "../push-DiHH52-G.js";
7
- import { a as resetAndPush, c as generate, i as reset, l as generateOne, n as registerDbCommands, o as formatStatus, r as validate, s as status, t as createDbCommand } from "../cli-BCgiaUy_.js";
7
+ import { a as resetAndPush, c as generate, i as reset, l as generateOne, n as registerDbCommands, o as formatStatus, r as validate, s as status, t as createDbCommand } from "../cli-m2H7mQpa.js";
8
8
 
9
9
  export { createDbCommand, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, saveDevState, status, validate };
@@ -334,17 +334,106 @@ async function resetAndPush(ctx = {}, options = {}) {
334
334
  init_state();
335
335
  init_debug();
336
336
  /**
337
- * Extract and normalize schema from a SQLite database.
338
- * Returns a sorted list of CREATE statements from sqlite_master.
337
+ * Extract and normalize non-table schema objects (indexes, views, triggers)
338
+ * from a SQLite database. Returns a sorted list of CREATE statements from
339
+ * sqlite_master.
340
+ *
341
+ * Tables are deliberately excluded: SQLite stores a table's CREATE statement
342
+ * as the original text and rewrites it on `ALTER TABLE ... ADD COLUMN` (the
343
+ * new column is spliced in before the closing paren), so the stored text of a
344
+ * migrated table never string-matches a from-scratch CREATE even when the
345
+ * schemas are identical. Tables are compared structurally instead — see
346
+ * {@link extractTableStructures}.
339
347
  */
340
- function extractSchema(db) {
348
+ function extractNonTableSchema(db) {
341
349
  return db.prepare(`SELECT type, name, tbl_name, sql FROM sqlite_master
342
- WHERE type IN ('table', 'index', 'view', 'trigger')
350
+ WHERE type IN ('index', 'view', 'trigger')
343
351
  AND name NOT LIKE 'sqlite_%'
344
352
  AND name NOT LIKE '\\_\\_%' ESCAPE '\\'
345
353
  ORDER BY type, name`).all().filter((r) => r.sql != null).map((r) => normalizeSql(r.sql));
346
354
  }
347
355
  /**
356
+ * Extract the structural shape of every user table via PRAGMA introspection.
357
+ *
358
+ * This is the drift comparison for tables: it reflects what SQLite actually
359
+ * enforces rather than the stored CREATE text, so it is immune to how the
360
+ * table came to be (fresh CREATE vs. CREATE + ALTERs) and to column order,
361
+ * which is irrelevant for the named-column access the framework generates.
362
+ *
363
+ * Not covered (not exposed by PRAGMAs): CHECK constraints, column collations,
364
+ * and WITHOUT ROWID / STRICT table options.
365
+ */
366
+ function extractTableStructures(db) {
367
+ const tables = db.prepare(`SELECT name FROM sqlite_master
368
+ WHERE type = 'table'
369
+ AND name NOT LIKE 'sqlite_%'
370
+ AND name NOT LIKE '\\_\\_%' ESCAPE '\\'
371
+ ORDER BY name`).all();
372
+ const structures = /* @__PURE__ */ new Map();
373
+ for (const { name } of tables) {
374
+ const columns = /* @__PURE__ */ new Map();
375
+ const columnRows = db.prepare(`SELECT cid, name, type, "notnull", dflt_value, pk FROM pragma_table_info(?)`).all(name);
376
+ for (const col of columnRows) {
377
+ const parts = [col.type.replace(/\s+/g, " ").trim().toLowerCase() || "(dynamic)"];
378
+ if (col.notnull) parts.push("NOT NULL");
379
+ if (col.dflt_value != null) parts.push(`DEFAULT ${col.dflt_value}`);
380
+ if (col.pk) parts.push(`PK ${col.pk}`);
381
+ columns.set(col.name, parts.join(" "));
382
+ }
383
+ const uniques = [];
384
+ const indexRows = db.prepare(`SELECT seq, name, "unique", origin, partial FROM pragma_index_list(?)`).all(name);
385
+ for (const idx of indexRows) {
386
+ if (idx.origin !== "u") continue;
387
+ const cols = db.prepare(`SELECT name FROM pragma_index_info(?) ORDER BY seqno`).all(idx.name).map((c) => c.name ?? "(expr)");
388
+ uniques.push(`(${cols.join(", ")})`);
389
+ }
390
+ uniques.sort();
391
+ const fkRows = db.prepare(`SELECT id, seq, "table", "from", "to", on_update, on_delete FROM pragma_foreign_key_list(?)
392
+ ORDER BY id, seq`).all(name);
393
+ const fkGroups = /* @__PURE__ */ new Map();
394
+ for (const row of fkRows) {
395
+ const group = fkGroups.get(row.id) ?? [];
396
+ group.push(row);
397
+ fkGroups.set(row.id, group);
398
+ }
399
+ const foreignKeys = [...fkGroups.values()].map((group) => {
400
+ const from = group.map((r) => r.from).join(", ");
401
+ const to = group.map((r) => r.to ?? "(implicit pk)").join(", ");
402
+ const { table, on_update, on_delete } = group[0];
403
+ return `(${from}) → ${table}(${to}) ON UPDATE ${on_update} ON DELETE ${on_delete}`;
404
+ }).sort();
405
+ structures.set(name, {
406
+ columns,
407
+ uniques,
408
+ foreignKeys
409
+ });
410
+ }
411
+ return structures;
412
+ }
413
+ /**
414
+ * Diff table structures. Returns a list of human-readable differences.
415
+ */
416
+ function diffTableStructures(fromMigrations, fromSchema) {
417
+ const diffs = [];
418
+ for (const [name, migrated] of fromMigrations) {
419
+ const fresh = fromSchema.get(name);
420
+ if (!fresh) {
421
+ diffs.push(`Table only in migrations: ${name}`);
422
+ continue;
423
+ }
424
+ for (const [col, descriptor] of migrated.columns) {
425
+ const other = fresh.columns.get(col);
426
+ if (other === void 0) diffs.push(`Column ${name}.${col} only in migrations: ${descriptor}`);
427
+ else if (other !== descriptor) diffs.push(`Column ${name}.${col} differs — migrations: ${descriptor}; schema: ${other}`);
428
+ }
429
+ for (const [col, descriptor] of fresh.columns) if (!migrated.columns.has(col)) diffs.push(`Column ${name}.${col} only in schema: ${descriptor}`);
430
+ if (migrated.uniques.join(" | ") !== fresh.uniques.join(" | ")) diffs.push(`Unique constraints on ${name} differ — migrations: [${migrated.uniques.join(" | ") || "none"}]; schema: [${fresh.uniques.join(" | ") || "none"}]`);
431
+ if (migrated.foreignKeys.join(" | ") !== fresh.foreignKeys.join(" | ")) diffs.push(`Foreign keys on ${name} differ — migrations: [${migrated.foreignKeys.join(" | ") || "none"}]; schema: [${fresh.foreignKeys.join(" | ") || "none"}]`);
432
+ }
433
+ for (const name of fromSchema.keys()) if (!fromMigrations.has(name)) diffs.push(`Table only in schema: ${name}`);
434
+ return diffs;
435
+ }
436
+ /**
348
437
  * Normalize SQL for comparison — collapse whitespace, remove trailing semicolons.
349
438
  */
350
439
  function normalizeSql(sql) {
@@ -452,7 +541,7 @@ async function validateDatabase(db, opts) {
452
541
  const schemaDb = new Database(":memory:");
453
542
  try {
454
543
  for (const stmt of createStatements) schemaDb.exec(stmt.endsWith(";") ? stmt : `${stmt};`);
455
- const diffs = diffSchemas(extractSchema(migrationsDb), extractSchema(schemaDb));
544
+ const diffs = [...diffTableStructures(extractTableStructures(migrationsDb), extractTableStructures(schemaDb)), ...diffSchemas(extractNonTableSchema(migrationsDb), extractNonTableSchema(schemaDb))];
456
545
  if (diffs.length > 0) {
457
546
  result.schemaMatches = false;
458
547
  result.schemaDiffs = diffs;
@@ -1,2 +1,2 @@
1
- import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../index-D9LHeBx2.js";
1
+ import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../index-BhRiKZ4j.js";
2
2
  export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
@@ -1,5 +1,5 @@
1
1
  import "../debug-DmBrUmwe.js";
2
2
  import "../state-DtZ70cBR.js";
3
- import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../context-DbGqDnBa.js";
3
+ import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../context-kIVZbhye.js";
4
4
 
5
5
  export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
@@ -38,15 +38,33 @@ function setTenantIdResolver(resolver) {
38
38
  * }
39
39
  * ```
40
40
  */
41
+ /**
42
+ * Inside a Durable Object the instance key IS the tenant (per-tenant DBs key
43
+ * their instances by tenant id, plus an optional `__dev_<epoch>` suffix in
44
+ * dev). The registry publishes its DoContext store getter on globalThis — see
45
+ * the note there for why this is not a module import — so getTenantId() works
46
+ * in action handlers without the worker-side resolver, which the DO execution
47
+ * context never registers.
48
+ */
49
+ function tenantIdFromDoContext() {
50
+ const getStore = globalThis[Symbol.for("durable-db.doContext")];
51
+ const key = getStore?.()?.instanceKey;
52
+ if (!key || key === "global") return null;
53
+ const suffixAt = key.lastIndexOf("__dev_");
54
+ return suffixAt === -1 ? key : key.slice(0, suffixAt);
55
+ }
41
56
  function getTenantId() {
42
57
  if (tenantIdResolver) return tenantIdResolver();
58
+ const doTenant = tenantIdFromDoContext();
59
+ if (doTenant) return doTenant;
43
60
  throw new Error("getTenantId() called without a resolver. Call setTenantIdResolver() first.");
44
61
  }
45
62
  /**
46
- * Check if a tenant ID resolver is configured.
63
+ * Check if a tenant ID resolver is configured (or a Durable Object context
64
+ * can supply the tenant).
47
65
  */
48
66
  function hasTenantId() {
49
- return tenantIdResolver !== null;
67
+ return tenantIdResolver !== null || tenantIdFromDoContext() !== null;
50
68
  }
51
69
  /**
52
70
  * One-time warning guard: we only log an unexpected dev-epoch load failure
@@ -14,24 +14,10 @@
14
14
  * ```
15
15
  */
16
16
  declare function setTenantIdResolver(resolver: (() => string) | null): void;
17
- /**
18
- * Get the current tenant ID from the configured resolver.
19
- *
20
- * @throws Error if no resolver is configured
21
- *
22
- * @example
23
- * ```ts
24
- * import { getTenantId } from 'durable-db/context';
25
- *
26
- * async function myHandler() {
27
- * const tenantId = getTenantId();
28
- * // ...
29
- * }
30
- * ```
31
- */
32
17
  declare function getTenantId(): string;
33
18
  /**
34
- * Check if a tenant ID resolver is configured.
19
+ * Check if a tenant ID resolver is configured (or a Durable Object context
20
+ * can supply the tenant).
35
21
  */
36
22
  declare function hasTenantId(): boolean;
37
23
  /**
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as type } from "./arktypeConfig--4OgOv4U.js";
2
2
  import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-Bjws1Jkd.js";
3
- import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./index-D9LHeBx2.js";
3
+ import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./index-BhRiKZ4j.js";
4
4
  import { a as integer, c as real, d as uniqueIndex, i as index, l as table, n as blob, o as numeric, r as foreignKey, s as primaryKey, t as AnySQLiteColumn, u as text } from "./schema-BCjqTRvV.js";
5
5
  import { Kysely } from "kysely";
6
6
  export { type Action, type ActionConfig, type ActionContext, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
package/dist/index.js CHANGED
@@ -3,6 +3,6 @@ import { t as type } from "./arktypeConfig-CTCJm4vA.js";
3
3
  import { n as defineDatabase } from "./defineDatabase-BD3k1L7d.js";
4
4
  import { a as numeric, c as table, i as integer, l as text, n as foreignKey, o as primaryKey, r as index, s as real, t as blob, u as uniqueIndex } from "./schema-IFq7ovQq.js";
5
5
  import "./state-DtZ70cBR.js";
6
- import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./context-DbGqDnBa.js";
6
+ import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./context-kIVZbhye.js";
7
7
 
8
8
  export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
package/dist/registry.js CHANGED
@@ -6,6 +6,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
6
6
  const actionsByDb = /* @__PURE__ */ new Map();
7
7
  const als = new AsyncLocalStorage();
8
8
  const wsTransportCache = /* @__PURE__ */ new Map();
9
+ globalThis[Symbol.for("durable-db.doContext")] = () => als.getStore();
9
10
  function getOrCreateWsTransport(bindingName, instanceKey, stub) {
10
11
  const cacheKey = `${bindingName}:${instanceKey}`;
11
12
  let transport = wsTransportCache.get(cacheKey);
@@ -2,7 +2,7 @@ import "../debug-DmBrUmwe.js";
2
2
  import { t as type } from "../arktypeConfig-CTCJm4vA.js";
3
3
  import { t as ACTION_TEST_META } from "../defineDatabase-BD3k1L7d.js";
4
4
  import "../state-DtZ70cBR.js";
5
- import { a as setTenantIdResolver } from "../context-DbGqDnBa.js";
5
+ import { a as setTenantIdResolver } from "../context-kIVZbhye.js";
6
6
  import { t as createKyselyFromSql } from "../kysely-BH7QZBZw.js";
7
7
  import { n as generateMigrationStatements, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "../snapshot-DMW6j2Ix.js";
8
8
  import { createRequire } from "node:module";
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"
7
7
  },
8
8
  "type": "module",
9
+ "packageManager": "pnpm@10.2.1",
9
10
  "bin": {
10
11
  "db": "./dist/cli/bin.js"
11
12
  },
@@ -69,6 +70,13 @@
69
70
  "publishConfig": {
70
71
  "access": "public"
71
72
  },
73
+ "scripts": {
74
+ "build": "tsdown",
75
+ "dev": "tsdown --watch",
76
+ "test": "vitest",
77
+ "test:run": "vitest run",
78
+ "changeset": "changeset"
79
+ },
72
80
  "dependencies": {
73
81
  "@babel/generator": "^7.0.0",
74
82
  "@babel/parser": "^7.0.0",
@@ -104,12 +112,5 @@
104
112
  "typescript": "^5.7.0",
105
113
  "vite": "^7.0.0",
106
114
  "vitest": "^2.1.0"
107
- },
108
- "scripts": {
109
- "build": "tsdown",
110
- "dev": "tsdown --watch",
111
- "test": "vitest",
112
- "test:run": "vitest run",
113
- "changeset": "changeset"
114
115
  }
115
- }
116
+ }