@duraxis/migrations 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @duraxis/migrations
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4904b00: - Implemented PrimaryKeyCodec for encoding, decoding, and normalizing primary key values.
8
+ - Introduced generation rules for document values, including support for UUID v7 and incremental strategies.
9
+ - Added tests for generated values and schema evolution to ensure correctness of new features.
10
+ - Created decorators for primary and generated columns in ORM to streamline entity definitions.
11
+ - Enhanced validation for generation rules to prevent invalid configurations.
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [4904b00]
16
+ - @duraxis/core@0.6.0
17
+
18
+ ## 0.3.1
19
+
20
+ ### Patch Changes
21
+
22
+ - 6377fde: Add framework-independent configuration and owned database/ORM factories, bounded decorated-entity discovery, and shared NestJS/CLI schema resolution. Initialize projects with one source-root configuration and direct AST-guided AppModule integration. Support static inspection/mutation, centralized named connections, registry-free generators and source/compiled deployments without runtime CLI dependencies. Use shared typed configuration across runtime and CLI, standard Nest feature modules, and authenticated encrypted cursors. Document storage, migration, discovery and lifecycle contracts.
23
+ - Updated dependencies [6377fde]
24
+ - @duraxis/core@0.5.0
25
+
3
26
  ## 0.3.0
4
27
 
5
28
  ### Minor Changes
package/README.md CHANGED
@@ -148,7 +148,7 @@ automatic plans refuse to invent values. Field removal rejects populated values.
148
148
 
149
149
  The engine accepts SHA-256 artifact digests from its loader. The CLI defines an
150
150
  identity using pinned TypeScript 5.9.3: two transpilation/printing passes targeting
151
- ES2022 ESM, with comments removed and legacy decorators enabled. It verifies the
151
+ ES2022 ESM, with comments removed and TypeScript decorators enabled. It verifies the
152
152
  same digest for TypeScript and JavaScript emitted using those options. Ship ESM
153
153
  migration files, preserve ESM imports, and do not bundle/minify or downlevel them.
154
154
  Formatting, comments, and type-only edits are excluded from executable identity.
@@ -189,9 +189,15 @@ Named connections, async configuration, and auto-loaded entities remain under
189
189
  NestJS's existing ownership model. A runner can reuse an already-owned Core
190
190
  connection programmatically, but application startup does not run migrations.
191
191
  For incompatible changes, stop older replicas, migrate once, then start compatible
192
- replicas. Use staged backward-compatible application/schema releases when downtime
192
+ replicas. Use staged coordinated application/schema releases when downtime
193
193
  is unsuitable.
194
194
 
195
195
  ## Production resource and lifecycle limits
196
196
 
197
197
  See the [production hardening guide](../../docs/PRODUCTION-HARDENING.md) for bounded defaults, cancellation, verified maintenance, tenant trust boundaries, encrypted cursors, upgrade instructions and remaining pilot limitations. Core rejects storage adapters without bounded-read capability; destructive shared-storage garbage collection is unsupported.
198
+
199
+ ## CLI project setup
200
+
201
+ Run `npx --package @duraxis/cli@latest duraxis init` to generate one source-root configuration. NestJS AppModule integration is automatic; standalone applications call the public runtime factories. See the [shared configuration API and examples](../../docs/CLI-SETUP.md) and [setup guide](../../docs/CLI-SETUP.md).
202
+
203
+ Enable shared migrations with `migrations: true`, or customize `directory` and `snapshots`. Core normalizes these settings for CLI/runtime; migrations imply validation and never enable schema creation. CLI resolves entity files without starting Nest. New CLI artifacts use `.mts`/`.mjs`; old artifacts, snapshots, history and locking remain unchanged.
package/dist/context.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type CollectionDefinition, type DocumentRecord, type FieldDefinition, type ForeignKeyDefinition, type SecondaryIndexDefinition, type Transaction } from "@duraxis/core";
1
+ import { type CollectionDefinition, type DocumentRecord, type FieldDefinition, type ForeignKeyDefinition, type SecondaryIndexDefinition, type Transaction, type PrimaryKeyValue } from "@duraxis/core";
2
2
  export declare class SchemaEditor {
3
3
  #private;
4
4
  constructor(tx: Transaction);
@@ -24,8 +24,10 @@ export interface MigrationContext {
24
24
  readonly schema: SchemaEditor;
25
25
  readonly get: Transaction["getDocument"];
26
26
  readonly scan: Transaction["scanCollection"];
27
- readonly put: Transaction["putDocument"];
27
+ readonly insert: Transaction["insertDocument"];
28
+ readonly update: Transaction["updateDocument"];
29
+ readonly upsert: Transaction["upsertDocument"];
28
30
  readonly delete: Transaction["deleteDocument"];
29
- transform(collection: string, transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>): Promise<void>;
31
+ transform(collection: string, transform: (document: DocumentRecord, id: PrimaryKeyValue) => DocumentRecord | Promise<DocumentRecord>): Promise<void>;
30
32
  }
31
33
  export declare function createMigrationContext(tx: Transaction): MigrationContext;
package/dist/index.cjs CHANGED
@@ -113,7 +113,7 @@ var SchemaEditor = class {
113
113
  if (options.strategy == "delete-values") for await (const row of this.#tx.scanCollection(collection)) {
114
114
  const document = { ...row.document };
115
115
  delete document[name];
116
- this.#tx.putDocument(collection, row.id, document);
116
+ await this.#tx[_duraxis_core.SCHEMA_TRANSFORMATION](collection, row.id, document);
117
117
  }
118
118
  }
119
119
  async renameField(collection, from, to) {
@@ -145,7 +145,7 @@ var SchemaEditor = class {
145
145
  document[to] = document[from];
146
146
  delete document[from];
147
147
  }
148
- this.#tx.putDocument(collection, row.id, document);
148
+ await this.#tx[_duraxis_core.SCHEMA_TRANSFORMATION](collection, row.id, document);
149
149
  }
150
150
  }
151
151
  addIndex(collection, index) {
@@ -177,10 +177,12 @@ function createMigrationContext(tx) {
177
177
  schema: new SchemaEditor(tx),
178
178
  get: tx.getDocument.bind(tx),
179
179
  scan: tx.scanCollection.bind(tx),
180
- put: tx.putDocument.bind(tx),
180
+ insert: tx.insertDocument.bind(tx),
181
+ update: tx.updateDocument.bind(tx),
182
+ upsert: tx.upsertDocument.bind(tx),
181
183
  delete: tx.deleteDocument.bind(tx),
182
184
  async transform(collection, transform) {
183
- for await (const row of tx.scanCollection(collection)) tx.putDocument(collection, row.id, await transform(row.document, row.id));
185
+ for await (const row of tx.scanCollection(collection)) await tx[_duraxis_core.SCHEMA_TRANSFORMATION](collection, row.id, await transform(row.document, row.id));
184
186
  }
185
187
  });
186
188
  }
@@ -188,7 +190,8 @@ function createMigrationContext(tx) {
188
190
  function fieldRisk(before, after) {
189
191
  if (!after) return "destructive";
190
192
  if (!before) return after.required ? "requires-data-transformation" : "safe";
191
- if (before.type != after.type || !before.required && after.required) return "requires-data-transformation";
193
+ if (before.type != after.type || before.primary !== after.primary || !before.required && after.required) return "requires-data-transformation";
194
+ if (before.generated !== after.generated || before.unique !== after.unique) return "requires-validation";
192
195
  if (before.nullable && !after.nullable) return "requires-validation";
193
196
  return "safe";
194
197
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["createHash","normalizeCollection","indexFields","randomUUID","TransactionConflictError","CommitOutcomeUnknownError"],"sources":["../src/schema.ts","../src/context.ts","../src/diff.ts","../src/runner.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { normalizeCollection, type CollectionDefinition } from \"@duraxis/core\";\n\nexport function canonicalJSON(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(\",\")}]`;\n\n if (value && typeof value == \"object\")\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJSON(v)}`)\n .join(\",\")}}`;\n\n const json = JSON.stringify(value);\n\n if (json === undefined) throw new Error(\"Non-JSON schema value\");\n\n return json;\n}\n\nexport function checksum(value: string): string {\n return `sha256:${createHash(\"sha256\").update(value).digest(\"hex\")}`;\n}\n\nexport function canonicalSchema(\n collections: readonly CollectionDefinition[],\n): readonly CollectionDefinition[] {\n const names = new Set<string>();\n\n return collections\n .map((definition) => {\n if (names.has(definition.name)) throw new Error(`Duplicate collection: ${definition.name}`);\n\n names.add(definition.name);\n\n const schema = normalizeCollection(definition);\n\n return {\n ...schema,\n indexes: [...schema.indexes].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n ...(schema.foreignKeys\n ? {\n foreignKeys: [...schema.foreignKeys].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n }\n : {}),\n };\n })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nexport function schemaHash(collections: readonly CollectionDefinition[]): string {\n return checksum(canonicalJSON(canonicalSchema(collections)));\n}\n\nexport interface SchemaSnapshot {\n readonly formatVersion: 1;\n readonly migrationId: string | null;\n readonly parentMigrationId: string | null;\n readonly schemaHash: string;\n readonly collections: readonly CollectionDefinition[];\n}\n\nexport function createSnapshot(\n migrationId: string | null,\n parentMigrationId: string | null,\n collections: readonly CollectionDefinition[],\n): SchemaSnapshot {\n const normalized = canonicalSchema(collections);\n\n return {\n formatVersion: 1,\n migrationId,\n parentMigrationId,\n schemaHash: schemaHash(normalized),\n collections: normalized,\n };\n}\n\nexport function validateSnapshot(snapshot: SchemaSnapshot): void {\n if (\n !snapshot ||\n snapshot.formatVersion !== 1 ||\n !Array.isArray(snapshot.collections) ||\n snapshot.schemaHash !== schemaHash(snapshot.collections)\n )\n throw new Error(\"Invalid or incompatible schema snapshot\");\n\n const catalog = new Map(snapshot.collections.map((schema) => [schema.name, schema]));\n\n for (const schema of snapshot.collections)\n for (const key of schema.foreignKeys ?? [])\n if (!catalog.has(key.references.collection))\n throw new Error(\"Snapshot foreign key references an unmanaged collection\");\n\n if (snapshot.migrationId === null && snapshot.parentMigrationId !== null)\n throw new Error(\"Invalid baseline parent\");\n\n if (snapshot.migrationId !== null) validateMigrationId(snapshot.migrationId);\n if (snapshot.parentMigrationId !== null) validateMigrationId(snapshot.parentMigrationId);\n}\n\nexport function validateMigrationId(id: string): void {\n if (typeof id != \"string\" || !/^\\d{17}_[a-z0-9]+(?:_[a-z0-9]+)*$/.test(id))\n throw new Error(`Invalid migration ID: ${id}`);\n}\n","import {\n type CollectionDefinition,\n type DocumentRecord,\n type FieldDefinition,\n type ForeignKeyDefinition,\n type SecondaryIndexDefinition,\n type Transaction,\n indexFields,\n} from \"@duraxis/core\";\n\nexport class SchemaEditor {\n readonly #tx: Transaction;\n\n public constructor(tx: Transaction) {\n this.#tx = tx;\n }\n\n public inspect(): readonly CollectionDefinition[] {\n return this.#tx.getCollectionDefinitions();\n }\n\n public definition(name: string): CollectionDefinition {\n const result = this.inspect().find((schema) => schema.name == name);\n if (!result) throw new Error(`Unknown collection: ${name}`);\n return result;\n }\n\n public createCollection(definition: CollectionDefinition): void {\n this.#tx.defineCollection(definition);\n }\n\n public createCollections(definitions: readonly CollectionDefinition[]): void {\n this.#tx.defineCollections(definitions);\n }\n\n public alterCollection(name: string, definition: CollectionDefinition): void {\n this.#tx.alterCollection(name, definition);\n }\n\n public dropCollection(name: string): void {\n this.#tx.dropCollection(name);\n }\n\n public addField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Field already exists: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public alterField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (!Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Unknown field: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public async removeField(\n collection: string,\n name: string,\n options: { strategy: \"reject-if-populated\" | \"delete-values\" },\n ): Promise<void> {\n const schema = this.definition(collection);\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, name)) throw new Error(`Unknown field: ${name}`);\n\n if (\n schema.indexes.some((index) => indexFields(index).some((part) => part.field == name)) ||\n schema.foreignKeys?.some((key) => key.field == name)\n )\n throw new Error(\"Remove dependent indexes and foreign keys first\");\n\n delete fields[name];\n\n if (options.strategy == \"reject-if-populated\") {\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, name))\n throw new Error(`Field is populated: ${collection}/${name}`);\n } else if (options.strategy != \"delete-values\")\n throw new Error(\"Explicit field removal strategy required\");\n\n this.alterCollection(collection, { ...schema, fields });\n\n if (options.strategy == \"delete-values\")\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n delete document[name];\n this.#tx.putDocument(collection, row.id, document);\n }\n }\n\n public async renameField(collection: string, from: string, to: string): Promise<void> {\n const schema = this.definition(collection);\n\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, from) || Object.hasOwn(fields, to))\n throw new Error(\"Invalid field rename\");\n\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, to)) throw new Error(`Rename would overwrite ${to}`);\n\n fields[to] = fields[from]!;\n\n delete fields[from];\n\n this.alterCollection(collection, {\n ...schema,\n fields,\n indexes: schema.indexes.map((index) => ({\n name: index.name,\n unique: index.unique,\n fields: indexFields(index).map((part) => ({\n ...part,\n field: part.field == from ? to : part.field,\n })),\n })),\n foreignKeys: schema.foreignKeys?.map((key) => ({\n ...key,\n field: key.field == from ? to : key.field,\n })),\n });\n\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n if (Object.hasOwn(document, from)) {\n document[to] = document[from];\n delete document[from];\n }\n\n this.#tx.putDocument(collection, row.id, document);\n }\n }\n\n public addIndex(collection: string, index: SecondaryIndexDefinition): void {\n this.#tx.addIndex(collection, index);\n }\n\n public removeIndex(collection: string, name: string): void {\n this.#tx.removeIndex(collection, name);\n }\n\n public addForeignKey(collection: string, definition: ForeignKeyDefinition): void {\n const schema = this.definition(collection);\n if (schema.foreignKeys?.some((key) => key.name == definition.name))\n throw new Error(\"Foreign key already exists\");\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: [...(schema.foreignKeys ?? []), definition],\n });\n }\n\n public removeForeignKey(collection: string, name: string): void {\n const schema = this.definition(collection);\n\n if (!schema.foreignKeys?.some((key) => key.name == name))\n throw new Error(\"Unknown foreign key\");\n\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: schema.foreignKeys.filter((key) => key.name != name),\n });\n }\n}\n\nexport interface MigrationContext {\n readonly signal: AbortSignal;\n readonly schema: SchemaEditor;\n readonly get: Transaction[\"getDocument\"];\n readonly scan: Transaction[\"scanCollection\"];\n readonly put: Transaction[\"putDocument\"];\n readonly delete: Transaction[\"deleteDocument\"];\n transform(\n collection: string,\n transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>,\n ): Promise<void>;\n}\n\nexport function createMigrationContext(tx: Transaction): MigrationContext {\n return Object.freeze({\n signal: tx.signal,\n schema: new SchemaEditor(tx),\n get: tx.getDocument.bind(tx),\n scan: tx.scanCollection.bind(tx),\n put: tx.putDocument.bind(tx),\n delete: tx.deleteDocument.bind(tx),\n async transform(\n collection: string,\n transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>,\n ) {\n for await (const row of tx.scanCollection(collection))\n tx.putDocument(collection, row.id, await transform(row.document, row.id));\n },\n });\n}\n","import type {\n CollectionDefinition,\n FieldDefinition,\n ForeignKeyDefinition,\n SecondaryIndexDefinition,\n} from \"@duraxis/core\";\nimport type { MigrationContext } from \"./context.js\";\nimport { canonicalJSON, canonicalSchema, schemaHash } from \"./schema.js\";\n\nexport type MigrationRisk =\n \"safe\" | \"requires-validation\" | \"requires-data-transformation\" | \"destructive\";\n\ninterface Change<K extends string, T> {\n readonly kind: K;\n readonly collection: string;\n readonly name: string;\n readonly before: T | null;\n readonly after: T | null;\n readonly risk: MigrationRisk;\n}\n\nexport type MigrationOperation =\n | Change<\"collection\", CollectionDefinition>\n | Change<\"field\", FieldDefinition>\n | Change<\"index\", SecondaryIndexDefinition>\n | Change<\"foreign-key\", ForeignKeyDefinition>\n | Change<\"additional-fields\", boolean>;\n\nexport interface SchemaPlan {\n readonly before: readonly CollectionDefinition[];\n readonly after: readonly CollectionDefinition[];\n readonly operations: readonly MigrationOperation[];\n}\n\nfunction fieldRisk(before: FieldDefinition | null, after: FieldDefinition | null): MigrationRisk {\n if (!after) return \"destructive\";\n\n if (!before) return after.required ? \"requires-data-transformation\" : \"safe\";\n\n if (before.type != after.type || (!before.required && after.required))\n return \"requires-data-transformation\";\n\n if (before.nullable && !after.nullable) return \"requires-validation\";\n\n return \"safe\";\n}\n\nexport function diffSchemas(\n before: readonly CollectionDefinition[],\n after: readonly CollectionDefinition[],\n): SchemaPlan {\n const previous = canonicalSchema(before);\n const next = canonicalSchema(after);\n\n const left = new Map(previous.map((schema) => [schema.name, schema]));\n const right = new Map(next.map((schema) => [schema.name, schema]));\n\n const operations: MigrationOperation[] = [];\n\n for (const name of [...new Set([...left.keys(), ...right.keys()])].sort()) {\n const a = left.get(name);\n const b = right.get(name);\n\n if (!a || !b) {\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a ?? null,\n after: b ?? null,\n risk: b ? \"requires-validation\" : \"destructive\",\n });\n\n continue;\n }\n\n if ((a.fields == null) != (b.fields == null))\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a,\n after: b,\n risk: \"requires-validation\",\n });\n\n const fields = new Set([...Object.keys(a.fields ?? {}), ...Object.keys(b.fields ?? {})]);\n\n for (const field of [...fields].sort()) {\n const from = a.fields?.[field] ?? null;\n const to = b.fields?.[field] ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"field\",\n collection: name,\n name: field,\n before: from,\n after: to,\n risk: fieldRisk(from, to),\n });\n }\n\n if (a.allowAdditionalFields != b.allowAdditionalFields)\n operations.push({\n kind: \"additional-fields\",\n collection: name,\n name,\n before: a.allowAdditionalFields ?? true,\n after: b.allowAdditionalFields ?? true,\n risk: b.allowAdditionalFields ? \"safe\" : \"requires-validation\",\n });\n\n for (const index of [\n ...new Set([...a.indexes, ...b.indexes].map((index) => index.name)),\n ].sort()) {\n const from = a.indexes.find((item) => item.name == index) ?? null;\n const to = b.indexes.find((item) => item.name == index) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"index\",\n collection: name,\n name: index,\n before: from,\n after: to,\n risk: to?.unique ? \"requires-validation\" : \"safe\",\n });\n }\n\n for (const key of [\n ...new Set([...(a.foreignKeys ?? []), ...(b.foreignKeys ?? [])].map((key) => key.name)),\n ].sort()) {\n const from = a.foreignKeys?.find((item) => item.name == key) ?? null;\n const to = b.foreignKeys?.find((item) => item.name == key) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"foreign-key\",\n collection: name,\n name: key,\n before: from,\n after: to,\n risk: to ? \"requires-validation\" : \"safe\",\n });\n }\n }\n\n return { before: previous, after: next, operations };\n}\n\nexport async function applySchemaPlan(context: MigrationContext, plan: SchemaPlan): Promise<void> {\n const names = new Set([...plan.before, ...plan.after].map((schema) => schema.name));\n\n if (\n schemaHash(context.schema.inspect().filter((schema) => names.has(schema.name))) !=\n schemaHash(plan.before)\n )\n throw new Error(\"Schema plan predecessor mismatch\");\n\n for (const operation of plan.operations) {\n if (operation.risk == \"requires-data-transformation\")\n throw new Error(\n `Manual data transformation required: ${operation.collection}/${operation.name}`,\n );\n\n if (operation.kind == \"field\" && !operation.after)\n for await (const row of context.scan(operation.collection))\n if (Object.hasOwn(row.document, operation.name))\n throw new Error(\n `Cannot remove populated field: ${operation.collection}/${operation.name}; write an explicit transformation`,\n );\n }\n\n const old = new Set(plan.before.map((schema) => schema.name));\n const next = new Set(plan.after.map((schema) => schema.name));\n\n for (const schema of plan.before)\n if (!next.has(schema.name)) context.schema.dropCollection(schema.name);\n\n for (const schema of plan.after)\n if (old.has(schema.name)) context.schema.alterCollection(schema.name, schema);\n else context.schema.createCollection(schema);\n}\n","import { diffSchemas, type SchemaPlan } from \"./diff.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CommitOutcomeUnknownError,\n TransactionConflictError,\n type DuraxisDatabase,\n type Transaction,\n} from \"@duraxis/core\";\nimport { createMigrationContext, type MigrationContext } from \"./context.js\";\nimport {\n canonicalJSON,\n schemaHash,\n validateMigrationId,\n validateSnapshot,\n type SchemaSnapshot,\n} from \"./schema.js\";\n\nexport interface DuraxisMigration {\n readonly id: string;\n up(context: MigrationContext): Promise<void> | void;\n down?(context: MigrationContext): Promise<void> | void;\n}\n\nexport function defineMigration<const T extends DuraxisMigration>(migration: T): T {\n validateMigrationId(migration.id);\n\n if (\n typeof migration.up != \"function\" ||\n (migration.down !== undefined && typeof migration.down != \"function\")\n )\n throw new Error(\"Invalid migration callbacks\");\n\n return Object.freeze(migration);\n}\n\nexport interface MigrationArtifact {\n readonly migration: DuraxisMigration;\n readonly checksum: string;\n readonly snapshot: SchemaSnapshot;\n}\n\nexport interface MigrationHistoryEntry {\n readonly id: string;\n readonly checksum: string;\n readonly appliedAt: string;\n readonly sequence: number;\n readonly schemaHash: string;\n readonly operationId: string;\n}\n\ninterface History {\n readonly formatVersion: 1;\n readonly revision: string;\n readonly entries: readonly MigrationHistoryEntry[];\n}\n\nconst namespace = \"migrations\";\nconst digest = /^sha256:[a-f0-9]{64}$/;\n\nasync function readHistory(tx: Transaction): Promise<History> {\n const bytes = await tx.getMetadata(namespace);\n\n if (bytes == null) return { formatVersion: 1, revision: \"\", entries: [] };\n const history: History = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (\n history.formatVersion !== 1 ||\n !Array.isArray(history.entries) ||\n typeof history.revision != \"string\"\n )\n throw new Error(\"Invalid migration history\");\n\n history.entries.forEach((entry, index) => {\n validateMigrationId(entry.id);\n\n if (\n entry.sequence != index + 1 ||\n !digest.test(entry.checksum) ||\n !digest.test(entry.schemaHash) ||\n typeof entry.operationId != \"string\" ||\n !Number.isFinite(Date.parse(entry.appliedAt)) ||\n (index && history.entries[index - 1]!.id >= entry.id)\n )\n throw new Error(\"Invalid migration history ordering or metadata\");\n });\n\n return history;\n}\n\nfunction writeHistory(tx: Transaction, history: History): void {\n tx.putMetadata(namespace, new TextEncoder().encode(canonicalJSON(history)));\n}\n\nexport function validateArtifacts(artifacts: readonly MigrationArtifact[]): void {\n let parent: string | null = null;\n\n for (const artifact of artifacts) {\n defineMigration(artifact.migration);\n validateSnapshot(artifact.snapshot);\n\n if (!digest.test(artifact.checksum)) throw new Error(\"Invalid artifact checksum\");\n\n if (\n artifact.snapshot.migrationId != artifact.migration.id ||\n artifact.snapshot.parentMigrationId != parent ||\n (parent && parent >= artifact.migration.id)\n )\n throw new Error(\"Duplicate, unordered, or divergent migration chain\");\n\n parent = artifact.migration.id;\n }\n}\n\nexport interface RunOptions {\n readonly steps?: number;\n readonly to?: string;\n readonly allowDestructive?: boolean;\n}\n\nexport class MigrationRunner {\n private readonly managedNames: ReadonlySet<string>;\n\n public constructor(\n private readonly database: DuraxisDatabase,\n private readonly artifacts: readonly MigrationArtifact[],\n ) {\n validateArtifacts(artifacts);\n\n this.managedNames = new Set(\n artifacts.flatMap((artifact) => artifact.snapshot.collections.map((schema) => schema.name)),\n );\n }\n\n private async validate(tx: Transaction, checkSchema = true): Promise<History> {\n const history = await readHistory(tx);\n\n history.entries.forEach((entry, index) => {\n const artifact = this.artifacts[index];\n\n if (!artifact || artifact.migration.id != entry.id)\n throw new Error(`Missing migration or divergent history: ${entry.id}`);\n\n if (artifact.checksum != entry.checksum)\n throw new Error(`Applied migration checksum mismatch: ${entry.id}`);\n\n if (artifact.snapshot.schemaHash != entry.schemaHash)\n throw new Error(`Applied snapshot mismatch: ${entry.id}`);\n });\n\n const expected = history.entries.at(-1)?.schemaHash ?? schemaHash([]);\n\n if (\n checkSchema &&\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != expected\n )\n throw new Error(\"Database schema drift detected\");\n\n return history;\n }\n\n public async status(): Promise<{\n applied: readonly MigrationHistoryEntry[];\n pending: readonly string[];\n }> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n\n return {\n applied: history.entries,\n pending: this.artifacts\n .slice(history.entries.length)\n .map((artifact) => artifact.migration.id),\n };\n });\n }\n\n public async drift(): Promise<SchemaPlan> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx, false);\n\n return diffSchemas(\n this.artifacts[history.entries.length - 1]?.snapshot.collections ?? [],\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n );\n });\n }\n\n private validateOptions(options: RunOptions): void {\n if (options.steps !== undefined && (!Number.isSafeInteger(options.steps) || options.steps < 0))\n throw new Error(\"Invalid migration steps\");\n\n if (options.to && !this.artifacts.some((artifact) => artifact.migration.id == options.to))\n throw new Error(`Unknown migration target: ${options.to}`);\n\n if (options.to && options.steps !== undefined) throw new Error(\"Use either --steps or --to\");\n }\n\n public async up(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n const status = await this.status();\n const selected = this.artifacts\n .slice(status.applied.length)\n .filter((artifact) => !options.to || artifact.migration.id <= options.to)\n .slice(0, options.steps ?? Infinity);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"up\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async down(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n if (!options.allowDestructive)\n throw new Error(\"Rollback requires explicit destructive authorization\");\n\n const status = await this.status();\n\n if (options.to && !status.applied.some((entry) => entry.id == options.to))\n throw new Error(\"Rollback target is not applied\");\n\n const selected = this.artifacts\n .slice(0, status.applied.length)\n .reverse()\n .filter((artifact) => !options.to || artifact.migration.id > options.to)\n .slice(0, options.steps ?? (options.to ? Infinity : 1));\n\n for (const artifact of selected)\n if (!artifact.migration.down)\n throw new Error(`Irreversible migration: ${artifact.migration.id}`);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"down\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async baseline(): Promise<void> {\n if (this.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const artifact = this.artifacts[0]!;\n const operationId = randomUUID();\n\n try {\n await this.database.transaction(async (tx) => {\n const history = await readHistory(tx);\n if (history.entries.length) throw new Error(\"Database already has migration history\");\n\n this.assertSchema(tx, artifact.snapshot);\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries: [this.entry(artifact, 1, operationId)],\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, \"up\", artifact);\n }\n }\n\n private entry(\n artifact: MigrationArtifact,\n sequence: number,\n operationId: string,\n ): MigrationHistoryEntry {\n return {\n id: artifact.migration.id,\n checksum: artifact.checksum,\n schemaHash: artifact.snapshot.schemaHash,\n appliedAt: new Date().toISOString(),\n sequence,\n operationId,\n };\n }\n\n private assertSchema(tx: Transaction, snapshot?: SchemaSnapshot): void {\n if (\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != (snapshot?.schemaHash ?? schemaHash([]))\n )\n throw new Error(\"Migration result does not match expected snapshot\");\n }\n\n private async execute(\n artifact: MigrationArtifact,\n direction: \"up\" | \"down\",\n options: RunOptions,\n ): Promise<void> {\n const operationId = randomUUID();\n try {\n await this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n const index = this.artifacts.indexOf(artifact);\n\n if (direction == \"up\" && history.entries[index]?.id == artifact.migration.id) return;\n if ((direction == \"up\" ? history.entries.length : history.entries.length - 1) != index)\n throw new Error(\"Migration predecessor changed\");\n\n const before = tx.getCollectionDefinitions();\n\n await (direction == \"up\" ? artifact.migration.up : artifact.migration.down!)(\n createMigrationContext(tx),\n );\n\n const after = new Map(tx.getCollectionDefinitions().map((schema) => [schema.name, schema]));\n\n if (\n !options.allowDestructive &&\n before.some(\n (schema) =>\n !after.has(schema.name) ||\n Object.keys(schema.fields ?? {}).some(\n (name) => !Object.hasOwn(after.get(schema.name)?.fields ?? {}, name),\n ),\n )\n )\n throw new Error(\"Destructive schema change requires explicit authorization\");\n\n if (\n schemaHash(before.filter((schema) => !this.managedNames.has(schema.name))) !=\n schemaHash([...after.values()].filter((schema) => !this.managedNames.has(schema.name)))\n )\n throw new Error(\"Migration changed collections outside its snapshots\");\n\n this.assertSchema(\n tx,\n direction == \"up\" ? artifact.snapshot : this.artifacts[index - 1]?.snapshot,\n );\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries:\n direction == \"up\"\n ? [...history.entries, this.entry(artifact, index + 1, operationId)]\n : history.entries.slice(0, -1),\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, direction, artifact);\n }\n }\n\n private async reconcile(\n error: unknown,\n operationId: string,\n direction: \"up\" | \"down\",\n artifact: MigrationArtifact,\n ): Promise<void> {\n if (\n !(error instanceof TransactionConflictError) &&\n !(error instanceof CommitOutcomeUnknownError)\n )\n throw error;\n\n const history = await this.database.transaction((tx) => this.validate(tx));\n\n if (\n history.revision == operationId ||\n (direction == \"up\" &&\n history.entries.some(\n (entry) => entry.id == artifact.migration.id && entry.checksum == artifact.checksum,\n ))\n )\n return;\n\n if (\n error instanceof CommitOutcomeUnknownError &&\n (await this.database.getCommitStatus(error.transactionId)) == \"committed\"\n )\n return;\n\n throw error;\n }\n}\n"],"mappings":";;;;AAGA,SAAgB,cAAc,OAAwB;CACpD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;CAExE,IAAI,SAAS,OAAO,SAAS,UAC3B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC,CAClC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,cAAc,CAAC,GAAG,CAAC,CAC3D,KAAK,GAAG,EAAE;CAEf,MAAM,OAAO,KAAK,UAAU,KAAK;CAEjC,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,uBAAuB;CAE/D,OAAO;AACT;AAEA,SAAgB,SAAS,OAAuB;CAC9C,OAAO,WAAA,GAAUA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO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,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,WAAW,CAAC,KAAK,aAAa,IAAI,OAAO,IAAI,CAAC,CAAC,GAEtF,MAAM,IAAI,MAAM,qDAAqD;IAEvE,KAAK,aACH,IACA,aAAa,OAAO,SAAS,WAAW,KAAK,UAAU,QAAQ,EAAE,EAAE,QACrE;IAEA,aAAa,IAAI;KACf,eAAe;KACf,UAAU;KACV,SACE,aAAa,OACT,CAAC,GAAG,QAAQ,SAAS,KAAK,MAAM,UAAU,QAAQ,GAAG,WAAW,CAAC,IACjE,QAAQ,QAAQ,MAAM,GAAG,EAAE;IACnC,CAAC;GACH,CAAC;EACH,SAAS,OAAO;GACd,MAAM,KAAK,UAAU,OAAO,aAAa,WAAW,QAAQ;EAC9D;CACF;CAEA,MAAc,UACZ,OACA,aACA,WACA,UACe;EACf,IACE,EAAE,iBAAiBC,cAAAA,6BACnB,EAAE,iBAAiBC,cAAAA,4BAEnB,MAAM;EAER,MAAM,UAAU,MAAM,KAAK,SAAS,aAAa,OAAO,KAAK,SAAS,EAAE,CAAC;EAEzE,IACE,QAAQ,YAAY,eACnB,aAAa,QACZ,QAAQ,QAAQ,MACb,UAAU,MAAM,MAAM,SAAS,UAAU,MAAM,MAAM,YAAY,SAAS,QAC7E,GAEF;EAEF,IACE,iBAAiBA,cAAAA,6BAChB,MAAM,KAAK,SAAS,gBAAgB,MAAM,aAAa,KAAM,aAE9D;EAEF,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["createHash","normalizeCollection","indexFields","SCHEMA_TRANSFORMATION","randomUUID","TransactionConflictError","CommitOutcomeUnknownError"],"sources":["../src/schema.ts","../src/context.ts","../src/diff.ts","../src/runner.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { normalizeCollection, type CollectionDefinition } from \"@duraxis/core\";\n\nexport function canonicalJSON(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(\",\")}]`;\n\n if (value && typeof value == \"object\")\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJSON(v)}`)\n .join(\",\")}}`;\n\n const json = JSON.stringify(value);\n\n if (json === undefined) throw new Error(\"Non-JSON schema value\");\n\n return json;\n}\n\nexport function checksum(value: string): string {\n return `sha256:${createHash(\"sha256\").update(value).digest(\"hex\")}`;\n}\n\nexport function canonicalSchema(\n collections: readonly CollectionDefinition[],\n): readonly CollectionDefinition[] {\n const names = new Set<string>();\n\n return collections\n .map((definition) => {\n if (names.has(definition.name)) throw new Error(`Duplicate collection: ${definition.name}`);\n\n names.add(definition.name);\n\n const schema = normalizeCollection(definition);\n\n return {\n ...schema,\n indexes: [...schema.indexes].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n ...(schema.foreignKeys\n ? {\n foreignKeys: [...schema.foreignKeys].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n }\n : {}),\n };\n })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nexport function schemaHash(collections: readonly CollectionDefinition[]): string {\n return checksum(canonicalJSON(canonicalSchema(collections)));\n}\n\nexport interface SchemaSnapshot {\n readonly formatVersion: 1;\n readonly migrationId: string | null;\n readonly parentMigrationId: string | null;\n readonly schemaHash: string;\n readonly collections: readonly CollectionDefinition[];\n}\n\nexport function createSnapshot(\n migrationId: string | null,\n parentMigrationId: string | null,\n collections: readonly CollectionDefinition[],\n): SchemaSnapshot {\n const normalized = canonicalSchema(collections);\n\n return {\n formatVersion: 1,\n migrationId,\n parentMigrationId,\n schemaHash: schemaHash(normalized),\n collections: normalized,\n };\n}\n\nexport function validateSnapshot(snapshot: SchemaSnapshot): void {\n if (\n !snapshot ||\n snapshot.formatVersion !== 1 ||\n !Array.isArray(snapshot.collections) ||\n snapshot.schemaHash !== schemaHash(snapshot.collections)\n )\n throw new Error(\"Invalid or incompatible schema snapshot\");\n\n const catalog = new Map(snapshot.collections.map((schema) => [schema.name, schema]));\n\n for (const schema of snapshot.collections)\n for (const key of schema.foreignKeys ?? [])\n if (!catalog.has(key.references.collection))\n throw new Error(\"Snapshot foreign key references an unmanaged collection\");\n\n if (snapshot.migrationId === null && snapshot.parentMigrationId !== null)\n throw new Error(\"Invalid baseline parent\");\n\n if (snapshot.migrationId !== null) validateMigrationId(snapshot.migrationId);\n if (snapshot.parentMigrationId !== null) validateMigrationId(snapshot.parentMigrationId);\n}\n\nexport function validateMigrationId(id: string): void {\n if (typeof id != \"string\" || !/^\\d{17}_[a-z0-9]+(?:_[a-z0-9]+)*$/.test(id))\n throw new Error(`Invalid migration ID: ${id}`);\n}\n","import {\n type CollectionDefinition,\n type DocumentRecord,\n type FieldDefinition,\n type ForeignKeyDefinition,\n type SecondaryIndexDefinition,\n type Transaction,\n indexFields,\n SCHEMA_TRANSFORMATION,\n type PrimaryKeyValue,\n} from \"@duraxis/core\";\n\nexport class SchemaEditor {\n readonly #tx: Transaction;\n\n public constructor(tx: Transaction) {\n this.#tx = tx;\n }\n\n public inspect(): readonly CollectionDefinition[] {\n return this.#tx.getCollectionDefinitions();\n }\n\n public definition(name: string): CollectionDefinition {\n const result = this.inspect().find((schema) => schema.name == name);\n if (!result) throw new Error(`Unknown collection: ${name}`);\n return result;\n }\n\n public createCollection(definition: CollectionDefinition): void {\n this.#tx.defineCollection(definition);\n }\n\n public createCollections(definitions: readonly CollectionDefinition[]): void {\n this.#tx.defineCollections(definitions);\n }\n\n public alterCollection(name: string, definition: CollectionDefinition): void {\n this.#tx.alterCollection(name, definition);\n }\n\n public dropCollection(name: string): void {\n this.#tx.dropCollection(name);\n }\n\n public addField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Field already exists: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public alterField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (!Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Unknown field: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public async removeField(\n collection: string,\n name: string,\n options: { strategy: \"reject-if-populated\" | \"delete-values\" },\n ): Promise<void> {\n const schema = this.definition(collection);\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, name)) throw new Error(`Unknown field: ${name}`);\n\n if (\n schema.indexes.some((index) => indexFields(index).some((part) => part.field == name)) ||\n schema.foreignKeys?.some((key) => key.field == name)\n )\n throw new Error(\"Remove dependent indexes and foreign keys first\");\n\n delete fields[name];\n\n if (options.strategy == \"reject-if-populated\") {\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, name))\n throw new Error(`Field is populated: ${collection}/${name}`);\n } else if (options.strategy != \"delete-values\")\n throw new Error(\"Explicit field removal strategy required\");\n\n this.alterCollection(collection, { ...schema, fields });\n\n if (options.strategy == \"delete-values\")\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n delete document[name];\n await this.#tx[SCHEMA_TRANSFORMATION](collection, row.id, document);\n }\n }\n\n public async renameField(collection: string, from: string, to: string): Promise<void> {\n const schema = this.definition(collection);\n\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, from) || Object.hasOwn(fields, to))\n throw new Error(\"Invalid field rename\");\n\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, to)) throw new Error(`Rename would overwrite ${to}`);\n\n fields[to] = fields[from]!;\n\n delete fields[from];\n\n this.alterCollection(collection, {\n ...schema,\n fields,\n indexes: schema.indexes.map((index) => ({\n name: index.name,\n unique: index.unique,\n fields: indexFields(index).map((part) => ({\n ...part,\n field: part.field == from ? to : part.field,\n })),\n })),\n foreignKeys: schema.foreignKeys?.map((key) => ({\n ...key,\n field: key.field == from ? to : key.field,\n })),\n });\n\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n if (Object.hasOwn(document, from)) {\n document[to] = document[from];\n delete document[from];\n }\n\n await this.#tx[SCHEMA_TRANSFORMATION](collection, row.id, document);\n }\n }\n\n public addIndex(collection: string, index: SecondaryIndexDefinition): void {\n this.#tx.addIndex(collection, index);\n }\n\n public removeIndex(collection: string, name: string): void {\n this.#tx.removeIndex(collection, name);\n }\n\n public addForeignKey(collection: string, definition: ForeignKeyDefinition): void {\n const schema = this.definition(collection);\n if (schema.foreignKeys?.some((key) => key.name == definition.name))\n throw new Error(\"Foreign key already exists\");\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: [...(schema.foreignKeys ?? []), definition],\n });\n }\n\n public removeForeignKey(collection: string, name: string): void {\n const schema = this.definition(collection);\n\n if (!schema.foreignKeys?.some((key) => key.name == name))\n throw new Error(\"Unknown foreign key\");\n\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: schema.foreignKeys.filter((key) => key.name != name),\n });\n }\n}\n\nexport interface MigrationContext {\n readonly signal: AbortSignal;\n readonly schema: SchemaEditor;\n readonly get: Transaction[\"getDocument\"];\n readonly scan: Transaction[\"scanCollection\"];\n readonly insert: Transaction[\"insertDocument\"];\n readonly update: Transaction[\"updateDocument\"];\n readonly upsert: Transaction[\"upsertDocument\"];\n readonly delete: Transaction[\"deleteDocument\"];\n transform(\n collection: string,\n transform: (\n document: DocumentRecord,\n id: PrimaryKeyValue,\n ) => DocumentRecord | Promise<DocumentRecord>,\n ): Promise<void>;\n}\n\nexport function createMigrationContext(tx: Transaction): MigrationContext {\n return Object.freeze({\n signal: tx.signal,\n schema: new SchemaEditor(tx),\n get: tx.getDocument.bind(tx),\n scan: tx.scanCollection.bind(tx),\n insert: tx.insertDocument.bind(tx),\n update: tx.updateDocument.bind(tx),\n upsert: tx.upsertDocument.bind(tx),\n delete: tx.deleteDocument.bind(tx),\n async transform(\n collection: string,\n transform: (\n document: DocumentRecord,\n id: PrimaryKeyValue,\n ) => DocumentRecord | Promise<DocumentRecord>,\n ) {\n for await (const row of tx.scanCollection(collection))\n await tx[SCHEMA_TRANSFORMATION](collection, row.id, await transform(row.document, row.id));\n },\n });\n}\n","import type {\n CollectionDefinition,\n FieldDefinition,\n ForeignKeyDefinition,\n SecondaryIndexDefinition,\n} from \"@duraxis/core\";\nimport type { MigrationContext } from \"./context.js\";\nimport { canonicalJSON, canonicalSchema, schemaHash } from \"./schema.js\";\n\nexport type MigrationRisk =\n \"safe\" | \"requires-validation\" | \"requires-data-transformation\" | \"destructive\";\n\ninterface Change<K extends string, T> {\n readonly kind: K;\n readonly collection: string;\n readonly name: string;\n readonly before: T | null;\n readonly after: T | null;\n readonly risk: MigrationRisk;\n}\n\nexport type MigrationOperation =\n | Change<\"collection\", CollectionDefinition>\n | Change<\"field\", FieldDefinition>\n | Change<\"index\", SecondaryIndexDefinition>\n | Change<\"foreign-key\", ForeignKeyDefinition>\n | Change<\"additional-fields\", boolean>;\n\nexport interface SchemaPlan {\n readonly before: readonly CollectionDefinition[];\n readonly after: readonly CollectionDefinition[];\n readonly operations: readonly MigrationOperation[];\n}\n\nfunction fieldRisk(before: FieldDefinition | null, after: FieldDefinition | null): MigrationRisk {\n if (!after) return \"destructive\";\n\n if (!before) return after.required ? \"requires-data-transformation\" : \"safe\";\n\n if (\n before.type != after.type ||\n before.primary !== after.primary ||\n (!before.required && after.required)\n )\n return \"requires-data-transformation\";\n\n if (before.generated !== after.generated || before.unique !== after.unique)\n return \"requires-validation\";\n\n if (before.nullable && !after.nullable) return \"requires-validation\";\n\n return \"safe\";\n}\n\nexport function diffSchemas(\n before: readonly CollectionDefinition[],\n after: readonly CollectionDefinition[],\n): SchemaPlan {\n const previous = canonicalSchema(before);\n const next = canonicalSchema(after);\n\n const left = new Map(previous.map((schema) => [schema.name, schema]));\n const right = new Map(next.map((schema) => [schema.name, schema]));\n\n const operations: MigrationOperation[] = [];\n\n for (const name of [...new Set([...left.keys(), ...right.keys()])].sort()) {\n const a = left.get(name);\n const b = right.get(name);\n\n if (!a || !b) {\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a ?? null,\n after: b ?? null,\n risk: b ? \"requires-validation\" : \"destructive\",\n });\n\n continue;\n }\n\n if ((a.fields == null) != (b.fields == null))\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a,\n after: b,\n risk: \"requires-validation\",\n });\n\n const fields = new Set([...Object.keys(a.fields ?? {}), ...Object.keys(b.fields ?? {})]);\n\n for (const field of [...fields].sort()) {\n const from = a.fields?.[field] ?? null;\n const to = b.fields?.[field] ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"field\",\n collection: name,\n name: field,\n before: from,\n after: to,\n risk: fieldRisk(from, to),\n });\n }\n\n if (a.allowAdditionalFields != b.allowAdditionalFields)\n operations.push({\n kind: \"additional-fields\",\n collection: name,\n name,\n before: a.allowAdditionalFields ?? true,\n after: b.allowAdditionalFields ?? true,\n risk: b.allowAdditionalFields ? \"safe\" : \"requires-validation\",\n });\n\n for (const index of [\n ...new Set([...a.indexes, ...b.indexes].map((index) => index.name)),\n ].sort()) {\n const from = a.indexes.find((item) => item.name == index) ?? null;\n const to = b.indexes.find((item) => item.name == index) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"index\",\n collection: name,\n name: index,\n before: from,\n after: to,\n risk: to?.unique ? \"requires-validation\" : \"safe\",\n });\n }\n\n for (const key of [\n ...new Set([...(a.foreignKeys ?? []), ...(b.foreignKeys ?? [])].map((key) => key.name)),\n ].sort()) {\n const from = a.foreignKeys?.find((item) => item.name == key) ?? null;\n const to = b.foreignKeys?.find((item) => item.name == key) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"foreign-key\",\n collection: name,\n name: key,\n before: from,\n after: to,\n risk: to ? \"requires-validation\" : \"safe\",\n });\n }\n }\n\n return { before: previous, after: next, operations };\n}\n\nexport async function applySchemaPlan(context: MigrationContext, plan: SchemaPlan): Promise<void> {\n const names = new Set([...plan.before, ...plan.after].map((schema) => schema.name));\n\n if (\n schemaHash(context.schema.inspect().filter((schema) => names.has(schema.name))) !=\n schemaHash(plan.before)\n )\n throw new Error(\"Schema plan predecessor mismatch\");\n\n for (const operation of plan.operations) {\n if (operation.risk == \"requires-data-transformation\")\n throw new Error(\n `Manual data transformation required: ${operation.collection}/${operation.name}`,\n );\n\n if (operation.kind == \"field\" && !operation.after)\n for await (const row of context.scan(operation.collection))\n if (Object.hasOwn(row.document, operation.name))\n throw new Error(\n `Cannot remove populated field: ${operation.collection}/${operation.name}; write an explicit transformation`,\n );\n }\n\n const old = new Set(plan.before.map((schema) => schema.name));\n const next = new Set(plan.after.map((schema) => schema.name));\n\n for (const schema of plan.before)\n if (!next.has(schema.name)) context.schema.dropCollection(schema.name);\n\n for (const schema of plan.after)\n if (old.has(schema.name)) context.schema.alterCollection(schema.name, schema);\n else context.schema.createCollection(schema);\n}\n","import { diffSchemas, type SchemaPlan } from \"./diff.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CommitOutcomeUnknownError,\n TransactionConflictError,\n type DuraxisDatabase,\n type Transaction,\n} from \"@duraxis/core\";\nimport { createMigrationContext, type MigrationContext } from \"./context.js\";\nimport {\n canonicalJSON,\n schemaHash,\n validateMigrationId,\n validateSnapshot,\n type SchemaSnapshot,\n} from \"./schema.js\";\n\nexport interface DuraxisMigration {\n readonly id: string;\n up(context: MigrationContext): Promise<void> | void;\n down?(context: MigrationContext): Promise<void> | void;\n}\n\nexport function defineMigration<const T extends DuraxisMigration>(migration: T): T {\n validateMigrationId(migration.id);\n\n if (\n typeof migration.up != \"function\" ||\n (migration.down !== undefined && typeof migration.down != \"function\")\n )\n throw new Error(\"Invalid migration callbacks\");\n\n return Object.freeze(migration);\n}\n\nexport interface MigrationArtifact {\n readonly migration: DuraxisMigration;\n readonly checksum: string;\n readonly snapshot: SchemaSnapshot;\n}\n\nexport interface MigrationHistoryEntry {\n readonly id: string;\n readonly checksum: string;\n readonly appliedAt: string;\n readonly sequence: number;\n readonly schemaHash: string;\n readonly operationId: string;\n}\n\ninterface History {\n readonly formatVersion: 1;\n readonly revision: string;\n readonly entries: readonly MigrationHistoryEntry[];\n}\n\nconst namespace = \"migrations\";\nconst digest = /^sha256:[a-f0-9]{64}$/;\n\nasync function readHistory(tx: Transaction): Promise<History> {\n const bytes = await tx.getMetadata(namespace);\n\n if (bytes == null) return { formatVersion: 1, revision: \"\", entries: [] };\n const history: History = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (\n history.formatVersion !== 1 ||\n !Array.isArray(history.entries) ||\n typeof history.revision != \"string\"\n )\n throw new Error(\"Invalid migration history\");\n\n history.entries.forEach((entry, index) => {\n validateMigrationId(entry.id);\n\n if (\n entry.sequence != index + 1 ||\n !digest.test(entry.checksum) ||\n !digest.test(entry.schemaHash) ||\n typeof entry.operationId != \"string\" ||\n !Number.isFinite(Date.parse(entry.appliedAt)) ||\n (index && history.entries[index - 1]!.id >= entry.id)\n )\n throw new Error(\"Invalid migration history ordering or metadata\");\n });\n\n return history;\n}\n\nfunction writeHistory(tx: Transaction, history: History): void {\n tx.putMetadata(namespace, new TextEncoder().encode(canonicalJSON(history)));\n}\n\nexport function validateArtifacts(artifacts: readonly MigrationArtifact[]): void {\n let parent: string | null = null;\n\n for (const artifact of artifacts) {\n defineMigration(artifact.migration);\n validateSnapshot(artifact.snapshot);\n\n if (!digest.test(artifact.checksum)) throw new Error(\"Invalid artifact checksum\");\n\n if (\n artifact.snapshot.migrationId != artifact.migration.id ||\n artifact.snapshot.parentMigrationId != parent ||\n (parent && parent >= artifact.migration.id)\n )\n throw new Error(\"Duplicate, unordered, or divergent migration chain\");\n\n parent = artifact.migration.id;\n }\n}\n\nexport interface RunOptions {\n readonly steps?: number;\n readonly to?: string;\n readonly allowDestructive?: boolean;\n}\n\nexport class MigrationRunner {\n private readonly managedNames: ReadonlySet<string>;\n\n public constructor(\n private readonly database: DuraxisDatabase,\n private readonly artifacts: readonly MigrationArtifact[],\n ) {\n validateArtifacts(artifacts);\n\n this.managedNames = new Set(\n artifacts.flatMap((artifact) => artifact.snapshot.collections.map((schema) => schema.name)),\n );\n }\n\n private async validate(tx: Transaction, checkSchema = true): Promise<History> {\n const history = await readHistory(tx);\n\n history.entries.forEach((entry, index) => {\n const artifact = this.artifacts[index];\n\n if (!artifact || artifact.migration.id != entry.id)\n throw new Error(`Missing migration or divergent history: ${entry.id}`);\n\n if (artifact.checksum != entry.checksum)\n throw new Error(`Applied migration checksum mismatch: ${entry.id}`);\n\n if (artifact.snapshot.schemaHash != entry.schemaHash)\n throw new Error(`Applied snapshot mismatch: ${entry.id}`);\n });\n\n const expected = history.entries.at(-1)?.schemaHash ?? schemaHash([]);\n\n if (\n checkSchema &&\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != expected\n )\n throw new Error(\"Database schema drift detected\");\n\n return history;\n }\n\n public async status(): Promise<{\n applied: readonly MigrationHistoryEntry[];\n pending: readonly string[];\n }> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n\n return {\n applied: history.entries,\n pending: this.artifacts\n .slice(history.entries.length)\n .map((artifact) => artifact.migration.id),\n };\n });\n }\n\n public async drift(): Promise<SchemaPlan> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx, false);\n\n return diffSchemas(\n this.artifacts[history.entries.length - 1]?.snapshot.collections ?? [],\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n );\n });\n }\n\n private validateOptions(options: RunOptions): void {\n if (options.steps !== undefined && (!Number.isSafeInteger(options.steps) || options.steps < 0))\n throw new Error(\"Invalid migration steps\");\n\n if (options.to && !this.artifacts.some((artifact) => artifact.migration.id == options.to))\n throw new Error(`Unknown migration target: ${options.to}`);\n\n if (options.to && options.steps !== undefined) throw new Error(\"Use either --steps or --to\");\n }\n\n public async up(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n const status = await this.status();\n const selected = this.artifacts\n .slice(status.applied.length)\n .filter((artifact) => !options.to || artifact.migration.id <= options.to)\n .slice(0, options.steps ?? Infinity);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"up\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async down(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n if (!options.allowDestructive)\n throw new Error(\"Rollback requires explicit destructive authorization\");\n\n const status = await this.status();\n\n if (options.to && !status.applied.some((entry) => entry.id == options.to))\n throw new Error(\"Rollback target is not applied\");\n\n const selected = this.artifacts\n .slice(0, status.applied.length)\n .reverse()\n .filter((artifact) => !options.to || artifact.migration.id > options.to)\n .slice(0, options.steps ?? (options.to ? Infinity : 1));\n\n for (const artifact of selected)\n if (!artifact.migration.down)\n throw new Error(`Irreversible migration: ${artifact.migration.id}`);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"down\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async baseline(): Promise<void> {\n if (this.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const artifact = this.artifacts[0]!;\n const operationId = randomUUID();\n\n try {\n await this.database.transaction(async (tx) => {\n const history = await readHistory(tx);\n if (history.entries.length) throw new Error(\"Database already has migration history\");\n\n this.assertSchema(tx, artifact.snapshot);\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries: [this.entry(artifact, 1, operationId)],\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, \"up\", artifact);\n }\n }\n\n private entry(\n artifact: MigrationArtifact,\n sequence: number,\n operationId: string,\n ): MigrationHistoryEntry {\n return {\n id: artifact.migration.id,\n checksum: artifact.checksum,\n schemaHash: artifact.snapshot.schemaHash,\n appliedAt: new Date().toISOString(),\n sequence,\n operationId,\n };\n }\n\n private assertSchema(tx: Transaction, snapshot?: SchemaSnapshot): void {\n if (\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != (snapshot?.schemaHash ?? schemaHash([]))\n )\n throw new Error(\"Migration result does not match expected snapshot\");\n }\n\n private async execute(\n artifact: MigrationArtifact,\n direction: \"up\" | \"down\",\n options: RunOptions,\n ): Promise<void> {\n const operationId = randomUUID();\n try {\n await this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n const index = this.artifacts.indexOf(artifact);\n\n if (direction == \"up\" && history.entries[index]?.id == artifact.migration.id) return;\n if ((direction == \"up\" ? history.entries.length : history.entries.length - 1) != index)\n throw new Error(\"Migration predecessor changed\");\n\n const before = tx.getCollectionDefinitions();\n\n await (direction == \"up\" ? artifact.migration.up : artifact.migration.down!)(\n createMigrationContext(tx),\n );\n\n const after = new Map(tx.getCollectionDefinitions().map((schema) => [schema.name, schema]));\n\n if (\n !options.allowDestructive &&\n before.some(\n (schema) =>\n !after.has(schema.name) ||\n Object.keys(schema.fields ?? {}).some(\n (name) => !Object.hasOwn(after.get(schema.name)?.fields ?? {}, name),\n ),\n )\n )\n throw new Error(\"Destructive schema change requires explicit authorization\");\n\n if (\n schemaHash(before.filter((schema) => !this.managedNames.has(schema.name))) !=\n schemaHash([...after.values()].filter((schema) => !this.managedNames.has(schema.name)))\n )\n throw new Error(\"Migration changed collections outside its snapshots\");\n\n this.assertSchema(\n tx,\n direction == \"up\" ? artifact.snapshot : this.artifacts[index - 1]?.snapshot,\n );\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries:\n direction == \"up\"\n ? [...history.entries, this.entry(artifact, index + 1, operationId)]\n : history.entries.slice(0, -1),\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, direction, artifact);\n }\n }\n\n private async reconcile(\n error: unknown,\n operationId: string,\n direction: \"up\" | \"down\",\n artifact: MigrationArtifact,\n ): Promise<void> {\n if (\n !(error instanceof TransactionConflictError) &&\n !(error instanceof CommitOutcomeUnknownError)\n )\n throw error;\n\n const history = await this.database.transaction((tx) => this.validate(tx));\n\n if (\n history.revision == operationId ||\n (direction == \"up\" &&\n history.entries.some(\n (entry) => entry.id == artifact.migration.id && entry.checksum == artifact.checksum,\n ))\n )\n return;\n\n if (\n error instanceof CommitOutcomeUnknownError &&\n (await this.database.getCommitStatus(error.transactionId)) == \"committed\"\n )\n return;\n\n throw error;\n }\n}\n"],"mappings":";;;;AAGA,SAAgB,cAAc,OAAwB;CACpD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;CAExE,IAAI,SAAS,OAAO,SAAS,UAC3B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC,CAClC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,cAAc,CAAC,GAAG,CAAC,CAC3D,KAAK,GAAG,EAAE;CAEf,MAAM,OAAO,KAAK,UAAU,KAAK;CAEjC,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,uBAAuB;CAE/D,OAAO;AACT;AAEA,SAAgB,SAAS,OAAuB;CAC9C,OAAO,WAAA,GAAUA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAClE;AAEA,SAAgB,gBACd,aACiC;CACjC,MAAM,wBAAQ,IAAI,IAAY;CAE9B,OAAO,YACJ,KAAK,eAAe;EACnB,IAAI,MAAM,IAAI,WAAW,IAAI,GAAG,MAAM,IAAI,MAAM,yBAAyB,WAAW,MAAM;EAE1F,MAAM,IAAI,WAAW,IAAI;EAEzB,MAAM,UAAA,GAASC,cAAAA,oBAA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Q,WAAW,CAAC,KAAK,aAAa,IAAI,OAAO,IAAI,CAAC,CAAC,GAEtF,MAAM,IAAI,MAAM,qDAAqD;IAEvE,KAAK,aACH,IACA,aAAa,OAAO,SAAS,WAAW,KAAK,UAAU,QAAQ,EAAE,EAAE,QACrE;IAEA,aAAa,IAAI;KACf,eAAe;KACf,UAAU;KACV,SACE,aAAa,OACT,CAAC,GAAG,QAAQ,SAAS,KAAK,MAAM,UAAU,QAAQ,GAAG,WAAW,CAAC,IACjE,QAAQ,QAAQ,MAAM,GAAG,EAAE;IACnC,CAAC;GACH,CAAC;EACH,SAAS,OAAO;GACd,MAAM,KAAK,UAAU,OAAO,aAAa,WAAW,QAAQ;EAC9D;CACF;CAEA,MAAc,UACZ,OACA,aACA,WACA,UACe;EACf,IACE,EAAE,iBAAiBC,cAAAA,6BACnB,EAAE,iBAAiBC,cAAAA,4BAEnB,MAAM;EAER,MAAM,UAAU,MAAM,KAAK,SAAS,aAAa,OAAO,KAAK,SAAS,EAAE,CAAC;EAEzE,IACE,QAAQ,YAAY,eACnB,aAAa,QACZ,QAAQ,QAAQ,MACb,UAAU,MAAM,MAAM,SAAS,UAAU,MAAM,MAAM,YAAY,SAAS,QAC7E,GAEF;EAEF,IACE,iBAAiBA,cAAAA,6BAChB,MAAM,KAAK,SAAS,gBAAgB,MAAM,aAAa,KAAM,aAE9D;EAEF,MAAM;CACR;AACF"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { CommitOutcomeUnknownError, TransactionConflictError, indexFields, normalizeCollection } from "@duraxis/core";
2
+ import { CommitOutcomeUnknownError, SCHEMA_TRANSFORMATION, TransactionConflictError, indexFields, normalizeCollection } from "@duraxis/core";
3
3
  // src/schema.ts
4
4
  function canonicalJSON(value) {
5
5
  if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(",")}]`;
@@ -112,7 +112,7 @@ var SchemaEditor = class {
112
112
  if (options.strategy == "delete-values") for await (const row of this.#tx.scanCollection(collection)) {
113
113
  const document = { ...row.document };
114
114
  delete document[name];
115
- this.#tx.putDocument(collection, row.id, document);
115
+ await this.#tx[SCHEMA_TRANSFORMATION](collection, row.id, document);
116
116
  }
117
117
  }
118
118
  async renameField(collection, from, to) {
@@ -144,7 +144,7 @@ var SchemaEditor = class {
144
144
  document[to] = document[from];
145
145
  delete document[from];
146
146
  }
147
- this.#tx.putDocument(collection, row.id, document);
147
+ await this.#tx[SCHEMA_TRANSFORMATION](collection, row.id, document);
148
148
  }
149
149
  }
150
150
  addIndex(collection, index) {
@@ -176,10 +176,12 @@ function createMigrationContext(tx) {
176
176
  schema: new SchemaEditor(tx),
177
177
  get: tx.getDocument.bind(tx),
178
178
  scan: tx.scanCollection.bind(tx),
179
- put: tx.putDocument.bind(tx),
179
+ insert: tx.insertDocument.bind(tx),
180
+ update: tx.updateDocument.bind(tx),
181
+ upsert: tx.upsertDocument.bind(tx),
180
182
  delete: tx.deleteDocument.bind(tx),
181
183
  async transform(collection, transform) {
182
- for await (const row of tx.scanCollection(collection)) tx.putDocument(collection, row.id, await transform(row.document, row.id));
184
+ for await (const row of tx.scanCollection(collection)) await tx[SCHEMA_TRANSFORMATION](collection, row.id, await transform(row.document, row.id));
183
185
  }
184
186
  });
185
187
  }
@@ -187,7 +189,8 @@ function createMigrationContext(tx) {
187
189
  function fieldRisk(before, after) {
188
190
  if (!after) return "destructive";
189
191
  if (!before) return after.required ? "requires-data-transformation" : "safe";
190
- if (before.type != after.type || !before.required && after.required) return "requires-data-transformation";
192
+ if (before.type != after.type || before.primary !== after.primary || !before.required && after.required) return "requires-data-transformation";
193
+ if (before.generated !== after.generated || before.unique !== after.unique) return "requires-validation";
191
194
  if (before.nullable && !after.nullable) return "requires-validation";
192
195
  return "safe";
193
196
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/schema.ts","../src/context.ts","../src/diff.ts","../src/runner.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { normalizeCollection, type CollectionDefinition } from \"@duraxis/core\";\n\nexport function canonicalJSON(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(\",\")}]`;\n\n if (value && typeof value == \"object\")\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJSON(v)}`)\n .join(\",\")}}`;\n\n const json = JSON.stringify(value);\n\n if (json === undefined) throw new Error(\"Non-JSON schema value\");\n\n return json;\n}\n\nexport function checksum(value: string): string {\n return `sha256:${createHash(\"sha256\").update(value).digest(\"hex\")}`;\n}\n\nexport function canonicalSchema(\n collections: readonly CollectionDefinition[],\n): readonly CollectionDefinition[] {\n const names = new Set<string>();\n\n return collections\n .map((definition) => {\n if (names.has(definition.name)) throw new Error(`Duplicate collection: ${definition.name}`);\n\n names.add(definition.name);\n\n const schema = normalizeCollection(definition);\n\n return {\n ...schema,\n indexes: [...schema.indexes].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n ...(schema.foreignKeys\n ? {\n foreignKeys: [...schema.foreignKeys].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n }\n : {}),\n };\n })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nexport function schemaHash(collections: readonly CollectionDefinition[]): string {\n return checksum(canonicalJSON(canonicalSchema(collections)));\n}\n\nexport interface SchemaSnapshot {\n readonly formatVersion: 1;\n readonly migrationId: string | null;\n readonly parentMigrationId: string | null;\n readonly schemaHash: string;\n readonly collections: readonly CollectionDefinition[];\n}\n\nexport function createSnapshot(\n migrationId: string | null,\n parentMigrationId: string | null,\n collections: readonly CollectionDefinition[],\n): SchemaSnapshot {\n const normalized = canonicalSchema(collections);\n\n return {\n formatVersion: 1,\n migrationId,\n parentMigrationId,\n schemaHash: schemaHash(normalized),\n collections: normalized,\n };\n}\n\nexport function validateSnapshot(snapshot: SchemaSnapshot): void {\n if (\n !snapshot ||\n snapshot.formatVersion !== 1 ||\n !Array.isArray(snapshot.collections) ||\n snapshot.schemaHash !== schemaHash(snapshot.collections)\n )\n throw new Error(\"Invalid or incompatible schema snapshot\");\n\n const catalog = new Map(snapshot.collections.map((schema) => [schema.name, schema]));\n\n for (const schema of snapshot.collections)\n for (const key of schema.foreignKeys ?? [])\n if (!catalog.has(key.references.collection))\n throw new Error(\"Snapshot foreign key references an unmanaged collection\");\n\n if (snapshot.migrationId === null && snapshot.parentMigrationId !== null)\n throw new Error(\"Invalid baseline parent\");\n\n if (snapshot.migrationId !== null) validateMigrationId(snapshot.migrationId);\n if (snapshot.parentMigrationId !== null) validateMigrationId(snapshot.parentMigrationId);\n}\n\nexport function validateMigrationId(id: string): void {\n if (typeof id != \"string\" || !/^\\d{17}_[a-z0-9]+(?:_[a-z0-9]+)*$/.test(id))\n throw new Error(`Invalid migration ID: ${id}`);\n}\n","import {\n type CollectionDefinition,\n type DocumentRecord,\n type FieldDefinition,\n type ForeignKeyDefinition,\n type SecondaryIndexDefinition,\n type Transaction,\n indexFields,\n} from \"@duraxis/core\";\n\nexport class SchemaEditor {\n readonly #tx: Transaction;\n\n public constructor(tx: Transaction) {\n this.#tx = tx;\n }\n\n public inspect(): readonly CollectionDefinition[] {\n return this.#tx.getCollectionDefinitions();\n }\n\n public definition(name: string): CollectionDefinition {\n const result = this.inspect().find((schema) => schema.name == name);\n if (!result) throw new Error(`Unknown collection: ${name}`);\n return result;\n }\n\n public createCollection(definition: CollectionDefinition): void {\n this.#tx.defineCollection(definition);\n }\n\n public createCollections(definitions: readonly CollectionDefinition[]): void {\n this.#tx.defineCollections(definitions);\n }\n\n public alterCollection(name: string, definition: CollectionDefinition): void {\n this.#tx.alterCollection(name, definition);\n }\n\n public dropCollection(name: string): void {\n this.#tx.dropCollection(name);\n }\n\n public addField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Field already exists: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public alterField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (!Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Unknown field: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public async removeField(\n collection: string,\n name: string,\n options: { strategy: \"reject-if-populated\" | \"delete-values\" },\n ): Promise<void> {\n const schema = this.definition(collection);\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, name)) throw new Error(`Unknown field: ${name}`);\n\n if (\n schema.indexes.some((index) => indexFields(index).some((part) => part.field == name)) ||\n schema.foreignKeys?.some((key) => key.field == name)\n )\n throw new Error(\"Remove dependent indexes and foreign keys first\");\n\n delete fields[name];\n\n if (options.strategy == \"reject-if-populated\") {\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, name))\n throw new Error(`Field is populated: ${collection}/${name}`);\n } else if (options.strategy != \"delete-values\")\n throw new Error(\"Explicit field removal strategy required\");\n\n this.alterCollection(collection, { ...schema, fields });\n\n if (options.strategy == \"delete-values\")\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n delete document[name];\n this.#tx.putDocument(collection, row.id, document);\n }\n }\n\n public async renameField(collection: string, from: string, to: string): Promise<void> {\n const schema = this.definition(collection);\n\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, from) || Object.hasOwn(fields, to))\n throw new Error(\"Invalid field rename\");\n\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, to)) throw new Error(`Rename would overwrite ${to}`);\n\n fields[to] = fields[from]!;\n\n delete fields[from];\n\n this.alterCollection(collection, {\n ...schema,\n fields,\n indexes: schema.indexes.map((index) => ({\n name: index.name,\n unique: index.unique,\n fields: indexFields(index).map((part) => ({\n ...part,\n field: part.field == from ? to : part.field,\n })),\n })),\n foreignKeys: schema.foreignKeys?.map((key) => ({\n ...key,\n field: key.field == from ? to : key.field,\n })),\n });\n\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n if (Object.hasOwn(document, from)) {\n document[to] = document[from];\n delete document[from];\n }\n\n this.#tx.putDocument(collection, row.id, document);\n }\n }\n\n public addIndex(collection: string, index: SecondaryIndexDefinition): void {\n this.#tx.addIndex(collection, index);\n }\n\n public removeIndex(collection: string, name: string): void {\n this.#tx.removeIndex(collection, name);\n }\n\n public addForeignKey(collection: string, definition: ForeignKeyDefinition): void {\n const schema = this.definition(collection);\n if (schema.foreignKeys?.some((key) => key.name == definition.name))\n throw new Error(\"Foreign key already exists\");\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: [...(schema.foreignKeys ?? []), definition],\n });\n }\n\n public removeForeignKey(collection: string, name: string): void {\n const schema = this.definition(collection);\n\n if (!schema.foreignKeys?.some((key) => key.name == name))\n throw new Error(\"Unknown foreign key\");\n\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: schema.foreignKeys.filter((key) => key.name != name),\n });\n }\n}\n\nexport interface MigrationContext {\n readonly signal: AbortSignal;\n readonly schema: SchemaEditor;\n readonly get: Transaction[\"getDocument\"];\n readonly scan: Transaction[\"scanCollection\"];\n readonly put: Transaction[\"putDocument\"];\n readonly delete: Transaction[\"deleteDocument\"];\n transform(\n collection: string,\n transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>,\n ): Promise<void>;\n}\n\nexport function createMigrationContext(tx: Transaction): MigrationContext {\n return Object.freeze({\n signal: tx.signal,\n schema: new SchemaEditor(tx),\n get: tx.getDocument.bind(tx),\n scan: tx.scanCollection.bind(tx),\n put: tx.putDocument.bind(tx),\n delete: tx.deleteDocument.bind(tx),\n async transform(\n collection: string,\n transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>,\n ) {\n for await (const row of tx.scanCollection(collection))\n tx.putDocument(collection, row.id, await transform(row.document, row.id));\n },\n });\n}\n","import type {\n CollectionDefinition,\n FieldDefinition,\n ForeignKeyDefinition,\n SecondaryIndexDefinition,\n} from \"@duraxis/core\";\nimport type { MigrationContext } from \"./context.js\";\nimport { canonicalJSON, canonicalSchema, schemaHash } from \"./schema.js\";\n\nexport type MigrationRisk =\n \"safe\" | \"requires-validation\" | \"requires-data-transformation\" | \"destructive\";\n\ninterface Change<K extends string, T> {\n readonly kind: K;\n readonly collection: string;\n readonly name: string;\n readonly before: T | null;\n readonly after: T | null;\n readonly risk: MigrationRisk;\n}\n\nexport type MigrationOperation =\n | Change<\"collection\", CollectionDefinition>\n | Change<\"field\", FieldDefinition>\n | Change<\"index\", SecondaryIndexDefinition>\n | Change<\"foreign-key\", ForeignKeyDefinition>\n | Change<\"additional-fields\", boolean>;\n\nexport interface SchemaPlan {\n readonly before: readonly CollectionDefinition[];\n readonly after: readonly CollectionDefinition[];\n readonly operations: readonly MigrationOperation[];\n}\n\nfunction fieldRisk(before: FieldDefinition | null, after: FieldDefinition | null): MigrationRisk {\n if (!after) return \"destructive\";\n\n if (!before) return after.required ? \"requires-data-transformation\" : \"safe\";\n\n if (before.type != after.type || (!before.required && after.required))\n return \"requires-data-transformation\";\n\n if (before.nullable && !after.nullable) return \"requires-validation\";\n\n return \"safe\";\n}\n\nexport function diffSchemas(\n before: readonly CollectionDefinition[],\n after: readonly CollectionDefinition[],\n): SchemaPlan {\n const previous = canonicalSchema(before);\n const next = canonicalSchema(after);\n\n const left = new Map(previous.map((schema) => [schema.name, schema]));\n const right = new Map(next.map((schema) => [schema.name, schema]));\n\n const operations: MigrationOperation[] = [];\n\n for (const name of [...new Set([...left.keys(), ...right.keys()])].sort()) {\n const a = left.get(name);\n const b = right.get(name);\n\n if (!a || !b) {\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a ?? null,\n after: b ?? null,\n risk: b ? \"requires-validation\" : \"destructive\",\n });\n\n continue;\n }\n\n if ((a.fields == null) != (b.fields == null))\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a,\n after: b,\n risk: \"requires-validation\",\n });\n\n const fields = new Set([...Object.keys(a.fields ?? {}), ...Object.keys(b.fields ?? {})]);\n\n for (const field of [...fields].sort()) {\n const from = a.fields?.[field] ?? null;\n const to = b.fields?.[field] ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"field\",\n collection: name,\n name: field,\n before: from,\n after: to,\n risk: fieldRisk(from, to),\n });\n }\n\n if (a.allowAdditionalFields != b.allowAdditionalFields)\n operations.push({\n kind: \"additional-fields\",\n collection: name,\n name,\n before: a.allowAdditionalFields ?? true,\n after: b.allowAdditionalFields ?? true,\n risk: b.allowAdditionalFields ? \"safe\" : \"requires-validation\",\n });\n\n for (const index of [\n ...new Set([...a.indexes, ...b.indexes].map((index) => index.name)),\n ].sort()) {\n const from = a.indexes.find((item) => item.name == index) ?? null;\n const to = b.indexes.find((item) => item.name == index) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"index\",\n collection: name,\n name: index,\n before: from,\n after: to,\n risk: to?.unique ? \"requires-validation\" : \"safe\",\n });\n }\n\n for (const key of [\n ...new Set([...(a.foreignKeys ?? []), ...(b.foreignKeys ?? [])].map((key) => key.name)),\n ].sort()) {\n const from = a.foreignKeys?.find((item) => item.name == key) ?? null;\n const to = b.foreignKeys?.find((item) => item.name == key) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"foreign-key\",\n collection: name,\n name: key,\n before: from,\n after: to,\n risk: to ? \"requires-validation\" : \"safe\",\n });\n }\n }\n\n return { before: previous, after: next, operations };\n}\n\nexport async function applySchemaPlan(context: MigrationContext, plan: SchemaPlan): Promise<void> {\n const names = new Set([...plan.before, ...plan.after].map((schema) => schema.name));\n\n if (\n schemaHash(context.schema.inspect().filter((schema) => names.has(schema.name))) !=\n schemaHash(plan.before)\n )\n throw new Error(\"Schema plan predecessor mismatch\");\n\n for (const operation of plan.operations) {\n if (operation.risk == \"requires-data-transformation\")\n throw new Error(\n `Manual data transformation required: ${operation.collection}/${operation.name}`,\n );\n\n if (operation.kind == \"field\" && !operation.after)\n for await (const row of context.scan(operation.collection))\n if (Object.hasOwn(row.document, operation.name))\n throw new Error(\n `Cannot remove populated field: ${operation.collection}/${operation.name}; write an explicit transformation`,\n );\n }\n\n const old = new Set(plan.before.map((schema) => schema.name));\n const next = new Set(plan.after.map((schema) => schema.name));\n\n for (const schema of plan.before)\n if (!next.has(schema.name)) context.schema.dropCollection(schema.name);\n\n for (const schema of plan.after)\n if (old.has(schema.name)) context.schema.alterCollection(schema.name, schema);\n else context.schema.createCollection(schema);\n}\n","import { diffSchemas, type SchemaPlan } from \"./diff.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CommitOutcomeUnknownError,\n TransactionConflictError,\n type DuraxisDatabase,\n type Transaction,\n} from \"@duraxis/core\";\nimport { createMigrationContext, type MigrationContext } from \"./context.js\";\nimport {\n canonicalJSON,\n schemaHash,\n validateMigrationId,\n validateSnapshot,\n type SchemaSnapshot,\n} from \"./schema.js\";\n\nexport interface DuraxisMigration {\n readonly id: string;\n up(context: MigrationContext): Promise<void> | void;\n down?(context: MigrationContext): Promise<void> | void;\n}\n\nexport function defineMigration<const T extends DuraxisMigration>(migration: T): T {\n validateMigrationId(migration.id);\n\n if (\n typeof migration.up != \"function\" ||\n (migration.down !== undefined && typeof migration.down != \"function\")\n )\n throw new Error(\"Invalid migration callbacks\");\n\n return Object.freeze(migration);\n}\n\nexport interface MigrationArtifact {\n readonly migration: DuraxisMigration;\n readonly checksum: string;\n readonly snapshot: SchemaSnapshot;\n}\n\nexport interface MigrationHistoryEntry {\n readonly id: string;\n readonly checksum: string;\n readonly appliedAt: string;\n readonly sequence: number;\n readonly schemaHash: string;\n readonly operationId: string;\n}\n\ninterface History {\n readonly formatVersion: 1;\n readonly revision: string;\n readonly entries: readonly MigrationHistoryEntry[];\n}\n\nconst namespace = \"migrations\";\nconst digest = /^sha256:[a-f0-9]{64}$/;\n\nasync function readHistory(tx: Transaction): Promise<History> {\n const bytes = await tx.getMetadata(namespace);\n\n if (bytes == null) return { formatVersion: 1, revision: \"\", entries: [] };\n const history: History = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (\n history.formatVersion !== 1 ||\n !Array.isArray(history.entries) ||\n typeof history.revision != \"string\"\n )\n throw new Error(\"Invalid migration history\");\n\n history.entries.forEach((entry, index) => {\n validateMigrationId(entry.id);\n\n if (\n entry.sequence != index + 1 ||\n !digest.test(entry.checksum) ||\n !digest.test(entry.schemaHash) ||\n typeof entry.operationId != \"string\" ||\n !Number.isFinite(Date.parse(entry.appliedAt)) ||\n (index && history.entries[index - 1]!.id >= entry.id)\n )\n throw new Error(\"Invalid migration history ordering or metadata\");\n });\n\n return history;\n}\n\nfunction writeHistory(tx: Transaction, history: History): void {\n tx.putMetadata(namespace, new TextEncoder().encode(canonicalJSON(history)));\n}\n\nexport function validateArtifacts(artifacts: readonly MigrationArtifact[]): void {\n let parent: string | null = null;\n\n for (const artifact of artifacts) {\n defineMigration(artifact.migration);\n validateSnapshot(artifact.snapshot);\n\n if (!digest.test(artifact.checksum)) throw new Error(\"Invalid artifact checksum\");\n\n if (\n artifact.snapshot.migrationId != artifact.migration.id ||\n artifact.snapshot.parentMigrationId != parent ||\n (parent && parent >= artifact.migration.id)\n )\n throw new Error(\"Duplicate, unordered, or divergent migration chain\");\n\n parent = artifact.migration.id;\n }\n}\n\nexport interface RunOptions {\n readonly steps?: number;\n readonly to?: string;\n readonly allowDestructive?: boolean;\n}\n\nexport class MigrationRunner {\n private readonly managedNames: ReadonlySet<string>;\n\n public constructor(\n private readonly database: DuraxisDatabase,\n private readonly artifacts: readonly MigrationArtifact[],\n ) {\n validateArtifacts(artifacts);\n\n this.managedNames = new Set(\n artifacts.flatMap((artifact) => artifact.snapshot.collections.map((schema) => schema.name)),\n );\n }\n\n private async validate(tx: Transaction, checkSchema = true): Promise<History> {\n const history = await readHistory(tx);\n\n history.entries.forEach((entry, index) => {\n const artifact = this.artifacts[index];\n\n if (!artifact || artifact.migration.id != entry.id)\n throw new Error(`Missing migration or divergent history: ${entry.id}`);\n\n if (artifact.checksum != entry.checksum)\n throw new Error(`Applied migration checksum mismatch: ${entry.id}`);\n\n if (artifact.snapshot.schemaHash != entry.schemaHash)\n throw new Error(`Applied snapshot mismatch: ${entry.id}`);\n });\n\n const expected = history.entries.at(-1)?.schemaHash ?? schemaHash([]);\n\n if (\n checkSchema &&\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != expected\n )\n throw new Error(\"Database schema drift detected\");\n\n return history;\n }\n\n public async status(): Promise<{\n applied: readonly MigrationHistoryEntry[];\n pending: readonly string[];\n }> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n\n return {\n applied: history.entries,\n pending: this.artifacts\n .slice(history.entries.length)\n .map((artifact) => artifact.migration.id),\n };\n });\n }\n\n public async drift(): Promise<SchemaPlan> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx, false);\n\n return diffSchemas(\n this.artifacts[history.entries.length - 1]?.snapshot.collections ?? [],\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n );\n });\n }\n\n private validateOptions(options: RunOptions): void {\n if (options.steps !== undefined && (!Number.isSafeInteger(options.steps) || options.steps < 0))\n throw new Error(\"Invalid migration steps\");\n\n if (options.to && !this.artifacts.some((artifact) => artifact.migration.id == options.to))\n throw new Error(`Unknown migration target: ${options.to}`);\n\n if (options.to && options.steps !== undefined) throw new Error(\"Use either --steps or --to\");\n }\n\n public async up(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n const status = await this.status();\n const selected = this.artifacts\n .slice(status.applied.length)\n .filter((artifact) => !options.to || artifact.migration.id <= options.to)\n .slice(0, options.steps ?? Infinity);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"up\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async down(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n if (!options.allowDestructive)\n throw new Error(\"Rollback requires explicit destructive authorization\");\n\n const status = await this.status();\n\n if (options.to && !status.applied.some((entry) => entry.id == options.to))\n throw new Error(\"Rollback target is not applied\");\n\n const selected = this.artifacts\n .slice(0, status.applied.length)\n .reverse()\n .filter((artifact) => !options.to || artifact.migration.id > options.to)\n .slice(0, options.steps ?? (options.to ? Infinity : 1));\n\n for (const artifact of selected)\n if (!artifact.migration.down)\n throw new Error(`Irreversible migration: ${artifact.migration.id}`);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"down\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async baseline(): Promise<void> {\n if (this.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const artifact = this.artifacts[0]!;\n const operationId = randomUUID();\n\n try {\n await this.database.transaction(async (tx) => {\n const history = await readHistory(tx);\n if (history.entries.length) throw new Error(\"Database already has migration history\");\n\n this.assertSchema(tx, artifact.snapshot);\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries: [this.entry(artifact, 1, operationId)],\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, \"up\", artifact);\n }\n }\n\n private entry(\n artifact: MigrationArtifact,\n sequence: number,\n operationId: string,\n ): MigrationHistoryEntry {\n return {\n id: artifact.migration.id,\n checksum: artifact.checksum,\n schemaHash: artifact.snapshot.schemaHash,\n appliedAt: new Date().toISOString(),\n sequence,\n operationId,\n };\n }\n\n private assertSchema(tx: Transaction, snapshot?: SchemaSnapshot): void {\n if (\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != (snapshot?.schemaHash ?? schemaHash([]))\n )\n throw new Error(\"Migration result does not match expected snapshot\");\n }\n\n private async execute(\n artifact: MigrationArtifact,\n direction: \"up\" | \"down\",\n options: RunOptions,\n ): Promise<void> {\n const operationId = randomUUID();\n try {\n await this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n const index = this.artifacts.indexOf(artifact);\n\n if (direction == \"up\" && history.entries[index]?.id == artifact.migration.id) return;\n if ((direction == \"up\" ? history.entries.length : history.entries.length - 1) != index)\n throw new Error(\"Migration predecessor changed\");\n\n const before = tx.getCollectionDefinitions();\n\n await (direction == \"up\" ? artifact.migration.up : artifact.migration.down!)(\n createMigrationContext(tx),\n );\n\n const after = new Map(tx.getCollectionDefinitions().map((schema) => [schema.name, schema]));\n\n if (\n !options.allowDestructive &&\n before.some(\n (schema) =>\n !after.has(schema.name) ||\n Object.keys(schema.fields ?? {}).some(\n (name) => !Object.hasOwn(after.get(schema.name)?.fields ?? {}, name),\n ),\n )\n )\n throw new Error(\"Destructive schema change requires explicit authorization\");\n\n if (\n schemaHash(before.filter((schema) => !this.managedNames.has(schema.name))) !=\n schemaHash([...after.values()].filter((schema) => !this.managedNames.has(schema.name)))\n )\n throw new Error(\"Migration changed collections outside its snapshots\");\n\n this.assertSchema(\n tx,\n direction == \"up\" ? artifact.snapshot : this.artifacts[index - 1]?.snapshot,\n );\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries:\n direction == \"up\"\n ? [...history.entries, this.entry(artifact, index + 1, operationId)]\n : history.entries.slice(0, -1),\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, direction, artifact);\n }\n }\n\n private async reconcile(\n error: unknown,\n operationId: string,\n direction: \"up\" | \"down\",\n artifact: MigrationArtifact,\n ): Promise<void> {\n if (\n !(error instanceof TransactionConflictError) &&\n !(error instanceof CommitOutcomeUnknownError)\n )\n throw error;\n\n const history = await this.database.transaction((tx) => this.validate(tx));\n\n if (\n history.revision == operationId ||\n (direction == \"up\" &&\n history.entries.some(\n (entry) => entry.id == artifact.migration.id && entry.checksum == artifact.checksum,\n ))\n )\n return;\n\n if (\n error instanceof CommitOutcomeUnknownError &&\n (await this.database.getCommitStatus(error.transactionId)) == \"committed\"\n )\n return;\n\n throw error;\n }\n}\n"],"mappings":";;;AAGA,SAAgB,cAAc,OAAwB;CACpD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;CAExE,IAAI,SAAS,OAAO,SAAS,UAC3B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC,CAClC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,cAAc,CAAC,GAAG,CAAC,CAC3D,KAAK,GAAG,EAAE;CAEf,MAAM,OAAO,KAAK,UAAU,KAAK;CAEjC,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,uBAAuB;CAE/D,OAAO;AACT;AAEA,SAAgB,SAAS,OAAuB;CAC9C,OAAO,UAAU,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAClE;AAEA,SAAgB,gBACd,aACiC;CACjC,MAAM,wBAAQ,IAAI,IAAY;CAE9B,OAAO,YACJ,KAAK,eAAe;EACnB,IAAI,MAAM,IAAI,WAAW,IAAI,GAAG,MAAM,IAAI,MAAM,yBAAyB,WAAW,MAAM;EAE1F,MAAM,IAAI,WAAW,IAAI;EAEzB,MAAM,SAAS,oBAAoB,UAAU;EAE7C,OAAO;GACL,GAAG;GACH,SAAS,CAAC,GAAG,OAAO,OAAO,CAAC,CAAC,MAAM,GAAG,MACpC,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAC/C;GACA,GAAI,OAAO,cACP,EACE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BAAiB,4BAEnB,MAAM;EAER,MAAM,UAAU,MAAM,KAAK,SAAS,aAAa,OAAO,KAAK,SAAS,EAAE,CAAC;EAEzE,IACE,QAAQ,YAAY,eACnB,aAAa,QACZ,QAAQ,QAAQ,MACb,UAAU,MAAM,MAAM,SAAS,UAAU,MAAM,MAAM,YAAY,SAAS,QAC7E,GAEF;EAEF,IACE,iBAAiB,6BAChB,MAAM,KAAK,SAAS,gBAAgB,MAAM,aAAa,KAAM,aAE9D;EAEF,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/schema.ts","../src/context.ts","../src/diff.ts","../src/runner.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { normalizeCollection, type CollectionDefinition } from \"@duraxis/core\";\n\nexport function canonicalJSON(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(\",\")}]`;\n\n if (value && typeof value == \"object\")\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJSON(v)}`)\n .join(\",\")}}`;\n\n const json = JSON.stringify(value);\n\n if (json === undefined) throw new Error(\"Non-JSON schema value\");\n\n return json;\n}\n\nexport function checksum(value: string): string {\n return `sha256:${createHash(\"sha256\").update(value).digest(\"hex\")}`;\n}\n\nexport function canonicalSchema(\n collections: readonly CollectionDefinition[],\n): readonly CollectionDefinition[] {\n const names = new Set<string>();\n\n return collections\n .map((definition) => {\n if (names.has(definition.name)) throw new Error(`Duplicate collection: ${definition.name}`);\n\n names.add(definition.name);\n\n const schema = normalizeCollection(definition);\n\n return {\n ...schema,\n indexes: [...schema.indexes].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n ...(schema.foreignKeys\n ? {\n foreignKeys: [...schema.foreignKeys].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n }\n : {}),\n };\n })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nexport function schemaHash(collections: readonly CollectionDefinition[]): string {\n return checksum(canonicalJSON(canonicalSchema(collections)));\n}\n\nexport interface SchemaSnapshot {\n readonly formatVersion: 1;\n readonly migrationId: string | null;\n readonly parentMigrationId: string | null;\n readonly schemaHash: string;\n readonly collections: readonly CollectionDefinition[];\n}\n\nexport function createSnapshot(\n migrationId: string | null,\n parentMigrationId: string | null,\n collections: readonly CollectionDefinition[],\n): SchemaSnapshot {\n const normalized = canonicalSchema(collections);\n\n return {\n formatVersion: 1,\n migrationId,\n parentMigrationId,\n schemaHash: schemaHash(normalized),\n collections: normalized,\n };\n}\n\nexport function validateSnapshot(snapshot: SchemaSnapshot): void {\n if (\n !snapshot ||\n snapshot.formatVersion !== 1 ||\n !Array.isArray(snapshot.collections) ||\n snapshot.schemaHash !== schemaHash(snapshot.collections)\n )\n throw new Error(\"Invalid or incompatible schema snapshot\");\n\n const catalog = new Map(snapshot.collections.map((schema) => [schema.name, schema]));\n\n for (const schema of snapshot.collections)\n for (const key of schema.foreignKeys ?? [])\n if (!catalog.has(key.references.collection))\n throw new Error(\"Snapshot foreign key references an unmanaged collection\");\n\n if (snapshot.migrationId === null && snapshot.parentMigrationId !== null)\n throw new Error(\"Invalid baseline parent\");\n\n if (snapshot.migrationId !== null) validateMigrationId(snapshot.migrationId);\n if (snapshot.parentMigrationId !== null) validateMigrationId(snapshot.parentMigrationId);\n}\n\nexport function validateMigrationId(id: string): void {\n if (typeof id != \"string\" || !/^\\d{17}_[a-z0-9]+(?:_[a-z0-9]+)*$/.test(id))\n throw new Error(`Invalid migration ID: ${id}`);\n}\n","import {\n type CollectionDefinition,\n type DocumentRecord,\n type FieldDefinition,\n type ForeignKeyDefinition,\n type SecondaryIndexDefinition,\n type Transaction,\n indexFields,\n SCHEMA_TRANSFORMATION,\n type PrimaryKeyValue,\n} from \"@duraxis/core\";\n\nexport class SchemaEditor {\n readonly #tx: Transaction;\n\n public constructor(tx: Transaction) {\n this.#tx = tx;\n }\n\n public inspect(): readonly CollectionDefinition[] {\n return this.#tx.getCollectionDefinitions();\n }\n\n public definition(name: string): CollectionDefinition {\n const result = this.inspect().find((schema) => schema.name == name);\n if (!result) throw new Error(`Unknown collection: ${name}`);\n return result;\n }\n\n public createCollection(definition: CollectionDefinition): void {\n this.#tx.defineCollection(definition);\n }\n\n public createCollections(definitions: readonly CollectionDefinition[]): void {\n this.#tx.defineCollections(definitions);\n }\n\n public alterCollection(name: string, definition: CollectionDefinition): void {\n this.#tx.alterCollection(name, definition);\n }\n\n public dropCollection(name: string): void {\n this.#tx.dropCollection(name);\n }\n\n public addField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Field already exists: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public alterField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (!Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Unknown field: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public async removeField(\n collection: string,\n name: string,\n options: { strategy: \"reject-if-populated\" | \"delete-values\" },\n ): Promise<void> {\n const schema = this.definition(collection);\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, name)) throw new Error(`Unknown field: ${name}`);\n\n if (\n schema.indexes.some((index) => indexFields(index).some((part) => part.field == name)) ||\n schema.foreignKeys?.some((key) => key.field == name)\n )\n throw new Error(\"Remove dependent indexes and foreign keys first\");\n\n delete fields[name];\n\n if (options.strategy == \"reject-if-populated\") {\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, name))\n throw new Error(`Field is populated: ${collection}/${name}`);\n } else if (options.strategy != \"delete-values\")\n throw new Error(\"Explicit field removal strategy required\");\n\n this.alterCollection(collection, { ...schema, fields });\n\n if (options.strategy == \"delete-values\")\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n delete document[name];\n await this.#tx[SCHEMA_TRANSFORMATION](collection, row.id, document);\n }\n }\n\n public async renameField(collection: string, from: string, to: string): Promise<void> {\n const schema = this.definition(collection);\n\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, from) || Object.hasOwn(fields, to))\n throw new Error(\"Invalid field rename\");\n\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, to)) throw new Error(`Rename would overwrite ${to}`);\n\n fields[to] = fields[from]!;\n\n delete fields[from];\n\n this.alterCollection(collection, {\n ...schema,\n fields,\n indexes: schema.indexes.map((index) => ({\n name: index.name,\n unique: index.unique,\n fields: indexFields(index).map((part) => ({\n ...part,\n field: part.field == from ? to : part.field,\n })),\n })),\n foreignKeys: schema.foreignKeys?.map((key) => ({\n ...key,\n field: key.field == from ? to : key.field,\n })),\n });\n\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n if (Object.hasOwn(document, from)) {\n document[to] = document[from];\n delete document[from];\n }\n\n await this.#tx[SCHEMA_TRANSFORMATION](collection, row.id, document);\n }\n }\n\n public addIndex(collection: string, index: SecondaryIndexDefinition): void {\n this.#tx.addIndex(collection, index);\n }\n\n public removeIndex(collection: string, name: string): void {\n this.#tx.removeIndex(collection, name);\n }\n\n public addForeignKey(collection: string, definition: ForeignKeyDefinition): void {\n const schema = this.definition(collection);\n if (schema.foreignKeys?.some((key) => key.name == definition.name))\n throw new Error(\"Foreign key already exists\");\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: [...(schema.foreignKeys ?? []), definition],\n });\n }\n\n public removeForeignKey(collection: string, name: string): void {\n const schema = this.definition(collection);\n\n if (!schema.foreignKeys?.some((key) => key.name == name))\n throw new Error(\"Unknown foreign key\");\n\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: schema.foreignKeys.filter((key) => key.name != name),\n });\n }\n}\n\nexport interface MigrationContext {\n readonly signal: AbortSignal;\n readonly schema: SchemaEditor;\n readonly get: Transaction[\"getDocument\"];\n readonly scan: Transaction[\"scanCollection\"];\n readonly insert: Transaction[\"insertDocument\"];\n readonly update: Transaction[\"updateDocument\"];\n readonly upsert: Transaction[\"upsertDocument\"];\n readonly delete: Transaction[\"deleteDocument\"];\n transform(\n collection: string,\n transform: (\n document: DocumentRecord,\n id: PrimaryKeyValue,\n ) => DocumentRecord | Promise<DocumentRecord>,\n ): Promise<void>;\n}\n\nexport function createMigrationContext(tx: Transaction): MigrationContext {\n return Object.freeze({\n signal: tx.signal,\n schema: new SchemaEditor(tx),\n get: tx.getDocument.bind(tx),\n scan: tx.scanCollection.bind(tx),\n insert: tx.insertDocument.bind(tx),\n update: tx.updateDocument.bind(tx),\n upsert: tx.upsertDocument.bind(tx),\n delete: tx.deleteDocument.bind(tx),\n async transform(\n collection: string,\n transform: (\n document: DocumentRecord,\n id: PrimaryKeyValue,\n ) => DocumentRecord | Promise<DocumentRecord>,\n ) {\n for await (const row of tx.scanCollection(collection))\n await tx[SCHEMA_TRANSFORMATION](collection, row.id, await transform(row.document, row.id));\n },\n });\n}\n","import type {\n CollectionDefinition,\n FieldDefinition,\n ForeignKeyDefinition,\n SecondaryIndexDefinition,\n} from \"@duraxis/core\";\nimport type { MigrationContext } from \"./context.js\";\nimport { canonicalJSON, canonicalSchema, schemaHash } from \"./schema.js\";\n\nexport type MigrationRisk =\n \"safe\" | \"requires-validation\" | \"requires-data-transformation\" | \"destructive\";\n\ninterface Change<K extends string, T> {\n readonly kind: K;\n readonly collection: string;\n readonly name: string;\n readonly before: T | null;\n readonly after: T | null;\n readonly risk: MigrationRisk;\n}\n\nexport type MigrationOperation =\n | Change<\"collection\", CollectionDefinition>\n | Change<\"field\", FieldDefinition>\n | Change<\"index\", SecondaryIndexDefinition>\n | Change<\"foreign-key\", ForeignKeyDefinition>\n | Change<\"additional-fields\", boolean>;\n\nexport interface SchemaPlan {\n readonly before: readonly CollectionDefinition[];\n readonly after: readonly CollectionDefinition[];\n readonly operations: readonly MigrationOperation[];\n}\n\nfunction fieldRisk(before: FieldDefinition | null, after: FieldDefinition | null): MigrationRisk {\n if (!after) return \"destructive\";\n\n if (!before) return after.required ? \"requires-data-transformation\" : \"safe\";\n\n if (\n before.type != after.type ||\n before.primary !== after.primary ||\n (!before.required && after.required)\n )\n return \"requires-data-transformation\";\n\n if (before.generated !== after.generated || before.unique !== after.unique)\n return \"requires-validation\";\n\n if (before.nullable && !after.nullable) return \"requires-validation\";\n\n return \"safe\";\n}\n\nexport function diffSchemas(\n before: readonly CollectionDefinition[],\n after: readonly CollectionDefinition[],\n): SchemaPlan {\n const previous = canonicalSchema(before);\n const next = canonicalSchema(after);\n\n const left = new Map(previous.map((schema) => [schema.name, schema]));\n const right = new Map(next.map((schema) => [schema.name, schema]));\n\n const operations: MigrationOperation[] = [];\n\n for (const name of [...new Set([...left.keys(), ...right.keys()])].sort()) {\n const a = left.get(name);\n const b = right.get(name);\n\n if (!a || !b) {\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a ?? null,\n after: b ?? null,\n risk: b ? \"requires-validation\" : \"destructive\",\n });\n\n continue;\n }\n\n if ((a.fields == null) != (b.fields == null))\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a,\n after: b,\n risk: \"requires-validation\",\n });\n\n const fields = new Set([...Object.keys(a.fields ?? {}), ...Object.keys(b.fields ?? {})]);\n\n for (const field of [...fields].sort()) {\n const from = a.fields?.[field] ?? null;\n const to = b.fields?.[field] ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"field\",\n collection: name,\n name: field,\n before: from,\n after: to,\n risk: fieldRisk(from, to),\n });\n }\n\n if (a.allowAdditionalFields != b.allowAdditionalFields)\n operations.push({\n kind: \"additional-fields\",\n collection: name,\n name,\n before: a.allowAdditionalFields ?? true,\n after: b.allowAdditionalFields ?? true,\n risk: b.allowAdditionalFields ? \"safe\" : \"requires-validation\",\n });\n\n for (const index of [\n ...new Set([...a.indexes, ...b.indexes].map((index) => index.name)),\n ].sort()) {\n const from = a.indexes.find((item) => item.name == index) ?? null;\n const to = b.indexes.find((item) => item.name == index) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"index\",\n collection: name,\n name: index,\n before: from,\n after: to,\n risk: to?.unique ? \"requires-validation\" : \"safe\",\n });\n }\n\n for (const key of [\n ...new Set([...(a.foreignKeys ?? []), ...(b.foreignKeys ?? [])].map((key) => key.name)),\n ].sort()) {\n const from = a.foreignKeys?.find((item) => item.name == key) ?? null;\n const to = b.foreignKeys?.find((item) => item.name == key) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"foreign-key\",\n collection: name,\n name: key,\n before: from,\n after: to,\n risk: to ? \"requires-validation\" : \"safe\",\n });\n }\n }\n\n return { before: previous, after: next, operations };\n}\n\nexport async function applySchemaPlan(context: MigrationContext, plan: SchemaPlan): Promise<void> {\n const names = new Set([...plan.before, ...plan.after].map((schema) => schema.name));\n\n if (\n schemaHash(context.schema.inspect().filter((schema) => names.has(schema.name))) !=\n schemaHash(plan.before)\n )\n throw new Error(\"Schema plan predecessor mismatch\");\n\n for (const operation of plan.operations) {\n if (operation.risk == \"requires-data-transformation\")\n throw new Error(\n `Manual data transformation required: ${operation.collection}/${operation.name}`,\n );\n\n if (operation.kind == \"field\" && !operation.after)\n for await (const row of context.scan(operation.collection))\n if (Object.hasOwn(row.document, operation.name))\n throw new Error(\n `Cannot remove populated field: ${operation.collection}/${operation.name}; write an explicit transformation`,\n );\n }\n\n const old = new Set(plan.before.map((schema) => schema.name));\n const next = new Set(plan.after.map((schema) => schema.name));\n\n for (const schema of plan.before)\n if (!next.has(schema.name)) context.schema.dropCollection(schema.name);\n\n for (const schema of plan.after)\n if (old.has(schema.name)) context.schema.alterCollection(schema.name, schema);\n else context.schema.createCollection(schema);\n}\n","import { diffSchemas, type SchemaPlan } from \"./diff.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CommitOutcomeUnknownError,\n TransactionConflictError,\n type DuraxisDatabase,\n type Transaction,\n} from \"@duraxis/core\";\nimport { createMigrationContext, type MigrationContext } from \"./context.js\";\nimport {\n canonicalJSON,\n schemaHash,\n validateMigrationId,\n validateSnapshot,\n type SchemaSnapshot,\n} from \"./schema.js\";\n\nexport interface DuraxisMigration {\n readonly id: string;\n up(context: MigrationContext): Promise<void> | void;\n down?(context: MigrationContext): Promise<void> | void;\n}\n\nexport function defineMigration<const T extends DuraxisMigration>(migration: T): T {\n validateMigrationId(migration.id);\n\n if (\n typeof migration.up != \"function\" ||\n (migration.down !== undefined && typeof migration.down != \"function\")\n )\n throw new Error(\"Invalid migration callbacks\");\n\n return Object.freeze(migration);\n}\n\nexport interface MigrationArtifact {\n readonly migration: DuraxisMigration;\n readonly checksum: string;\n readonly snapshot: SchemaSnapshot;\n}\n\nexport interface MigrationHistoryEntry {\n readonly id: string;\n readonly checksum: string;\n readonly appliedAt: string;\n readonly sequence: number;\n readonly schemaHash: string;\n readonly operationId: string;\n}\n\ninterface History {\n readonly formatVersion: 1;\n readonly revision: string;\n readonly entries: readonly MigrationHistoryEntry[];\n}\n\nconst namespace = \"migrations\";\nconst digest = /^sha256:[a-f0-9]{64}$/;\n\nasync function readHistory(tx: Transaction): Promise<History> {\n const bytes = await tx.getMetadata(namespace);\n\n if (bytes == null) return { formatVersion: 1, revision: \"\", entries: [] };\n const history: History = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (\n history.formatVersion !== 1 ||\n !Array.isArray(history.entries) ||\n typeof history.revision != \"string\"\n )\n throw new Error(\"Invalid migration history\");\n\n history.entries.forEach((entry, index) => {\n validateMigrationId(entry.id);\n\n if (\n entry.sequence != index + 1 ||\n !digest.test(entry.checksum) ||\n !digest.test(entry.schemaHash) ||\n typeof entry.operationId != \"string\" ||\n !Number.isFinite(Date.parse(entry.appliedAt)) ||\n (index && history.entries[index - 1]!.id >= entry.id)\n )\n throw new Error(\"Invalid migration history ordering or metadata\");\n });\n\n return history;\n}\n\nfunction writeHistory(tx: Transaction, history: History): void {\n tx.putMetadata(namespace, new TextEncoder().encode(canonicalJSON(history)));\n}\n\nexport function validateArtifacts(artifacts: readonly MigrationArtifact[]): void {\n let parent: string | null = null;\n\n for (const artifact of artifacts) {\n defineMigration(artifact.migration);\n validateSnapshot(artifact.snapshot);\n\n if (!digest.test(artifact.checksum)) throw new Error(\"Invalid artifact checksum\");\n\n if (\n artifact.snapshot.migrationId != artifact.migration.id ||\n artifact.snapshot.parentMigrationId != parent ||\n (parent && parent >= artifact.migration.id)\n )\n throw new Error(\"Duplicate, unordered, or divergent migration chain\");\n\n parent = artifact.migration.id;\n }\n}\n\nexport interface RunOptions {\n readonly steps?: number;\n readonly to?: string;\n readonly allowDestructive?: boolean;\n}\n\nexport class MigrationRunner {\n private readonly managedNames: ReadonlySet<string>;\n\n public constructor(\n private readonly database: DuraxisDatabase,\n private readonly artifacts: readonly MigrationArtifact[],\n ) {\n validateArtifacts(artifacts);\n\n this.managedNames = new Set(\n artifacts.flatMap((artifact) => artifact.snapshot.collections.map((schema) => schema.name)),\n );\n }\n\n private async validate(tx: Transaction, checkSchema = true): Promise<History> {\n const history = await readHistory(tx);\n\n history.entries.forEach((entry, index) => {\n const artifact = this.artifacts[index];\n\n if (!artifact || artifact.migration.id != entry.id)\n throw new Error(`Missing migration or divergent history: ${entry.id}`);\n\n if (artifact.checksum != entry.checksum)\n throw new Error(`Applied migration checksum mismatch: ${entry.id}`);\n\n if (artifact.snapshot.schemaHash != entry.schemaHash)\n throw new Error(`Applied snapshot mismatch: ${entry.id}`);\n });\n\n const expected = history.entries.at(-1)?.schemaHash ?? schemaHash([]);\n\n if (\n checkSchema &&\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != expected\n )\n throw new Error(\"Database schema drift detected\");\n\n return history;\n }\n\n public async status(): Promise<{\n applied: readonly MigrationHistoryEntry[];\n pending: readonly string[];\n }> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n\n return {\n applied: history.entries,\n pending: this.artifacts\n .slice(history.entries.length)\n .map((artifact) => artifact.migration.id),\n };\n });\n }\n\n public async drift(): Promise<SchemaPlan> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx, false);\n\n return diffSchemas(\n this.artifacts[history.entries.length - 1]?.snapshot.collections ?? [],\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n );\n });\n }\n\n private validateOptions(options: RunOptions): void {\n if (options.steps !== undefined && (!Number.isSafeInteger(options.steps) || options.steps < 0))\n throw new Error(\"Invalid migration steps\");\n\n if (options.to && !this.artifacts.some((artifact) => artifact.migration.id == options.to))\n throw new Error(`Unknown migration target: ${options.to}`);\n\n if (options.to && options.steps !== undefined) throw new Error(\"Use either --steps or --to\");\n }\n\n public async up(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n const status = await this.status();\n const selected = this.artifacts\n .slice(status.applied.length)\n .filter((artifact) => !options.to || artifact.migration.id <= options.to)\n .slice(0, options.steps ?? Infinity);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"up\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async down(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n if (!options.allowDestructive)\n throw new Error(\"Rollback requires explicit destructive authorization\");\n\n const status = await this.status();\n\n if (options.to && !status.applied.some((entry) => entry.id == options.to))\n throw new Error(\"Rollback target is not applied\");\n\n const selected = this.artifacts\n .slice(0, status.applied.length)\n .reverse()\n .filter((artifact) => !options.to || artifact.migration.id > options.to)\n .slice(0, options.steps ?? (options.to ? Infinity : 1));\n\n for (const artifact of selected)\n if (!artifact.migration.down)\n throw new Error(`Irreversible migration: ${artifact.migration.id}`);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"down\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async baseline(): Promise<void> {\n if (this.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const artifact = this.artifacts[0]!;\n const operationId = randomUUID();\n\n try {\n await this.database.transaction(async (tx) => {\n const history = await readHistory(tx);\n if (history.entries.length) throw new Error(\"Database already has migration history\");\n\n this.assertSchema(tx, artifact.snapshot);\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries: [this.entry(artifact, 1, operationId)],\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, \"up\", artifact);\n }\n }\n\n private entry(\n artifact: MigrationArtifact,\n sequence: number,\n operationId: string,\n ): MigrationHistoryEntry {\n return {\n id: artifact.migration.id,\n checksum: artifact.checksum,\n schemaHash: artifact.snapshot.schemaHash,\n appliedAt: new Date().toISOString(),\n sequence,\n operationId,\n };\n }\n\n private assertSchema(tx: Transaction, snapshot?: SchemaSnapshot): void {\n if (\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != (snapshot?.schemaHash ?? schemaHash([]))\n )\n throw new Error(\"Migration result does not match expected snapshot\");\n }\n\n private async execute(\n artifact: MigrationArtifact,\n direction: \"up\" | \"down\",\n options: RunOptions,\n ): Promise<void> {\n const operationId = randomUUID();\n try {\n await this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n const index = this.artifacts.indexOf(artifact);\n\n if (direction == \"up\" && history.entries[index]?.id == artifact.migration.id) return;\n if ((direction == \"up\" ? history.entries.length : history.entries.length - 1) != index)\n throw new Error(\"Migration predecessor changed\");\n\n const before = tx.getCollectionDefinitions();\n\n await (direction == \"up\" ? artifact.migration.up : artifact.migration.down!)(\n createMigrationContext(tx),\n );\n\n const after = new Map(tx.getCollectionDefinitions().map((schema) => [schema.name, schema]));\n\n if (\n !options.allowDestructive &&\n before.some(\n (schema) =>\n !after.has(schema.name) ||\n Object.keys(schema.fields ?? {}).some(\n (name) => !Object.hasOwn(after.get(schema.name)?.fields ?? {}, name),\n ),\n )\n )\n throw new Error(\"Destructive schema change requires explicit authorization\");\n\n if (\n schemaHash(before.filter((schema) => !this.managedNames.has(schema.name))) !=\n schemaHash([...after.values()].filter((schema) => !this.managedNames.has(schema.name)))\n )\n throw new Error(\"Migration changed collections outside its snapshots\");\n\n this.assertSchema(\n tx,\n direction == \"up\" ? artifact.snapshot : this.artifacts[index - 1]?.snapshot,\n );\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries:\n direction == \"up\"\n ? [...history.entries, this.entry(artifact, index + 1, operationId)]\n : history.entries.slice(0, -1),\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, direction, artifact);\n }\n }\n\n private async reconcile(\n error: unknown,\n operationId: string,\n direction: \"up\" | \"down\",\n artifact: MigrationArtifact,\n ): Promise<void> {\n if (\n !(error instanceof TransactionConflictError) &&\n !(error instanceof CommitOutcomeUnknownError)\n )\n throw error;\n\n const history = await this.database.transaction((tx) => this.validate(tx));\n\n if (\n history.revision == operationId ||\n (direction == \"up\" &&\n history.entries.some(\n (entry) => entry.id == artifact.migration.id && entry.checksum == artifact.checksum,\n ))\n )\n return;\n\n if (\n error instanceof CommitOutcomeUnknownError &&\n (await this.database.getCommitStatus(error.transactionId)) == \"committed\"\n )\n return;\n\n throw error;\n }\n}\n"],"mappings":";;;AAGA,SAAgB,cAAc,OAAwB;CACpD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;CAExE,IAAI,SAAS,OAAO,SAAS,UAC3B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC,CAClC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,GAAG,OAAO,GA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D;EAEF,MAAM;CACR;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duraxis/migrations",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Transactional schema migrations for Duraxis.",
5
5
  "license": "ISC",
6
6
  "author": "João Paulo Dias <joaopdias.dev@gmail.com>",
@@ -46,11 +46,11 @@
46
46
  ],
47
47
  "sideEffects": false,
48
48
  "dependencies": {
49
- "@duraxis/core": "0.4.0"
49
+ "@duraxis/core": "0.6.0"
50
50
  },
51
51
  "devDependencies": {
52
- "@duraxis/storage-memory": "0.2.0",
53
- "@duraxis/storage-disk": "0.2.0"
52
+ "@duraxis/storage-memory": "0.2.1",
53
+ "@duraxis/storage-disk": "0.3.0"
54
54
  },
55
55
  "scripts": {
56
56
  "build": "vite build && tsc -p tsconfig.build.json",