@lunora/cli 1.0.0-alpha.22 → 1.0.0-alpha.23

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.
@@ -1,105 +1,43 @@
1
- import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, writeFileSync } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
- import { AGENT_RULES_DIR, detectAgentRules, LUNORA_SKILL_NAMES } from '@lunora/config';
4
- import { join, relative, dirname } from '@visulima/path';
5
1
  import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
2
+ import { r as runAddCommand, b as runRegistryViewCommand, a as runBuildIndexCommand } from '../packem_shared/commands-hl0mRqqg.mjs';
6
3
 
7
- const resolveBundledSkillsDirectory = (startDirectory = dirname(fileURLToPath(import.meta.url))) => {
8
- let directory = startDirectory;
9
- for (let index = 0; index < 6; index += 1) {
10
- const packageJson = join(directory, "package.json");
11
- if (existsSync(packageJson)) {
12
- try {
13
- const parsed = JSON.parse(readFileSync(packageJson, "utf8"));
14
- if (parsed.name === "@lunora/cli") {
15
- const skills = join(directory, "skills");
16
- return existsSync(skills) ? skills : void 0;
17
- }
18
- } catch {
19
- }
20
- }
21
- const parent = dirname(directory);
22
- if (parent === directory) {
23
- break;
24
- }
25
- directory = parent;
26
- }
27
- return void 0;
28
- };
29
- const listBundledSkills = (skillsDirectory) => readdirSync(skillsDirectory).filter((name) => {
30
- const directory = join(skillsDirectory, name);
31
- return statSync(directory).isDirectory() && existsSync(join(directory, "SKILL.md"));
32
- });
33
- const copySkill = (source, destination, overwrite) => {
34
- mkdirSync(destination, { recursive: true });
35
- let wrote = false;
36
- for (const entry of readdirSync(source)) {
37
- const from = join(source, entry);
38
- const to = join(destination, entry);
39
- if (statSync(from).isDirectory()) {
40
- wrote = copySkill(from, to, overwrite) || wrote;
41
- continue;
42
- }
43
- if (existsSync(to) && !overwrite) {
44
- continue;
45
- }
46
- writeFileSync(to, readFileSync(from));
47
- wrote = true;
48
- }
49
- return wrote;
50
- };
51
- const runRulesInstall = (options) => {
52
- const cwd = options.cwd ?? process.cwd();
53
- const overwrite = options.overwrite === true;
54
- const skillsDirectory = resolveBundledSkillsDirectory();
55
- if (skillsDirectory === void 0) {
56
- options.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?).");
57
- return { code: 1, installed: [], skipped: [] };
58
- }
59
- const installed = [];
60
- const skipped = [];
61
- for (const name of listBundledSkills(skillsDirectory)) {
62
- const destination = join(cwd, AGENT_RULES_DIR, name);
63
- const wrote = copySkill(join(skillsDirectory, name), destination, overwrite);
64
- if (wrote) {
65
- installed.push(name);
66
- } else {
67
- skipped.push(name);
68
- }
69
- }
70
- const target = relative(cwd, join(cwd, AGENT_RULES_DIR)) || AGENT_RULES_DIR;
71
- if (installed.length > 0) {
72
- options.logger.success(`Installed ${String(installed.length)} Lunora skill(s) into ${target}/: ${installed.join(", ")}.`);
73
- }
74
- if (skipped.length > 0) {
75
- options.logger.info(`Skipped ${String(skipped.length)} existing skill(s) (re-run with --overwrite to replace): ${skipped.join(", ")}.`);
76
- }
77
- options.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill.");
78
- return { code: 0, installed, skipped };
79
- };
80
- const runRulesCheck = (options) => {
81
- const cwd = options.cwd ?? process.cwd();
82
- const status = detectAgentRules(cwd);
83
- if (status.installed) {
84
- options.logger.success(`Lunora agent rules are installed (${String(status.present.length)}/${String(LUNORA_SKILL_NAMES.length)} skills).`);
85
- if (status.missing.length > 0) {
86
- options.logger.info(`Missing: ${status.missing.join(", ")}. Run \`lunora rules install\` to add them.`);
87
- }
88
- return { code: 0, installed: status.present, skipped: [] };
89
- }
90
- options.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora.");
91
- return { code: options.strict === true ? 1 : 0, installed: status.present, skipped: [] };
92
- };
93
4
  const execute = defineHandler(({ argument, cwd, logger, options }) => {
94
- const subcommand = argument[0] ?? "check";
95
- if (subcommand === "install") {
96
- return runRulesInstall({ cwd, logger, overwrite: options.overwrite === true });
97
- }
98
- if (subcommand === "check") {
99
- return runRulesCheck({ cwd, logger, strict: options.strict === true });
100
- }
101
- logger.error("rules: unknown subcommand. Usage: lunora rules <install|check>");
5
+ const subcommand = argument[0];
6
+ const names = argument.slice(1);
7
+ if (subcommand === "add") {
8
+ return runAddCommand({
9
+ allowUnsafeSource: options.allowUnsafeSource === true,
10
+ cwd,
11
+ diff: options.diff === true,
12
+ dryRun: options.dryRun === true,
13
+ from: options.from,
14
+ json: options.json === true,
15
+ logger,
16
+ names,
17
+ overwrite: options.overwrite === true,
18
+ ref: options.ref,
19
+ source: options.source,
20
+ yes: options.yes === true
21
+ });
22
+ }
23
+ if (subcommand === "list") {
24
+ return runAddCommand({ cwd, from: options.from, json: options.json === true, list: true, logger, names: [], ref: options.ref, source: options.source });
25
+ }
26
+ if (subcommand === "view") {
27
+ return runRegistryViewCommand({
28
+ allowUnsafeSource: options.allowUnsafeSource === true,
29
+ from: options.from,
30
+ logger,
31
+ names,
32
+ ref: options.ref,
33
+ source: options.source
34
+ });
35
+ }
36
+ if (subcommand === "build") {
37
+ return runBuildIndexCommand({ check: options.check === true, from: options.from, logger, out: options.out });
38
+ }
39
+ logger.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]");
102
40
  return { code: 1 };
103
41
  });
104
42
 
105
- export { execute, resolveBundledSkillsDirectory, runRulesCheck, runRulesInstall };
43
+ export { execute };
@@ -1,170 +1,105 @@
1
- import { existsSync } from 'node:fs';
2
- import { mkdtemp, writeFile, rm } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
- import { discoverSchema, schemaFromIr } from '@lunora/codegen';
5
- import { seedPlan } from '@lunora/seed';
6
- import { join } from '@visulima/path';
7
- import { Project } from 'ts-morph';
1
+ import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { AGENT_RULES_DIR, detectAgentRules, LUNORA_SKILL_NAMES } from '@lunora/config';
4
+ import { join, relative, dirname } from '@visulima/path';
8
5
  import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
9
- import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
10
- import { b as tuiConfirm } from '../packem_shared/tui-prompts-M6OWsuyw.mjs';
11
- import { runImportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
12
- import { runResetCommand } from './runResetCommand.mjs';
13
6
 
14
- const isLocalUrl = (url) => {
15
- if (url === void 0) {
16
- return true;
17
- }
18
- try {
19
- const { hostname } = new URL(url);
20
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
21
- } catch {
22
- return false;
23
- }
24
- };
25
- const ndjsonReplacer = (_key, value) => {
26
- if (typeof value === "bigint") {
27
- return Number(value);
28
- }
29
- if (value instanceof ArrayBuffer) {
30
- return [...new Uint8Array(value)];
31
- }
32
- return value;
33
- };
34
- const seedFailure = (code) => {
35
- return { code, conflicts: 0, generated: 0, inserted: 0, ndjson: "" };
36
- };
37
- const guardSeedTargets = (options, schemaPath) => {
38
- if (!existsSync(schemaPath)) {
39
- options.logger.error(`schema not found: ${schemaPath} — run \`vis generate lunora-table --name=<name>\` to create one`);
40
- return seedFailure(1);
41
- }
42
- if (options.reset === true && (options.prod === true || !isLocalUrl(options.url))) {
43
- options.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url");
44
- return seedFailure(1);
7
+ const resolveBundledSkillsDirectory = (startDirectory = dirname(fileURLToPath(import.meta.url))) => {
8
+ let directory = startDirectory;
9
+ for (let index = 0; index < 6; index += 1) {
10
+ const packageJson = join(directory, "package.json");
11
+ if (existsSync(packageJson)) {
12
+ try {
13
+ const parsed = JSON.parse(readFileSync(packageJson, "utf8"));
14
+ if (parsed.name === "@lunora/cli") {
15
+ const skills = join(directory, "skills");
16
+ return existsSync(skills) ? skills : void 0;
17
+ }
18
+ } catch {
19
+ }
20
+ }
21
+ const parent = dirname(directory);
22
+ if (parent === directory) {
23
+ break;
24
+ }
25
+ directory = parent;
45
26
  }
46
27
  return void 0;
47
28
  };
48
- const insertSeedRows = async (ndjson, generated, cwd, options) => {
49
- const scratchDirectory = await mkdtemp(join(tmpdir(), "lunora-seed-"));
50
- const temporaryFile = join(scratchDirectory, "rows.ndjson");
51
- await writeFile(temporaryFile, ndjson, "utf8");
52
- try {
53
- const result = await runImportCommand({
54
- batchSize: options.batchSize,
55
- fetchImpl: options.fetchImpl,
56
- file: temporaryFile,
57
- logger: options.logger,
58
- prod: options.prod,
59
- token: options.token,
60
- url: options.url
61
- });
62
- const conflicts = result.body?.conflicts ?? 0;
63
- if (conflicts > 0) {
64
- options.logger.warn(
65
- `${String(conflicts)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`
66
- );
29
+ const listBundledSkills = (skillsDirectory) => readdirSync(skillsDirectory).filter((name) => {
30
+ const directory = join(skillsDirectory, name);
31
+ return statSync(directory).isDirectory() && existsSync(join(directory, "SKILL.md"));
32
+ });
33
+ const copySkill = (source, destination, overwrite) => {
34
+ mkdirSync(destination, { recursive: true });
35
+ let wrote = false;
36
+ for (const entry of readdirSync(source)) {
37
+ const from = join(source, entry);
38
+ const to = join(destination, entry);
39
+ if (statSync(from).isDirectory()) {
40
+ wrote = copySkill(from, to, overwrite) || wrote;
41
+ continue;
67
42
  }
68
- return { code: result.code, conflicts, generated, inserted: result.inserted, ndjson };
69
- } finally {
70
- await rm(scratchDirectory, { force: true, recursive: true }).catch(() => {
71
- });
72
- }
73
- };
74
- const validateSeedTable = (options, ir) => {
75
- if (options.table === void 0 || ir.tables.some((table) => table.name === options.table)) {
76
- return void 0;
43
+ if (existsSync(to) && !overwrite) {
44
+ continue;
45
+ }
46
+ writeFileSync(to, readFileSync(from));
47
+ wrote = true;
77
48
  }
78
- const available = ir.tables.map((table) => table.name).join(", ");
79
- options.logger.error(`unknown table "${options.table}" — schema defines: ${available || "(no tables)"}`);
80
- return seedFailure(1);
49
+ return wrote;
81
50
  };
82
- const confirmRemoteSeedTarget = async (options, generated) => {
83
- const targetsRemote = options.prod === true || !isLocalUrl(options.url);
84
- if (!targetsRemote || options.yes === true) {
85
- return void 0;
51
+ const runRulesInstall = (options) => {
52
+ const cwd = options.cwd ?? process.cwd();
53
+ const overwrite = options.overwrite === true;
54
+ const skillsDirectory = resolveBundledSkillsDirectory();
55
+ if (skillsDirectory === void 0) {
56
+ options.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?).");
57
+ return { code: 1, installed: [], skipped: [] };
58
+ }
59
+ const installed = [];
60
+ const skipped = [];
61
+ for (const name of listBundledSkills(skillsDirectory)) {
62
+ const destination = join(cwd, AGENT_RULES_DIR, name);
63
+ const wrote = copySkill(join(skillsDirectory, name), destination, overwrite);
64
+ if (wrote) {
65
+ installed.push(name);
66
+ } else {
67
+ skipped.push(name);
68
+ }
86
69
  }
87
- if (!process.stdin.isTTY && options.confirm === void 0) {
88
- options.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes");
89
- return seedFailure(1);
70
+ const target = relative(cwd, join(cwd, AGENT_RULES_DIR)) || AGENT_RULES_DIR;
71
+ if (installed.length > 0) {
72
+ options.logger.success(`Installed ${String(installed.length)} Lunora skill(s) into ${target}/: ${installed.join(", ")}.`);
90
73
  }
91
- const confirmer = options.confirm ?? tuiConfirm;
92
- const confirmed = await confirmer(`This will insert ${String(generated)} generated row(s) into ${options.url ?? "the production worker"}. Continue?`);
93
- if (!confirmed) {
94
- options.logger.info("seed: aborted");
95
- return seedFailure(1);
74
+ if (skipped.length > 0) {
75
+ options.logger.info(`Skipped ${String(skipped.length)} existing skill(s) (re-run with --overwrite to replace): ${skipped.join(", ")}.`);
96
76
  }
97
- return void 0;
77
+ options.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill.");
78
+ return { code: 0, installed, skipped };
98
79
  };
99
- const runSeedCommand = async (options) => {
80
+ const runRulesCheck = (options) => {
100
81
  const cwd = options.cwd ?? process.cwd();
101
- const schemaPath = join(cwd, "lunora", "schema.ts");
102
- const guard = guardSeedTargets(options, schemaPath);
103
- if (guard !== void 0) {
104
- return guard;
105
- }
106
- const project = new Project({ skipAddingFilesFromTsConfig: true });
107
- const ir = discoverSchema(project, schemaPath);
108
- const unknownTable = validateSeedTable(options, ir);
109
- if (unknownTable !== void 0) {
110
- return unknownTable;
111
- }
112
- const schema = schemaFromIr(ir);
113
- const plan = seedPlan(schema, {
114
- defaultCount: options.count ?? 10,
115
- only: options.table === void 0 ? void 0 : [options.table],
116
- seed: options.seed ?? 0
117
- });
118
- const lines = [];
119
- for (const { rows, table } of plan) {
120
- for (const row of rows) {
121
- lines.push(JSON.stringify({ doc: row, table }, ndjsonReplacer));
82
+ const status = detectAgentRules(cwd);
83
+ if (status.installed) {
84
+ options.logger.success(`Lunora agent rules are installed (${String(status.present.length)}/${String(LUNORA_SKILL_NAMES.length)} skills).`);
85
+ if (status.missing.length > 0) {
86
+ options.logger.info(`Missing: ${status.missing.join(", ")}. Run \`lunora rules install\` to add them.`);
122
87
  }
88
+ return { code: 0, installed: status.present, skipped: [] };
123
89
  }
124
- const ndjson = lines.length > 0 ? `${lines.join("\n")}
125
- ` : "";
126
- const generated = lines.length;
127
- if (options.dryRun === true) {
128
- if (ndjson.length > 0) {
129
- process.stdout.write(ndjson);
130
- }
131
- options.logger.info(`generated ${String(generated)} row(s) across ${String(plan.length)} table(s) — dry run, nothing inserted`);
132
- return { code: 0, conflicts: 0, generated, inserted: 0, ndjson };
133
- }
134
- if (options.reset === true) {
135
- const reset = await runResetCommand({ cwd, logger: options.logger, yes: true });
136
- if (reset.code !== 0) {
137
- return { code: reset.code, conflicts: 0, generated, inserted: 0, ndjson };
138
- }
139
- }
140
- if (generated === 0) {
141
- options.logger.warn("no rows generated — nothing to insert");
142
- return { code: 0, conflicts: 0, generated: 0, inserted: 0, ndjson };
90
+ options.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora.");
91
+ return { code: options.strict === true ? 1 : 0, installed: status.present, skipped: [] };
92
+ };
93
+ const execute = defineHandler(({ argument, cwd, logger, options }) => {
94
+ const subcommand = argument[0] ?? "check";
95
+ if (subcommand === "install") {
96
+ return runRulesInstall({ cwd, logger, overwrite: options.overwrite === true });
143
97
  }
144
- const aborted = await confirmRemoteSeedTarget(options, generated);
145
- if (aborted !== void 0) {
146
- return aborted;
98
+ if (subcommand === "check") {
99
+ return runRulesCheck({ cwd, logger, strict: options.strict === true });
147
100
  }
148
- return insertSeedRows(ndjson, generated, cwd, options);
149
- };
150
- const execute = defineHandler(async ({ cwd, logger, options }) => {
151
- const result = await runSeedCommand({
152
- batchSize: options.batchSize,
153
- count: options.count,
154
- cwd,
155
- dryRun: options.dryRun === true,
156
- logger,
157
- prod: options.prod === true,
158
- reset: options.reset === true,
159
- seed: options.seed,
160
- table: options.table,
161
- token: options.token,
162
- // Resolve the link here (only under --prod) so seed's own remote/confirm
163
- // logic and the downstream import both see the same effective target.
164
- url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url }),
165
- yes: options.yes === true
166
- });
167
- return { code: result.code };
101
+ logger.error("rules: unknown subcommand. Usage: lunora rules <install|check>");
102
+ return { code: 1 };
168
103
  });
169
104
 
170
- export { execute, runSeedCommand };
105
+ export { execute, resolveBundledSkillsDirectory, runRulesCheck, runRulesInstall };
@@ -1,89 +1,170 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { runCodegen } from '@lunora/codegen';
4
- import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
2
+ import { mkdtemp, writeFile, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { discoverSchema, schemaFromIr } from '@lunora/codegen';
5
+ import { seedPlan } from '@lunora/seed';
6
+ import { join } from '@visulima/path';
7
+ import { Project } from 'ts-morph';
5
8
  import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
6
- import { v as validateOutputFormat, i as isJsonFormat, p as printJson, l as loggerForFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
7
- import { r as runSchemaDriftGate } from '../packem_shared/schema-drift-gate-BtBt0as0.mjs';
8
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
9
- import { validateWranglerProject } from '@lunora/config';
9
+ import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
10
+ import { b as tuiConfirm } from '../packem_shared/tui-prompts-M6OWsuyw.mjs';
11
+ import { runImportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
12
+ import { runResetCommand } from './runResetCommand.mjs';
10
13
 
11
- const runTypecheckStep = async (cwd, spawner) => {
12
- if (!existsSync(join(cwd, "tsconfig.json"))) {
13
- return { warning: "no tsconfig.json found — skipping TypeScript type-check" };
14
+ const isLocalUrl = (url) => {
15
+ if (url === void 0) {
16
+ return true;
17
+ }
18
+ try {
19
+ const { hostname } = new URL(url);
20
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
21
+ } catch {
22
+ return false;
14
23
  }
15
- const result = await spawner({ args: ["exec", "tsc", "--noEmit", "-p", "tsconfig.json"], command: "pnpm", cwd });
16
- return result.code === 0 ? {} : { error: `type errors: tsc --noEmit exited ${String(result.code)}` };
17
24
  };
18
- const reportVerifyResult = (logger, errors, warnings, wranglerPath) => {
19
- if (errors.length === 0 && warnings.length === 0) {
20
- logger.success("verify: project is valid");
21
- return { code: 0, errors: [], warnings: [], wranglerPath };
22
- }
23
- if (warnings.length > 0) {
24
- logger.warn("verify: warnings:");
25
- for (const warning of warnings) {
26
- logger.warn(` - ${warning}`);
27
- }
25
+ const ndjsonReplacer = (_key, value) => {
26
+ if (typeof value === "bigint") {
27
+ return Number(value);
28
+ }
29
+ if (value instanceof ArrayBuffer) {
30
+ return [...new Uint8Array(value)];
31
+ }
32
+ return value;
33
+ };
34
+ const seedFailure = (code) => {
35
+ return { code, conflicts: 0, generated: 0, inserted: 0, ndjson: "" };
36
+ };
37
+ const guardSeedTargets = (options, schemaPath) => {
38
+ if (!existsSync(schemaPath)) {
39
+ options.logger.error(`schema not found: ${schemaPath} — run \`vis generate lunora-table --name=<name>\` to create one`);
40
+ return seedFailure(1);
41
+ }
42
+ if (options.reset === true && (options.prod === true || !isLocalUrl(options.url))) {
43
+ options.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url");
44
+ return seedFailure(1);
28
45
  }
29
- if (errors.length > 0) {
30
- logger.error("verify: errors:");
31
- for (const error of errors) {
32
- logger.error(` - ${error}`);
46
+ return void 0;
47
+ };
48
+ const insertSeedRows = async (ndjson, generated, cwd, options) => {
49
+ const scratchDirectory = await mkdtemp(join(tmpdir(), "lunora-seed-"));
50
+ const temporaryFile = join(scratchDirectory, "rows.ndjson");
51
+ await writeFile(temporaryFile, ndjson, "utf8");
52
+ try {
53
+ const result = await runImportCommand({
54
+ batchSize: options.batchSize,
55
+ fetchImpl: options.fetchImpl,
56
+ file: temporaryFile,
57
+ logger: options.logger,
58
+ prod: options.prod,
59
+ token: options.token,
60
+ url: options.url
61
+ });
62
+ const conflicts = result.body?.conflicts ?? 0;
63
+ if (conflicts > 0) {
64
+ options.logger.warn(
65
+ `${String(conflicts)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`
66
+ );
33
67
  }
34
- return { code: 1, errors, warnings, wranglerPath };
68
+ return { code: result.code, conflicts, generated, inserted: result.inserted, ndjson };
69
+ } finally {
70
+ await rm(scratchDirectory, { force: true, recursive: true }).catch(() => {
71
+ });
72
+ }
73
+ };
74
+ const validateSeedTable = (options, ir) => {
75
+ if (options.table === void 0 || ir.tables.some((table) => table.name === options.table)) {
76
+ return void 0;
35
77
  }
36
- logger.success("verify: project is valid (with warnings)");
37
- return { code: 0, errors: [], warnings, wranglerPath };
78
+ const available = ir.tables.map((table) => table.name).join(", ");
79
+ options.logger.error(`unknown table "${options.table}" schema defines: ${available || "(no tables)"}`);
80
+ return seedFailure(1);
38
81
  };
39
- const runVerifyCommand = async (options) => {
82
+ const confirmRemoteSeedTarget = async (options, generated) => {
83
+ const targetsRemote = options.prod === true || !isLocalUrl(options.url);
84
+ if (!targetsRemote || options.yes === true) {
85
+ return void 0;
86
+ }
87
+ if (!process.stdin.isTTY && options.confirm === void 0) {
88
+ options.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes");
89
+ return seedFailure(1);
90
+ }
91
+ const confirmer = options.confirm ?? tuiConfirm;
92
+ const confirmed = await confirmer(`This will insert ${String(generated)} generated row(s) into ${options.url ?? "the production worker"}. Continue?`);
93
+ if (!confirmed) {
94
+ options.logger.info("seed: aborted");
95
+ return seedFailure(1);
96
+ }
97
+ return void 0;
98
+ };
99
+ const runSeedCommand = async (options) => {
40
100
  const cwd = options.cwd ?? process.cwd();
41
- const logger = loggerForFormat(options.format, options.logger);
42
- const formatError = validateOutputFormat("verify", options.format);
43
- if (formatError !== void 0) {
44
- options.logger.error(formatError);
45
- return { code: 1, error: formatError, errors: [], warnings: [], wranglerPath: void 0 };
46
- }
47
- const validation = validateWranglerProject({ projectRoot: cwd });
48
- const errors = [...validation.report.errors];
49
- const warnings = [...validation.report.warnings];
50
- try {
51
- const codegen = runCodegen({ apiSpec: options.apiSpec, dryRun: true, projectRoot: cwd });
52
- const gate = runSchemaDriftGate({ allowDrift: options.allowSchemaDrift === true, codegen, logger, readOnly: true });
53
- if (gate.blocked) {
54
- errors.push(gate.reason);
101
+ const schemaPath = join(cwd, "lunora", "schema.ts");
102
+ const guard = guardSeedTargets(options, schemaPath);
103
+ if (guard !== void 0) {
104
+ return guard;
105
+ }
106
+ const project = new Project({ skipAddingFilesFromTsConfig: true });
107
+ const ir = discoverSchema(project, schemaPath);
108
+ const unknownTable = validateSeedTable(options, ir);
109
+ if (unknownTable !== void 0) {
110
+ return unknownTable;
111
+ }
112
+ const schema = schemaFromIr(ir);
113
+ const plan = seedPlan(schema, {
114
+ defaultCount: options.count ?? 10,
115
+ only: options.table === void 0 ? void 0 : [options.table],
116
+ seed: options.seed ?? 0
117
+ });
118
+ const lines = [];
119
+ for (const { rows, table } of plan) {
120
+ for (const row of rows) {
121
+ lines.push(JSON.stringify({ doc: row, table }, ndjsonReplacer));
55
122
  }
56
- } catch (error) {
57
- const message = error instanceof Error ? error.message : String(error);
58
- errors.push(`codegen failed: ${message}`);
59
- }
60
- if (options.typecheck !== false) {
61
- const typecheck = await runTypecheckStep(cwd, options.spawner ?? defaultSpawner);
62
- if (typecheck.error !== void 0) {
63
- errors.push(typecheck.error);
123
+ }
124
+ const ndjson = lines.length > 0 ? `${lines.join("\n")}
125
+ ` : "";
126
+ const generated = lines.length;
127
+ if (options.dryRun === true) {
128
+ if (ndjson.length > 0) {
129
+ process.stdout.write(ndjson);
64
130
  }
65
- if (typecheck.warning !== void 0) {
66
- warnings.push(typecheck.warning);
131
+ options.logger.info(`generated ${String(generated)} row(s) across ${String(plan.length)} table(s) dry run, nothing inserted`);
132
+ return { code: 0, conflicts: 0, generated, inserted: 0, ndjson };
133
+ }
134
+ if (options.reset === true) {
135
+ const reset = await runResetCommand({ cwd, logger: options.logger, yes: true });
136
+ if (reset.code !== 0) {
137
+ return { code: reset.code, conflicts: 0, generated, inserted: 0, ndjson };
67
138
  }
68
139
  }
69
- const result = reportVerifyResult(logger, errors, warnings, validation.wranglerPath);
70
- if (isJsonFormat(options.format)) {
71
- printJson(result);
140
+ if (generated === 0) {
141
+ options.logger.warn("no rows generated — nothing to insert");
142
+ return { code: 0, conflicts: 0, generated: 0, inserted: 0, ndjson };
143
+ }
144
+ const aborted = await confirmRemoteSeedTarget(options, generated);
145
+ if (aborted !== void 0) {
146
+ return aborted;
72
147
  }
73
- return result;
148
+ return insertSeedRows(ndjson, generated, cwd, options);
74
149
  };
75
150
  const execute = defineHandler(async ({ cwd, logger, options }) => {
76
- const result = await runVerifyCommand({
77
- allowSchemaDrift: options.allowSchemaDrift === true,
78
- apiSpec: parseApiSpec(options.apiSpec),
151
+ const result = await runSeedCommand({
152
+ batchSize: options.batchSize,
153
+ count: options.count,
79
154
  cwd,
80
- format: options.format,
155
+ dryRun: options.dryRun === true,
81
156
  logger,
82
- // `--no-typecheck` is declared as a `no-*` option but cerebro exposes it
83
- // under the negated `typecheck` key (false when passed, true when absent).
84
- typecheck: options.typecheck === false ? false : void 0
157
+ prod: options.prod === true,
158
+ reset: options.reset === true,
159
+ seed: options.seed,
160
+ table: options.table,
161
+ token: options.token,
162
+ // Resolve the link here (only under --prod) so seed's own remote/confirm
163
+ // logic and the downstream import both see the same effective target.
164
+ url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url }),
165
+ yes: options.yes === true
85
166
  });
86
167
  return { code: result.code };
87
168
  });
88
169
 
89
- export { execute, runVerifyCommand };
170
+ export { execute, runSeedCommand };