@voyantjs/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +59 -0
  3. package/bin/voyant.mjs +9 -0
  4. package/dist/commands/config.d.ts +10 -0
  5. package/dist/commands/config.d.ts.map +1 -0
  6. package/dist/commands/config.js +90 -0
  7. package/dist/commands/db-sync-links.d.ts +19 -0
  8. package/dist/commands/db-sync-links.d.ts.map +1 -0
  9. package/dist/commands/db-sync-links.js +250 -0
  10. package/dist/commands/db.d.ts +18 -0
  11. package/dist/commands/db.d.ts.map +1 -0
  12. package/dist/commands/db.js +69 -0
  13. package/dist/commands/exec.d.ts +20 -0
  14. package/dist/commands/exec.d.ts.map +1 -0
  15. package/dist/commands/exec.js +109 -0
  16. package/dist/commands/generate-link.d.ts +11 -0
  17. package/dist/commands/generate-link.d.ts.map +1 -0
  18. package/dist/commands/generate-link.js +64 -0
  19. package/dist/commands/generate-module.d.ts +13 -0
  20. package/dist/commands/generate-module.d.ts.map +1 -0
  21. package/dist/commands/generate-module.js +64 -0
  22. package/dist/commands/help.d.ts +3 -0
  23. package/dist/commands/help.d.ts.map +1 -0
  24. package/dist/commands/help.js +31 -0
  25. package/dist/commands/new.d.ts +18 -0
  26. package/dist/commands/new.d.ts.map +1 -0
  27. package/dist/commands/new.js +317 -0
  28. package/dist/index.d.ts +16 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +62 -0
  31. package/dist/lib/args.d.ts +17 -0
  32. package/dist/lib/args.d.ts.map +1 -0
  33. package/dist/lib/args.js +32 -0
  34. package/dist/lib/config-loader.d.ts +45 -0
  35. package/dist/lib/config-loader.d.ts.map +1 -0
  36. package/dist/lib/config-loader.js +69 -0
  37. package/dist/lib/fs.d.ts +5 -0
  38. package/dist/lib/fs.d.ts.map +1 -0
  39. package/dist/lib/fs.js +11 -0
  40. package/dist/lib/strings.d.ts +12 -0
  41. package/dist/lib/strings.d.ts.map +1 -0
  42. package/dist/lib/strings.js +33 -0
  43. package/dist/templates/module-files.d.ts +16 -0
  44. package/dist/templates/module-files.d.ts.map +1 -0
  45. package/dist/templates/module-files.js +157 -0
  46. package/dist/types.d.ts +13 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/dist/types.js +1 -0
  49. package/package.json +77 -0
package/LICENSE ADDED
@@ -0,0 +1,109 @@
1
+ # Functional Source License, Version 1.1, Apache 2.0 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 PixelMakers Studio SRL
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly
28
+ display and redistribute the Software for any Permitted Purpose identified
29
+ below.
30
+
31
+ ### Permitted Purpose
32
+
33
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing
34
+ Use means making the Software available to others in a commercial product or
35
+ service that:
36
+
37
+ 1. substitutes for the Software;
38
+
39
+ 2. substitutes for any other product or service we offer using the Software
40
+ that exists as of the date we make the Software available; or
41
+
42
+ 3. offers the same or substantially similar functionality as the Software.
43
+
44
+ Permitted Purposes specifically include using the Software:
45
+
46
+ 1. for your internal use and access;
47
+
48
+ 2. for non-commercial education;
49
+
50
+ 3. for non-commercial research; and
51
+
52
+ 4. in connection with professional services that you provide to a licensee
53
+ using the Software in accordance with these Terms and Conditions.
54
+
55
+ ### Patents
56
+
57
+ To the extent your use for a Permitted Purpose would necessarily infringe
58
+ our patents, the license grant above includes a license under our patents.
59
+ If you make a claim against any party that the Software infringes or
60
+ contributes to the infringement of any patent, then your patent license to
61
+ the Software ends immediately.
62
+
63
+ ### Redistribution
64
+
65
+ The Terms and Conditions apply to all copies, modifications and derivatives
66
+ of the Software.
67
+
68
+ If you redistribute any copies, modifications or derivatives of the
69
+ Software, you must include a copy of or a link to these Terms and Conditions
70
+ and not remove any copyright notices provided in or with the Software.
71
+
72
+ ### Disclaimer
73
+
74
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS
75
+ OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A
76
+ PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
77
+
78
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO
79
+ THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
80
+ DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
81
+
82
+ ### Trademarks
83
+
84
+ Except for displaying the License Details and identifying us as the origin
85
+ of the Software, you have no right under these Terms and Conditions to use
86
+ our trademarks, trade names, service marks or product names.
87
+
88
+ ---
89
+
90
+ ## Grant of Future License
91
+
92
+ We hereby irrevocably grant you an additional license to use the Software
93
+ under the Apache License, Version 2.0 that is effective on the second
94
+ anniversary of the date we make the Software available. On or after that
95
+ date, you may use the Software under the Apache License, Version 2.0, in
96
+ which case the following will apply:
97
+
98
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
99
+ use this file except in compliance with the License.
100
+
101
+ You may obtain a copy of the License at
102
+
103
+ http://www.apache.org/licenses/LICENSE-2.0
104
+
105
+ Unless required by applicable law or agreed to in writing, software
106
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
107
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
108
+ License for the specific language governing permissions and limitations
109
+ under the License.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @voyantjs/cli
2
+
3
+ The `voyant` CLI. Scaffolding, code generation, config loading, database commands, and a TypeScript script runner with native strip-types.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add -D @voyantjs/cli
9
+ ```
10
+
11
+ Or as a global install:
12
+
13
+ ```bash
14
+ npm install -g @voyantjs/cli
15
+ ```
16
+
17
+ Built-in starters can be referenced by name:
18
+
19
+ ```bash
20
+ voyant new my-app --template dmc
21
+ voyant new my-app --template operator
22
+ ```
23
+
24
+ Built-in starters are downloaded from the matching GitHub Release for the installed CLI version.
25
+
26
+ You can also point at a custom local template directory:
27
+
28
+ ```bash
29
+ voyant new my-app --template ./templates/custom
30
+ ```
31
+
32
+ ## Commands
33
+
34
+ | Command | Description |
35
+ | --- | --- |
36
+ | `voyant new <name> [--template <name\|path>] [--force]` | Clone a built-in or custom template into a new directory |
37
+ | `voyant generate module <name> [--dir <path>]` | Scaffold a new module package (schema, validation, service, routes) |
38
+ | `voyant generate link <a.entity> <b.entity>` | Print a `defineLink` snippet |
39
+ | `voyant config <show\|validate\|path> [--path <file>]` | Load + inspect `voyant.config.ts` |
40
+ | `voyant db <generate\|migrate\|studio\|push\|check>` | Drizzle-kit subcommands for the DMC template |
41
+ | `voyant db sync-links [--links <path>] [--out <file>]` | Emit DDL for link pivot tables |
42
+ | `voyant exec <script.ts> [args...]` | Run a TS script with native strip-types + extensionless imports |
43
+ | `voyant --help` | Print usage |
44
+
45
+ Requires Node 22.6+ for native TypeScript strip-types.
46
+
47
+ ## Exports
48
+
49
+ | Entry | Description |
50
+ | --- | --- |
51
+ | `.` | CLI `main(argv, ctx)` entry point |
52
+ | `./commands/*` | Individual command handlers |
53
+ | `./lib/strings` | `toKebabCase`, `toCamelCase`, `toPascalCase` |
54
+ | `./lib/args` | Hand-rolled arg parser |
55
+ | `./lib/config-loader` | `voyant.config.*` loader |
56
+
57
+ ## License
58
+
59
+ FSL-1.1-Apache-2.0
package/bin/voyant.mjs ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../dist/index.js"
3
+
4
+ main(process.argv.slice(2))
5
+ .then((code) => process.exit(code ?? 0))
6
+ .catch((err) => {
7
+ process.stderr.write(`${err?.stack ?? String(err)}\n`)
8
+ process.exit(1)
9
+ })
@@ -0,0 +1,10 @@
1
+ import type { CommandContext, CommandResult } from "../types.js";
2
+ /**
3
+ * `voyant config <show|validate|path>`
4
+ *
5
+ * Inspects the voyant.config.* manifest discovered by walking parent
6
+ * directories from the current working directory. Used by other CLI
7
+ * commands and by users verifying their configuration shape.
8
+ */
9
+ export declare function configCommand(ctx: CommandContext): Promise<CommandResult>;
10
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/commands/config.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAEhE;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC,CAwC/E"}
@@ -0,0 +1,90 @@
1
+ import { resolveEntry, validateVoyantConfig, } from "@voyantjs/core/config";
2
+ import { parseArgs } from "../lib/args.js";
3
+ import { loadVoyantConfigFile, resolveConfigPath } from "../lib/config-loader.js";
4
+ /**
5
+ * `voyant config <show|validate|path>`
6
+ *
7
+ * Inspects the voyant.config.* manifest discovered by walking parent
8
+ * directories from the current working directory. Used by other CLI
9
+ * commands and by users verifying their configuration shape.
10
+ */
11
+ export async function configCommand(ctx) {
12
+ const { positionals, flags } = parseArgs(ctx.argv);
13
+ const sub = positionals[0] ?? "show";
14
+ const pathFlag = typeof flags.path === "string" ? flags.path : undefined;
15
+ const resolved = resolveConfigPath({ path: pathFlag, cwd: ctx.cwd });
16
+ if (!resolved) {
17
+ ctx.stderr(pathFlag
18
+ ? `No voyant config found at ${pathFlag}\n`
19
+ : `No voyant.config.* found in ${ctx.cwd} or any parent directory.\n`);
20
+ return 1;
21
+ }
22
+ if (sub === "path") {
23
+ ctx.stdout(`${resolved}\n`);
24
+ return 0;
25
+ }
26
+ let loaded;
27
+ try {
28
+ loaded = await loadVoyantConfigFile(resolved);
29
+ }
30
+ catch (err) {
31
+ ctx.stderr(`${err instanceof Error ? err.message : String(err)}\n`);
32
+ return 1;
33
+ }
34
+ const result = validateVoyantConfig(loaded.config);
35
+ if (sub === "validate") {
36
+ return emitValidation(ctx, loaded.path, result);
37
+ }
38
+ if (sub === "show") {
39
+ return emitShow(ctx, loaded.path, loaded.config, result);
40
+ }
41
+ ctx.stderr(`Unknown config subcommand: ${sub}. Expected "show", "validate", or "path".\n`);
42
+ return 1;
43
+ }
44
+ function emitValidation(ctx, path, result) {
45
+ if (result.ok) {
46
+ ctx.stdout(`voyant config ok: ${path}\n`);
47
+ return 0;
48
+ }
49
+ ctx.stderr(`voyant config invalid: ${path}\n`);
50
+ for (const issue of result.issues) {
51
+ ctx.stderr(` - ${issue.path || "(root)"}: ${issue.message}\n`);
52
+ }
53
+ return 1;
54
+ }
55
+ function emitShow(ctx, path, config, validation) {
56
+ ctx.stdout(`voyant config: ${path}\n`);
57
+ if (!validation.ok) {
58
+ ctx.stderr(`\nManifest has ${validation.issues.length} issue(s):\n`);
59
+ for (const issue of validation.issues) {
60
+ ctx.stderr(` - ${issue.path || "(root)"}: ${issue.message}\n`);
61
+ }
62
+ return 1;
63
+ }
64
+ const cfg = config;
65
+ ctx.stdout(`\nDeployment: ${cfg.deployment ?? "(unset)"}\n`);
66
+ const modules = cfg.modules ?? [];
67
+ ctx.stdout(`Modules (${modules.length}):\n`);
68
+ for (const entry of modules) {
69
+ const { resolve, options } = resolveEntry(entry);
70
+ const opts = Object.keys(options).length > 0 ? ` [${Object.keys(options).join(", ")}]` : "";
71
+ ctx.stdout(` - ${resolve}${opts}\n`);
72
+ }
73
+ const plugins = cfg.plugins ?? [];
74
+ ctx.stdout(`Plugins (${plugins.length}):\n`);
75
+ for (const entry of plugins) {
76
+ const { resolve, options } = resolveEntry(entry);
77
+ const opts = Object.keys(options).length > 0 ? ` [${Object.keys(options).join(", ")}]` : "";
78
+ ctx.stdout(` - ${resolve}${opts}\n`);
79
+ }
80
+ if (cfg.admin) {
81
+ ctx.stdout(`Admin: enabled=${cfg.admin.enabled ?? false} path=${cfg.admin.path ?? "(unset)"}\n`);
82
+ }
83
+ if (cfg.featureFlags && Object.keys(cfg.featureFlags).length > 0) {
84
+ ctx.stdout("Feature flags:\n");
85
+ for (const [key, value] of Object.entries(cfg.featureFlags)) {
86
+ ctx.stdout(` - ${key}: ${value}\n`);
87
+ }
88
+ }
89
+ return 0;
90
+ }
@@ -0,0 +1,19 @@
1
+ import type { CommandContext, CommandResult } from "../types.js";
2
+ /**
3
+ * `voyant db sync-links [--links <path>] [--template <path>] [--out <file>]`
4
+ *
5
+ * Loads a template's link definitions and prints the DDL produced by
6
+ * {@link generateLinkTableSql} — one `CREATE TABLE` + N indexes per link.
7
+ *
8
+ * MVP: prints SQL to stdout (or to `--out <file>`). Does not touch the
9
+ * database. Pair with `psql` / `drizzle-kit push` to apply the DDL.
10
+ *
11
+ * The target file must export either a named `links` array or a default-
12
+ * exported array of {@link LinkDefinition} objects.
13
+ *
14
+ * For `.ts` source files, this command spawns a Node subprocess with
15
+ * `--experimental-strip-types --experimental-transform-types` so that
16
+ * NodeNext-style `.js` import specifiers resolve to sibling `.ts` files.
17
+ */
18
+ export declare function dbSyncLinksCommand(ctx: CommandContext): Promise<CommandResult>;
19
+ //# sourceMappingURL=db-sync-links.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db-sync-links.d.ts","sourceRoot":"","sources":["../../src/commands/db-sync-links.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAiBhE;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC,CA4CpF"}
@@ -0,0 +1,250 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, writeFileSync } from "node:fs";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { generateLinkTableSql } from "@voyantjs/core/links";
6
+ import { parseArgs } from "../lib/args.js";
7
+ /**
8
+ * Candidate locations (relative to a template root) where a `links` array
9
+ * may live. Probed in declaration order, first hit wins.
10
+ */
11
+ const DEFAULT_LINKS_PATHS = [
12
+ "src/links/index.ts",
13
+ "src/links/index.mts",
14
+ "src/links/index.mjs",
15
+ "src/links/index.js",
16
+ "src/links.ts",
17
+ "src/links.mts",
18
+ "src/links.mjs",
19
+ "src/links.js",
20
+ ];
21
+ /**
22
+ * `voyant db sync-links [--links <path>] [--template <path>] [--out <file>]`
23
+ *
24
+ * Loads a template's link definitions and prints the DDL produced by
25
+ * {@link generateLinkTableSql} — one `CREATE TABLE` + N indexes per link.
26
+ *
27
+ * MVP: prints SQL to stdout (or to `--out <file>`). Does not touch the
28
+ * database. Pair with `psql` / `drizzle-kit push` to apply the DDL.
29
+ *
30
+ * The target file must export either a named `links` array or a default-
31
+ * exported array of {@link LinkDefinition} objects.
32
+ *
33
+ * For `.ts` source files, this command spawns a Node subprocess with
34
+ * `--experimental-strip-types --experimental-transform-types` so that
35
+ * NodeNext-style `.js` import specifiers resolve to sibling `.ts` files.
36
+ */
37
+ export async function dbSyncLinksCommand(ctx) {
38
+ const { flags } = parseArgs(ctx.argv);
39
+ const linksPath = resolveLinksPath(ctx.cwd, flags);
40
+ if (!linksPath) {
41
+ ctx.stderr("Could not find a links file. " +
42
+ "Pass --links <path> or --template <path>, or run this from a template directory.\n");
43
+ return 1;
44
+ }
45
+ let links;
46
+ try {
47
+ links = await loadLinks(linksPath);
48
+ }
49
+ catch (err) {
50
+ const reason = err instanceof Error ? err.message : String(err);
51
+ ctx.stderr(`Failed to load links from ${linksPath}: ${reason}\n`);
52
+ return 1;
53
+ }
54
+ if (links.length === 0) {
55
+ ctx.stderr(`No link definitions exported from ${linksPath}\n`);
56
+ return 1;
57
+ }
58
+ const sql = renderLinksSql(links, linksPath);
59
+ const outFlag = flags.out;
60
+ if (typeof outFlag === "string") {
61
+ const outPath = isAbsolute(outFlag) ? outFlag : resolve(ctx.cwd, outFlag);
62
+ try {
63
+ writeFileSync(outPath, sql);
64
+ }
65
+ catch (err) {
66
+ const reason = err instanceof Error ? err.message : String(err);
67
+ ctx.stderr(`Failed to write ${outPath}: ${reason}\n`);
68
+ return 1;
69
+ }
70
+ ctx.stdout(`Wrote ${links.length} link table(s) to ${outPath}\n`);
71
+ return 0;
72
+ }
73
+ ctx.stdout(sql);
74
+ return 0;
75
+ }
76
+ function resolveLinksPath(cwd, flags) {
77
+ // --links <path> takes priority.
78
+ if (typeof flags.links === "string") {
79
+ const abs = isAbsolute(flags.links) ? flags.links : resolve(cwd, flags.links);
80
+ return existsSync(abs) ? abs : null;
81
+ }
82
+ // --template <path> locks us to a single template root.
83
+ const templateOverride = typeof flags.template === "string" ? flags.template : null;
84
+ const roots = templateOverride
85
+ ? [isAbsolute(templateOverride) ? templateOverride : resolve(cwd, templateOverride)]
86
+ : [join(cwd, "templates/dmc"), cwd];
87
+ for (const root of roots) {
88
+ for (const rel of DEFAULT_LINKS_PATHS) {
89
+ const candidate = join(root, rel);
90
+ if (existsSync(candidate))
91
+ return candidate;
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+ async function loadLinks(absPath) {
97
+ const isTypeScript = /\.(m|c)?ts$/i.test(absPath);
98
+ const raw = isTypeScript
99
+ ? await loadLinksViaSubprocess(absPath)
100
+ : await loadLinksViaImport(absPath);
101
+ if (!Array.isArray(raw)) {
102
+ throw new Error("expected a named export `links` or a default-exported array of LinkDefinition");
103
+ }
104
+ // Shape-check each entry so we fail with a useful message.
105
+ for (const [i, def] of raw.entries()) {
106
+ if (!def || typeof def !== "object") {
107
+ throw new Error(`links[${i}] is not an object`);
108
+ }
109
+ const d = def;
110
+ if (!d.tableName || !d.leftColumn || !d.rightColumn || !d.left || !d.right) {
111
+ throw new Error(`links[${i}] is not a LinkDefinition (missing tableName/leftColumn/rightColumn/left/right)`);
112
+ }
113
+ }
114
+ return raw;
115
+ }
116
+ async function loadLinksViaImport(absPath) {
117
+ const href = pathToFileURL(absPath).href;
118
+ const mod = (await import(href));
119
+ return mod.links ?? mod.default;
120
+ }
121
+ /**
122
+ * Node loader hook that rewrites NodeNext-style `.js` specifiers to the
123
+ * matching TypeScript source on disk. This is what TypeScript's
124
+ * `rewriteRelativeImportExtensions` does at compile time; here we do it
125
+ * at resolve time so the template's source tree imports as-is.
126
+ *
127
+ * Emitted as a data: URL so we can ship it without touching the
128
+ * filesystem.
129
+ */
130
+ const LOADER_HOOK_SRC = `
131
+ import { existsSync, statSync } from "node:fs"
132
+ import { fileURLToPath, pathToFileURL } from "node:url"
133
+ function tryResolveTs(specifier, parentDir) {
134
+ // Rewrite NodeNext-style .js -> .ts / .mjs -> .mts / .cjs -> .cts.
135
+ if (specifier.endsWith(".js") || specifier.endsWith(".mjs") || specifier.endsWith(".cjs")) {
136
+ const ext = specifier.endsWith(".mjs") ? ".mjs" : specifier.endsWith(".cjs") ? ".cjs" : ".js"
137
+ const tsExt = ext === ".mjs" ? ".mts" : ext === ".cjs" ? ".cts" : ".ts"
138
+ const candidate = parentDir + "/" + specifier.slice(0, -ext.length) + tsExt
139
+ if (existsSync(candidate)) return candidate
140
+ return null
141
+ }
142
+ // Bundler-style extensionless imports: try .ts / .mts / /index.ts.
143
+ const base = parentDir + "/" + specifier
144
+ for (const ext of [".ts", ".mts", ".tsx"]) {
145
+ if (existsSync(base + ext)) return base + ext
146
+ }
147
+ try {
148
+ if (statSync(base).isDirectory()) {
149
+ for (const idx of ["/index.ts", "/index.mts", "/index.tsx"]) {
150
+ if (existsSync(base + idx)) return base + idx
151
+ }
152
+ }
153
+ } catch {}
154
+ return null
155
+ }
156
+ export async function resolve(specifier, context, nextResolve) {
157
+ if ((specifier.startsWith("./") || specifier.startsWith("../")) && context.parentURL) {
158
+ const parentPath = fileURLToPath(context.parentURL)
159
+ const lastSlash = parentPath.lastIndexOf("/")
160
+ const parentDir = lastSlash >= 0 ? parentPath.slice(0, lastSlash) : parentPath
161
+ const found = tryResolveTs(specifier, parentDir)
162
+ if (found) return nextResolve(pathToFileURL(found).href, context)
163
+ }
164
+ return nextResolve(specifier, context)
165
+ }
166
+ `;
167
+ const REGISTER_HOOK_SRC = `import { register } from "node:module";` +
168
+ `register(${JSON.stringify(`data:text/javascript,${encodeURIComponent(LOADER_HOOK_SRC)}`)},` +
169
+ ` import.meta.url);`;
170
+ /**
171
+ * Spawn a Node subprocess that imports the TypeScript file with
172
+ * transform-types + a resolver hook that rewrites `.js` specifiers to
173
+ * their `.ts` siblings. Prints the link array as JSON.
174
+ *
175
+ * LinkDefinitions are plain data (no functions), so JSON round-tripping
176
+ * preserves their shape.
177
+ */
178
+ async function loadLinksViaSubprocess(absPath) {
179
+ const href = pathToFileURL(absPath).href;
180
+ // Marker prefix so we can skip over any logs / warnings emitted on
181
+ // stdout before the JSON payload.
182
+ const marker = "__VOYANT_LINKS_JSON__:";
183
+ const script = `import(${JSON.stringify(href)}).then((m)=>{` +
184
+ `const v=m.links??m.default;` +
185
+ `process.stdout.write(${JSON.stringify(marker)}+JSON.stringify(v??null));` +
186
+ `}).catch((e)=>{` +
187
+ `process.stderr.write(e?.stack??String(e));` +
188
+ `process.exit(1);` +
189
+ `});`;
190
+ const importHookUrl = `data:text/javascript,${encodeURIComponent(REGISTER_HOOK_SRC)}`;
191
+ const args = [
192
+ "--experimental-strip-types",
193
+ "--experimental-transform-types",
194
+ "--no-warnings",
195
+ `--import=${importHookUrl}`,
196
+ "--input-type=module",
197
+ "-e",
198
+ script,
199
+ ];
200
+ return new Promise((resolvePromise, rejectPromise) => {
201
+ const child = spawn(process.execPath, args, { stdio: ["ignore", "pipe", "pipe"] });
202
+ let stdout = "";
203
+ let stderr = "";
204
+ child.stdout.on("data", (d) => {
205
+ stdout += d.toString();
206
+ });
207
+ child.stderr.on("data", (d) => {
208
+ stderr += d.toString();
209
+ });
210
+ child.on("error", (err) => rejectPromise(err));
211
+ child.on("exit", (code) => {
212
+ if (code !== 0) {
213
+ rejectPromise(new Error(stderr.trim() || `subprocess exited with code ${code}`));
214
+ return;
215
+ }
216
+ const idx = stdout.indexOf(marker);
217
+ if (idx < 0) {
218
+ rejectPromise(new Error("subprocess returned no link payload"));
219
+ return;
220
+ }
221
+ const payload = stdout.slice(idx + marker.length).trim();
222
+ try {
223
+ resolvePromise(JSON.parse(payload));
224
+ }
225
+ catch (err) {
226
+ const reason = err instanceof Error ? err.message : String(err);
227
+ rejectPromise(new Error(`could not parse link payload: ${reason}`));
228
+ }
229
+ });
230
+ });
231
+ }
232
+ function renderLinksSql(links, sourcePath) {
233
+ const lines = [];
234
+ lines.push("-- Voyant link tables — generated by `voyant db sync-links`");
235
+ lines.push(`-- Source: ${sourcePath}`);
236
+ lines.push(`-- ${links.length} link${links.length === 1 ? "" : "s"}`);
237
+ lines.push("");
238
+ for (const link of links) {
239
+ const sql = generateLinkTableSql(link);
240
+ const leftRef = `${link.left.linkable.module}.${link.left.linkable.entity}`;
241
+ const rightRef = `${link.right.linkable.module}.${link.right.linkable.entity}`;
242
+ lines.push(`-- ${leftRef} <-> ${rightRef} (${link.cardinality})`);
243
+ lines.push(`${sql.createTable};`);
244
+ for (const idx of sql.indexes) {
245
+ lines.push(`${idx};`);
246
+ }
247
+ lines.push("");
248
+ }
249
+ return `${lines.join("\n")}\n`;
250
+ }
@@ -0,0 +1,18 @@
1
+ import type { CommandContext, CommandResult } from "../types.js";
2
+ /**
3
+ * `voyant db <subcommand>` — proxy drizzle-kit operations to the nearest
4
+ * template package that owns a `drizzle.config.ts`, plus Voyant-specific
5
+ * database helpers that don't map 1:1 onto drizzle-kit.
6
+ *
7
+ * Drizzle-kit proxies: `generate`, `migrate`, `studio`, `push`, `check`.
8
+ * Additional arguments are forwarded verbatim.
9
+ *
10
+ * Voyant helpers:
11
+ * - `sync-links` — emit DDL for cross-module link tables from a template's
12
+ * `links` array (see {@link dbSyncLinksCommand}).
13
+ *
14
+ * Resolution order for drizzle-kit proxies (first hit wins): `--template
15
+ * <path>`, `templates/dmc`, or the current working directory.
16
+ */
17
+ export declare function dbCommand(ctx: CommandContext): Promise<CommandResult>;
18
+ //# sourceMappingURL=db.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/commands/db.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAGhE;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,SAAS,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC,CA4C3E"}
@@ -0,0 +1,69 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { parseArgs } from "../lib/args.js";
5
+ import { dbSyncLinksCommand } from "./db-sync-links.js";
6
+ /**
7
+ * `voyant db <subcommand>` — proxy drizzle-kit operations to the nearest
8
+ * template package that owns a `drizzle.config.ts`, plus Voyant-specific
9
+ * database helpers that don't map 1:1 onto drizzle-kit.
10
+ *
11
+ * Drizzle-kit proxies: `generate`, `migrate`, `studio`, `push`, `check`.
12
+ * Additional arguments are forwarded verbatim.
13
+ *
14
+ * Voyant helpers:
15
+ * - `sync-links` — emit DDL for cross-module link tables from a template's
16
+ * `links` array (see {@link dbSyncLinksCommand}).
17
+ *
18
+ * Resolution order for drizzle-kit proxies (first hit wins): `--template
19
+ * <path>`, `templates/dmc`, or the current working directory.
20
+ */
21
+ export async function dbCommand(ctx) {
22
+ const { positionals, flags } = parseArgs(ctx.argv);
23
+ const [sub, ...rest] = positionals;
24
+ if (!sub) {
25
+ ctx.stderr("Usage: voyant db <generate|migrate|studio|push|check|sync-links> [...args]\n");
26
+ return 1;
27
+ }
28
+ // Voyant-specific helpers — do not proxy to drizzle-kit.
29
+ if (sub === "sync-links") {
30
+ const idx = ctx.argv.indexOf(sub);
31
+ const subArgs = idx >= 0 ? ctx.argv.slice(idx + 1) : [];
32
+ return dbSyncLinksCommand({ ...ctx, argv: subArgs });
33
+ }
34
+ const known = new Set(["generate", "migrate", "studio", "push", "check"]);
35
+ if (!known.has(sub)) {
36
+ ctx.stderr(`Unknown drizzle-kit subcommand: ${sub}\n`);
37
+ return 1;
38
+ }
39
+ const templateDir = resolveTemplateDir(ctx.cwd, flags.template);
40
+ if (!templateDir) {
41
+ ctx.stderr("Could not find a template with drizzle.config.ts. " +
42
+ "Run this command from the repo root, or pass --template <path>.\n");
43
+ return 1;
44
+ }
45
+ const args = ["drizzle-kit", sub, ...rest];
46
+ ctx.stdout(`> pnpm -C ${templateDir} ${args.join(" ")}\n`);
47
+ return new Promise((resolve) => {
48
+ const child = spawn("pnpm", ["-C", templateDir, ...args], {
49
+ stdio: "inherit",
50
+ shell: false,
51
+ });
52
+ child.on("exit", (code) => resolve(code ?? 0));
53
+ child.on("error", (err) => {
54
+ ctx.stderr(`Failed to spawn pnpm: ${err.message}\n`);
55
+ resolve(1);
56
+ });
57
+ });
58
+ }
59
+ function resolveTemplateDir(cwd, override) {
60
+ if (typeof override === "string") {
61
+ return existsSync(join(override, "drizzle.config.ts")) ? override : null;
62
+ }
63
+ const candidates = [join(cwd, "templates/dmc"), cwd];
64
+ for (const candidate of candidates) {
65
+ if (existsSync(join(candidate, "drizzle.config.ts")))
66
+ return candidate;
67
+ }
68
+ return null;
69
+ }
@@ -0,0 +1,20 @@
1
+ import type { CommandContext, CommandResult } from "../types.js";
2
+ /**
3
+ * `voyant exec <script> [args...]`
4
+ *
5
+ * Run a TypeScript/JavaScript script inside a Node subprocess with
6
+ * `--experimental-strip-types --experimental-transform-types` + the
7
+ * voyant loader hook (so bundler-style and `.js`→`.ts` imports work
8
+ * out of the box).
9
+ *
10
+ * The script receives `args` via `process.argv` starting at position 2
11
+ * (standard Node behavior). Stdout/stderr are inherited, so the
12
+ * script can log freely and its exit code propagates.
13
+ *
14
+ * Use this for:
15
+ * - one-off migrations or data tasks
16
+ * - exercising workspace code without bundling
17
+ * - reproducing test cases that hit real module code paths
18
+ */
19
+ export declare function execCommand(ctx: CommandContext): Promise<CommandResult>;
20
+ //# sourceMappingURL=exec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../src/commands/exec.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAmDhE;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC,CA6C7E"}