@duraxis/cli 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +16 -53
  3. package/dist/admin.command-Chb6x9mF.js +413 -0
  4. package/dist/admin.command-Chb6x9mF.js.map +1 -0
  5. package/dist/cli.d.ts +7 -0
  6. package/dist/commands/admin.command.d.ts +3 -0
  7. package/dist/commands/doctor.command.d.ts +10 -0
  8. package/dist/commands/init.command.d.ts +3 -0
  9. package/dist/commands/migration.command.d.ts +3 -0
  10. package/dist/config-CjMUqEhV.js +165 -0
  11. package/dist/config-CjMUqEhV.js.map +1 -0
  12. package/dist/config.d.ts +6 -2
  13. package/dist/dependencies/configured-registry.d.ts +3 -0
  14. package/dist/dependencies/dependency-resolver.d.ts +2 -0
  15. package/dist/dependencies/installed-package.d.ts +1 -0
  16. package/dist/dependencies/package-manager.d.ts +10 -0
  17. package/dist/dependencies/registry-client.d.ts +21 -0
  18. package/dist/dependencies/version-compatibility.d.ts +9 -0
  19. package/dist/filesystem/file-plan.d.ts +32 -0
  20. package/dist/index.js +365 -550
  21. package/dist/index.js.map +1 -1
  22. package/dist/init/initialization-options.d.ts +32 -0
  23. package/dist/init/initialization-planner.d.ts +7 -0
  24. package/dist/init/managed-project.d.ts +9 -0
  25. package/dist/init/project-detector.d.ts +27 -0
  26. package/dist/init.command-B2kKoyfi.js +172 -0
  27. package/dist/init.command-B2kKoyfi.js.map +1 -0
  28. package/dist/migration.command-N7ahyx92.js +361 -0
  29. package/dist/migration.command-N7ahyx92.js.map +1 -0
  30. package/dist/package-manager-BBRBhsIe.js +972 -0
  31. package/dist/package-manager-BBRBhsIe.js.map +1 -0
  32. package/dist/registry/argument-parser.d.ts +65 -0
  33. package/dist/registry/command-registry.d.ts +198 -0
  34. package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
  35. package/dist/templates/project.d.ts +8 -0
  36. package/dist/terminal/prompts.d.ts +2 -0
  37. package/package.json +8 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @duraxis/cli
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 8ef8100: Expand the migration CLI into project setup and administration tooling with native interactive/non-interactive initialization, standalone Core/ORM and NestJS shared factories, official/custom storage integration, optional migrations, named connections, static diagnostics, configuration commands, generators and compatible dependency updates.
8
+
9
+ Generate command help and argument validation from one registry. Add native registry/version compatibility checks, package-manager execution, guarded filesystem plans and rollback. Migration cancellation now closes owned database resources cooperatively while preserving in-flight publication semantics and explicitly reporting cleanup failures. No new third-party dependencies or migration checksum compiler changes.
10
+
11
+ Pre-1.0 behavior change: `init` now creates functional project settings and shared application factories, installs dependencies by default, and requires `--yes` in non-interactive mode. Use `--no-install` for offline scaffolding and explicitly select migrations. Existing executable configurations remain supported and are never automatically rewritten. See the CLI README for trust boundaries and supported combinations.
12
+
3
13
  ## 0.3.0
4
14
 
5
15
  ### Minor Changes
package/README.md CHANGED
@@ -1,65 +1,31 @@
1
1
  # @duraxis/cli
2
2
 
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.
3
+ Project initialization, configuration, diagnostics, generators, dependency updates and migrations for Duraxis. Node.js 24.15.0 or newer is required.
5
4
 
6
5
  ## Quick start
7
6
 
8
7
  ```bash
9
- pnpm add @duraxis/core @duraxis/orm @duraxis/migrations @duraxis/storage-disk
10
- pnpm add -D @duraxis/cli
8
+ npx --package @duraxis/cli@latest duraxis init
9
+ # After local installation:
11
10
  pnpm exec duraxis init
11
+ # Or with the executable on PATH:
12
+ duraxis init
12
13
  ```
13
14
 
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
- ```
15
+ For a reproducible non-interactive persistent ORM project:
38
16
 
39
17
  ```bash
40
- pnpm exec duraxis migration:generate initial-schema
18
+ duraxis init --framework standalone --driver disk --orm --migrations --package-manager pnpm --yes
19
+ pnpm exec duraxis migration:generate initial
41
20
  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
21
+ pnpm exec duraxis doctor
49
22
  ```
50
23
 
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:
24
+ Use `--no-install` for offline scaffolding, `--dry-run` to inspect a plan, and `--yes` for redirected input. Migrations are optional; Memory defaults to no migrations. NestJS requires ORM. Generated application factories share settings/entities with administration and do not import the CLI at runtime. Existing application files and executable configuration are preserved.
56
25
 
57
- ```bash
58
- npx --package @duraxis/cli duraxis --help
59
- ```
26
+ The [setup and administration guide](../../docs/CLI-SETUP.md) documents all options, package managers, storage configurations, named connections, environment provisioning, generated code, production deployment, safeguards and limitations.
60
27
 
61
- An unscoped `npx duraxis` does not identify this package. Install the dev dependency
62
- before using `pnpm exec duraxis`.
28
+ `duraxis help` lists every command; `duraxis help init` lists every initialization option. New administration commands include `doctor`, `config:show`, `config:validate`, `config:set`, `connection:add`, `connection:list`, `storage:list`, `storage:check`, `generate:entity`, `generate:module`, and `upgrade --check/--apply`. An unscoped `npx duraxis` does not identify this package.
63
29
 
64
30
  ## Configuration and loading
65
31
 
@@ -72,8 +38,7 @@ above instead of depending on the command's working directory.
72
38
 
73
39
  `entities` accepts a class array or an async factory returning classes, allowing
74
40
  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>`;
41
+ A `databases` object can hold named connection configs with a required `createDatabase` factory and optional `entities`/`migrations`. Select one with `--database <name>`;
77
42
  the top-level connection is the default.
78
43
 
79
44
  The factory returns an owned Core database, not a NestJS connection. The CLI closes
@@ -108,9 +73,7 @@ usual `reflect-metadata` dependency before decorated modules. Entity columns
108
73
  should declare their Core `type` explicitly. `tsconfig.json` path aliases,
109
74
  custom compiler plugins, `.tsx`/`.jsx`, and TypeScript package sources inside
110
75
  `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.
76
+ Generated CommonJS configurations use `.cjs`/`.cts`, declare `moduleFormat: "cjs"`, and select matching CommonJS ORM/migration runners. Legacy wrappers without this declaration retain their ESM entity/factory contract. Generated migrations remain ESM in a type:module migration directory to preserve checksum identity. Avoid mixing independent ESM/CommonJS decorator registries within one entity graph.
114
77
  Config files and migrations are trusted executable code; keep module initialization
115
78
  free of database writes and external side effects.
116
79
 
@@ -141,11 +104,11 @@ releases that directory before invoking the CLI.
141
104
  Every command supports `--config`, `--database`, and `--json`. Unknown options and
142
105
  options inappropriate for a command are errors. Errors exit with code 1; success
143
106
  exits 0. `--json` emits machine-readable success results for inspection commands
144
- and JSON errors on stderr. No command requires an interactive prompt.
107
+ and JSON errors on stderr. Initialization prompts on a terminal unless `--yes` is provided; redirected input never waits for prompts.
145
108
 
146
109
  | Command | Behavior and options |
147
110
  | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
148
- | `init` | Creates a config, migration/snapshot directories, and an empty `baseline.json`; refuses existing files. Does not modify application source. |
111
+ | `init` | Creates a managed project and shared application factories; installs compatible dependencies by default. Migrations and ORM are optional. Use --dry-run and --no-install as needed. |
149
112
  | `migration:create <name>` | Creates a throwing manual template. Complete it and provide an expected snapshot before use. |
150
113
  | `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
114
  | `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. |
@@ -0,0 +1,413 @@
1
+ import { C as stringMap, S as record, T as satisfies, _ as executeFiles, a as assertStorageDirectory, c as findManagedRoot, d as planInitialization, f as requiredPackages, g as describePlan, h as addFile, i as resolveDependencies, l as readManaged, m as extensions, n as runProcess, o as initializationOptions, p as entitySource, r as RegistryClient, s as connectionName, t as installCommands, u as configuredRegistry, v as detectProject, w as compare, x as readObject, y as exists } from "./package-manager-BBRBhsIe.js";
2
+ import { readFile } from "node:fs/promises";
3
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
4
+ import { existsSync } from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ // src/dependencies/installed-package.ts
7
+ async function installedPackage(root, name) {
8
+ let directory;
9
+ try {
10
+ directory = dirname(createRequire(join(root, "package.json")).resolve(name));
11
+ } catch {
12
+ return;
13
+ }
14
+ for (let depth = 0; depth < 12; depth++) {
15
+ try {
16
+ const manifest = await readObject(join(directory, "package.json"));
17
+ if (manifest.name === name) return manifest;
18
+ } catch (error) {
19
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
20
+ }
21
+ if (dirname(directory) === directory) break;
22
+ directory = dirname(directory);
23
+ }
24
+ }
25
+ // src/commands/doctor.command.ts
26
+ function available(project, name) {
27
+ if (!project.dependencies[name] && !project.devDependencies[name] && !existsSync(join(project.root, "node_modules", name))) return false;
28
+ try {
29
+ createRequire(join(project.root, "package.json")).resolve(name);
30
+ return true;
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+ async function diagnostics(project, managed, selected = "default") {
36
+ const checks = [];
37
+ const add = (level, check, message) => checks.push({
38
+ level,
39
+ check,
40
+ message
41
+ });
42
+ add(satisfies(process.versions.node, ">=24.15.0") ? "PASS" : "FAIL", "runtime", `Node.js ${process.versions.node}; requires >=24.15.0 (Bun is a package manager only)`);
43
+ add(project.hasManifest ? "PASS" : "FAIL", "manifest", project.hasManifest ? project.root : "Create package.json with duraxis init --yes");
44
+ add(project.managerConflict ? "FAIL" : "PASS", "package-manager", project.managerConflict ? "Conflicting lockfiles; choose --package-manager explicitly" : project.manager ?? "npm default (no lockfile detected)");
45
+ add("PASS", "workspace", project.workspace ? `Application ${project.root}; workspace ${project.workspace}; installations use the application directory` : "Standalone package");
46
+ const manager = project.manager ?? "npm";
47
+ const suffixes = process.platform === "win32" ? [
48
+ ".cmd",
49
+ ".exe",
50
+ ""
51
+ ] : [""];
52
+ const managerAvailable = (process.env.PATH ?? "").split(delimiter).slice(0, 512).some((directory) => suffixes.some((suffix) => existsSync(join(directory, manager + suffix))));
53
+ add(managerAvailable ? "PASS" : "WARN", "package-manager-availability", managerAvailable ? `${manager} executable found on PATH (not executed)` : `Install ${manager} or add it to PATH`);
54
+ add("PASS", "module-format", project.moduleFormat);
55
+ if (await exists(join(project.root, "tsconfig.json"))) {
56
+ const ts = (await import("typescript")).default;
57
+ const parsed = ts.readConfigFile(join(project.root, "tsconfig.json"), ts.sys.readFile);
58
+ if (parsed.error) add("FAIL", "typescript", "Cannot parse tsconfig.json");
59
+ else {
60
+ const compiler = ts.parseJsonConfigFileContent(parsed.config, ts.sys, project.root).options;
61
+ add(compiler.experimentalDecorators && compiler.emitDecoratorMetadata && compiler.useDefineForClassFields === false ? "PASS" : "WARN", "typescript", "Legacy ORM entities require experimentalDecorators:true, emitDecoratorMetadata:true, useDefineForClassFields:false; generated .mts/.cts modules require NodeNext");
62
+ }
63
+ } else add(project.language === "typescript" ? "WARN" : "SKIP", "typescript", "No tsconfig.json; use explicit fields with JavaScript decorator functions");
64
+ if (!managed) {
65
+ add(project.configFiles.length ? "WARN" : "FAIL", "configuration", project.configFiles.length ? "Executable configuration detected, not evaluated. Use config:validate --evaluate only for trusted code." : "Run duraxis init");
66
+ return checks;
67
+ }
68
+ add("PASS", "project-files", `Source ${project.sourceDir}; module candidates: ${project.nestModules.join(", ") || "none"}; entry points: ${project.entryPoints.join(", ") || "none"}; existing migration directories: ${project.migrationDirectories.join(", ") || "none"}; .gitignore: ${project.hasGitignore ? "present" : "absent"}. Inspection is bounded and does not execute source.`);
69
+ const options = managed.connections[selected];
70
+ if (!options) {
71
+ add("FAIL", "connection", "Unknown named connection");
72
+ return checks;
73
+ }
74
+ add("PASS", "configuration", `Managed version 1; connections: ${Object.keys(managed.connections).join(", ")}`);
75
+ for (const name of [...requiredPackages(options), "@duraxis/cli"]) add(available(project, name) ? "PASS" : "FAIL", `package:${name}`, available(project, name) ? "Resolvable without executing package code" : `Install ${name} in ${project.root}`);
76
+ for (const name of requiredPackages(options)) {
77
+ const manifest = await installedPackage(project.root, name);
78
+ if (!manifest) continue;
79
+ try {
80
+ if (record(manifest.engines) && typeof manifest.engines.node === "string") add(satisfies(process.versions.node, manifest.engines.node) ? "PASS" : "FAIL", `engines:${name}`, `Installed ${name} Node.js engine compatibility`);
81
+ for (const [peer, range] of Object.entries(stringMap(manifest.peerDependencies))) {
82
+ const installed = await installedPackage(project.root, peer);
83
+ const peerMeta = record(manifest.peerDependenciesMeta) ? manifest.peerDependenciesMeta[peer] : void 0;
84
+ if (!installed && record(peerMeta) && peerMeta.optional === true) continue;
85
+ add(installed && typeof installed.version === "string" && satisfies(installed.version, range) ? "PASS" : "FAIL", `peer:${name}:${peer}`, `Requires ${peer} ${range}; install compatible peer dependencies`);
86
+ }
87
+ } catch {
88
+ add("WARN", `compatibility:${name}`, "Installed metadata uses unsupported version range syntax; verify compatibility manually");
89
+ }
90
+ }
91
+ add(options.framework !== "nestjs" || options.orm ? "PASS" : "FAIL", "framework", `${options.framework}${options.framework === "nestjs" ? "; import generated module and enableShutdownHooks()" : ""}`);
92
+ if (options.cursorKeyEnv) add(/^[a-fA-F0-9]{64}$/.test(process.env[options.cursorKeyEnv] ?? "") ? "PASS" : "FAIL", "cursor-key", `Provision ${options.cursorKeyEnv} securely as 32 bytes in hex (value redacted)`);
93
+ if (options.driver === "s3") add(options.bucket || process.env.DURAXIS_S3_BUCKET ? "PASS" : "FAIL", "storage", "S3 configuration only; credentials use the default AWS chain, connectivity not tested");
94
+ else add("PASS", "storage", options.driver === "memory" ? "Volatile storage; independent CLI processes do not share data" : options.driver === "disk" ? "Exclusive directory ownership required; no automatic lock recovery" : "Custom implementation must enforce conditional operations and bounded reads");
95
+ if (options.migrations) {
96
+ const base = selected === "default" ? "duraxis" : `duraxis/${selected}`;
97
+ add(await exists(join(project.root, base, "snapshots/baseline.json")) ? "PASS" : "FAIL", "migrations", "Baseline and directories checked statically; use migrate:check --offline for artifact validation (executes trusted migration modules)");
98
+ } else add("SKIP", "migrations", "Disabled");
99
+ add("SKIP", "connectivity", "No database opened; use storage:check --live explicitly where supported");
100
+ return checks;
101
+ }
102
+ // src/commands/admin.command.ts
103
+ function plan(root) {
104
+ return {
105
+ root,
106
+ files: [],
107
+ directories: [],
108
+ warnings: [],
109
+ dependencies: {},
110
+ devDependencies: {},
111
+ commands: []
112
+ };
113
+ }
114
+ function redact(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
115
+ if (depth > 16) return "[unresolved: inspection depth limit]";
116
+ if (value && typeof value === "object") {
117
+ if (seen.has(value)) return "[circular/shared reference]";
118
+ seen.add(value);
119
+ if (Array.isArray(value)) return value.map((item) => redact(item, seen, depth + 1));
120
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, /secret|password|token|credential|signingkey|encryption|access[_-]?key|private[_-]?key|api[_-]?key|^keys?$/i.test(key) ? "[REDACTED]" : redact(item, seen, depth + 1)]));
121
+ }
122
+ if (typeof value === "function") return "[trusted function; not evaluated]";
123
+ if (typeof value === "string" && /^https?:/.test(value)) try {
124
+ const url = new URL(value);
125
+ if (url.username || url.password || url.search) return "[REDACTED URL]";
126
+ } catch {}
127
+ return value;
128
+ }
129
+ async function administer(parsed, io) {
130
+ const { values, definition, positionals } = parsed;
131
+ const cwd = values.directory ? resolve(io.cwd ?? process.cwd(), values.directory) : io.cwd ?? process.cwd();
132
+ const explicit = values.config ? resolve(cwd, values.config) : void 0;
133
+ if (explicit && !await exists(explicit)) throw new Error("Explicit configuration file does not exist");
134
+ const explicitManaged = explicit && /^duraxis\.config\.[cm]?[jt]s$/.test(basename(explicit)) && await exists(join(dirname(explicit), "duraxis.project.json"));
135
+ const managedRoot = explicit ? explicitManaged ? dirname(explicit) : void 0 : values.directory ? await exists(join(cwd, "duraxis.project.json")) ? cwd : void 0 : await findManagedRoot(cwd);
136
+ if (values.directory && !managedRoot) throw new Error("The selected directory has no managed Duraxis project; run init there first");
137
+ const project = await detectProject(managedRoot ?? (explicit ? dirname(explicit) : cwd));
138
+ if (explicit) project.configFiles = [basename(explicit)];
139
+ const root = managedRoot ?? project.root;
140
+ const managed = managedRoot ? await readManaged(root) : void 0;
141
+ const selected = values.database ?? managed?.defaultConnection ?? "default";
142
+ const selectedOptions = managed?.connections[selected];
143
+ const execute = async (files, after = async () => {}) => {
144
+ if (values["dry-run"]) return {
145
+ status: "planned",
146
+ ...describePlan(files)
147
+ };
148
+ await executeFiles(files, after);
149
+ return {
150
+ status: "updated",
151
+ files: files.files.map((f) => f.path),
152
+ warnings: files.warnings
153
+ };
154
+ };
155
+ if (definition.name === "storage:list") return [
156
+ {
157
+ driver: "memory",
158
+ persistent: false,
159
+ limitation: "Process-local volatile data",
160
+ package: "@duraxis/storage-memory"
161
+ },
162
+ {
163
+ driver: "disk",
164
+ persistent: true,
165
+ limitation: "Single-owner local directory; recovery requires operator action",
166
+ package: "@duraxis/storage-disk"
167
+ },
168
+ {
169
+ driver: "s3",
170
+ persistent: true,
171
+ limitation: "Conditional-request-compatible provider required; destructive distributed GC unsupported",
172
+ package: "@duraxis/storage-s3"
173
+ },
174
+ {
175
+ driver: "custom",
176
+ persistent: "implementation-dependent",
177
+ limitation: "Conditional semantics and bounded reads required",
178
+ package: "@duraxis/storage"
179
+ }
180
+ ].map((driver) => ({
181
+ ...driver,
182
+ available: true,
183
+ installed: available(project, driver.package),
184
+ configured: selectedOptions?.driver === driver.driver
185
+ }));
186
+ if (definition.name === "doctor") {
187
+ const checks = await diagnostics(project, managed, selected);
188
+ return {
189
+ failed: checks.some((c) => c.level === "FAIL"),
190
+ diagnostics: checks
191
+ };
192
+ }
193
+ if (definition.name === "upgrade") {
194
+ const installed = Object.fromEntries(Object.entries({
195
+ ...project.dependencies,
196
+ ...project.devDependencies
197
+ }).filter(([name]) => name.startsWith("@duraxis/")));
198
+ if (!Object.keys(installed).length) throw new Error("No Duraxis dependencies found in the selected project");
199
+ for (const [name, specification] of Object.entries(installed)) try {
200
+ satisfies("0.0.0", specification);
201
+ } catch {
202
+ throw new Error(`Cannot upgrade unsupported dependency specification for ${name}; update workspace-owned versions with workspace release tooling, or use a supported registry version range`);
203
+ }
204
+ const resolved = await resolveDependencies(Object.keys(installed), {
205
+ ...project.dependencies,
206
+ ...project.devDependencies
207
+ }, new RegistryClient(await configuredRegistry(project, values.registry), io.fetch, io.signal), values.prerelease, process.versions.node, false);
208
+ const packages = await Promise.all(Object.keys(installed).map(async (name) => {
209
+ const actual = (await installedPackage(root, name))?.version ?? installed[name];
210
+ const downgradeBlocked = typeof actual === "string" && /^v?\d+\.\d+\.\d+(?:[-+]|$)/.test(actual) && compare(resolved[name], actual) < 0;
211
+ return {
212
+ package: name,
213
+ installed: actual,
214
+ declaration: installed[name],
215
+ target: resolved[name],
216
+ downgradeBlocked,
217
+ status: downgradeBlocked ? "downgrade blocked" : actual === resolved[name] ? "up to date" : "update available"
218
+ };
219
+ }));
220
+ if (!values.apply) return {
221
+ packages,
222
+ warning: "Pre-1.0 minor updates may break compatibility. Review changelogs. No data format migration is performed."
223
+ };
224
+ if (packages.some((item) => item.downgradeBlocked)) throw new Error("Automatic downgrades are unsupported; no dependencies were changed. Review the proposed versions and workspace release state manually.");
225
+ const production = Object.fromEntries(packages.filter((p) => project.dependencies[p.package] && p.target !== p.installed).map((p) => [p.package, p.target]));
226
+ const development = Object.fromEntries(packages.filter((p) => project.devDependencies[p.package] && p.target !== p.installed).map((p) => [p.package, p.target]));
227
+ const update = plan(root);
228
+ update.commands = installCommands((await import("./package-manager-BBRBhsIe.js").then((n) => n.b)).selectManager(project, values["package-manager"]), production, development);
229
+ io.signal?.throwIfAborted();
230
+ await executeFiles(update, async () => {
231
+ for (const [command, ...args] of update.commands) await (io.runProcess ?? runProcess)({
232
+ command,
233
+ args,
234
+ cwd: root,
235
+ signal: io.signal
236
+ });
237
+ io.signal?.throwIfAborted();
238
+ });
239
+ return {
240
+ status: "updated",
241
+ packages,
242
+ warning: "Review pre-1.0 changes before deployment. Database formats were not migrated."
243
+ };
244
+ }
245
+ if (values.evaluate || definition.name === "storage:check" && values.live) {
246
+ const { config } = await (await import("./config-CjMUqEhV.js").then((n) => n.t)).loadConfig(cwd, values.config, values.database);
247
+ if (definition.name === "config:show") return {
248
+ trustedCodeEvaluated: true,
249
+ configuration: redact(config)
250
+ };
251
+ if (definition.name === "config:validate") return {
252
+ valid: true,
253
+ trustedCodeEvaluated: true,
254
+ databaseOpened: false
255
+ };
256
+ if (definition.name === "storage:check") {
257
+ if (selectedOptions?.driver === "disk" && !await exists(resolve(root, process.env[(selected === "default" ? "DURAXIS" : "DURAXIS_" + selected.toUpperCase().replace(/-/g, "_")) + "_STORAGE_DIRECTORY"] ?? selectedOptions.storageDirectory, "journal.log"))) throw new Error("Live Disk check requires an existing initialized directory; refusing to create database files");
258
+ const database = await config.createDatabase();
259
+ try {
260
+ await database.getCollectionDefinitions();
261
+ return {
262
+ valid: true,
263
+ live: true,
264
+ warning: "Trusted factory executed. Disk ownership was temporarily acquired; normal driver recovery may occur. No test objects were written."
265
+ };
266
+ } finally {
267
+ await database.close({ closeStorage: true });
268
+ }
269
+ }
270
+ }
271
+ if (!managed) return (() => {
272
+ if (definition.name === "config:show" || definition.name === "config:validate") {
273
+ if (!project.configFiles.length && !values.config) throw new Error("No configuration found; run duraxis init");
274
+ return {
275
+ unresolved: true,
276
+ files: values.config ? [resolve(cwd, values.config)] : project.configFiles,
277
+ message: "Executable configuration was not evaluated. Use --evaluate explicitly for trusted application code."
278
+ };
279
+ }
280
+ throw new Error("This operation requires duraxis.project.json managed settings; preserve executable configurations and integrate manually.");
281
+ })();
282
+ if (!selectedOptions) throw new Error("Unknown named database");
283
+ if (definition.name === "connection:list") return {
284
+ default: managed.defaultConnection,
285
+ connections: Object.entries(managed.connections).map(([name, connection]) => ({
286
+ name,
287
+ driver: connection.driver,
288
+ namespace: connection.namespace,
289
+ migrations: connection.migrations
290
+ }))
291
+ };
292
+ if (definition.name === "config:show") return {
293
+ configuration: redact(selectedOptions),
294
+ connection: selected,
295
+ environment: "Values are not read or displayed",
296
+ databaseOpened: false
297
+ };
298
+ if (definition.name === "config:validate" || definition.name === "storage:check") {
299
+ const checks = await diagnostics(project, managed, selected);
300
+ return {
301
+ failed: checks.some((c) => c.level === "FAIL"),
302
+ diagnostics: checks,
303
+ databaseOpened: false
304
+ };
305
+ }
306
+ if (definition.name === "config:set") {
307
+ const [key, value] = positionals;
308
+ if (!key || value === void 0) throw new Error("Usage: config:set <key> <value>");
309
+ if (!(/* @__PURE__ */ new Set([
310
+ "namespace",
311
+ "storageDirectory",
312
+ "bucket",
313
+ "prefix",
314
+ "region",
315
+ "endpoint",
316
+ "schemaMode"
317
+ ])).has(key)) throw new Error("Unsupported managed key; edit application factories and settings manually. Secrets must use environment references.");
318
+ if (key === "storageDirectory" && selectedOptions.driver === "disk") assertStorageDirectory(root, value, selectedOptions.sourceDir, selectedOptions.migrations);
319
+ if (key === "namespace" && (!/^[A-Za-z0-9_/-]{1,128}$/.test(value) || value.split("/").some((part) => !part || part === ".."))) throw new Error("Invalid namespace");
320
+ if (key === "schemaMode" && ![
321
+ "create",
322
+ "validate",
323
+ "validate-managed"
324
+ ].includes(value)) throw new Error("Invalid schemaMode");
325
+ if (key === "schemaMode" && selectedOptions.migrations && value === "create") throw new Error("Migrations require validation schema mode");
326
+ if (key === "endpoint") {
327
+ const url = new URL(value);
328
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error("Endpoint must not contain secrets");
329
+ }
330
+ if (/[\r\n\0]/.test(value)) throw new Error("Configuration values must not contain control characters");
331
+ if (key === "bucket" && !/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(value)) throw new Error("Invalid bucket");
332
+ const files = plan(root);
333
+ await addFile(files, "duraxis.project.json", JSON.stringify({
334
+ ...managed,
335
+ connections: {
336
+ ...managed.connections,
337
+ [selected]: {
338
+ ...selectedOptions,
339
+ [key]: value
340
+ }
341
+ }
342
+ }, null, 2) + "\n", true);
343
+ return execute(files);
344
+ }
345
+ if (definition.name === "connection:add") {
346
+ const name = connectionName(positionals[0] ?? "");
347
+ const options = await initializationOptions(project, {
348
+ ...values,
349
+ namespace: values.namespace ?? name,
350
+ language: values.language ?? selectedOptions.language,
351
+ "module-format": values["module-format"] ?? selectedOptions.moduleFormat,
352
+ "source-dir": values["source-dir"] ?? selectedOptions.sourceDir
353
+ });
354
+ if (options.driver === "disk" && Object.values(managed.connections).some((existing) => existing.driver === "disk" && existing.storageDirectory === options.storageDirectory)) throw new Error("Named Disk connections require a distinct --storage-directory to avoid ownership conflicts");
355
+ const needed = [...requiredPackages(options), "@duraxis/cli"];
356
+ const existing = {
357
+ ...project.dependencies,
358
+ ...project.devDependencies
359
+ };
360
+ const resolved = options.install ? await resolveDependencies(needed, existing, new RegistryClient(await configuredRegistry(project, values.registry), io.fetch, io.signal), values.prerelease) : Object.fromEntries(needed.map((n) => [n, existing[n] ?? "latest"]));
361
+ const dependencies = Object.fromEntries(Object.entries(resolved).filter(([n]) => n !== "@duraxis/cli" && needed.includes(n) && !existing[n]));
362
+ const dev = existing["@duraxis/cli"] ? {} : { "@duraxis/cli": resolved["@duraxis/cli"] };
363
+ const files = await planInitialization(project, options, dependencies, dev, managed, name);
364
+ files.commands = options.install ? installCommands(options.manager, dependencies, dev) : [];
365
+ if (options.install && !files.commands.length) files.commands.push([options.manager, "install"]);
366
+ return execute(files, async () => {
367
+ for (const [command, ...args] of files.commands) await (io.runProcess ?? runProcess)({
368
+ command,
369
+ args,
370
+ cwd: root,
371
+ signal: io.signal
372
+ });
373
+ });
374
+ }
375
+ if (definition.name === "generate:entity" || definition.name === "generate:module") {
376
+ const name = positionals[0];
377
+ if (!name || !/^[A-Z][A-Za-z0-9]{0,63}$/.test(name)) throw new Error("Use a PascalCase identifier (letters and digits only)");
378
+ const files = plan(root);
379
+ const { source, runtime } = extensions(selectedOptions);
380
+ const base = `${selectedOptions.sourceDir}/duraxis${selected === "default" ? "" : `/connections/${selected}`}`;
381
+ if (definition.name === "generate:entity") {
382
+ if (!selectedOptions.orm) throw new Error("Entity generation requires ORM integration");
383
+ const filename = `${name.replace(/[A-Z]/g, (letter, index) => `${index ? "-" : ""}${letter.toLowerCase()}`)}.entity`;
384
+ await addFile(files, `${base}/${filename}.${source}`, entitySource(name, name.toLowerCase() + "s", selectedOptions.language, selectedOptions.moduleFormat));
385
+ const registryPath = `${base}/entities.${source}`;
386
+ const original = await readFile(join(root, registryPath), "utf8");
387
+ const ts = (await import("typescript")).default;
388
+ const ast = ts.createSourceFile(registryPath, original, ts.ScriptTarget.Latest, true);
389
+ let array;
390
+ for (const statement of ast.statements) {
391
+ if (ts.isVariableStatement(statement)) {
392
+ for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === "entities" && declaration.initializer && ts.isArrayLiteralExpression(declaration.initializer)) array = declaration.initializer;
393
+ }
394
+ if (ts.isExpressionStatement(statement) && ts.isBinaryExpression(statement.expression) && ts.isPropertyAccessExpression(statement.expression.left) && statement.expression.left.getText(ast) === "exports.entities" && ts.isArrayLiteralExpression(statement.expression.right)) array = statement.expression.right;
395
+ }
396
+ if (!original.startsWith("// Duraxis managed entity registry") || !array || array.elements.some((e) => !ts.isIdentifier(e))) throw new Error("Entity registry is user-authored or unsupported; add the entity manually. No files were written.");
397
+ const imported = selectedOptions.language === "typescript" || selectedOptions.moduleFormat === "esm" ? `import { ${name} } from "./${filename}.${runtime}";\n` : `const { ${name} } = require("./${filename}.${runtime}");\n`;
398
+ const updated = original.slice(0, array.end - 1) + (array.elements.length ? ", " : "") + name + original.slice(array.end - 1);
399
+ await addFile(files, registryPath, "// Duraxis managed entity registry\n" + imported + updated.slice(35), true);
400
+ } else {
401
+ if (selectedOptions.framework !== "nestjs") throw new Error("Module generation requires NestJS integration");
402
+ const es = selectedOptions.language === "typescript" || selectedOptions.moduleFormat === "esm";
403
+ const imports = es ? `import { Module } from "@nestjs/common";\nimport { DuraxisModule } from "@duraxis/nestjs";\nimport { entities } from "./entities.${runtime}";` : `const { Module } = require("@nestjs/common");\nconst { DuraxisModule } = require("@duraxis/nestjs");\nconst { entities } = require("./entities.${runtime}");`;
404
+ const metadata = `{ imports: [DuraxisModule.forFeature(entities, ${JSON.stringify(selected)})], exports: [DuraxisModule] }`;
405
+ await addFile(files, `${base}/${name}.module.${source}`, `${imports}\n${selectedOptions.language === "typescript" ? `@Module(${metadata})\nexport class ${name}Module {}` : `${selectedOptions.moduleFormat === "esm" ? "export " : ""}class ${name}Module {}\nModule(${metadata})(${name}Module);\n${!es ? `exports.${name}Module = ${name}Module;` : ""}`}\n`);
406
+ }
407
+ return execute(files);
408
+ }
409
+ throw new Error(`No handler for ${definition.name}`);
410
+ }
411
+ export { administer };
412
+
413
+ //# sourceMappingURL=admin.command-Chb6x9mF.js.map