@duraxis/cli 0.0.0-stage → 0.2.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 +18 -0
- package/LICENSE +15 -0
- package/README.md +286 -2
- package/dist/artifacts.d.ts +17 -0
- package/dist/bin.js +10 -0
- package/dist/cli.d.ts +6 -0
- package/dist/config.d.ts +22 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +578 -0
- package/dist/index.js.map +1 -0
- package/dist/runtime.mjs +15 -0
- package/dist/typescript-loader.d.ts +4 -0
- package/package.json +66 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# @duraxis/cli
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- eb56e40: Add transactional collection alteration/removal, final-schema validation, schema-aware index rebuilding, and protected subsystem metadata. Add standalone ORM schema export and opt-in strict managed validation. Introduce the migration runtime and CLI with snapshots, schema comparison, atomic history, conservative rollback, baseline adoption, and recovery-aware publication. Document deployment sequencing and transaction memory limits.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [eb56e40]
|
|
12
|
+
- @duraxis/core@0.3.0
|
|
13
|
+
- @duraxis/orm@0.3.0
|
|
14
|
+
- @duraxis/migrations@0.2.0
|
|
15
|
+
|
|
16
|
+
## 0.1.0
|
|
17
|
+
|
|
18
|
+
Initial migration tooling.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 João Paulo Dias
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
10
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
11
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
12
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
13
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
14
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
15
|
+
PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,287 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @duraxis/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Standalone Duraxis migration tooling. Node.js 24.15.0 or newer is required. The CLI builds on
|
|
4
|
+
`@duraxis/migrations` and the ORM's database-independent schema exporter.
|
|
5
|
+
|
|
6
|
+
## Quick start
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pnpm add @duraxis/core @duraxis/orm @duraxis/migrations @duraxis/storage-disk
|
|
10
|
+
pnpm add -D @duraxis/cli
|
|
11
|
+
pnpm exec duraxis init
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Edit the generated config to import your decorated entities and open your storage:
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
import { defineDuraxisConfig } from "@duraxis/cli";
|
|
19
|
+
import { DuraxisDatabase } from "@duraxis/core";
|
|
20
|
+
import { AsyncDiskStorageDriver } from "@duraxis/storage-disk";
|
|
21
|
+
import { User } from "./src/entities/user.entity.js";
|
|
22
|
+
|
|
23
|
+
export default defineDuraxisConfig({
|
|
24
|
+
entities: [User],
|
|
25
|
+
migrations: {
|
|
26
|
+
directory: "./duraxis/migrations",
|
|
27
|
+
snapshots: "./duraxis/snapshots",
|
|
28
|
+
format: "ts",
|
|
29
|
+
},
|
|
30
|
+
async createDatabase() {
|
|
31
|
+
const storage = await AsyncDiskStorageDriver.open({
|
|
32
|
+
directory: fileURLToPath(new URL("./data/duraxis", import.meta.url)),
|
|
33
|
+
});
|
|
34
|
+
return new DuraxisDatabase({ storage });
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pnpm exec duraxis migration:generate initial-schema
|
|
41
|
+
pnpm exec duraxis migrate:up
|
|
42
|
+
# Modify entity definitions to add an optional status column.
|
|
43
|
+
pnpm exec duraxis migration:generate add-user-status
|
|
44
|
+
pnpm exec duraxis migrate:diff
|
|
45
|
+
pnpm exec duraxis migrate:up
|
|
46
|
+
pnpm exec duraxis migrate:status
|
|
47
|
+
pnpm exec duraxis migrate:check
|
|
48
|
+
pnpm exec duraxis migrate:down --yes
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Generated rollback rejects populated fields or collections it would remove. For
|
|
52
|
+
production, review generated files, constraints, data transformations, and backups
|
|
53
|
+
before applying or reverting. Never edit a shared or applied migration.
|
|
54
|
+
|
|
55
|
+
Without a local installation, use the scoped package name explicitly:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
npx --package @duraxis/cli duraxis --help
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
An unscoped `npx duraxis` does not identify this package. Install the dev dependency
|
|
62
|
+
before using `pnpm exec duraxis`.
|
|
63
|
+
|
|
64
|
+
## Configuration and loading
|
|
65
|
+
|
|
66
|
+
Discovery walks from the working directory upward for `duraxis.config.ts`,
|
|
67
|
+
`duraxis.config.mts`, `duraxis.config.js`, `duraxis.config.mjs`,
|
|
68
|
+
`duraxis.config.cts`, or `duraxis.config.cjs`. `--config <path>` overrides discovery.
|
|
69
|
+
Migration and snapshot directories resolve relative to the config file. Paths
|
|
70
|
+
inside your database factory are your responsibility; use `import.meta.url` as
|
|
71
|
+
above instead of depending on the command's working directory.
|
|
72
|
+
|
|
73
|
+
`entities` accepts a class array or an async factory returning classes, allowing
|
|
74
|
+
project-specific entity discovery. `migrations.format` is `ts` (default) or `js`.
|
|
75
|
+
A `databases` object can hold named connection configs with the same three fields
|
|
76
|
+
(`entities`, `migrations`, `createDatabase`). Select one with `--database <name>`;
|
|
77
|
+
the top-level connection is the default.
|
|
78
|
+
|
|
79
|
+
The factory returns an owned Core database, not a NestJS connection. The CLI closes
|
|
80
|
+
that database and storage in a `finally` block. Factories must clean up resources
|
|
81
|
+
if they fail before returning. Do not pass an application-owned connection to
|
|
82
|
+
this CLI API; use the programmatic runner for that scenario.
|
|
83
|
+
|
|
84
|
+
Duraxis registers synchronous Node.js `registerHooks()` before loading a config,
|
|
85
|
+
entity, or migration, including programmatic `loadConfig()` calls. No manual
|
|
86
|
+
loader registration, experimental Node flags, or extra runtime transpiler is
|
|
87
|
+
required. Native type stripping alone cannot implement legacy decorators.
|
|
88
|
+
|
|
89
|
+
Supported configuration formats are `.ts`, `.mts`, `.js`, `.mjs`, `.cts`, and
|
|
90
|
+
`.cjs`. Discovery checks those extensions in that order. `.ts` and `.mts` source
|
|
91
|
+
modules execute as ESM; `.cts` uses CommonJS. JavaScript keeps Node's ordinary
|
|
92
|
+
package/module semantics. Executable migration artifacts support ESM `.ts`,
|
|
93
|
+
`.mts`, `.js`, and `.mjs`; CommonJS migration artifacts are unsupported because
|
|
94
|
+
their executable form does not share the ESM checksum identity contract.
|
|
95
|
+
|
|
96
|
+
Standard Node resolution runs first. Only missing local relative/file-URL imports
|
|
97
|
+
in module graphs loaded by Duraxis receive source-extension fallbacks:
|
|
98
|
+
`.js` → `.ts`, `.mjs` → `.mts`, `.cjs` → `.cts`. Existing JavaScript wins. Bare
|
|
99
|
+
packages, package exports, built-ins, and dependencies under `node_modules` are
|
|
100
|
+
left to Node. Missing dependencies and execution errors propagate without retrying
|
|
101
|
+
another source module. Direct TypeScript imports, nested and dynamic imports,
|
|
102
|
+
file URLs, spaces, and Unicode filesystem names work through the same path.
|
|
103
|
+
|
|
104
|
+
The production dependency TypeScript 5.9.3 transpiles source with ES2022 output,
|
|
105
|
+
`experimentalDecorators: true`, `emitDecoratorMetadata: true`, and
|
|
106
|
+
`useDefineForClassFields: false`. Reflective metadata consumers must load their
|
|
107
|
+
usual `reflect-metadata` dependency before decorated modules. Entity columns
|
|
108
|
+
should declare their Core `type` explicitly. `tsconfig.json` path aliases,
|
|
109
|
+
custom compiler plugins, `.tsx`/`.jsx`, and TypeScript package sources inside
|
|
110
|
+
`node_modules` are not supported. Use relative imports or published package exports.
|
|
111
|
+
When using a CommonJS config, load decorated entities and Duraxis connections
|
|
112
|
+
from ESM with native dynamic imports. Mixing independent ESM and CommonJS copies
|
|
113
|
+
of ORM decorators/Core constructors is unsupported; the CLI executes as ESM.
|
|
114
|
+
Config files and migrations are trusted executable code; keep module initialization
|
|
115
|
+
free of database writes and external side effects.
|
|
116
|
+
|
|
117
|
+
Programmatic use needs no executable bootstrap:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { loadConfig, disposeTypeScriptLoader } from "@duraxis/cli";
|
|
121
|
+
const { config } = await loadConfig(process.cwd());
|
|
122
|
+
// Use config and its asynchronous entity/migration callbacks here.
|
|
123
|
+
disposeTypeScriptLoader();
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
A library instance registers one hook pair, reuses it for repeated calls, and
|
|
127
|
+
tracks only explicitly loaded local module graphs. Hooks stay active for later
|
|
128
|
+
dynamic imports from those graphs. Call `disposeTypeScriptLoader()` when callbacks
|
|
129
|
+
no longer need them; it deregisters the hooks. Later loads initialize a new pair.
|
|
130
|
+
Graph tracking and Node's module cache remain in effect so cached callbacks keep
|
|
131
|
+
working after reinitialization. This is not a watch-mode/hot-reload facility. The CommonJS entry uses Node 24 require(ESM),
|
|
132
|
+
so both programmatic exports share the same implementation and hook state.
|
|
133
|
+
|
|
134
|
+
Local generation, local diff, offline check, and dry-run never call the database
|
|
135
|
+
factory. Other commands open the configured database. Disk requires exclusive
|
|
136
|
+
directory ownership: stop the application or use deployment sequencing that
|
|
137
|
+
releases that directory before invoking the CLI.
|
|
138
|
+
|
|
139
|
+
## Commands
|
|
140
|
+
|
|
141
|
+
Every command supports `--config`, `--database`, and `--json`. Unknown options and
|
|
142
|
+
options inappropriate for a command are errors. Errors exit with code 1; success
|
|
143
|
+
exits 0. `--json` emits machine-readable success results for inspection commands
|
|
144
|
+
and JSON errors on stderr. No command requires an interactive prompt.
|
|
145
|
+
|
|
146
|
+
| Command | Behavior and options |
|
|
147
|
+
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
148
|
+
| `init` | Creates a config, migration/snapshot directories, and an empty `baseline.json`; refuses existing files. Does not modify application source. |
|
|
149
|
+
| `migration:create <name>` | Creates a throwing manual template. Complete it and provide an expected snapshot before use. |
|
|
150
|
+
| `migration:snapshot --schema <file>` | Saves an intended snapshot for the latest manual migration from a JSON array of Core collection definitions. Never overwrites a snapshot. Application verifies the result atomically. |
|
|
151
|
+
| `migration:generate <name>` | Compares the latest local snapshot with exported entities and generates a self-contained migration/snapshot pair. No file on no-change. `--allow-destructive` authorizes generating removals. |
|
|
152
|
+
| `migration:remove --yes` | Removes the latest unpublished local migration and its snapshot after proving it is unapplied to this configured database. Also accepts an unfinished latest template. |
|
|
153
|
+
| `migration:baseline <name> --yes` | Adopts an existing matching managed catalog without reapplying creation. Creates initial artifacts, or validates and registers a single unmodified generated initial artifact. |
|
|
154
|
+
| `migrate:up` | Applies pending versions in ascending order, one transaction each. `--steps N` or `--to ID` (inclusive); `--allow-destructive` for schema removal. |
|
|
155
|
+
| `migrate:up --dry-run` | Static local artifact preview; does not open the target database or execute callbacks. Applied/pending status is explicitly unknown. Supports `--steps` or `--to`. |
|
|
156
|
+
| `migrate:down --yes` | Reverts the latest version; `--steps N` or `--to ID`. `--to` **retains** the target and reverts later versions. Requires usable `down()` implementations. |
|
|
157
|
+
| `migrate:status` | Displays applied/pending versions and validates checksums, history, snapshots, and managed catalog drift. Integrity failures exit nonzero. |
|
|
158
|
+
| `migrate:diff` | Compares the latest local snapshot with current entities. `--persisted` instead compares the applied expected snapshot with persisted managed catalog in one transaction, while checking history integrity. |
|
|
159
|
+
| `migrate:check` | Checks local artifacts, snapshots, chain, applied checksums, managed drift, and unrepresented entity changes. `--offline` excludes database/history checks. |
|
|
160
|
+
|
|
161
|
+
`steps` and `to` are mutually exclusive. Names are sanitized to lowercase
|
|
162
|
+
underscore-separated names; paths and traversal components are rejected. IDs use
|
|
163
|
+
UTC milliseconds and advance beyond the latest local timestamp on collisions.
|
|
164
|
+
Exclusive filesystem creation prevents overwrites. Concurrent development branches
|
|
165
|
+
can produce divergent parents: rebase and regenerate unpublished branches before
|
|
166
|
+
release. There is no automatic history merge.
|
|
167
|
+
|
|
168
|
+
## Automatic and manual migrations
|
|
169
|
+
|
|
170
|
+
Generation uses snapshots, not an arbitrary development database. Entity metadata
|
|
171
|
+
is desired schema; snapshots are versioned expected schema; migration files are
|
|
172
|
+
executable changes; the persisted catalog and internal history are actual state.
|
|
173
|
+
Generated files embed definitions and never import current entities. Plans stage
|
|
174
|
+
the final catalog graph atomically, supporting circular foreign keys.
|
|
175
|
+
|
|
176
|
+
Type changes and newly required fields on existing collections require explicit
|
|
177
|
+
manual transformations, so generation rejects them. It does not infer renames.
|
|
178
|
+
Use `migration:create` and write `context.schema.renameField`, backfills, or other
|
|
179
|
+
transformations. For example:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { defineMigration } from "@duraxis/migrations";
|
|
183
|
+
export default defineMigration({
|
|
184
|
+
id: "20261127110000000_add_status", // Use the generated filename's ID.
|
|
185
|
+
async up(context) {
|
|
186
|
+
context.schema.addField("users", "status", { type: "string", required: true });
|
|
187
|
+
await context.transform("users", (document) => ({ ...document, status: "active" }));
|
|
188
|
+
},
|
|
189
|
+
// Omit down when values cannot be safely restored.
|
|
190
|
+
});
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Prepare a complete JSON array of intended managed collection definitions, then run:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
pnpm exec duraxis migration:snapshot --schema expected-schema.json
|
|
197
|
+
pnpm exec duraxis migrate:up
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The supplied snapshot is an intention, not proof that a manual callback is correct.
|
|
201
|
+
The runner verifies the actual resulting catalog hash before publication; Core
|
|
202
|
+
then validates existing documents, constraints, and indexes. A throwing template
|
|
203
|
+
or mismatched schema cannot acquire an applied history entry.
|
|
204
|
+
|
|
205
|
+
Generated removal of a field rejects existing values, even with
|
|
206
|
+
`--allow-destructive`; write an explicit `removeField` with `delete-values` to
|
|
207
|
+
acknowledge data loss. Generated collection drops have no automatic rollback.
|
|
208
|
+
Generated inverses for field/collection creation reject populated data. Unique
|
|
209
|
+
index creation validates duplicates; constraint failures roll back the version.
|
|
210
|
+
|
|
211
|
+
## Snapshots and immutable identity
|
|
212
|
+
|
|
213
|
+
Commit all migration files and snapshots, including the empty baseline. Every
|
|
214
|
+
migration must have one snapshot with matching ID, parent, and hash. Duplicate
|
|
215
|
+
TS/JS copies, missing applied files, orphan snapshots, incompatible formats,
|
|
216
|
+
checksum mismatches, and divergent chains are rejected. Production should contain
|
|
217
|
+
one executable format per migration, not both `.ts` and `.js` copies.
|
|
218
|
+
|
|
219
|
+
Artifact checksums normalize executable code with pinned TypeScript 5.9.3 (two
|
|
220
|
+
passes, ES2022 ESM, comments removed, legacy decorators, metadata enabled,
|
|
221
|
+
`useDefineForClassFields: false`). Compiled migrations must preserve this target
|
|
222
|
+
and ESM module form. Comments/types/formatting do not change identity; executable
|
|
223
|
+
edits do. External helper content is not transitively hashed: keep historical
|
|
224
|
+
migrations self-contained and pin unavoidable dependencies. Do not bundle,
|
|
225
|
+
minify, or downlevel production migrations. Snapshots and IDs accompany compiled
|
|
226
|
+
files unchanged. The packed consumer test verifies this deployment path.
|
|
227
|
+
|
|
228
|
+
## Existing databases and recovery
|
|
229
|
+
|
|
230
|
+
Baseline compares only entity-owned collections, permits unrelated collections,
|
|
231
|
+
and registers the initial generated schema in the same transaction that verifies
|
|
232
|
+
its persisted definitions. The same initial migration creates the schema on a new
|
|
233
|
+
empty database. Baseline refuses incompatible catalogs or existing history. If
|
|
234
|
+
registration fails after files were written, retain those files; rerun the
|
|
235
|
+
baseline command to validate the single generated initial artifact and register
|
|
236
|
+
it, provided persisted history is still empty. If history is already recorded,
|
|
237
|
+
inspect `migrate:status` instead.
|
|
238
|
+
|
|
239
|
+
History lives in protected transactional Core metadata, never a local JSON history
|
|
240
|
+
file. CAS publication coordinates runners across processes. Conflicts reload
|
|
241
|
+
history; identical committed versions are accepted and arbitrary callbacks are
|
|
242
|
+
never automatically replayed. Unknown publication outcomes are reconciled against
|
|
243
|
+
persisted receipts and Core recovery; inconclusive outcomes stop safely. Do not
|
|
244
|
+
assume an unknown outcome rolled back. Restore storage availability and inspect
|
|
245
|
+
status before further action. Checkpoints do not invalidate persisted receipts.
|
|
246
|
+
|
|
247
|
+
Generation/removal uses an exclusive `.duraxis-artifacts.lock` guard. Ordinary
|
|
248
|
+
pair-write failures remove the newly created migration. Removal renames both files
|
|
249
|
+
before deleting either. A process crash may leave the guard, a partial pair, or
|
|
250
|
+
`.removing-*` tombstones. Stop other writers, inspect/recover the intended pair
|
|
251
|
+
from version control or tombstones, verify the snapshot chain, then remove the
|
|
252
|
+
stale guard and run `migrate:check`. Filesystem pair updates are not a power-loss
|
|
253
|
+
atomic database transaction. Never remove guards automatically based on age.
|
|
254
|
+
|
|
255
|
+
Checking one configured database cannot prove a migration was never applied in
|
|
256
|
+
another environment. Never remove shared or released migrations. Checksums have
|
|
257
|
+
no default bypass flag. Rollback runs explicit transactional code against current
|
|
258
|
+
data; it never restores an old manifest or discards unrelated later writes.
|
|
259
|
+
|
|
260
|
+
## Deployment and CI
|
|
261
|
+
|
|
262
|
+
```bash
|
|
263
|
+
pnpm exec duraxis migrate:check --offline
|
|
264
|
+
pnpm exec duraxis migrate:up
|
|
265
|
+
pnpm exec duraxis migrate:check
|
|
266
|
+
# Start the application only after successful validation.
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Ship the CLI in the migration job's image even when application dev dependencies
|
|
270
|
+
are omitted. For disk, release exclusive storage ownership before the job. For
|
|
271
|
+
S3, use the existing driver's conditional publication and namespace configuration;
|
|
272
|
+
ordinary application writers are not locked out by migrations. Quiesce writers
|
|
273
|
+
for incompatible changes. Use one deployment job, backups, and representative
|
|
274
|
+
pre-production data. Do not depend on process-local locks across replicas.
|
|
275
|
+
|
|
276
|
+
For NestJS, run migrations before application initialization with
|
|
277
|
+
`schema: { mode: "validate" }`, or `validate-managed` to reject extra indexes in
|
|
278
|
+
managed collections. No mandatory CLI dependency or automatic startup migration
|
|
279
|
+
is added to NestJS. Existing named connections, `forRootAsync`, entity auto-loading,
|
|
280
|
+
and transaction ownership are unchanged. Stop incompatible older replicas before
|
|
281
|
+
schema changes; use staged compatible releases for rolling deployments.
|
|
282
|
+
|
|
283
|
+
All transformed writes and affected-schema validation writes are staged in memory
|
|
284
|
+
until one atomic commit. Streaming reads do not provide bounded transaction size.
|
|
285
|
+
There is no online DDL, resumable batching, distributed maintenance lock, or
|
|
286
|
+
implicit partial migration commit. See [`@duraxis/migrations`](../migrations/README.md)
|
|
287
|
+
for the programmatic API, recovery guarantees, and Core compatibility details.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type MigrationArtifact, type SchemaSnapshot, type SchemaPlan } from "@duraxis/migrations";
|
|
2
|
+
import type { CollectionDefinition } from "@duraxis/core";
|
|
3
|
+
import { type DuraxisConnectionConfig } from "./config.js";
|
|
4
|
+
export declare function artifactChecksum(source: string): string;
|
|
5
|
+
export interface LocalArtifacts {
|
|
6
|
+
readonly artifacts: readonly MigrationArtifact[];
|
|
7
|
+
readonly files: readonly string[];
|
|
8
|
+
readonly snapshots: string;
|
|
9
|
+
readonly directory: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function loadArtifacts(config: DuraxisConnectionConfig, root: string, ownsLock?: boolean, omitLatest?: boolean): Promise<LocalArtifacts>;
|
|
12
|
+
export declare function migrationId(name: string, previous?: string): string;
|
|
13
|
+
export declare function renderMigration(id: string, plan?: SchemaPlan): string;
|
|
14
|
+
export declare function withArtifactLock<T>(directory: string, callback: () => Promise<T>): Promise<T>;
|
|
15
|
+
export declare function writePair(migrationPath: string, source: string, snapshotPath: string, snapshot: SchemaSnapshot): Promise<void>;
|
|
16
|
+
export declare function removePair(migrationPath: string, snapshotPath: string): Promise<void>;
|
|
17
|
+
export declare function snapshotFor(id: string, parent: string | null, schema: readonly CollectionDefinition[]): SchemaSnapshot;
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { assertSupportedRuntime } from "./runtime.mjs";
|
|
3
|
+
try {
|
|
4
|
+
assertSupportedRuntime();
|
|
5
|
+
const { runCLI } = await import("./index.js");
|
|
6
|
+
process.exitCode = await runCLI(process.argv.slice(2));
|
|
7
|
+
} catch (error) {
|
|
8
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { DuraxisDatabase } from "@duraxis/core";
|
|
2
|
+
import type { EntityClass } from "@duraxis/orm";
|
|
3
|
+
export interface DuraxisConnectionConfig {
|
|
4
|
+
readonly entities: readonly EntityClass[] | (() => readonly EntityClass[] | Promise<readonly EntityClass[]>);
|
|
5
|
+
readonly migrations: {
|
|
6
|
+
readonly directory: string;
|
|
7
|
+
readonly snapshots: string;
|
|
8
|
+
readonly format?: "ts" | "js";
|
|
9
|
+
};
|
|
10
|
+
readonly createDatabase: () => DuraxisDatabase | Promise<DuraxisDatabase>;
|
|
11
|
+
}
|
|
12
|
+
export interface DuraxisConfig extends DuraxisConnectionConfig {
|
|
13
|
+
readonly databases?: Readonly<Record<string, DuraxisConnectionConfig>>;
|
|
14
|
+
}
|
|
15
|
+
export declare function defineDuraxisConfig<const T extends DuraxisConfig>(config: T): T;
|
|
16
|
+
export declare function importFile(path: string | URL): Promise<unknown>;
|
|
17
|
+
export declare function loadConfig(cwd: string, explicit?: string, database?: string): Promise<{
|
|
18
|
+
config: DuraxisConnectionConfig;
|
|
19
|
+
root: string;
|
|
20
|
+
path: string;
|
|
21
|
+
}>;
|
|
22
|
+
export declare function readJSON<T>(path: string): Promise<T>;
|
package/dist/index.cjs
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { runCLI } from "./cli.js";
|
|
2
|
+
export type { CLIIO } from "./cli.js";
|
|
3
|
+
export { defineDuraxisConfig, loadConfig } from "./config.js";
|
|
4
|
+
export type { DuraxisConfig, DuraxisConnectionConfig } from "./config.js";
|
|
5
|
+
export { disposeTypeScriptLoader } from "./typescript-loader.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { access, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
4
|
+
import { exportSchema } from "@duraxis/orm";
|
|
5
|
+
import { MigrationRunner, canonicalJSON, checksum, createSnapshot, diffSchemas, schemaHash, validateArtifacts, validateMigrationId, validateSnapshot } from "@duraxis/migrations";
|
|
6
|
+
import { readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { registerHooks } from "node:module";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
import ts from "typescript";
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
// src/runtime.mjs
|
|
12
|
+
var MINIMUM_NODE_VERSION = "24.15.0";
|
|
13
|
+
/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */
|
|
14
|
+
function assertSupportedRuntime(version = process.versions.node) {
|
|
15
|
+
const actual = version.split(".").map(Number);
|
|
16
|
+
const minimum = MINIMUM_NODE_VERSION.split(".").map(Number);
|
|
17
|
+
const difference = actual.findIndex((part, index) => part !== minimum[index]);
|
|
18
|
+
if (!(/^\d+\.\d+\.\d+$/.test(version) && (difference === -1 || actual[difference] > minimum[difference]))) throw new Error(`Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\nCurrent version: ${version}\nPlease upgrade your Node.js installation.`);
|
|
19
|
+
}
|
|
20
|
+
// src/typescript-loader.ts
|
|
21
|
+
var sourceExtensions = {
|
|
22
|
+
".js": ".ts",
|
|
23
|
+
".mjs": ".mts",
|
|
24
|
+
".cjs": ".cts"
|
|
25
|
+
};
|
|
26
|
+
var hooks;
|
|
27
|
+
var modules = /* @__PURE__ */ new Set();
|
|
28
|
+
function localFile(value) {
|
|
29
|
+
if (!value.startsWith("file:")) return;
|
|
30
|
+
const url = new URL(value);
|
|
31
|
+
if (fileURLToPath(url).split(/[\\/]/).includes("node_modules")) return;
|
|
32
|
+
return url;
|
|
33
|
+
}
|
|
34
|
+
function exists(url) {
|
|
35
|
+
try {
|
|
36
|
+
return statSync(url).isFile();
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (["ENOENT", "ENOTDIR"].includes(error.code ?? "")) return false;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function remember(url) {
|
|
43
|
+
if (localFile(url)) modules.add(url);
|
|
44
|
+
}
|
|
45
|
+
/** One hook pair per library instance, limited to explicitly loaded local module graphs. */
|
|
46
|
+
function initializeTypeScriptLoader(entry) {
|
|
47
|
+
assertSupportedRuntime();
|
|
48
|
+
remember(entry.href);
|
|
49
|
+
if (hooks) return;
|
|
50
|
+
hooks = registerHooks({
|
|
51
|
+
resolve(specifier, context, nextResolve) {
|
|
52
|
+
const managed = /^(?:\.{1,2}[\\/]|\/|file:)/.test(specifier) && (modules.has(specifier) || context.parentURL !== void 0 && modules.has(context.parentURL));
|
|
53
|
+
try {
|
|
54
|
+
const resolved = nextResolve(specifier, context);
|
|
55
|
+
if (managed) remember(resolved.url);
|
|
56
|
+
return resolved;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (!managed || !["ERR_MODULE_NOT_FOUND", "MODULE_NOT_FOUND"].includes(error.code ?? "")) throw error;
|
|
59
|
+
const requested = localFile(new URL(specifier, context.parentURL).href);
|
|
60
|
+
if (!requested || exists(requested)) throw error;
|
|
61
|
+
const path = fileURLToPath(requested);
|
|
62
|
+
const extension = extname(path);
|
|
63
|
+
const mapped = sourceExtensions[extension];
|
|
64
|
+
if (!mapped) throw error;
|
|
65
|
+
const candidate = pathToFileURL(path.slice(0, -extension.length) + mapped);
|
|
66
|
+
candidate.search = requested.search;
|
|
67
|
+
candidate.hash = requested.hash;
|
|
68
|
+
if (!exists(candidate)) throw error;
|
|
69
|
+
const resolved = nextResolve(context.conditions.includes("require") ? fileURLToPath(candidate) : candidate.href, context);
|
|
70
|
+
remember(resolved.url);
|
|
71
|
+
return resolved;
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
load(url, context, nextLoad) {
|
|
75
|
+
if (!modules.has(url)) return nextLoad(url, context);
|
|
76
|
+
const file = localFile(url);
|
|
77
|
+
if (!file) return nextLoad(url, context);
|
|
78
|
+
const path = fileURLToPath(file);
|
|
79
|
+
if (!/\.(?:ts|mts|cts)$/.test(path) || /\.d\.(?:ts|mts|cts)$/.test(path)) return nextLoad(url, context);
|
|
80
|
+
const commonjs = path.endsWith(".cts");
|
|
81
|
+
const result = ts.transpileModule(readFileSync(file, "utf8"), {
|
|
82
|
+
fileName: path,
|
|
83
|
+
reportDiagnostics: true,
|
|
84
|
+
compilerOptions: {
|
|
85
|
+
target: ts.ScriptTarget.ES2022,
|
|
86
|
+
module: commonjs ? ts.ModuleKind.NodeNext : ts.ModuleKind.ESNext,
|
|
87
|
+
...commonjs ? { moduleResolution: ts.ModuleResolutionKind.NodeNext } : {},
|
|
88
|
+
experimentalDecorators: true,
|
|
89
|
+
emitDecoratorMetadata: true,
|
|
90
|
+
useDefineForClassFields: false,
|
|
91
|
+
sourceMap: false
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
const errors = (result.diagnostics ?? []).filter((item) => item.category == ts.DiagnosticCategory.Error);
|
|
95
|
+
if (errors.length) throw new Error(ts.formatDiagnosticsWithColorAndContext(errors, {
|
|
96
|
+
getCurrentDirectory: () => process.cwd(),
|
|
97
|
+
getCanonicalFileName: (file) => file,
|
|
98
|
+
getNewLine: () => "\n"
|
|
99
|
+
}));
|
|
100
|
+
return {
|
|
101
|
+
format: commonjs ? "commonjs" : "module",
|
|
102
|
+
source: (commonjs ? "\"use strict\";\nrequire = require(\"node:module\").createRequire(__filename);\n" : "") + result.outputText,
|
|
103
|
+
shortCircuit: true
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */
|
|
109
|
+
function disposeTypeScriptLoader() {
|
|
110
|
+
hooks?.deregister();
|
|
111
|
+
hooks = void 0;
|
|
112
|
+
}
|
|
113
|
+
// src/config.ts
|
|
114
|
+
function defineDuraxisConfig(config) {
|
|
115
|
+
return config;
|
|
116
|
+
}
|
|
117
|
+
async function importFile(path) {
|
|
118
|
+
const url = path instanceof URL ? path : pathToFileURL(path);
|
|
119
|
+
initializeTypeScriptLoader(url);
|
|
120
|
+
return import(url.href);
|
|
121
|
+
}
|
|
122
|
+
async function loadConfig(cwd, explicit, database) {
|
|
123
|
+
let path;
|
|
124
|
+
if (explicit) path = resolve(cwd, explicit);
|
|
125
|
+
else {
|
|
126
|
+
let directory = resolve(cwd);
|
|
127
|
+
while (true) {
|
|
128
|
+
for (const name of [
|
|
129
|
+
"duraxis.config.ts",
|
|
130
|
+
"duraxis.config.mts",
|
|
131
|
+
"duraxis.config.js",
|
|
132
|
+
"duraxis.config.mjs",
|
|
133
|
+
"duraxis.config.cts",
|
|
134
|
+
"duraxis.config.cjs"
|
|
135
|
+
]) {
|
|
136
|
+
const candidate = resolve(directory, name);
|
|
137
|
+
try {
|
|
138
|
+
await access(candidate);
|
|
139
|
+
path = candidate;
|
|
140
|
+
break;
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error.code != "ENOENT") throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (path || dirname(directory) == directory) break;
|
|
146
|
+
directory = dirname(directory);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!path) throw new Error("No duraxis.config.ts or JavaScript configuration found");
|
|
150
|
+
const base = (await importFile(path)).default;
|
|
151
|
+
const config = database ? base?.databases?.[database] : base;
|
|
152
|
+
if (!config || typeof config.createDatabase != "function" || !Array.isArray(config.entities) && typeof config.entities != "function" || typeof config.migrations?.directory != "string" || typeof config.migrations.snapshots != "string" || config.migrations.format !== void 0 && !["ts", "js"].includes(config.migrations.format)) throw new Error("Invalid Duraxis configuration or unknown named database");
|
|
153
|
+
return {
|
|
154
|
+
config,
|
|
155
|
+
root: dirname(path),
|
|
156
|
+
path
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
async function readJSON(path) {
|
|
160
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
161
|
+
}
|
|
162
|
+
// src/artifacts.ts
|
|
163
|
+
function artifactChecksum(source) {
|
|
164
|
+
const options = { compilerOptions: {
|
|
165
|
+
target: ts.ScriptTarget.ES2022,
|
|
166
|
+
module: ts.ModuleKind.ESNext,
|
|
167
|
+
removeComments: true,
|
|
168
|
+
newLine: ts.NewLineKind.LineFeed,
|
|
169
|
+
experimentalDecorators: true,
|
|
170
|
+
emitDecoratorMetadata: true,
|
|
171
|
+
useDefineForClassFields: false
|
|
172
|
+
} };
|
|
173
|
+
const first = ts.transpileModule(source, options).outputText;
|
|
174
|
+
return checksum(ts.transpileModule(first, options).outputText);
|
|
175
|
+
}
|
|
176
|
+
async function loadArtifacts(config, root, ownsLock = false, omitLatest = false) {
|
|
177
|
+
const directory = resolve(root, config.migrations.directory);
|
|
178
|
+
const snapshots = resolve(root, config.migrations.snapshots);
|
|
179
|
+
if (!ownsLock) try {
|
|
180
|
+
await access(join(directory, ".duraxis-artifacts.lock"));
|
|
181
|
+
throw new Error("Artifact update in progress or stale guard; inspect artifacts before removing the guard");
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (error.code != "ENOENT") throw error;
|
|
184
|
+
}
|
|
185
|
+
const files = (await readdir(directory)).filter((file) => /\.(ts|mts|js|mjs)$/.test(file) && !/\.d\.(?:ts|mts)$/.test(file)).sort();
|
|
186
|
+
const artifacts = [];
|
|
187
|
+
const ids = /* @__PURE__ */ new Set();
|
|
188
|
+
for (const file of files) {
|
|
189
|
+
const id = file.replace(/\.(ts|mts|js|mjs)$/, "");
|
|
190
|
+
validateMigrationId(id);
|
|
191
|
+
if (ids.has(id)) throw new Error(`Duplicate migration filename: ${id}`);
|
|
192
|
+
ids.add(id);
|
|
193
|
+
if (omitLatest && file == files.at(-1)) continue;
|
|
194
|
+
const source = await readFile(join(directory, file), "utf8");
|
|
195
|
+
const module = await importFile(join(directory, file));
|
|
196
|
+
if (module.default?.id != id) throw new Error(`Migration ID does not match filename: ${file}`);
|
|
197
|
+
const snapshot = await readJSON(join(snapshots, `${id}.json`));
|
|
198
|
+
validateSnapshot(snapshot);
|
|
199
|
+
artifacts.push({
|
|
200
|
+
migration: module.default,
|
|
201
|
+
checksum: artifactChecksum(source),
|
|
202
|
+
snapshot
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
const expected = new Set([...ids].map((id) => `${id}.json`));
|
|
206
|
+
for (const file of await readdir(snapshots)) if (file.endsWith(".json") && file != "baseline.json" && !expected.has(file)) throw new Error(`Orphaned snapshot: ${file}`);
|
|
207
|
+
const initial = await readJSON(join(snapshots, "baseline.json"));
|
|
208
|
+
validateSnapshot(initial);
|
|
209
|
+
if (initial.migrationId !== null || initial.parentMigrationId !== null || initial.collections.length) throw new Error("Invalid empty baseline snapshot");
|
|
210
|
+
validateArtifacts(artifacts);
|
|
211
|
+
return {
|
|
212
|
+
artifacts,
|
|
213
|
+
files,
|
|
214
|
+
snapshots,
|
|
215
|
+
directory
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function migrationId(name, previous) {
|
|
219
|
+
if (name.includes("..") || /[\\/]/.test(name)) throw new Error("Migration names cannot contain paths");
|
|
220
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
221
|
+
if (!slug || slug.length > 64) throw new Error("Invalid migration name");
|
|
222
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "");
|
|
223
|
+
const previousStamp = previous?.slice(0, 17);
|
|
224
|
+
return `${previousStamp && previousStamp >= stamp ? (BigInt(previousStamp) + 1n).toString().padStart(17, "0") : stamp}_${slug}`;
|
|
225
|
+
}
|
|
226
|
+
function literal(value) {
|
|
227
|
+
return JSON.stringify(value, null, 2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
228
|
+
}
|
|
229
|
+
function renderMigration(id, plan) {
|
|
230
|
+
if (!plan) return `import { defineMigration } from "@duraxis/migrations";\n\nexport default defineMigration({\n id: ${JSON.stringify(id)},\n async up(context) {\n throw new Error("Unfinished migration: implement up and provide its expected snapshot");\n },\n});\n`;
|
|
231
|
+
const inverse = diffSchemas(plan.after, plan.before);
|
|
232
|
+
const reversible = !plan.operations.some((operation) => operation.kind == "collection" && operation.after == null) && inverse.operations.every((operation) => operation.risk != "requires-data-transformation");
|
|
233
|
+
return `import { defineMigration, applySchemaPlan } from "@duraxis/migrations";\n\nexport default defineMigration({\n id: ${JSON.stringify(id)},\n async up(context) {\n await applySchemaPlan(context, ${literal(plan)});\n },\n${reversible ? ` async down(context) {\n${inverse.operations.filter((operation) => operation.kind == "collection" && operation.after == null).map((operation) => ` for await (const row of context.scan(${JSON.stringify(operation.collection)})) throw new Error("Cannot drop a populated collection during generated rollback");\n`).join("")} await applySchemaPlan(context, ${literal(inverse)});\n },\n` : " // Irreversible automatically: write an explicit data-safe down() if needed.\n"} });\n`;
|
|
234
|
+
}
|
|
235
|
+
async function withArtifactLock(directory, callback) {
|
|
236
|
+
await mkdir(directory, { recursive: true });
|
|
237
|
+
const lock = join(directory, ".duraxis-artifacts.lock");
|
|
238
|
+
await writeFile(lock, canonicalJSON({
|
|
239
|
+
pid: process.pid,
|
|
240
|
+
purpose: "artifact update; inspect files before removing a stale guard"
|
|
241
|
+
}), { flag: "wx" });
|
|
242
|
+
try {
|
|
243
|
+
return await callback();
|
|
244
|
+
} finally {
|
|
245
|
+
await unlink(lock);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
async function writePair(migrationPath, source, snapshotPath, snapshot) {
|
|
249
|
+
await mkdir(resolve(snapshotPath, ".."), { recursive: true });
|
|
250
|
+
await writeFile(migrationPath, source, { flag: "wx" });
|
|
251
|
+
try {
|
|
252
|
+
await writeFile(snapshotPath, JSON.stringify(snapshot, null, 2) + "\n", { flag: "wx" });
|
|
253
|
+
} catch (error) {
|
|
254
|
+
await unlink(migrationPath);
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
async function removePair(migrationPath, snapshotPath) {
|
|
259
|
+
const suffix = `.removing-${randomBytes(6).toString("hex")}`;
|
|
260
|
+
await rename(migrationPath, migrationPath + suffix);
|
|
261
|
+
try {
|
|
262
|
+
await rename(snapshotPath, snapshotPath + suffix);
|
|
263
|
+
} catch (error) {
|
|
264
|
+
await rename(migrationPath + suffix, migrationPath);
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
await unlink(migrationPath + suffix);
|
|
268
|
+
await unlink(snapshotPath + suffix);
|
|
269
|
+
}
|
|
270
|
+
// src/cli.ts
|
|
271
|
+
var help = `duraxis <command> [options]
|
|
272
|
+
init
|
|
273
|
+
migration:create <name>
|
|
274
|
+
migration:generate <name> [--allow-destructive]
|
|
275
|
+
migration:snapshot --schema <collections.json>
|
|
276
|
+
migration:remove --yes
|
|
277
|
+
migration:baseline <name> --yes
|
|
278
|
+
migrate:up [--steps N | --to ID] [--dry-run] [--allow-destructive]
|
|
279
|
+
migrate:down [--steps N | --to ID] --yes
|
|
280
|
+
migrate:status
|
|
281
|
+
migrate:diff [--persisted]
|
|
282
|
+
migrate:check [--offline]
|
|
283
|
+
Options: --config PATH --database NAME --json
|
|
284
|
+
Rollback --to retains the target version. Dry-run is a static preview only.`;
|
|
285
|
+
async function withDatabase(config, callback) {
|
|
286
|
+
const database = await config.createDatabase();
|
|
287
|
+
try {
|
|
288
|
+
return await callback(database);
|
|
289
|
+
} finally {
|
|
290
|
+
await database.close({ closeStorage: true });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
function summary(plan) {
|
|
294
|
+
return plan.operations.length ? plan.operations.map((operation) => `${operation.before == null ? "+" : operation.after == null ? "-" : "~"} ${operation.kind} ${operation.collection}/${operation.name} (${operation.risk})`).join("\n") : "No schema differences.";
|
|
295
|
+
}
|
|
296
|
+
async function init(cwd) {
|
|
297
|
+
const configPath = resolve(cwd, "duraxis.config.ts");
|
|
298
|
+
const base = resolve(cwd, "duraxis/snapshots/baseline.json");
|
|
299
|
+
for (const path of [configPath, base]) try {
|
|
300
|
+
await access(path);
|
|
301
|
+
throw new Error(`Refusing to overwrite ${path}`);
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (error.code != "ENOENT") throw error;
|
|
304
|
+
}
|
|
305
|
+
await mkdir(resolve(cwd, "duraxis/migrations"), { recursive: true });
|
|
306
|
+
await mkdir(resolve(cwd, "duraxis/snapshots"), { recursive: true });
|
|
307
|
+
await writeFile(configPath, `import { defineDuraxisConfig } from "@duraxis/cli";
|
|
308
|
+
|
|
309
|
+
export default defineDuraxisConfig({
|
|
310
|
+
entities: [], // Import your decorated entity classes here.
|
|
311
|
+
migrations: { directory: "./duraxis/migrations", snapshots: "./duraxis/snapshots", format: "ts" },
|
|
312
|
+
async createDatabase() {
|
|
313
|
+
// Return a DuraxisDatabase configured with your storage driver.
|
|
314
|
+
// The CLI closes this database and its storage after every command.
|
|
315
|
+
throw new Error("Configure createDatabase() before accessing a database");
|
|
316
|
+
},
|
|
317
|
+
});
|
|
318
|
+
`, { flag: "wx" });
|
|
319
|
+
try {
|
|
320
|
+
await writeFile(base, JSON.stringify(createSnapshot(null, null, []), null, 2) + "\n", { flag: "wx" });
|
|
321
|
+
} catch (error) {
|
|
322
|
+
await unlink(configPath);
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
async function runCLI(args, io = {}) {
|
|
327
|
+
const cwd = io.cwd ?? process.cwd();
|
|
328
|
+
const out = io.out ?? console.log;
|
|
329
|
+
const errorOut = io.error ?? console.error;
|
|
330
|
+
let jsonErrors = false;
|
|
331
|
+
try {
|
|
332
|
+
const { values, positionals } = parseArgs({
|
|
333
|
+
args: [...args],
|
|
334
|
+
allowPositionals: true,
|
|
335
|
+
strict: true,
|
|
336
|
+
options: {
|
|
337
|
+
config: { type: "string" },
|
|
338
|
+
database: { type: "string" },
|
|
339
|
+
json: { type: "boolean" },
|
|
340
|
+
steps: { type: "string" },
|
|
341
|
+
to: { type: "string" },
|
|
342
|
+
"dry-run": { type: "boolean" },
|
|
343
|
+
"allow-destructive": { type: "boolean" },
|
|
344
|
+
yes: { type: "boolean" },
|
|
345
|
+
offline: { type: "boolean" },
|
|
346
|
+
persisted: { type: "boolean" },
|
|
347
|
+
schema: { type: "string" },
|
|
348
|
+
help: { type: "boolean" }
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
jsonErrors = values.json ?? false;
|
|
352
|
+
const command = positionals[0];
|
|
353
|
+
const name = positionals[1];
|
|
354
|
+
if (!command || values.help) {
|
|
355
|
+
out(help);
|
|
356
|
+
return 0;
|
|
357
|
+
}
|
|
358
|
+
if (![
|
|
359
|
+
"init",
|
|
360
|
+
"migration:create",
|
|
361
|
+
"migration:generate",
|
|
362
|
+
"migration:snapshot",
|
|
363
|
+
"migration:remove",
|
|
364
|
+
"migration:baseline",
|
|
365
|
+
"migrate:up",
|
|
366
|
+
"migrate:down",
|
|
367
|
+
"migrate:status",
|
|
368
|
+
"migrate:diff",
|
|
369
|
+
"migrate:check"
|
|
370
|
+
].includes(command)) throw new Error(`Unknown command: ${command}`);
|
|
371
|
+
if (positionals.length > 2 || name && ![
|
|
372
|
+
"migration:create",
|
|
373
|
+
"migration:generate",
|
|
374
|
+
"migration:baseline"
|
|
375
|
+
].includes(command)) throw new Error("Unexpected positional arguments");
|
|
376
|
+
const allowed = {
|
|
377
|
+
init: [],
|
|
378
|
+
"migration:create": [],
|
|
379
|
+
"migration:generate": ["allow-destructive"],
|
|
380
|
+
"migration:snapshot": ["schema"],
|
|
381
|
+
"migration:remove": ["yes"],
|
|
382
|
+
"migration:baseline": ["yes"],
|
|
383
|
+
"migrate:up": [
|
|
384
|
+
"steps",
|
|
385
|
+
"to",
|
|
386
|
+
"dry-run",
|
|
387
|
+
"allow-destructive"
|
|
388
|
+
],
|
|
389
|
+
"migrate:down": [
|
|
390
|
+
"steps",
|
|
391
|
+
"to",
|
|
392
|
+
"yes"
|
|
393
|
+
],
|
|
394
|
+
"migrate:status": [],
|
|
395
|
+
"migrate:diff": ["persisted"],
|
|
396
|
+
"migrate:check": ["offline"]
|
|
397
|
+
};
|
|
398
|
+
for (const option of Object.keys(values)) if (![
|
|
399
|
+
"config",
|
|
400
|
+
"database",
|
|
401
|
+
"json",
|
|
402
|
+
"help",
|
|
403
|
+
...allowed[command]
|
|
404
|
+
].includes(option)) throw new Error(`Option --${option} is not supported by ${command}`);
|
|
405
|
+
if (command == "init") {
|
|
406
|
+
await init(cwd);
|
|
407
|
+
out("Initialized duraxis.config.ts and migration directories. Configure entities and createDatabase().");
|
|
408
|
+
return 0;
|
|
409
|
+
}
|
|
410
|
+
const { config, root } = await loadConfig(cwd, values.config, values.database);
|
|
411
|
+
const directory = resolve(root, config.migrations.directory);
|
|
412
|
+
const snapshots = resolve(root, config.migrations.snapshots);
|
|
413
|
+
const print = (value, text) => out(values.json ? JSON.stringify(value, null, 2) : text);
|
|
414
|
+
const entities = async () => exportSchema(typeof config.entities == "function" ? await config.entities() : config.entities);
|
|
415
|
+
if (command == "migration:snapshot") {
|
|
416
|
+
if (!values.schema) throw new Error("Provide --schema with a JSON array of expected collection definitions");
|
|
417
|
+
await withArtifactLock(directory, async () => {
|
|
418
|
+
const { readdir } = await import("node:fs/promises");
|
|
419
|
+
const files = (await readdir(directory)).filter((file) => /\.(ts|mts|js|mjs)$/.test(file) && !/\.d\.(?:ts|mts)$/.test(file)).sort();
|
|
420
|
+
const latest = files.at(-1);
|
|
421
|
+
if (!latest) throw new Error("No manual migration found");
|
|
422
|
+
const id = latest.replace(/\.(ts|mts|js|mjs)$/, "");
|
|
423
|
+
const parent = files.at(-2)?.replace(/\.(ts|mts|js|mjs)$/, "") ?? null;
|
|
424
|
+
if (parent) {
|
|
425
|
+
if ((await readJSON(join(snapshots, `${parent}.json`))).migrationId != parent) throw new Error("Invalid predecessor snapshot");
|
|
426
|
+
}
|
|
427
|
+
const definitions = await readJSON(resolve(cwd, values.schema));
|
|
428
|
+
await writeFile(join(snapshots, `${id}.json`), JSON.stringify(createSnapshot(id, parent, definitions), null, 2) + "\n", { flag: "wx" });
|
|
429
|
+
});
|
|
430
|
+
out("Saved intended manual snapshot. migrate:up verifies the actual result atomically.");
|
|
431
|
+
return 0;
|
|
432
|
+
}
|
|
433
|
+
if ([
|
|
434
|
+
"migration:create",
|
|
435
|
+
"migration:generate",
|
|
436
|
+
"migration:baseline"
|
|
437
|
+
].includes(command)) {
|
|
438
|
+
if (!name) throw new Error("A migration name is required");
|
|
439
|
+
if (command == "migration:baseline" && !values.yes) throw new Error("Baseline adoption requires --yes");
|
|
440
|
+
await withArtifactLock(directory, async () => {
|
|
441
|
+
const local = await loadArtifacts(config, root, true);
|
|
442
|
+
const previous = local.artifacts.at(-1);
|
|
443
|
+
const id = migrationId(name, previous?.migration.id);
|
|
444
|
+
const migrationPath = join(directory, `${id}.${config.migrations.format ?? "ts"}`);
|
|
445
|
+
if (command == "migration:create") {
|
|
446
|
+
await writeFile(migrationPath, renderMigration(id), { flag: "wx" });
|
|
447
|
+
print({
|
|
448
|
+
id,
|
|
449
|
+
unfinished: true
|
|
450
|
+
}, `Created ${id}. Implement up(), then use migration:snapshot --schema <collections.json>.`);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
const desired = await entities();
|
|
454
|
+
const before = previous?.snapshot.collections ?? [];
|
|
455
|
+
const plan = diffSchemas(before, desired);
|
|
456
|
+
if (command == "migration:baseline" && local.artifacts.length) {
|
|
457
|
+
if (local.artifacts.length != 1) throw new Error("Baseline requires exactly one initial artifact");
|
|
458
|
+
const initial = local.artifacts[0];
|
|
459
|
+
const creation = diffSchemas([], desired);
|
|
460
|
+
if (initial.snapshot.schemaHash != schemaHash(desired) || initial.checksum != artifactChecksum(renderMigration(initial.migration.id, creation))) throw new Error("Existing baseline must be an unmodified generated initial-schema migration matching entities");
|
|
461
|
+
await withDatabase(config, (database) => new MigrationRunner(database, local.artifacts).baseline());
|
|
462
|
+
out(`Registered existing baseline ${initial.migration.id}`);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
if (!plan.operations.length) {
|
|
466
|
+
print({ operations: [] }, "No schema differences.");
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
if (plan.operations.some((operation) => operation.risk == "requires-data-transformation")) throw new Error("Automatic generation requires a manual data transformation. Use migration:create and provide a snapshot.");
|
|
470
|
+
if (plan.operations.some((operation) => operation.risk == "destructive") && !values["allow-destructive"]) throw new Error("Destructive generation requires --allow-destructive");
|
|
471
|
+
const snapshot = createSnapshot(id, previous?.migration.id ?? null, desired);
|
|
472
|
+
if (command == "migration:baseline") await withDatabase(config, async (database) => {
|
|
473
|
+
const actual = await database.getCollectionDefinitions();
|
|
474
|
+
const names = new Set(desired.map((schema) => schema.name));
|
|
475
|
+
if (schemaHash(actual.filter((schema) => names.has(schema.name))) != snapshot.schemaHash) throw new Error("Persisted managed schema is incompatible with baseline");
|
|
476
|
+
await writePair(migrationPath, renderMigration(id, plan), join(snapshots, `${id}.json`), snapshot);
|
|
477
|
+
const loaded = await loadArtifacts(config, root, true);
|
|
478
|
+
await new MigrationRunner(database, loaded.artifacts).baseline();
|
|
479
|
+
});
|
|
480
|
+
else await writePair(migrationPath, renderMigration(id, plan), join(snapshots, `${id}.json`), snapshot);
|
|
481
|
+
print({
|
|
482
|
+
id,
|
|
483
|
+
operations: plan.operations
|
|
484
|
+
}, `Created ${id}\n${summary(plan)}`);
|
|
485
|
+
});
|
|
486
|
+
return 0;
|
|
487
|
+
}
|
|
488
|
+
if (command == "migration:remove") {
|
|
489
|
+
if (!values.yes) throw new Error("Removing the latest unpublished local migration requires --yes");
|
|
490
|
+
await withArtifactLock(directory, async () => {
|
|
491
|
+
const local = await loadArtifacts(config, root, true, true);
|
|
492
|
+
const latestFile = local.files.at(-1);
|
|
493
|
+
const latest = latestFile?.replace(/\.(ts|mts|js|mjs)$/, "");
|
|
494
|
+
if (!latest) throw new Error("No local migration to remove");
|
|
495
|
+
await withDatabase(config, async (database) => {
|
|
496
|
+
if ((await new MigrationRunner(database, local.artifacts).status()).applied.some((entry) => entry.id == latest)) throw new Error("Cannot remove an applied migration");
|
|
497
|
+
const snapshotPath = join(snapshots, `${latest}.json`);
|
|
498
|
+
try {
|
|
499
|
+
await access(snapshotPath);
|
|
500
|
+
} catch (error) {
|
|
501
|
+
if (error.code != "ENOENT") throw error;
|
|
502
|
+
await unlink(join(directory, latestFile));
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
await removePair(join(directory, latestFile), snapshotPath);
|
|
506
|
+
});
|
|
507
|
+
out(`Removed ${latest}. This checks only the configured database; never remove shared or released migrations.`);
|
|
508
|
+
});
|
|
509
|
+
return 0;
|
|
510
|
+
}
|
|
511
|
+
const local = await loadArtifacts(config, root);
|
|
512
|
+
if (command == "migrate:diff" && !values.persisted) {
|
|
513
|
+
const plan = diffSchemas(local.artifacts.at(-1)?.snapshot.collections ?? [], await entities());
|
|
514
|
+
print(plan, summary(plan));
|
|
515
|
+
return 0;
|
|
516
|
+
}
|
|
517
|
+
if (command == "migrate:check" && values.offline) {
|
|
518
|
+
validateArtifacts(local.artifacts);
|
|
519
|
+
const plan = diffSchemas(local.artifacts.at(-1)?.snapshot.collections ?? [], await entities());
|
|
520
|
+
if (plan.operations.length) throw new Error(`Unrepresented entity changes:\n${summary(plan)}`);
|
|
521
|
+
print({
|
|
522
|
+
valid: true,
|
|
523
|
+
mode: "offline"
|
|
524
|
+
}, "Local files, snapshots, and entity schema are valid. Database history was not checked.");
|
|
525
|
+
return 0;
|
|
526
|
+
}
|
|
527
|
+
if (command == "migrate:up" && values["dry-run"]) {
|
|
528
|
+
const steps = values.steps === void 0 ? void 0 : Number(values.steps);
|
|
529
|
+
if (steps !== void 0 && (!Number.isSafeInteger(steps) || steps < 0)) throw new Error("Invalid steps");
|
|
530
|
+
if (values.to && (!local.artifacts.some((artifact) => artifact.migration.id == values.to) || steps !== void 0)) throw new Error("Invalid target or conflicting --steps");
|
|
531
|
+
const candidates = local.artifacts.filter((artifact) => !values.to || artifact.migration.id <= values.to).slice(0, steps ?? Infinity).map((artifact) => artifact.migration.id);
|
|
532
|
+
print({
|
|
533
|
+
dryRun: true,
|
|
534
|
+
appliedStateChecked: false,
|
|
535
|
+
candidates
|
|
536
|
+
}, `Static preview only; database was not opened and applied state was not checked. Migration callbacks were not executed.\n${candidates.join("\n")}`);
|
|
537
|
+
return 0;
|
|
538
|
+
}
|
|
539
|
+
await withDatabase(config, async (database) => {
|
|
540
|
+
const runner = new MigrationRunner(database, local.artifacts);
|
|
541
|
+
const options = {
|
|
542
|
+
...values.steps === void 0 ? {} : { steps: Number(values.steps) },
|
|
543
|
+
...values.to ? { to: values.to } : {},
|
|
544
|
+
allowDestructive: values["allow-destructive"] ?? false
|
|
545
|
+
};
|
|
546
|
+
if (command == "migrate:up") {
|
|
547
|
+
const applied = await runner.up(options);
|
|
548
|
+
print({ applied }, `Applied ${applied.length} migration(s).\n${applied.join("\n")}`);
|
|
549
|
+
} else if (command == "migrate:down") {
|
|
550
|
+
if (!values.yes) throw new Error("Rollback requires --yes; review backups and down() first");
|
|
551
|
+
const reverted = await runner.down({
|
|
552
|
+
...options,
|
|
553
|
+
allowDestructive: true
|
|
554
|
+
});
|
|
555
|
+
print({ reverted }, `Reverted ${reverted.length} migration(s).`);
|
|
556
|
+
} else if (command == "migrate:status") {
|
|
557
|
+
const status = await runner.status();
|
|
558
|
+
print(status, `Duraxis migration status\nDatabase: ${values.database ?? "default"}\n\nApplied:\n${status.applied.map((entry) => ` ${entry.id}`).join("\n")}\nPending:\n${status.pending.map((id) => ` ${id}`).join("\n")}\nSchema drift: none\n${status.applied.length} applied, ${status.pending.length} pending`);
|
|
559
|
+
} else if (command == "migrate:diff") {
|
|
560
|
+
const plan = await runner.drift();
|
|
561
|
+
print(plan, summary(plan));
|
|
562
|
+
} else if (command == "migrate:check") {
|
|
563
|
+
await runner.status();
|
|
564
|
+
const plan = diffSchemas(local.artifacts.at(-1)?.snapshot.collections ?? [], await entities());
|
|
565
|
+
if (plan.operations.length) throw new Error(`Unrepresented entity changes:\n${summary(plan)}`);
|
|
566
|
+
print({ valid: true }, "Migration files, snapshots, history, schema, and entities are valid.");
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
return 0;
|
|
570
|
+
} catch (error) {
|
|
571
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
572
|
+
errorOut(jsonErrors ? JSON.stringify({ error: message }) : message);
|
|
573
|
+
return 1;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
export { defineDuraxisConfig, disposeTypeScriptLoader, loadConfig, runCLI };
|
|
577
|
+
|
|
578
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/runtime.mjs","../src/typescript-loader.ts","../src/config.ts","../src/artifacts.ts","../src/cli.ts"],"sourcesContent":["export const MINIMUM_NODE_VERSION = \"24.15.0\";\n\n/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */\nexport function assertSupportedRuntime(version = process.versions.node) {\n const actual = version.split(\".\").map(Number);\n const minimum = MINIMUM_NODE_VERSION.split(\".\").map(Number);\n const difference = actual.findIndex((part, index) => part !== minimum[index]);\n const supported =\n /^\\d+\\.\\d+\\.\\d+$/.test(version) &&\n (difference === -1 || actual[difference] > minimum[difference]);\n if (!supported)\n throw new Error(\n `Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\\nCurrent version: ${version}\\nPlease upgrade your Node.js installation.`,\n );\n}\n","import { readFileSync, statSync } from \"node:fs\";\nimport { registerHooks, type ModuleHooks } from \"node:module\";\nimport { extname } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport ts from \"typescript\";\nimport { assertSupportedRuntime } from \"./runtime.mjs\";\n\nconst sourceExtensions: Readonly<Record<string, string>> = {\n \".js\": \".ts\",\n \".mjs\": \".mts\",\n \".cjs\": \".cts\",\n};\nlet hooks: ModuleHooks | undefined;\nconst modules = new Set<string>();\n\nfunction localFile(value: string): URL | undefined {\n if (!value.startsWith(\"file:\")) return;\n const url = new URL(value);\n const path = fileURLToPath(url);\n if (path.split(/[\\\\/]/).includes(\"node_modules\")) return;\n return url;\n}\nfunction exists(url: URL): boolean {\n try {\n return statSync(url).isFile();\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return false;\n throw error;\n }\n}\nfunction remember(url: string): void {\n if (localFile(url)) modules.add(url);\n}\n\n/** One hook pair per library instance, limited to explicitly loaded local module graphs. */\nexport function initializeTypeScriptLoader(entry: URL): void {\n assertSupportedRuntime();\n remember(entry.href);\n if (hooks) return;\n hooks = registerHooks({\n resolve(specifier, context, nextResolve) {\n const relative = /^(?:\\.{1,2}[\\\\/]|\\/|file:)/.test(specifier);\n const managed =\n relative &&\n (modules.has(specifier) ||\n (context.parentURL !== undefined && modules.has(context.parentURL)));\n try {\n const resolved = nextResolve(specifier, context);\n if (managed) remember(resolved.url);\n return resolved;\n } catch (error) {\n if (\n !managed ||\n ![\"ERR_MODULE_NOT_FOUND\", \"MODULE_NOT_FOUND\"].includes(\n (error as NodeJS.ErrnoException).code ?? \"\",\n )\n )\n throw error;\n const requested = localFile(new URL(specifier, context.parentURL).href);\n if (!requested || exists(requested)) throw error;\n const path = fileURLToPath(requested);\n const extension = extname(path);\n const mapped = sourceExtensions[extension];\n if (!mapped) throw error;\n const candidate = pathToFileURL(path.slice(0, -extension.length) + mapped);\n candidate.search = requested.search;\n candidate.hash = requested.hash;\n if (!exists(candidate)) throw error;\n const resolved = nextResolve(\n context.conditions.includes(\"require\") ? fileURLToPath(candidate) : candidate.href,\n context,\n );\n remember(resolved.url);\n return resolved;\n }\n },\n load(url, context, nextLoad) {\n if (!modules.has(url)) return nextLoad(url, context);\n const file = localFile(url);\n if (!file) return nextLoad(url, context);\n const path = fileURLToPath(file);\n if (!/\\.(?:ts|mts|cts)$/.test(path) || /\\.d\\.(?:ts|mts|cts)$/.test(path))\n return nextLoad(url, context);\n const commonjs = path.endsWith(\".cts\");\n const result = ts.transpileModule(readFileSync(file, \"utf8\"), {\n fileName: path,\n reportDiagnostics: true,\n compilerOptions: {\n target: ts.ScriptTarget.ES2022,\n module: commonjs ? ts.ModuleKind.NodeNext : ts.ModuleKind.ESNext,\n ...(commonjs ? { moduleResolution: ts.ModuleResolutionKind.NodeNext } : {}),\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n useDefineForClassFields: false,\n sourceMap: false,\n },\n });\n const errors = (result.diagnostics ?? []).filter(\n (item) => item.category == ts.DiagnosticCategory.Error,\n );\n if (errors.length)\n throw new Error(\n ts.formatDiagnosticsWithColorAndContext(errors, {\n getCurrentDirectory: () => process.cwd(),\n getCanonicalFileName: (file) => file,\n getNewLine: () => \"\\n\",\n }),\n );\n // Imported CommonJS source otherwise receives the ESM translator's synthetic\n // require, which bypasses customization hooks. Use Node's hook-aware require.\n return {\n format: commonjs ? \"commonjs\" : \"module\",\n source:\n (commonjs\n ? '\"use strict\";\\nrequire = require(\"node:module\").createRequire(__filename);\\n'\n : \"\") + result.outputText,\n shortCircuit: true,\n };\n },\n });\n}\n\n/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */\nexport function disposeTypeScriptLoader(): void {\n hooks?.deregister();\n hooks = undefined;\n // Retain graph identity alongside Node's module cache so cached callbacks can\n // resolve further imports after a later initialization.\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { initializeTypeScriptLoader } from \"./typescript-loader.js\";\nimport { pathToFileURL } from \"node:url\";\nimport type { DuraxisDatabase } from \"@duraxis/core\";\nimport type { EntityClass } from \"@duraxis/orm\";\n\nexport interface DuraxisConnectionConfig {\n readonly entities:\n readonly EntityClass[] | (() => readonly EntityClass[] | Promise<readonly EntityClass[]>);\n readonly migrations: {\n readonly directory: string;\n readonly snapshots: string;\n readonly format?: \"ts\" | \"js\";\n };\n readonly createDatabase: () => DuraxisDatabase | Promise<DuraxisDatabase>;\n}\n\nexport interface DuraxisConfig extends DuraxisConnectionConfig {\n readonly databases?: Readonly<Record<string, DuraxisConnectionConfig>>;\n}\n\nexport function defineDuraxisConfig<const T extends DuraxisConfig>(config: T): T {\n return config;\n}\n\nexport async function importFile(path: string | URL): Promise<unknown> {\n const url = path instanceof URL ? path : pathToFileURL(path);\n initializeTypeScriptLoader(url);\n return import(url.href);\n}\n\nexport async function loadConfig(\n cwd: string,\n explicit?: string,\n database?: string,\n): Promise<{ config: DuraxisConnectionConfig; root: string; path: string }> {\n let path: string | undefined;\n\n if (explicit) path = resolve(cwd, explicit);\n else {\n let directory = resolve(cwd);\n\n while (true) {\n for (const name of [\n \"duraxis.config.ts\",\n \"duraxis.config.mts\",\n \"duraxis.config.js\",\n \"duraxis.config.mjs\",\n \"duraxis.config.cts\",\n \"duraxis.config.cjs\",\n ]) {\n const candidate = resolve(directory, name);\n\n try {\n await access(candidate);\n\n path = candidate;\n\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n }\n\n if (path || dirname(directory) == directory) break;\n\n directory = dirname(directory);\n }\n }\n\n if (!path) throw new Error(\"No duraxis.config.ts or JavaScript configuration found\");\n\n const module = (await importFile(path)) as { default?: DuraxisConfig };\n\n const base = module.default;\n\n const config = database ? base?.databases?.[database] : base;\n\n if (\n !config ||\n typeof config.createDatabase != \"function\" ||\n (!Array.isArray(config.entities) && typeof config.entities != \"function\") ||\n typeof config.migrations?.directory != \"string\" ||\n typeof config.migrations.snapshots != \"string\" ||\n (config.migrations.format !== undefined && ![\"ts\", \"js\"].includes(config.migrations.format))\n )\n throw new Error(\"Invalid Duraxis configuration or unknown named database\");\n\n return { config, root: dirname(path), path };\n}\n\nexport async function readJSON<T>(path: string): Promise<T> {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n}\n","import { randomBytes } from \"node:crypto\";\nimport { access, mkdir, readdir, readFile, writeFile, unlink, rename } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport ts from \"typescript\";\nimport {\n checksum,\n canonicalJSON,\n createSnapshot,\n validateSnapshot,\n validateMigrationId,\n validateArtifacts,\n type DuraxisMigration,\n type MigrationArtifact,\n type SchemaSnapshot,\n type SchemaPlan,\n diffSchemas,\n} from \"@duraxis/migrations\";\nimport type { CollectionDefinition } from \"@duraxis/core\";\nimport { importFile, readJSON, type DuraxisConnectionConfig } from \"./config.js\";\n\nexport function artifactChecksum(source: string): string {\n const options: ts.TranspileOptions = {\n compilerOptions: {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n removeComments: true,\n newLine: ts.NewLineKind.LineFeed,\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n useDefineForClassFields: false,\n },\n };\n\n const first = ts.transpileModule(source, options).outputText;\n\n return checksum(ts.transpileModule(first, options).outputText);\n}\n\nexport interface LocalArtifacts {\n readonly artifacts: readonly MigrationArtifact[];\n readonly files: readonly string[];\n readonly snapshots: string;\n readonly directory: string;\n}\n\nexport async function loadArtifacts(\n config: DuraxisConnectionConfig,\n root: string,\n ownsLock = false,\n omitLatest = false,\n): Promise<LocalArtifacts> {\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n if (!ownsLock)\n try {\n await access(join(directory, \".duraxis-artifacts.lock\"));\n throw new Error(\n \"Artifact update in progress or stale guard; inspect artifacts before removing the guard\",\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\n .sort();\n\n const artifacts: MigrationArtifact[] = [];\n\n const ids = new Set<string>();\n\n for (const file of files) {\n const id = file.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n validateMigrationId(id);\n\n if (ids.has(id)) throw new Error(`Duplicate migration filename: ${id}`);\n\n ids.add(id);\n\n if (omitLatest && file == files.at(-1)) continue;\n\n const source = await readFile(join(directory, file), \"utf8\");\n const module = (await importFile(join(directory, file))) as { default: DuraxisMigration };\n\n if (module.default?.id != id) throw new Error(`Migration ID does not match filename: ${file}`);\n\n const snapshot = await readJSON<SchemaSnapshot>(join(snapshots, `${id}.json`));\n\n validateSnapshot(snapshot);\n\n artifacts.push({ migration: module.default, checksum: artifactChecksum(source), snapshot });\n }\n\n const expected = new Set([...ids].map((id) => `${id}.json`));\n\n for (const file of await readdir(snapshots))\n if (file.endsWith(\".json\") && file != \"baseline.json\" && !expected.has(file))\n throw new Error(`Orphaned snapshot: ${file}`);\n\n const initial = await readJSON<SchemaSnapshot>(join(snapshots, \"baseline.json\"));\n\n validateSnapshot(initial);\n\n if (\n initial.migrationId !== null ||\n initial.parentMigrationId !== null ||\n initial.collections.length\n )\n throw new Error(\"Invalid empty baseline snapshot\");\n\n validateArtifacts(artifacts);\n\n return { artifacts, files, snapshots, directory };\n}\nexport function migrationId(name: string, previous?: string): string {\n if (name.includes(\"..\") || /[\\\\/]/.test(name))\n throw new Error(\"Migration names cannot contain paths\");\n\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n if (!slug || slug.length > 64) throw new Error(\"Invalid migration name\");\n\n const stamp = new Date().toISOString().replace(/\\D/g, \"\");\n\n const previousStamp = previous?.slice(0, 17);\n\n const prefix =\n previousStamp && previousStamp >= stamp\n ? (BigInt(previousStamp) + 1n).toString().padStart(17, \"0\")\n : stamp;\n\n return `${prefix}_${slug}`;\n}\n\nfunction literal(value: unknown): string {\n return JSON.stringify(value, null, 2)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nexport function renderMigration(id: string, plan?: SchemaPlan): string {\n if (!plan)\n return `import { defineMigration } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n throw new Error(\"Unfinished migration: implement up and provide its expected snapshot\");\\n },\\n});\\n`;\n\n const inverse = diffSchemas(plan.after, plan.before);\n\n const reversible =\n !plan.operations.some(\n (operation) => operation.kind == \"collection\" && operation.after == null,\n ) && inverse.operations.every((operation) => operation.risk != \"requires-data-transformation\");\n\n return `import { defineMigration, applySchemaPlan } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n await applySchemaPlan(context, ${literal(plan)});\\n },\\n${\n reversible\n ? ` async down(context) {\\n${inverse.operations\n .filter((operation) => operation.kind == \"collection\" && operation.after == null)\n .map(\n (operation) =>\n ` for await (const row of context.scan(${JSON.stringify(operation.collection)})) throw new Error(\"Cannot drop a populated collection during generated rollback\");\\n`,\n )\n .join(\"\")} await applySchemaPlan(context, ${literal(inverse)});\\n },\\n`\n : \" // Irreversible automatically: write an explicit data-safe down() if needed.\\n\"\n } });\\n`;\n}\n\nexport async function withArtifactLock<T>(\n directory: string,\n callback: () => Promise<T>,\n): Promise<T> {\n await mkdir(directory, { recursive: true });\n\n const lock = join(directory, \".duraxis-artifacts.lock\");\n\n await writeFile(\n lock,\n canonicalJSON({\n pid: process.pid,\n purpose: \"artifact update; inspect files before removing a stale guard\",\n }),\n { flag: \"wx\" },\n );\n\n try {\n return await callback();\n } finally {\n await unlink(lock);\n }\n}\n\nexport async function writePair(\n migrationPath: string,\n source: string,\n snapshotPath: string,\n snapshot: SchemaSnapshot,\n): Promise<void> {\n await mkdir(resolve(snapshotPath, \"..\"), { recursive: true });\n await writeFile(migrationPath, source, { flag: \"wx\" });\n\n try {\n await writeFile(snapshotPath, JSON.stringify(snapshot, null, 2) + \"\\n\", { flag: \"wx\" });\n } catch (error) {\n await unlink(migrationPath);\n throw error;\n }\n}\n\nexport async function removePair(migrationPath: string, snapshotPath: string): Promise<void> {\n const suffix = `.removing-${randomBytes(6).toString(\"hex\")}`;\n await rename(migrationPath, migrationPath + suffix);\n\n try {\n await rename(snapshotPath, snapshotPath + suffix);\n } catch (error) {\n await rename(migrationPath + suffix, migrationPath);\n throw error;\n }\n\n await unlink(migrationPath + suffix);\n await unlink(snapshotPath + suffix);\n}\n\nexport function snapshotFor(\n id: string,\n parent: string | null,\n schema: readonly CollectionDefinition[],\n): SchemaSnapshot {\n return createSnapshot(id, parent, schema);\n}\n","import { parseArgs } from \"node:util\";\nimport { access, mkdir, writeFile, unlink } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { exportSchema } from \"@duraxis/orm\";\nimport {\n MigrationRunner,\n validateArtifacts,\n createSnapshot,\n diffSchemas,\n schemaHash,\n type SchemaSnapshot,\n type SchemaPlan,\n} from \"@duraxis/migrations\";\nimport type { CollectionDefinition, DuraxisDatabase } from \"@duraxis/core\";\nimport { loadConfig, readJSON, type DuraxisConnectionConfig } from \"./config.js\";\nimport {\n artifactChecksum,\n loadArtifacts,\n migrationId,\n renderMigration,\n withArtifactLock,\n writePair,\n removePair,\n} from \"./artifacts.js\";\n\nexport interface CLIIO {\n readonly cwd?: string;\n readonly out?: (message: string) => void;\n readonly error?: (message: string) => void;\n}\n\nconst help = `duraxis <command> [options]\n init\n migration:create <name>\n migration:generate <name> [--allow-destructive]\n migration:snapshot --schema <collections.json>\n migration:remove --yes\n migration:baseline <name> --yes\n migrate:up [--steps N | --to ID] [--dry-run] [--allow-destructive]\n migrate:down [--steps N | --to ID] --yes\n migrate:status\n migrate:diff [--persisted]\n migrate:check [--offline]\nOptions: --config PATH --database NAME --json\nRollback --to retains the target version. Dry-run is a static preview only.`;\n\nasync function withDatabase<T>(\n config: DuraxisConnectionConfig,\n callback: (database: DuraxisDatabase) => Promise<T>,\n): Promise<T> {\n const database = await config.createDatabase();\n\n try {\n return await callback(database);\n } finally {\n await database.close({ closeStorage: true });\n }\n}\n\nfunction summary(plan: SchemaPlan): string {\n return plan.operations.length\n ? plan.operations\n .map(\n (operation) =>\n `${operation.before == null ? \"+\" : operation.after == null ? \"-\" : \"~\"} ${operation.kind} ${operation.collection}/${operation.name} (${operation.risk})`,\n )\n .join(\"\\n\")\n : \"No schema differences.\";\n}\n\nasync function init(cwd: string): Promise<void> {\n const configPath = resolve(cwd, \"duraxis.config.ts\");\n const base = resolve(cwd, \"duraxis/snapshots/baseline.json\");\n\n for (const path of [configPath, base])\n try {\n await access(path);\n throw new Error(`Refusing to overwrite ${path}`);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n\n await mkdir(resolve(cwd, \"duraxis/migrations\"), { recursive: true });\n await mkdir(resolve(cwd, \"duraxis/snapshots\"), { recursive: true });\n\n await writeFile(\n configPath,\n `import { defineDuraxisConfig } from \"@duraxis/cli\";\n\nexport default defineDuraxisConfig({\n entities: [], // Import your decorated entity classes here.\n migrations: { directory: \"./duraxis/migrations\", snapshots: \"./duraxis/snapshots\", format: \"ts\" },\n async createDatabase() {\n // Return a DuraxisDatabase configured with your storage driver.\n // The CLI closes this database and its storage after every command.\n throw new Error(\"Configure createDatabase() before accessing a database\");\n },\n});\n`,\n { flag: \"wx\" },\n );\n\n try {\n await writeFile(base, JSON.stringify(createSnapshot(null, null, []), null, 2) + \"\\n\", {\n flag: \"wx\",\n });\n } catch (error) {\n await unlink(configPath);\n throw error;\n }\n}\n\nexport async function runCLI(args: readonly string[], io: CLIIO = {}): Promise<number> {\n const cwd = io.cwd ?? process.cwd();\n const out = io.out ?? console.log;\n\n const errorOut = io.error ?? console.error;\n\n let jsonErrors = false;\n\n try {\n const { values, positionals } = parseArgs({\n args: [...args],\n allowPositionals: true,\n strict: true,\n options: {\n config: { type: \"string\" },\n database: { type: \"string\" },\n json: { type: \"boolean\" },\n steps: { type: \"string\" },\n to: { type: \"string\" },\n \"dry-run\": { type: \"boolean\" },\n \"allow-destructive\": { type: \"boolean\" },\n yes: { type: \"boolean\" },\n offline: { type: \"boolean\" },\n persisted: { type: \"boolean\" },\n schema: { type: \"string\" },\n help: { type: \"boolean\" },\n },\n });\n\n jsonErrors = values.json ?? false;\n\n const command = positionals[0];\n const name = positionals[1];\n\n if (!command || values.help) {\n out(help);\n return 0;\n }\n\n const commands = [\n \"init\",\n \"migration:create\",\n \"migration:generate\",\n \"migration:snapshot\",\n \"migration:remove\",\n \"migration:baseline\",\n \"migrate:up\",\n \"migrate:down\",\n \"migrate:status\",\n \"migrate:diff\",\n \"migrate:check\",\n ];\n\n if (!commands.includes(command)) throw new Error(`Unknown command: ${command}`);\n\n if (\n positionals.length > 2 ||\n (name && ![\"migration:create\", \"migration:generate\", \"migration:baseline\"].includes(command))\n )\n throw new Error(\"Unexpected positional arguments\");\n\n const allowed: Record<string, readonly string[]> = {\n init: [],\n \"migration:create\": [],\n \"migration:generate\": [\"allow-destructive\"],\n \"migration:snapshot\": [\"schema\"],\n \"migration:remove\": [\"yes\"],\n \"migration:baseline\": [\"yes\"],\n \"migrate:up\": [\"steps\", \"to\", \"dry-run\", \"allow-destructive\"],\n \"migrate:down\": [\"steps\", \"to\", \"yes\"],\n \"migrate:status\": [],\n \"migrate:diff\": [\"persisted\"],\n \"migrate:check\": [\"offline\"],\n };\n\n for (const option of Object.keys(values))\n if (![\"config\", \"database\", \"json\", \"help\", ...allowed[command]].includes(option))\n throw new Error(`Option --${option} is not supported by ${command}`);\n\n if (command == \"init\") {\n await init(cwd);\n out(\n \"Initialized duraxis.config.ts and migration directories. Configure entities and createDatabase().\",\n );\n return 0;\n }\n\n const { config, root } = await loadConfig(cwd, values.config, values.database);\n\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n const print = (value: unknown, text: string) =>\n out(values.json ? JSON.stringify(value, null, 2) : text);\n\n const entities = async () =>\n exportSchema(\n typeof config.entities == \"function\" ? await config.entities() : config.entities,\n );\n\n if (command == \"migration:snapshot\") {\n if (!values.schema)\n throw new Error(\"Provide --schema with a JSON array of expected collection definitions\");\n\n await withArtifactLock(directory, async () => {\n const { readdir } = await import(\"node:fs/promises\");\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\n .sort();\n\n const latest = files.at(-1);\n\n if (!latest) throw new Error(\"No manual migration found\");\n\n const id = latest.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n const parent = files.at(-2)?.replace(/\\.(ts|mts|js|mjs)$/, \"\") ?? null;\n\n if (parent) {\n const previous = await readJSON<SchemaSnapshot>(join(snapshots, `${parent}.json`));\n if (previous.migrationId != parent) throw new Error(\"Invalid predecessor snapshot\");\n }\n\n const definitions = await readJSON<readonly CollectionDefinition[]>(\n resolve(cwd, values.schema!),\n );\n\n await writeFile(\n join(snapshots, `${id}.json`),\n JSON.stringify(createSnapshot(id, parent, definitions), null, 2) + \"\\n\",\n { flag: \"wx\" },\n );\n });\n\n out(\"Saved intended manual snapshot. migrate:up verifies the actual result atomically.\");\n\n return 0;\n }\n\n if ([\"migration:create\", \"migration:generate\", \"migration:baseline\"].includes(command)) {\n if (!name) throw new Error(\"A migration name is required\");\n\n if (command == \"migration:baseline\" && !values.yes)\n throw new Error(\"Baseline adoption requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true);\n const previous = local.artifacts.at(-1);\n\n const id = migrationId(name, previous?.migration.id);\n const migrationPath = join(directory, `${id}.${config.migrations.format ?? \"ts\"}`);\n\n if (command == \"migration:create\") {\n await writeFile(migrationPath, renderMigration(id), { flag: \"wx\" });\n print(\n { id, unfinished: true },\n `Created ${id}. Implement up(), then use migration:snapshot --schema <collections.json>.`,\n );\n return;\n }\n\n const desired = await entities();\n\n const before = previous?.snapshot.collections ?? [];\n const plan = diffSchemas(before, desired);\n\n if (command == \"migration:baseline\" && local.artifacts.length) {\n if (local.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const initial = local.artifacts[0]!;\n const creation = diffSchemas([], desired);\n\n if (\n initial.snapshot.schemaHash != schemaHash(desired) ||\n initial.checksum != artifactChecksum(renderMigration(initial.migration.id, creation))\n )\n throw new Error(\n \"Existing baseline must be an unmodified generated initial-schema migration matching entities\",\n );\n await withDatabase(config, (database) =>\n new MigrationRunner(database, local.artifacts).baseline(),\n );\n\n out(`Registered existing baseline ${initial.migration.id}`);\n return;\n }\n\n if (!plan.operations.length) {\n print({ operations: [] }, \"No schema differences.\");\n return;\n }\n\n if (plan.operations.some((operation) => operation.risk == \"requires-data-transformation\"))\n throw new Error(\n \"Automatic generation requires a manual data transformation. Use migration:create and provide a snapshot.\",\n );\n\n if (\n plan.operations.some((operation) => operation.risk == \"destructive\") &&\n !values[\"allow-destructive\"]\n )\n throw new Error(\"Destructive generation requires --allow-destructive\");\n\n const snapshot = createSnapshot(id, previous?.migration.id ?? null, desired);\n\n if (command == \"migration:baseline\") {\n await withDatabase(config, async (database) => {\n const actual = await database.getCollectionDefinitions();\n const names = new Set(desired.map((schema) => schema.name));\n\n if (\n schemaHash(actual.filter((schema) => names.has(schema.name))) != snapshot.schemaHash\n )\n throw new Error(\"Persisted managed schema is incompatible with baseline\");\n\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n const loaded = await loadArtifacts(config, root, true);\n\n await new MigrationRunner(database, loaded.artifacts).baseline();\n });\n } else\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n print({ id, operations: plan.operations }, `Created ${id}\\n${summary(plan)}`);\n });\n\n return 0;\n }\n\n if (command == \"migration:remove\") {\n if (!values.yes)\n throw new Error(\"Removing the latest unpublished local migration requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true, true);\n\n const latestFile = local.files.at(-1);\n\n const latest = latestFile?.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n if (!latest) throw new Error(\"No local migration to remove\");\n\n await withDatabase(config, async (database) => {\n const status = await new MigrationRunner(database, local.artifacts).status();\n\n if (status.applied.some((entry) => entry.id == latest))\n throw new Error(\"Cannot remove an applied migration\");\n\n const snapshotPath = join(snapshots, `${latest}.json`);\n\n try {\n await access(snapshotPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n\n await unlink(join(directory, latestFile!));\n\n return;\n }\n\n await removePair(join(directory, latestFile!), snapshotPath);\n });\n\n out(\n `Removed ${latest}. This checks only the configured database; never remove shared or released migrations.`,\n );\n });\n\n return 0;\n }\n\n const local = await loadArtifacts(config, root);\n\n if (command == \"migrate:diff\" && !values.persisted) {\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n print(plan, summary(plan));\n\n return 0;\n }\n\n if (command == \"migrate:check\" && values.offline) {\n validateArtifacts(local.artifacts);\n\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n if (plan.operations.length)\n throw new Error(`Unrepresented entity changes:\\n${summary(plan)}`);\n\n print(\n { valid: true, mode: \"offline\" },\n \"Local files, snapshots, and entity schema are valid. Database history was not checked.\",\n );\n\n return 0;\n }\n\n if (command == \"migrate:up\" && values[\"dry-run\"]) {\n const steps = values.steps === undefined ? undefined : Number(values.steps);\n\n if (steps !== undefined && (!Number.isSafeInteger(steps) || steps < 0))\n throw new Error(\"Invalid steps\");\n\n if (\n values.to &&\n (!local.artifacts.some((artifact) => artifact.migration.id == values.to) ||\n steps !== undefined)\n )\n throw new Error(\"Invalid target or conflicting --steps\");\n\n const candidates = local.artifacts\n .filter((artifact) => !values.to || artifact.migration.id <= values.to)\n .slice(0, steps ?? Infinity)\n .map((artifact) => artifact.migration.id);\n\n print(\n { dryRun: true, appliedStateChecked: false, candidates },\n `Static preview only; database was not opened and applied state was not checked. Migration callbacks were not executed.\\n${candidates.join(\"\\n\")}`,\n );\n\n return 0;\n }\n\n await withDatabase(config, async (database) => {\n const runner = new MigrationRunner(database, local.artifacts);\n\n const options = {\n ...(values.steps === undefined ? {} : { steps: Number(values.steps) }),\n ...(values.to ? { to: values.to } : {}),\n allowDestructive: values[\"allow-destructive\"] ?? false,\n };\n\n if (command == \"migrate:up\") {\n const applied = await runner.up(options);\n\n print({ applied }, `Applied ${applied.length} migration(s).\\n${applied.join(\"\\n\")}`);\n } else if (command == \"migrate:down\") {\n if (!values.yes)\n throw new Error(\"Rollback requires --yes; review backups and down() first\");\n\n const reverted = await runner.down({ ...options, allowDestructive: true });\n\n print({ reverted }, `Reverted ${reverted.length} migration(s).`);\n } else if (command == \"migrate:status\") {\n const status = await runner.status();\n\n print(\n status,\n `Duraxis migration status\\nDatabase: ${values.database ?? \"default\"}\\n\\nApplied:\\n${status.applied.map((entry) => ` ${entry.id}`).join(\"\\n\")}\\nPending:\\n${status.pending.map((id) => ` ${id}`).join(\"\\n\")}\\nSchema drift: none\\n${status.applied.length} applied, ${status.pending.length} pending`,\n );\n } else if (command == \"migrate:diff\") {\n const plan = await runner.drift();\n\n print(plan, summary(plan));\n } else if (command == \"migrate:check\") {\n await runner.status();\n\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n if (plan.operations.length)\n throw new Error(`Unrepresented entity changes:\\n${summary(plan)}`);\n\n print(\n { valid: true },\n \"Migration files, snapshots, history, schema, and entities are valid.\",\n );\n }\n });\n\n return 0;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n errorOut(jsonErrors ? JSON.stringify({ error: message }) : message);\n\n return 1;\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,IAAa,uBAAuB;;AAGpC,SAAgB,uBAAuB,UAAU,QAAQ,SAAS,MAAM;CACtE,MAAM,SAAS,QAAQ,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC5C,MAAM,UAAU,qBAAqB,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC1D,MAAM,aAAa,OAAO,WAAW,MAAM,UAAU,SAAS,QAAQ,MAAM;CAI5E,IAAI,EAFF,kBAAkB,KAAK,OAAO,MAC7B,eAAe,MAAM,OAAO,cAAc,QAAQ,eAEnD,MAAM,IAAI,MACR,4BAA4B,qBAAqB,+BAA+B,QAAQ,4CAC1F;AACJ;;ACPA,IAAM,mBAAqD;CACzD,OAAO;CACP,QAAQ;CACR,QAAQ;AACV;AACA,IAAI;AACJ,IAAM,0BAAU,IAAI,IAAY;AAEhC,SAAS,UAAU,OAAgC;CACjD,IAAI,CAAC,MAAM,WAAW,OAAO,GAAG;CAChC,MAAM,MAAM,IAAI,IAAI,KAAK;CAEzB,IADa,cAAc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AEhC,MAAM,MAAM,QAAQ,IAAI,CAAC;GAC3B,OAAO,IAAI,WAAW,iBAAiB;IACrC,MAAM,OAAO,OAAO;IAEpB,MAAM,OAAO,YACX,MAAM,UAAU,GAAG,EAAE,CAAC,EAAE,SAAS,eAAe,CAAC,GACjD,MAAM,SAAS,CACjB;IAEA,IAAI,KAAK,WAAW,QAClB,MAAM,IAAI,MAAM,kCAAkC,QAAQ,IAAI,GAAG;IAEnE,MACE,EAAE,OAAO,KAAK,GACd,sEACF;GACF;EACF,CAAC;EAED,OAAO;CACT,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAErE,SAAS,aAAa,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC,IAAI,OAAO;EAElE,OAAO;CACT;AACF"}
|
package/dist/runtime.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const MINIMUM_NODE_VERSION = "24.15.0";
|
|
2
|
+
|
|
3
|
+
/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */
|
|
4
|
+
export function assertSupportedRuntime(version = process.versions.node) {
|
|
5
|
+
const actual = version.split(".").map(Number);
|
|
6
|
+
const minimum = MINIMUM_NODE_VERSION.split(".").map(Number);
|
|
7
|
+
const difference = actual.findIndex((part, index) => part !== minimum[index]);
|
|
8
|
+
const supported =
|
|
9
|
+
/^\d+\.\d+\.\d+$/.test(version) &&
|
|
10
|
+
(difference === -1 || actual[difference] > minimum[difference]);
|
|
11
|
+
if (!supported)
|
|
12
|
+
throw new Error(
|
|
13
|
+
`Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\nCurrent version: ${version}\nPlease upgrade your Node.js installation.`,
|
|
14
|
+
);
|
|
15
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** One hook pair per library instance, limited to explicitly loaded local module graphs. */
|
|
2
|
+
export declare function initializeTypeScriptLoader(entry: URL): void;
|
|
3
|
+
/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */
|
|
4
|
+
export declare function disposeTypeScriptLoader(): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@duraxis/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Standalone migration CLI for Duraxis.",
|
|
5
|
+
"license": "ISC",
|
|
6
|
+
"author": "João Paulo Dias <joaopdias.dev@gmail.com>",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"duraxis",
|
|
9
|
+
"database",
|
|
10
|
+
"embedded",
|
|
11
|
+
"transactions",
|
|
12
|
+
"typescript"
|
|
13
|
+
],
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "https://github.com/Joaopdiasventura/Duraxis.git",
|
|
17
|
+
"directory": "packages/cli"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/Joaopdiasventura/Duraxis/tree/main/packages/cli#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/Joaopdiasventura/Duraxis/issues"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=24.15.0"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
29
|
+
},
|
|
30
|
+
"type": "module",
|
|
31
|
+
"main": "./dist/index.cjs",
|
|
32
|
+
"module": "./dist/index.js",
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"exports": {
|
|
35
|
+
".": {
|
|
36
|
+
"types": "./dist/index.d.ts",
|
|
37
|
+
"import": "./dist/index.js",
|
|
38
|
+
"require": "./dist/index.cjs"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"dist",
|
|
43
|
+
"README.md",
|
|
44
|
+
"LICENSE",
|
|
45
|
+
"CHANGELOG.md"
|
|
46
|
+
],
|
|
47
|
+
"sideEffects": false,
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@duraxis/core": "0.3.0",
|
|
50
|
+
"@duraxis/migrations": "0.2.0",
|
|
51
|
+
"@duraxis/orm": "0.3.0",
|
|
52
|
+
"typescript": "5.9.3"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@duraxis/storage-memory": "0.1.3",
|
|
56
|
+
"@duraxis/storage-disk": "0.1.3",
|
|
57
|
+
"reflect-metadata": "^0.2.2"
|
|
58
|
+
},
|
|
59
|
+
"bin": {
|
|
60
|
+
"duraxis": "./dist/bin.js"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "vite build && tsc -p tsconfig.build.json && node ../../scripts/build-cli-bin.mjs",
|
|
64
|
+
"dev": "vite build --watch",
|
|
65
|
+
"typecheck": "tsc --noEmit",
|
|
66
|
+
"test": "vitest run",
|
|
67
|
+
"test:watch": "vitest"
|
|
68
|
+
}
|
|
6
69
|
}
|