@lunora/cli 1.0.0-alpha.41 → 1.0.0-alpha.410
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +33 -0
- package/README.md +3 -1
- package/dist/bin.mjs +2 -10
- package/dist/index.d.mts +1045 -374
- package/dist/index.d.ts +1045 -374
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/dispatch.mjs +1 -0
- package/dist/packem_chunks/handler.mjs +1 -160
- package/dist/packem_chunks/handler10.mjs +1 -16
- package/dist/packem_chunks/handler11.mjs +1 -22
- package/dist/packem_chunks/handler12.mjs +1 -192
- package/dist/packem_chunks/handler13.mjs +3 -131
- package/dist/packem_chunks/handler14.mjs +1 -65
- package/dist/packem_chunks/handler15.mjs +1 -58
- package/dist/packem_chunks/handler16.mjs +1 -80
- package/dist/packem_chunks/handler17.mjs +7 -43
- package/dist/packem_chunks/handler18.mjs +1 -105
- package/dist/packem_chunks/handler19.mjs +1 -170
- package/dist/packem_chunks/handler2.mjs +1 -114
- package/dist/packem_chunks/handler20.mjs +3 -94
- package/dist/packem_chunks/handler21.mjs +3 -94
- package/dist/packem_chunks/handler22.mjs +1 -0
- package/dist/packem_chunks/handler23.mjs +2 -0
- package/dist/packem_chunks/handler24.mjs +99 -0
- package/dist/packem_chunks/handler25.mjs +2 -0
- package/dist/packem_chunks/handler26.mjs +9 -0
- package/dist/packem_chunks/handler27.mjs +1 -0
- package/dist/packem_chunks/handler3.mjs +1 -204
- package/dist/packem_chunks/handler4.mjs +3 -33
- package/dist/packem_chunks/handler5.mjs +1 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +1 -42
- package/dist/packem_chunks/handler8.mjs +2 -174
- package/dist/packem_chunks/handler9.mjs +1 -315
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDeployCommand.mjs +23 -592
- package/dist/packem_chunks/runDevCommand.mjs +2 -0
- package/dist/packem_chunks/runInitCommand.mjs +165 -1432
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/COMMANDS-BpfWKiiZ.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyIsI3S1.mjs +1 -0
- package/dist/packem_shared/EXIT_CODE-D_XCixv8.mjs +1 -0
- package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
- package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
- package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
- package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
- package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
- package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
- package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
- package/dist/packem_shared/cli-CPcfZdt0.mjs +2 -0
- package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
- package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
- package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
- package/dist/packem_shared/command-CB4JM-Jl.mjs +1 -0
- package/dist/packem_shared/commands-DvSfLvyt.mjs +13 -0
- package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-Ch7zuQQE.mjs +1 -0
- package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
- package/dist/packem_shared/docker-AqLAkOyY.mjs +1 -0
- package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
- package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
- package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
- package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
- package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
- package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
- package/dist/packem_shared/mcp-config-file-CcDTeXIq.mjs +2 -0
- package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
- package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
- package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
- package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
- package/dist/packem_shared/plan-DFY3CqHD.mjs +5 -0
- package/dist/packem_shared/planDevCommand-BDoJUgQ4.mjs +1 -0
- package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
- package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
- package/dist/packem_shared/render-lunora-error-B6893vbU.mjs +2 -0
- package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
- package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
- package/dist/packem_shared/runAddCommand-BChdJQ5L.mjs +1 -0
- package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
- package/dist/packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs +11 -0
- package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
- package/dist/packem_shared/secret-key-8DPOH98z.mjs +1 -0
- package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
- package/dist/packem_shared/storage-DNzYhXR-.mjs +1 -0
- package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
- package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
- package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-CTQPpalP.mjs +1 -0
- package/package.json +39 -19
- package/skills/README.md +36 -17
- package/skills/lunora/SKILL.md +158 -65
- package/skills/lunora-cloudflare-audit/SKILL.md +163 -0
- package/skills/lunora-create-package/SKILL.md +97 -84
- package/skills/lunora-deploy/SKILL.md +175 -105
- package/skills/lunora-functions/SKILL.md +363 -56
- package/skills/lunora-migration-helper/SKILL.md +162 -137
- package/skills/lunora-performance-audit/SKILL.md +137 -95
- package/skills/lunora-quickstart/SKILL.md +137 -136
- package/skills/lunora-realtime/SKILL.md +217 -97
- package/skills/lunora-setup-auth/SKILL.md +162 -102
- package/skills/lunora-setup-hyperdrive/SKILL.md +130 -109
- package/skills/lunora-setup-hyperdrive-global/SKILL.md +93 -90
- package/skills/lunora-setup-mail/SKILL.md +85 -113
- package/skills/lunora-setup-scheduler/SKILL.md +132 -96
- package/skills/lunora-setup-storage/SKILL.md +189 -95
- package/dist/packem_chunks/planDevCommand.mjs +0 -541
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
- package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
- package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
- package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
- package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
- package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
- package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
- package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
- package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
- package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
- package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
- package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
- package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
- package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
- package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
- package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
- package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
- package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
- package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
- package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
- package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
- package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
- package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
- package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
- package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
|
@@ -1,114 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { tmpdir } from 'node:os';
|
|
3
|
-
import { join, relative } from 'node:path';
|
|
4
|
-
import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
|
|
5
|
-
import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
|
|
6
|
-
|
|
7
|
-
const walk = (root) => {
|
|
8
|
-
const entries = [];
|
|
9
|
-
const recurse = (directory) => {
|
|
10
|
-
for (const name of readdirSync(directory)) {
|
|
11
|
-
const full = join(directory, name);
|
|
12
|
-
const info = statSync(full);
|
|
13
|
-
if (info.isDirectory()) {
|
|
14
|
-
recurse(full);
|
|
15
|
-
} else if (info.isFile()) {
|
|
16
|
-
entries.push({ path: relative(root, full), sizeBytes: info.size });
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
recurse(root);
|
|
21
|
-
return entries;
|
|
22
|
-
};
|
|
23
|
-
const formatBytes = (bytes) => {
|
|
24
|
-
if (bytes < 1024) {
|
|
25
|
-
return `${String(bytes)} B`;
|
|
26
|
-
}
|
|
27
|
-
if (bytes < 1024 * 1024) {
|
|
28
|
-
return `${(bytes / 1024).toFixed(1)} KiB`;
|
|
29
|
-
}
|
|
30
|
-
return `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;
|
|
31
|
-
};
|
|
32
|
-
const buildReport = (outdir) => {
|
|
33
|
-
const all = walk(outdir);
|
|
34
|
-
const sorted = all.toSorted((a, b) => b.sizeBytes - a.sizeBytes);
|
|
35
|
-
const totalBytes = all.reduce((sum, entry) => sum + entry.sizeBytes, 0);
|
|
36
|
-
const generatedFiles = all.filter((entry) => entry.path.includes("_generated"));
|
|
37
|
-
return {
|
|
38
|
-
generatedFiles,
|
|
39
|
-
outdir,
|
|
40
|
-
topModules: sorted.slice(0, 10),
|
|
41
|
-
totalBytes,
|
|
42
|
-
totalFiles: all.length
|
|
43
|
-
};
|
|
44
|
-
};
|
|
45
|
-
const renderText = (report, logger) => {
|
|
46
|
-
logger.info(`outdir: ${report.outdir}`);
|
|
47
|
-
logger.info(`total: ${String(report.totalFiles)} files, ${formatBytes(report.totalBytes)}`);
|
|
48
|
-
if (report.topModules.length > 0) {
|
|
49
|
-
logger.info("");
|
|
50
|
-
logger.info("top modules by size:");
|
|
51
|
-
for (const entry of report.topModules) {
|
|
52
|
-
logger.info(` ${formatBytes(entry.sizeBytes).padStart(10, " ")} ${entry.path}`);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
if (report.generatedFiles.length > 0) {
|
|
56
|
-
logger.info("");
|
|
57
|
-
logger.info(`_generated/ files: ${String(report.generatedFiles.length)}`);
|
|
58
|
-
for (const entry of report.generatedFiles) {
|
|
59
|
-
logger.info(` ${formatBytes(entry.sizeBytes).padStart(10, " ")} ${entry.path}`);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
const runAnalyzeCommand = async (options) => {
|
|
64
|
-
const cwd = options.cwd ?? process.cwd();
|
|
65
|
-
const { logger } = options;
|
|
66
|
-
let outdir;
|
|
67
|
-
let descriptor;
|
|
68
|
-
let temporary = false;
|
|
69
|
-
if (options.inspectOnly) {
|
|
70
|
-
outdir = options.inspectOnly;
|
|
71
|
-
} else {
|
|
72
|
-
outdir = mkdtempSync(join(tmpdir(), "lunora-analyze-"));
|
|
73
|
-
temporary = true;
|
|
74
|
-
descriptor = {
|
|
75
|
-
args: ["exec", "wrangler", "deploy", "--dry-run", "--outdir", outdir],
|
|
76
|
-
command: "pnpm",
|
|
77
|
-
cwd
|
|
78
|
-
};
|
|
79
|
-
logger.info(`analyze: building via ${descriptor.command} ${descriptor.args.join(" ")}`);
|
|
80
|
-
const spawner = options.spawner ?? defaultSpawner;
|
|
81
|
-
const spawned = await spawner(descriptor);
|
|
82
|
-
if (spawned.code !== 0) {
|
|
83
|
-
logger.error(`analyze: wrangler dry-run failed (exit ${String(spawned.code)})`);
|
|
84
|
-
rmSync(outdir, { force: true, recursive: true });
|
|
85
|
-
return { code: spawned.code, descriptor, report: void 0 };
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
try {
|
|
89
|
-
if (!existsSync(outdir)) {
|
|
90
|
-
logger.error(`analyze: outdir not found at ${outdir}`);
|
|
91
|
-
return { code: 1, descriptor, report: void 0 };
|
|
92
|
-
}
|
|
93
|
-
const report = buildReport(outdir);
|
|
94
|
-
if (options.json) {
|
|
95
|
-
process.stdout.write(`${JSON.stringify(report, void 0, 2)}
|
|
96
|
-
`);
|
|
97
|
-
} else {
|
|
98
|
-
renderText(report, logger);
|
|
99
|
-
}
|
|
100
|
-
return { code: 0, descriptor, report };
|
|
101
|
-
} finally {
|
|
102
|
-
if (temporary && existsSync(outdir)) {
|
|
103
|
-
try {
|
|
104
|
-
rmSync(outdir, { force: true, recursive: true });
|
|
105
|
-
} catch {
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
const execute = defineHandler(
|
|
111
|
-
({ cwd, logger, options }) => runAnalyzeCommand({ cwd, json: options.json === true, logger })
|
|
112
|
-
);
|
|
113
|
-
|
|
114
|
-
export { execute, runAnalyzeCommand };
|
|
1
|
+
import{mkdtempSync as p,rmSync as u,existsSync as m,readdirSync as $,statSync as g}from"node:fs";import{tmpdir as S}from"node:os";import{join as y,relative as w}from"node:path";import{d as z}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as B}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as h,detectPackageManager as x}from"@lunora/config/cli";const v=e=>{const t=[],n=o=>{for(const s of $(o)){const r=y(o,s),i=g(r);i.isDirectory()?n(r):i.isFile()&&t.push({path:w(e,r),sizeBytes:i.size})}};return n(e),t},l=e=>e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(2)} MiB`,M=e=>{const t=v(e),n=t.toSorted((r,i)=>i.sizeBytes-r.sizeBytes),o=t.reduce((r,i)=>r+i.sizeBytes,0);return{generatedFiles:t.filter(r=>r.path.includes("_generated")),outdir:e,topModules:n.slice(0,10),totalBytes:o,totalFiles:t.length}},O=(e,t)=>{if(t.info(`outdir: ${e.outdir}`),t.info(`total: ${String(e.totalFiles)} files, ${l(e.totalBytes)}`),e.topModules.length>0){t.info(""),t.info("top modules by size:");for(const n of e.topModules)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}if(e.generatedFiles.length>0){t.info(""),t.info(`_generated/ files: ${String(e.generatedFiles.length)}`);for(const n of e.generatedFiles)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}},j=async e=>{const t=e.cwd??process.cwd(),n=e.format==="json",{logger:o}=e;let s,r,i=!1;if(e.inspectOnly)s=e.inspectOnly;else{s=p(y(S(),"lunora-analyze-")),i=!0;const a=h(x(t),"wrangler",["deploy","--dry-run","--outdir",s]);r={args:a.args,command:a.command,cwd:t,stdoutToStderr:n},o.info(`analyze: building via ${r.command} ${r.args.join(" ")}`);const d=await(e.spawner??F)(r);if(d.code!==0){const f=`analyze: wrangler dry-run failed (exit ${String(d.code)})`;return o.error(f),u(s,{force:!0,recursive:!0}),{code:d.code,descriptor:r,error:f,report:void 0}}}try{if(!m(s)){const c=`analyze: outdir not found at ${s}`;return o.error(c),{code:B.NOT_FOUND,descriptor:r,error:c,report:void 0}}const a=M(s);return n||O(a,o),{code:0,descriptor:r,report:a}}finally{if(i&&m(s))try{u(s,{force:!0,recursive:!0})}catch{}}},N=z(async({cwd:e,format:t,logger:n})=>{const o=await j({cwd:e,format:t,logger:n});return{code:o.code,data:o.report,error:o.error}});export{N as execute,j as runAnalyzeCommand};
|
|
@@ -1,94 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
|
|
5
|
-
import { a as renderCodegenHint } from '../packem_shared/codegen-error-DJG-ghs_.mjs';
|
|
6
|
-
import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
|
|
7
|
-
import { v as validateOutputFormat, i as isJsonFormat, p as printJson, l as loggerForFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
|
|
8
|
-
import { r as runSchemaDriftGate } from '../packem_shared/schema-drift-gate-BtBt0as0.mjs';
|
|
9
|
-
import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
|
|
10
|
-
import { validateWranglerProject } from '@lunora/config';
|
|
11
|
-
|
|
12
|
-
const runTypecheckStep = async (cwd, spawner) => {
|
|
13
|
-
if (!existsSync(join(cwd, "tsconfig.json"))) {
|
|
14
|
-
return { warning: "no tsconfig.json found — skipping TypeScript type-check" };
|
|
15
|
-
}
|
|
16
|
-
const result = await spawner({ args: ["exec", "tsc", "--noEmit", "-p", "tsconfig.json"], command: "pnpm", cwd });
|
|
17
|
-
return result.code === 0 ? {} : { error: `type errors: tsc --noEmit exited ${String(result.code)}` };
|
|
18
|
-
};
|
|
19
|
-
const reportVerifyResult = (logger, errors, warnings, wranglerPath) => {
|
|
20
|
-
if (errors.length === 0 && warnings.length === 0) {
|
|
21
|
-
logger.success("verify: project is valid");
|
|
22
|
-
return { code: 0, errors: [], warnings: [], wranglerPath };
|
|
23
|
-
}
|
|
24
|
-
if (warnings.length > 0) {
|
|
25
|
-
logger.warn("verify: warnings:");
|
|
26
|
-
for (const warning of warnings) {
|
|
27
|
-
logger.warn(` - ${warning}`);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
if (errors.length > 0) {
|
|
31
|
-
logger.error("verify: errors:");
|
|
32
|
-
for (const error of errors) {
|
|
33
|
-
logger.error(` - ${error}`);
|
|
34
|
-
const hint = renderCodegenHint(error);
|
|
35
|
-
if (hint !== void 0) {
|
|
36
|
-
logger.error(hint);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return { code: 1, errors, warnings, wranglerPath };
|
|
40
|
-
}
|
|
41
|
-
logger.success("verify: project is valid (with warnings)");
|
|
42
|
-
return { code: 0, errors: [], warnings, wranglerPath };
|
|
43
|
-
};
|
|
44
|
-
const runVerifyCommand = async (options) => {
|
|
45
|
-
const cwd = options.cwd ?? process.cwd();
|
|
46
|
-
const logger = loggerForFormat(options.format, options.logger);
|
|
47
|
-
const formatError = validateOutputFormat("verify", options.format);
|
|
48
|
-
if (formatError !== void 0) {
|
|
49
|
-
options.logger.error(formatError);
|
|
50
|
-
return { code: 1, error: formatError, errors: [], warnings: [], wranglerPath: void 0 };
|
|
51
|
-
}
|
|
52
|
-
const validation = validateWranglerProject({ projectRoot: cwd });
|
|
53
|
-
const errors = [...validation.report.errors];
|
|
54
|
-
const warnings = [...validation.report.warnings];
|
|
55
|
-
try {
|
|
56
|
-
const codegen = runCodegen({ apiSpec: options.apiSpec, dryRun: true, projectRoot: cwd });
|
|
57
|
-
const gate = runSchemaDriftGate({ allowDrift: options.allowSchemaDrift === true, codegen, logger, readOnly: true });
|
|
58
|
-
if (gate.blocked) {
|
|
59
|
-
errors.push(gate.reason);
|
|
60
|
-
}
|
|
61
|
-
} catch (error) {
|
|
62
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
63
|
-
errors.push(`codegen failed: ${message}`);
|
|
64
|
-
}
|
|
65
|
-
if (options.typecheck !== false) {
|
|
66
|
-
const typecheck = await runTypecheckStep(cwd, options.spawner ?? defaultSpawner);
|
|
67
|
-
if (typecheck.error !== void 0) {
|
|
68
|
-
errors.push(typecheck.error);
|
|
69
|
-
}
|
|
70
|
-
if (typecheck.warning !== void 0) {
|
|
71
|
-
warnings.push(typecheck.warning);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
const result = reportVerifyResult(logger, errors, warnings, validation.wranglerPath);
|
|
75
|
-
if (isJsonFormat(options.format)) {
|
|
76
|
-
printJson(result);
|
|
77
|
-
}
|
|
78
|
-
return result;
|
|
79
|
-
};
|
|
80
|
-
const execute = defineHandler(async ({ cwd, logger, options }) => {
|
|
81
|
-
const result = await runVerifyCommand({
|
|
82
|
-
allowSchemaDrift: options.allowSchemaDrift === true,
|
|
83
|
-
apiSpec: parseApiSpec(options.apiSpec),
|
|
84
|
-
cwd,
|
|
85
|
-
format: options.format,
|
|
86
|
-
logger,
|
|
87
|
-
// `--no-typecheck` is declared as a `no-*` option but cerebro exposes it
|
|
88
|
-
// under the negated `typecheck` key (false when passed, true when absent).
|
|
89
|
-
typecheck: options.typecheck === false ? false : void 0
|
|
90
|
-
});
|
|
91
|
-
return { code: result.code };
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
export { execute, runVerifyCommand };
|
|
1
|
+
import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as _,a as q,b as H,s as W}from"../packem_shared/resolve-Bdc9KEUv.mjs";import{r as U}from"../packem_shared/cli-manifest-DoQ_3bzs.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,o="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=o.length>0?`${o}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,o)=>{const e=I(o);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,o)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(o))k(r)||C(t,u(o,r))},F=(t,o,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(o,r);return j(a,s,{filter:n=>!k(n.slice(n.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(n=>`${r}/${n}`):[r]},R=(t,o)=>o.vendor.every(e=>w(u(t,e.from))),z=async(t,o)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:n}=o,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,n)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:n.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,o)=>{const{language:e,outputDirectory:r,target:a}=o,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const n=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${n}`)}return{files:a.vendor.flatMap(n=>F(s,r,n.from,n.to)).toSorted((n,f)=>n.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:o,from:e,language:r,logger:a,outputDirectory:s,ref:n,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:o,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(n!==void 0&&n.length>0){const i=await l(n);if(i===void 0)throw new d("NOT_FOUND",`--ref ${n} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const p=_(),g=await l(p).catch(i=>{const y=i instanceof Error?i.message.split(`
|
|
2
|
+
`)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${p} (${y}).`)});if(g!==void 0)return g;const m=await l(void 0);if(m===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${p} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${p}, used ${m.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),m},ee=(t,o,e)=>{const r={cliVersion:U(),files:e.files,language:o,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
|
|
3
|
+
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let o;try{o=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(o===null||typeof o!="object"||!Array.isArray(o.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return o},le=J(async({argument:t,cwd:o,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",n=V[s];if(n===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(o,r.spec??te),c=O(o,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:p,undeclared:g,unrepresentable:m}=await P(l,n);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:n});ee(c,s,i);for(const[S,L]of Object.entries(p)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(n.requires.length>0?`Install in the consuming project: ${n.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),m.length>0&&e.warn(`${String(m.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${m.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{le as execute};
|
|
@@ -1,94 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { parse } from 'jsonc-parser';
|
|
4
|
-
import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
|
|
5
|
-
import { o as openUrl } from '../packem_shared/open-url-Dfq6fAyT.mjs';
|
|
6
|
-
|
|
7
|
-
const DEFAULT_DEV_PORT = 8787;
|
|
8
|
-
const STUDIO_PATH = "/_lunora/studio";
|
|
9
|
-
const findWranglerFile = (projectRoot) => {
|
|
10
|
-
for (const candidate of ["wrangler.jsonc", "wrangler.json"]) {
|
|
11
|
-
const fullPath = join(projectRoot, candidate);
|
|
12
|
-
if (existsSync(fullPath)) {
|
|
13
|
-
return fullPath;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
return void 0;
|
|
17
|
-
};
|
|
18
|
-
const readWrangler = (projectRoot) => {
|
|
19
|
-
const file = findWranglerFile(projectRoot);
|
|
20
|
-
if (!file) {
|
|
21
|
-
return void 0;
|
|
22
|
-
}
|
|
23
|
-
try {
|
|
24
|
-
const parsed = parse(readFileSync(file, "utf8"));
|
|
25
|
-
return parsed !== null && typeof parsed === "object" ? parsed : void 0;
|
|
26
|
-
} catch {
|
|
27
|
-
return void 0;
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
const resolveDevPort = (wrangler) => {
|
|
31
|
-
if (!wrangler) {
|
|
32
|
-
return DEFAULT_DEV_PORT;
|
|
33
|
-
}
|
|
34
|
-
const { dev } = wrangler;
|
|
35
|
-
if (dev !== null && typeof dev === "object") {
|
|
36
|
-
const { port } = dev;
|
|
37
|
-
if (typeof port === "number" && Number.isFinite(port)) {
|
|
38
|
-
return port;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return DEFAULT_DEV_PORT;
|
|
42
|
-
};
|
|
43
|
-
const resolveRemoteUrl = (wrangler) => {
|
|
44
|
-
if (!wrangler) {
|
|
45
|
-
return void 0;
|
|
46
|
-
}
|
|
47
|
-
const { routes } = wrangler;
|
|
48
|
-
if (Array.isArray(routes) && routes.length > 0) {
|
|
49
|
-
const first = routes[0];
|
|
50
|
-
if (typeof first === "string") {
|
|
51
|
-
return `https://${first.split("/")[0] ?? first}${STUDIO_PATH}`;
|
|
52
|
-
}
|
|
53
|
-
if (first !== null && typeof first === "object") {
|
|
54
|
-
const { pattern } = first;
|
|
55
|
-
if (typeof pattern === "string" && pattern.length > 0) {
|
|
56
|
-
return `https://${pattern.split("/")[0] ?? pattern}${STUDIO_PATH}`;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
const { name } = wrangler;
|
|
61
|
-
if (typeof name === "string" && name.length > 0) {
|
|
62
|
-
return `https://${name}.workers.dev${STUDIO_PATH}`;
|
|
63
|
-
}
|
|
64
|
-
return void 0;
|
|
65
|
-
};
|
|
66
|
-
const runViewCommand = async (options) => {
|
|
67
|
-
const cwd = options.cwd ?? process.cwd();
|
|
68
|
-
const wrangler = readWrangler(cwd);
|
|
69
|
-
const { logger } = options;
|
|
70
|
-
let url;
|
|
71
|
-
if (options.remote) {
|
|
72
|
-
url = resolveRemoteUrl(wrangler);
|
|
73
|
-
if (!url) {
|
|
74
|
-
logger.error("view --remote: could not determine the remote URL from wrangler config (set `routes` or `name`).");
|
|
75
|
-
return { code: 1, url: void 0 };
|
|
76
|
-
}
|
|
77
|
-
} else {
|
|
78
|
-
url = `http://localhost:${String(resolveDevPort(wrangler))}${STUDIO_PATH}`;
|
|
79
|
-
}
|
|
80
|
-
logger.info(`opening ${url}`);
|
|
81
|
-
try {
|
|
82
|
-
await openUrl(url, { opener: options.opener });
|
|
83
|
-
} catch (error) {
|
|
84
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
85
|
-
logger.error(`view: failed to open URL: ${message}`);
|
|
86
|
-
return { code: 1, url };
|
|
87
|
-
}
|
|
88
|
-
return { code: 0, url };
|
|
89
|
-
};
|
|
90
|
-
const execute = defineHandler(
|
|
91
|
-
({ cwd, logger, options }) => runViewCommand({ cwd, logger, remote: options.remote === true })
|
|
92
|
-
);
|
|
93
|
-
|
|
94
|
-
export { execute, runViewCommand };
|
|
1
|
+
import z,{join as m,resolve as I}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as D,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as G}from"@lunora/runtime";import{r as E,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as T}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-slAq5BCF.mjs";import{b as ae,l as oe,M as U,u as ne,r as ie}from"../packem_shared/import-BRM1hs7j.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as se}from"node:crypto";import{existsSync as N,createReadStream as ce,createWriteStream as de}from"node:fs";import{mkdir as ue,rm as b,rename as C,readFile as q,writeFile as le,realpath as _,mkdtemp as x}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as R}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as O}from"node:os";import{Readable as fe}from"node:stream";import{pipeline as me}from"node:stream/promises";const S="manifest.json",L=async e=>{const t=se("sha256");let r=0;for await(const a of ce(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},P=async e=>{const t=m(e,S);if(!N(t))return[];let r;try{r=JSON.parse(await q(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>D(a))},ge=async(e,t)=>{const r=m(e,`${S}.${j()}.tmp`);try{await le(r,`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`,"utf8"),await C(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},he=async(e,t)=>{const r=I(e),a=I(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(R(r,a)||o(),!!N(a))return R(await _(r),await _(a))||o(),a},we=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await C(a,m(e,r))},label:e,list:async()=>P(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await he(e,r))},record:async r=>{const a=await P(e);a.push(r),await ge(e,a)},stage:async r=>{await ue(e,{recursive:!0});const a=m(e,`${t(r)}.${j()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},be="/_lunora/admin/storage/object",ke="/_lunora/admin/storage",B=8,ye=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},pe=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${be}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},H=async c=>{try{const s=JSON.parse(await f(c));if(D(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>U)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(U)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await q(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=B){const g=await Promise.all(s.slice(d,d+B).map(async h=>H(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await x(m(O(),"lunora-backup-")),h=m(g,ye(l));try{await me(fe.from(d.body),de(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${ke}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
|
|
3
|
+
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ne=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ie=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ue=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Oe=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):we(m(t,e.dir??$e));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${G(r)}`)},Pe=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(K(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},De=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${ve}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await je({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{nr as execute,je as runBackupCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as g,lstatSync as S,existsSync as y}from"node:fs";import{join as E,basename as T}from"node:path";import{pathToFileURL as w}from"node:url";import{d as R}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";const l=".eval.ts",$=new Set([".git","_generated","dist","node_modules"]),v=(e,s=[])=>{let r;try{r=g(e)}catch{return s}for(const t of r){const o=E(e,t);let n;try{n=S(o)}catch{continue}if(n.isDirectory()){if($.has(t))continue;v(o,s)}else n.isFile()&&t.endsWith(l)&&s.push(o)}return s.toSorted((t,o)=>t.localeCompare(o))},_=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",m=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,F="evals",O='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',N=/unknown file extension ".ts"/i,p=e=>e instanceof Error?e.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:N.test(e.message):!1,f=e=>T(e,l),x=e=>({average:e.result?.average,error:e.error,items:e.result?.items,name:e.name,passed:e.passed,path:e.path,threshold:e.threshold}),b=e=>({evals:e.evals.map(s=>x(s))}),i=(e,s,r)=>(e.error(s),{code:r,error:s,evals:[]}),A=(e,s,r)=>{if(!y(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=v(e);return t.length===0&&r.info(`eval: no ${l} files found under "${s}"`),t},I=async e=>{const r=(await import(w(e).href)).default;if(!_(r))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return r},L=async(e,s)=>{let r;try{r=await I(e)}catch(n){if(p(n))throw n;return{error:n instanceof Error?n.message:String(n),name:f(e),passed:!1,path:e}}const t=r.name??f(e);if(r.threshold!==void 0&&!m(r.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(r.threshold)}`,name:t,passed:!1,path:e};const o=r.threshold??s;try{const n=await r.run(),a=o===void 0||n.average>=o;return{name:t,passed:a,path:e,result:n,threshold:o}}catch(n){return{error:n instanceof Error?n.message:String(n),name:t,passed:!1,path:e,threshold:o}}},U=async(e,s)=>{const r=[];for(const t of e)r.push(await L(t,s));return r},D=e=>{if(e.error!==void 0)return`ERROR: ${e.error}`;const s=e.passed?"pass":"FAIL",r=e.result?.items.length??0;return`${s} (${String(r)} cases)`},C=e=>{if(e.length===0)return[];const s=Math.max(4,...e.map(t=>t.name.length)),r=[`${"NAME".padEnd(s)} SCORE THRESHOLD STATUS`];for(const t of e){const o=t.result===void 0?"—":t.result.average.toFixed(3),n=t.threshold===void 0?"—":t.threshold.toFixed(3);r.push(`${t.name.padEnd(s)} ${o.padEnd(6)} ${n.padEnd(9)} ${D(t)}`)}return r},M=async e=>{const s=e.cwd??process.cwd(),{logger:r}=e;if(e.threshold!==void 0&&!m(e.threshold))return i(r,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`,u.USAGE);const t=e.dir??F,o=E(s,t),n=A(o,t,r);let a;try{a=await U(n,e.threshold)}catch(d){if(!p(d))throw d;return i(r,O,1)}if(e.threshold!==void 0&&a.length===0){const d=`eval: --threshold ${String(e.threshold)} was set but 0 eval files were discovered under "${t}" — nothing was gated`;return i(r,d,u.USAGE)}for(const d of C(a))r.info(d);const c=a.filter(d=>!d.passed),h=c.length>0?1:0;return h===0?r.success(`eval: ${String(a.length)} eval(s) passed`):r.error(`eval: ${String(c.length)}/${String(a.length)} eval(s) failed`),{code:h,evals:a}},V=R(async({cwd:e,format:s,logger:r,options:t})=>{const o=await M({cwd:e,dir:t.dir,format:s,logger:r,threshold:t.threshold});return{code:o.code,data:b(o),error:o.error}});export{V as execute,M as runEvalCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readLinkedProject as h,resolveDeployDriver as b}from"@lunora/config";import{d as y}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as w}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as E}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{createR2Sql as L}from"@lunora/bindings/r2sql";import{createPipelineLogReader as S}from"@lunora/runtime";import{toolchainExecArgs as _,detectPackageManager as T}from"@lunora/config/cli";const p=["trace","debug","log","info","warn","error","fatal"],C=new Set(p),v=/^\d+$/,f=(e,r)=>{if(e===void 0)return;const a=e.trim();if(v.test(a))return Number(a);const n=Date.parse(a);if(Number.isNaN(n))throw new TypeError(`logs: invalid ${r} "${e}" — pass epoch-millis or an ISO 8601 date`);return n},I=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),$=e=>{const r=e.trim();if(v.test(r))return{ts:Number(r)};let a;try{a=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:n}=a,t=a.seen,s=Array.isArray(t)?t.filter(o=>typeof o=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:n}:{ts:n}},g=(e,r)=>{if(e!==void 0){if(!C.has(e))throw new TypeError(`logs: invalid ${r} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},R=e=>{const r={},a=f(e.since,"--since");a!==void 0&&(r.sinceTs=a);const n=f(e.until,"--until");n!==void 0&&(r.untilTs=n);const t=g(e.level,"--level");t!==void 0&&(r.level=t);const s=g(e.minLevel,"--min-level");if(s!==void 0&&(r.minLevel=s),e.functionPrefix!==void 0&&(r.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(r.traceId=e.traceId),e.shardKey!==void 0&&(r.shardKey=e.shardKey),e.userId!==void 0&&(r.userId=e.userId),e.limit!==void 0){const o=Number(e.limit);if(!Number.isFinite(o))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);r.limit=o}return e.cursor!==void 0&&(r.cursor=$(e.cursor)),r},N=e=>{const r=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${r} ${a} ${e.functionPath} ${e.message}`},O=async e=>{const r=e.environment??process.env,a=r.R2_SQL_ACCOUNT_ID,n=r.R2_SQL_TOKEN,t=r.R2_SQL_BUCKET,s=[];if((a===void 0||a.length===0)&&s.push("R2_SQL_ACCOUNT_ID"),(n===void 0||n.length===0)&&s.push("R2_SQL_TOKEN"),(t===void 0||t.length===0)&&s.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&s.push("--table"),s.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${s.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:m.USAGE,error:"not configured"};let o;try{o=R(e)}catch(i){return e.logger.error(i instanceof Error?i.message:String(i)),{code:m.USAGE,error:"invalid option"}}const u=L({accountId:a,apiToken:n,bucket:t,fetch:e.fetch}),c=await S(u,{namespace:e.namespace,table:e.table}).query(o);for(const i of c.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(i):N(i)}
|
|
2
|
+
`);return c.rows.length===0?e.logger.info("logs --durable: no matching log records"):c.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${I(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},x=async e=>{const r=e.cwd??process.cwd(),a=e.env??h(r)?.env,n=w(r,e.target);if(n.target===void 0){const d=`logs: ${n.error??"no deploy target"}`;return e.logger.error(d),{code:m.USAGE,descriptor:void 0,error:d}}const t=b(n.target),s=t.toolchain?.tail;if(s===void 0){const d=`logs: deploy target "${t.id}" has no log tail`;return e.logger.error(d),{code:m.USAGE,descriptor:void 0,error:d}}const o=s({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),u=_(T(r),o),l={args:u.args,command:u.command,cwd:r};return e.logger.info(`tailing logs via ${l.command} ${l.args.join(" ")}`),{code:(await(e.spawner??E)(l)).code,delegated:!0,descriptor:l}},G=y(async({argument:e,cwd:r,format:a,logger:n,options:t})=>{if(t.durable===!0){const s=await O({cursor:t.cursor,functionPrefix:t.functionPrefix,level:t.level,limit:t.limit,logger:n,minLevel:t.minLevel,namespace:t.namespace,ndjson:t.ndjson===!0,shardKey:t.shardKey,since:t.since,table:t.table,traceId:t.traceId,until:t.until,userId:t.userId});return{...s,...s.rows===void 0?{}:{delegated:!0}}}return x({cwd:r,env:t.env,format:a,logger:n,search:t.search,status:t.status,target:t.target,temporary:t.temporary===!0,worker:e[0]})});export{G as execute,x as runLogsCommand};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import{existsSync as O,readFileSync as k}from"node:fs";import{writeFile as I,mkdir as U}from"node:fs/promises";import{parseSchema as B,applyAdditiveEdit as F,projectUsesUmbrella as Y}from"@lunora/config";import{join as _}from"@visulima/path";import{d as q}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{createRequire as P}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as H,detectPackageManager as K}from"@lunora/config/cli";const j=/^\//,G=(e,r)=>{try{const{args:n,command:t}=H(K(e),[r],{dev:!0});return`${t} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${r}`}},T=(e,r,n)=>{const t=P(_(n,"noop.cjs"));try{t.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${r}\` driver to read this database, and it isn't installed.
|
|
2
|
+
|
|
3
|
+
Install it in your project:
|
|
4
|
+
|
|
5
|
+
${G(n,r)}`)}return t(e)},Q=e=>{const r=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(r==="postgres"||r==="postgresql")return"postgres";if(r==="mysql"||r==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${r}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},J=e=>{try{const r=new URL(e).pathname.replace(j,"");return r===""?void 0:decodeURIComponent(r)}catch{return}},W=async(e,r,n,t=process.cwd())=>{if(r==="postgres"){const m=T("pg","pg",t).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,p)=>(await u.query(l,[...p])).rows,schema:n??"public"}}const a=T("mysql2/promise","mysql2",t).createConnection,o=await a(e),i=n??J(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),X={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},z={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,r)=>{const t=(r==="postgres"?X:z)[e.dataType],s=e.references===void 0?t:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,Z=/[^\dA-Z]+(.)?/gi,V=/^\d+/,ee=/[^\w-]/g,ne=/[\u003C\u003E\u002F\u2028\u2029]/g,te={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(ne,r=>te[r]??r),S=e=>M.test(e)?e:f(e),re=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),ae=e=>{const r=e.replaceAll(ee,"_");return r===""?"table":r},se=e=>{const n=e.replaceAll(Z,(t,s)=>s?.toUpperCase()??"").replace(V,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(r=>!h.has(r.name)),oe=e=>{const r=new Set(e.primaryKey);for(const n of e.indexes)for(const t of n.columns)r.add(t);for(const n of e.columns)n.references!==void 0&&r.add(n.name);return[...r].filter(n=>!h.has(n))},D=(e,r,n,t)=>e.references===void 0||r.has(e.references.table)?e:(t.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),ie=(e,r,n,t)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){t.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,t),{expression:c,known:m}=w(i,r);!m&&i.references===void 0&&(t.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
|
|
6
|
+
${s.join(`
|
|
7
|
+
`)}
|
|
8
|
+
})
|
|
9
|
+
${a.join(`
|
|
10
|
+
`)},`},ce=(e,r,n)=>{const t=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>ie(a,e.dialect,t,n)).join(`
|
|
11
|
+
`);return`/**
|
|
12
|
+
* Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
|
|
13
|
+
*
|
|
14
|
+
* This file is a STARTING POINT, not a build artifact — it is written once and is
|
|
15
|
+
* yours to edit. Review it before shipping: column types are mapped
|
|
16
|
+
* conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
|
|
17
|
+
* its rows live in the external database. Re-running \`lunora introspect\` will not
|
|
18
|
+
* overwrite it unless you pass \`--force\`.
|
|
19
|
+
*/
|
|
20
|
+
import { defineSchema, defineTable, v } from "${r.serverImport}";
|
|
21
|
+
|
|
22
|
+
export default defineSchema({
|
|
23
|
+
${s}
|
|
24
|
+
});
|
|
25
|
+
`},me=(e,r,n,t=new Set([e.name]),s=[])=>{const a=se(e.name),o=oe(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const p=i.get(l);if(p===void 0)return;const v=D({...p,nullable:!1},t,e.name,[]),{expression:d,known:A}=w(v,r);return!A&&v.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${p.dataType}\`).`),` ${S(l)}: ${d},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${re(e.name)}`;return`/**
|
|
26
|
+
* Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
|
|
27
|
+
* starting point you own and edit.
|
|
28
|
+
*
|
|
29
|
+
* Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
|
|
30
|
+
* this data should be public, and gate them with your auth/RLS middleware first —
|
|
31
|
+
* \`introspect\` cannot know who is allowed to read this table.
|
|
32
|
+
*/
|
|
33
|
+
import { defineListArgs, v } from "${n.serverImport}";
|
|
34
|
+
|
|
35
|
+
import type { Doc } from "./_generated/dataModel";
|
|
36
|
+
import { c } from "./_generated/server";
|
|
37
|
+
|
|
38
|
+
const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
|
|
39
|
+
// Only index-backed columns are published as filterable, so a caller cannot
|
|
40
|
+
// reach a column you did not choose to expose. Note that \`contains\` and the
|
|
41
|
+
// negative operators still scan — narrow this list, and review it, before
|
|
42
|
+
// adding \`.expose({ rest: true })\`.
|
|
43
|
+
filter: {
|
|
44
|
+
${c.join(`
|
|
45
|
+
`)}
|
|
46
|
+
},
|
|
47
|
+
orderBy: [${m}],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
|
|
51
|
+
|
|
52
|
+
export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
|
|
53
|
+
`},le=(e,r)=>{const n=[],t=new Set(e.tables.map(a=>a.name)),s=[{contents:ce(e,r,n),path:"schema.ts"}];if(r.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=ae(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:me(o,e.dialect,r,t,n),path:`${i}.ts`})}}return{files:s,warnings:n}},y=/^[A-Z_$][\w$]*$/i,ue=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,de=(e,r,n)=>{const t=[],s=new Set(r?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!y.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);t.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:ue(i)}),!a.nullable&&r!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return t},pe=(e,r,n)=>{const t=[],s=new Set(r?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!y.test(a.name)||!o.every(i=>y.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}t.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return t},ge=(e,r,n)=>{const t=[],s=[],a=new Map(r.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!y.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&t.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),t.push(...de(i,c,{dialect:n,present:o,warnings:s}),...pe(i,c,s))}return{edits:t,warnings:s}},fe=(e,r,n)=>{const t=B(e);if(!t.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${t.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=ge(r,t.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=F(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,r)=>{const n=e[r]??e[r.toLowerCase()]??e[r.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ve=`
|
|
54
|
+
SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
|
|
55
|
+
FROM information_schema.columns c
|
|
56
|
+
JOIN information_schema.tables t
|
|
57
|
+
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
58
|
+
WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
|
|
59
|
+
ORDER BY c.table_name, c.ordinal_position`,be=`
|
|
60
|
+
SELECT tc.table_name, kcu.column_name
|
|
61
|
+
FROM information_schema.table_constraints tc
|
|
62
|
+
JOIN information_schema.key_column_usage kcu
|
|
63
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
64
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
|
|
65
|
+
ORDER BY tc.table_name, kcu.ordinal_position`,he=`
|
|
66
|
+
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
|
|
67
|
+
FROM information_schema.table_constraints tc
|
|
68
|
+
JOIN information_schema.key_column_usage kcu
|
|
69
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
70
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
71
|
+
ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
|
|
72
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,Ee=`
|
|
73
|
+
SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
74
|
+
FROM pg_class t
|
|
75
|
+
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
76
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
77
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
78
|
+
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
79
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
80
|
+
WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
|
|
81
|
+
ORDER BY t.relname, i.relname, k.ord`,_e=`
|
|
82
|
+
SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
|
|
83
|
+
FROM information_schema.COLUMNS c
|
|
84
|
+
JOIN information_schema.TABLES t
|
|
85
|
+
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
|
|
86
|
+
WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
|
|
87
|
+
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,ye=`
|
|
88
|
+
SELECT TABLE_NAME, COLUMN_NAME
|
|
89
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
90
|
+
WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
|
|
91
|
+
ORDER BY TABLE_NAME, ORDINAL_POSITION`,Ae=`
|
|
92
|
+
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
|
|
93
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
94
|
+
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Se=`
|
|
95
|
+
SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
|
|
96
|
+
FROM information_schema.STATISTICS
|
|
97
|
+
WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
|
|
98
|
+
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const r=new Map;for(const n of e){const t=g(n,"table_name"),s=r.get(t);s===void 0?r.set(t,[n]):s.push(n)}return r},Ne=(e,r)=>{const n=g(e,"data_type").toLowerCase();if(r!=="postgres")return{arrayDepth:0,dataType:n};const t=g(e,"udt_name").toLowerCase();return n==="array"&&t.startsWith("_")?{arrayDepth:1,dataType:t.slice(1)}:{arrayDepth:0,dataType:t===""?n:t}},we=(e,r)=>{const n=new Map;for(const t of e){const s=g(t,"index_name"),a=r==="postgres"?g(t,"is_unique")==="true":g(t,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(t,"column_name")],unique:a}):o.columns.push(g(t,"column_name"))}return[...n.entries()].map(([t,s])=>({columns:s.columns,name:t,unique:s.unique}))},Re=async(e,r,n)=>{const t=r==="postgres",[s,a,o,i]=await Promise.all([e(t?ve:_e,[n]),e(t?be:ye,[n]),e(t?he:Ae,[n]),e(t?Ee:Se,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[p,v]of E(s)){const d=new Map((m.get(p)??[]).map(b=>[g(b,"column_name"),{column:g(b,"foreign_column"),table:g(b,"foreign_table")}])),A=v.map(b=>{const R=g(b,"column_name"),$=d.get(R);return{...Ne(b,r),name:R,nullable:g(b,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:we(u.get(p)??[],r),name:p,primaryKey:(c.get(p)??[]).map(b=>g(b,"column_name"))})}return l.sort((p,v)=>p.name.localeCompare(v.name)),{dialect:r,tables:l}},$e=e=>Y(e)?"lunorash/server":"@lunora/server",Le=async(e,r,n)=>{const t=_(r,e.path);return O(t)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
|
|
99
|
+
`).length)} lines)`),!1):(await U(r,{recursive:!0}),await I(t,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},Te=(e,r)=>{const n=r.tables;if(n===void 0||n.length===0)return e.tables;for(const t of n)e.tables.some(s=>s.name===t)||r.logger.warn(`--tables: no table named "${t}" exists in this schema — skipped.`);return e.tables.filter(t=>n.includes(t.name))},Oe=async(e,r,n,t)=>{const s=fe(k(e,"utf8"),r,n);for(const a of s.warnings)t.logger.warn(a);return s.text===void 0?(t.logger.info("lunora/schema.ts is already up to date with the database."),!1):t.dryRun===!0?(t.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),t.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Ie=async e=>{const r=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url==="")){const d="`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL.";return e.logger.error(d),{code:L.USAGE,error:d,written:[]}}const n=e.connection===void 0?Q(e.url):e.dialect??"postgres",t=e.connection??await W(e.url,n,e.schema,r);let s;try{s=await Re(t.execute,n,t.schema)}finally{e.connection===void 0&&await t.close()}const a=Te(s,e);if(a.length===0){const d="no tables found to introspect — check --schema and --tables.";return e.logger.error(d),{code:L.NOT_FOUND,error:d,written:[]}}const{files:o,warnings:i}=le({...s,tables:a},{procedures:e.procedures!==!1,serverImport:$e(r)}),c=_(r,"lunora"),m=[],u=_(c,"schema.ts"),l=O(u)&&e.force!==!0,p=l?o.filter(d=>d.path!=="schema.ts"):o;l&&await Oe(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const d of p)await Le(d,c,e)&&m.push(d.path);for(const d of i)e.logger.warn(d);e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`);const v=a.map(d=>d.name);return{code:0,dialect:n,tables:v,written:m}},qe=q(async({cwd:e,format:r,logger:n,options:t})=>{const s=await Ie({cwd:e,dryRun:t.dryRun===!0,force:t.force===!0,format:r,logger:n,procedures:t.procedures!==!1,schema:t.schema,tables:t.tables===void 0?void 0:t.tables.split(",").map(a=>a.trim()),url:t.url??process.env.DATABASE_URL});return{code:s.code,data:s.dialect===void 0?void 0:{dialect:s.dialect,dryRun:t.dryRun===!0,tables:s.tables??[],written:s.written},error:s.error}});export{qe as execute,$e as resolveServerImport,Ie as runIntrospectCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{existsSync as p,readFileSync as m,writeFileSync as U,realpathSync as _}from"node:fs";import{join as f}from"node:path";import{readProjectTarget as y,DEFAULT_TARGET as k,readServiceBindings as F}from"@lunora/codegen";import{DEV_VARS_FILE as d,parseDevVariableEntries as b,upsertDevVariableLine as B,generateSecretValue as V,writeDevVariablesFileAtomically as G,isPlaceholderValue as v,isMintableSecretKey as W,readProjectDependencies as K,discoverSchemaInfo as z,inferLunoraBindings as J,resolveSchemaDirectory as q}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as h,resolveObservabilitySampling as H,findWranglerFile as L,readWranglerJsonc as D,buildBindingManifest as Y,validateWranglerProject as X,UNEXPORTED_CLASS_MARKER as x,detectCloudflareCliConfig as Q,collectExportGaps as Z}from"@lunora/config/cloudflare";import{i as O,m as ee,c as ne,a as te,b as re}from"../packem_shared/secret-key-8DPOH98z.mjs";import{r as N,d as ae}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as E}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as oe}from"../packem_shared/command-CB4JM-Jl.mjs";import{i as se}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A,a as R,b as w}from"../packem_shared/variables-CPYyJtsL.mjs";import{spawnSync as ie}from"node:child_process";import{modify as ce,applyEdits as le,parse as de}from"jsonc-parser";import{defaultSpawner as ue}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{toolchainExecArgs as fe,detectPackageManager as pe}from"@lunora/config/cli";const ge=(r,t)=>{const e=new Set,n=o=>{for(const[s,c]of Object.entries(o??{}))typeof c=="string"&&c.trim().length>0&&e.add(s)};n(r.vars);for(const o of Object.values(r.env??{}))n(o.vars);const a=f(t,d);if(p(a))try{n(Object.fromEntries(b(m(a,"utf8")).map(o=>[o.key,o.value])))}catch{}return e},me=(r,t,e,n)=>{if(r===void 0||!e)return;const a=ge(r,t),o=a.has(A),s=r.ai?.binding;!o&&(typeof s!="string"||s.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${A} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),a.has(R)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${R} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!o&&!a.has(w)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${w} into wrangler vars.`,level:"info",message:`no ${w} in vars or ${d} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},he=(r,t,e)=>{if(r===void 0||!t)return;const n=[];(r.compatibility_flags??[]).includes(h)||n.push("the top level");for(const[a,o]of Object.entries(r.env??{}))o.compatibility_flags!==void 0&&!o.compatibility_flags.includes(h)&&n.push(`env.${a}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${h}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${h} compatibility flag — workersCimdFetch() refuses to build without it.`})},C=r=>{const t=r.trim();if(t==="")return!0;const e=t.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},P=/\r?\n/u,ve=async(r,t)=>{const{args:e,command:n}=fe(pe(t),{args:r,tool:"wrangler"});try{const a=await ue({args:e,captureStderr:!0,captureStdoutSilently:!0,command:n,cwd:t});return{code:a.code,stderr:a.stderr??"",stdout:a.stdout??""}}catch(a){return{code:1,stderr:a instanceof Error?a.message:String(a),stdout:""}}},S=async(r,t)=>{const e=await r(["d1","list","--json"],t);if(e.code!==0)return;let n;try{n=JSON.parse(e.stdout)}catch{return}if(!Array.isArray(n))return;const a=new Map;for(const o of n)typeof o.name=="string"&&typeof o.uuid=="string"&&a.set(o.name,o.uuid);return a},be=r=>{const t=de(r);return(Array.isArray(t?.d1_databases)?t.d1_databases:[]).flatMap((n,a)=>{if(n===null||typeof n!="object")return[];const o=n,s=typeof o.database_id=="string"?o.database_id:"";return C(s)?[{binding:typeof o.binding=="string"&&o.binding!==""?o.binding:"<unnamed>",index:a,name:typeof o.database_name=="string"&&o.database_name!==""?o.database_name:void 0}]:[]})},we=async(r,t,e,n)=>{const a=await S(e,t.cwd);if(a===void 0){n.skipped.push(`D1 "${r.binding}": could not run \`wrangler d1 list --json\`. Check that wrangler is installed in this project and logged in (\`wrangler login\`), then retry.`);return}const o=a.get(r.name);if(o!==void 0)return o;if(t.dryRun){n.applied.push(`would run \`wrangler d1 create ${r.name}\` and write its id into ${r.binding}`);return}const s=await e(["d1","create",r.name],t.cwd);if(s.code!==0){const l=s.stderr.trim()||`exit ${String(s.code)}`;n.skipped.push(`D1 "${r.binding}": \`wrangler d1 create ${r.name}\` failed: ${l}`);return}const i=(await S(e,t.cwd))?.get(r.name);return i===void 0&&n.skipped.push(`D1 "${r.binding}": created ${r.name} but could not read back its id.`),i},ye=async(r,t)=>{if(r.configPath===void 0)return;const e=r.runner??ve,n=m(r.configPath,"utf8"),a=be(n);let o=n;for(const s of a){if(s.name===void 0){t.skipped.push(`D1 "${s.binding}" has no database_name, so there is no database to create or reuse.`);continue}const c=await we({...s,name:s.name},r,e,t);if(c!==void 0){const i=ce(o,["d1_databases",s.index,"database_id"],c,{formattingOptions:{eol:`
|
|
2
|
+
`,insertSpaces:!0,tabSize:4}});o=le(o,i),t.applied.push(`${s.binding}: database_id set to the id of D1 "${s.name}"`)}}!r.dryRun&&o!==n&&U(r.configPath,o)},ke=r=>{const t=ie("git",["check-ignore","-q",d],{cwd:r,stdio:"ignore"});if(t.status===0)return!0;if(t.status===1)return!1;const e=f(r,".gitignore");return p(e)&&m(e,"utf8").split(P).some(n=>n.trim()===d)},$e=(r,t,e,n)=>{const a=[],o=new Set(t.split(P).flatMap(s=>{const[c]=b(s);return c!==void 0&&!v(c.value)?[c.key]:[]}));N({cwd:r}).source===void 0&&!o.has("LUNORA_ADMIN_TOKEN")&&a.push("LUNORA_ADMIN_TOKEN");for(const s of e)!O(s.key)||!v(s.value)||o.has(s.key)||(W(s.key)?a.push(s.key):n.skipped.push(`${d}: ${s.key} is a provider key and cannot be minted here; fill it in by hand.`));return a},_e=(r,t)=>{const e=f(r.cwd,d),n=p(e)?m(e,"utf8"):"",a=$e(r.cwd,n,b(n),t);if(a.length===0)return;if(!ke(r.cwd)){t.skipped.push(`${d} is not in .gitignore, so no secret is written there. Add \`${d}\` to .gitignore first.`);return}if(r.dryRun){t.applied.push(`would mint ${a.join(", ")} into ${d}`);return}let o=n;for(const s of a)o=B(o,s,V());G(e,o),t.applied.push(`minted ${a.join(", ")} into ${d}`)},xe=async r=>{const t={applied:[],skipped:[]};return await ye(r,t),_e(r,t),t},I=r=>{const{logs:t,traces:e}=H(r);return Object.entries({logs:t,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},Ae=(r,t)=>{if(r===void 0)return;const e=[],n=I(r.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[a,o]of Object.entries(r.env??{})){if(o.observability===void 0)continue;const s=I(o.observability);s.length>0&&e.push(`${s.join(" + ")} (env.${a})`)}e.length!==0&&t.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},T={ai:"Workers AI",browser:"Browser Rendering",images:"Cloudflare Images (Image Transformations)"},j=["Argo Smart Routing","Log Explorer"],Re=r=>{const t=[["top level",r],...Object.entries(r.env??{}).flatMap(([n,a])=>a?[[`env.${n}`,a]]:[])],e=new Map;for(const[n,a]of t)for(const o of Y(a).bindings)T[o.type]!==void 0&&e.set(o.type,[...e.get(o.type)??[],n]);return e},Se=(r,t)=>{if((y(r)??k)!=="cloudflare")return;const e=L(r),n=e===void 0?void 0:D(e).parsed;if(n!==void 0)for(const[a,o]of Re(n)){const s=T[a]??a;t.push({code:"paid-product-bound",fix:"Create an account budget alert in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert. Lunora cannot create or read one.",level:"info",message:`${s} is bound (${o.join(", ")}) and billed per use. No documented usage-alert product covers it, and lunora cannot read budget alerts, so an account budget alert is the only cap.`})}t.push({code:"paid-product-unknown",level:"info",message:`enablement of ${j.join(" and ")} cannot be read by lunora (dashboard settings); check the dashboard if your account uses ${j.length>1?"them":"it"}.`})},Ie=(r,t)=>{for(const e of F(r).services)for(const n of e.publicScopes){const a=n===""?"":` (env.${n})`;t.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${a}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${a}; a custom domain set elsewhere would also be public.`})}},M=r=>{const t=L(r);if(t===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=D(t);return{parsed:e,path:t}},je=(r,t,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(t===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:a}=X({projectRoot:r});for(const c of a.errors.filter(i=>i.includes(x)))n.push({code:"wrangler-class-unexported",level:"fail",message:c});for(const c of a.warnings.filter(i=>i.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:c});const o=c=>c.includes(x)||c.includes("SHARD");for(const c of a.errors.filter(i=>!o(i)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:c});for(const c of a.warnings.filter(i=>!i.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:c});const s=a.errors.find(c=>c.includes("SHARD"));s===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:s})},Le=(r,t)=>{p(f(r,"lunora.json"))&&t.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},De=(r,t)=>{const e=Q(r);e!==void 0&&t.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},Oe=(r,t)=>{r===void 0||r.limits?.cpu_ms!==void 0||t.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},Ne=(r,t)=>{const e=(r?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&t.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},Ee=(r,t)=>{const{error:e,info:n}=z(r,"lunora");if(e!==void 0){t.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const a of n?.vectorMetadata??[]){const o=ee(a.kind);if(o===void 0){t.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${a.index}" declares metadata "${a.property}", whose type Vectorize cannot filter on.`});continue}t.push({code:"vector-metadata-index-required",fix:`wrangler ${ne({index:a.index,property:a.property,type:o}).join(" ")}`,level:"info",message:`vector index "${a.index}" filters on metadata "${a.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},Ce=(r,t)=>{if(r===void 0)return;const e=(r.d1_databases??[]).filter(Boolean);for(const n of e){const a=typeof n.database_id=="string"?n.database_id:"";if(C(a)){const o=typeof n.binding=="string"&&n.binding.length>0?n.binding:"<unnamed>";t.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${o}" has a placeholder database_id ("${a||"<empty>"}").`})}}},Pe=(r,t)=>{if(r===void 0)return;const e=(r.send_email??[]).filter(Boolean);for(const n of e){const a=typeof n.destination_address=="string"?n.destination_address:"";if(a!==""&&v(a)){const o=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";t.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${o}" has a placeholder destination_address ("${a}").`})}}},Te=(r,t)=>{const e=f(r,d);if(!p(e))return;let n;try{n=m(e,"utf8")}catch{return}const a=b(n).filter(o=>O(o.key)&&v(o.value)).map(o=>o.key);a.length>0&&t.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${d} has unfilled secret value(s): ${a.join(", ")}.`})},Me=(r,t)=>{const{source:e}=N({cwd:r});e===void 0?t.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):t.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${ae(e)}).`})},Ue=async(r,t)=>{try{return await J({projectRoot:r,schemaDir:q(r)})}catch(e){t.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},Fe=(r,t)=>{const e=Z(r),n=[...r.containers.map(a=>({...a,kind:"container"})),...r.workflows.map(a=>({...a,kind:"workflow"})),...r.agents.map(a=>({...a,kind:"agent"}))];for(const a of n.filter(o=>o.exported))t.push({code:"declared-export-ok",level:"pass",message:`${a.kind} "${a.exportName}" is exported by the worker entry.`});for(const a of e)t.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${a.module}"\` to your worker entry (or re-run \`vis generate lunora-${a.kind}\`).`,level:"fail",message:`${a.kind} "${a.exportName}" is declared but ${a.className} is not exported by the worker entry.`})},Be=/^[\^~><= ]+/u,Ve=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Ge=r=>{const t=r.replace(Be,"").trim(),e=Ve.exec(t);if(!e?.groups)return;const{channel:n,core:a,counter:o}=e.groups;return{channel:n??"",core:a??"",counter:o===void 0?void 0:Number.parseInt(o,10),raw:t}},We=(r,t)=>{const e=K(r),n=[];for(const[i,l]of Object.entries(e)){if(i!=="lunorash"&&!i.startsWith("@lunora/"))continue;const u=Ge(l);u&&n.push({name:i,version:u})}if(n.length<2)return;const a=i=>i.map(l=>`${l.name}@${l.version.raw}`).join(", "),o=new Set(n.map(i=>i.version.core)),s=new Set(n.map(i=>i.version.channel));if(o.size>1){t.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(o.size)} different versions: ${a(n)}.`});return}if(s.size>1){t.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...s].map(i=>i===""?"stable":i).join(" + ")}): ${a(n)}.`});return}const c=n.map(i=>i.version.counter).filter(i=>i!==void 0);if(c.length>1){const i=Math.min(...c),l=Math.max(...c);t.push({code:"version-counter-spread",level:"info",message:c.length===n.length&&i===l?`Lunora packages are all at ${[...s][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(i)}–${String(l)}: ${a(n)}.`})}},Ke=[f("@lunora","cli"),"lunorash"],ze=(r,t,e)=>{if(t===void 0)return;const n=[];for(const o of Ke){const s=f(r,"node_modules",o);if(p(s))try{n.push(_(s))}catch{}}if(n.length===0)return;let a;try{a=_(t)}catch{return}n.some(o=>se(o,a))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${a}) is not the project's own install (${n.join(", ")}).`})},Je={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},qe=r=>{const t=new Map,e=(n,a)=>{const o=E(n);o!==void 0&&t.set(o,[...t.get(o)??[],a])};e(r?.account_id,"top level");for(const[n,a]of Object.entries(r?.env??{}))e(a?.account_id,`env.${n}`);return t},He=async(r,t,e,n)=>{if((y(r)??k)!=="cloudflare")return;const o=E((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...qe(t)],s=o.length===0?[[void 0,[]]]:o,c=await Promise.all(s.map(async([i,l])=>({accountId:i,blocks:l,budget:await te({accountId:i,environment:e.environment,fetch:e.fetch})})));for(const{accountId:i,blocks:l,budget:u}of c)n.push({...Je[u.verdict],message:c.length>1?`account ${String(i)} (${l.join(", ")}): ${u.message}`:u.message,...u.fix===void 0?{}:{fix:u.fix}})},Ye={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},Xe=async(r,t,e,n,a)=>{if(e===void 0||t===void 0||(y(r)??k)!=="cloudflare")return;const o=[["",t],...Object.entries(t.env??{}).map(([i,l])=>[`env.${i}: `,l])],s=new Map;for(const[i,l]of o){const u=l.account_id??t.account_id;for(const g of l.artifacts??[]){const $=`${String(u)}/${String(g?.namespace)}`;typeof g?.binding=="string"&&typeof g.namespace=="string"&&!s.has($)&&s.set($,{accountId:u,binding:g.binding,label:i,namespace:g.namespace})}}const c=await Promise.all([...s.values()].map(async({label:i,...l})=>({check:await re({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e,missingOk:!0}),label:i})));for(const{check:i,label:l}of c)a.push({...Ye[i.verdict],message:`${l}${i.message}`,...i.fix===void 0?{}:{fix:i.fix}})},Qe=async r=>{const t=r.cwd??process.cwd(),e=[],{parsed:n,path:a}=M(t);je(t,n,a,e),De(t,e),Ce(n,e),Pe(n,e),Oe(n,e),Ne(n,e),Ae(n,e),Te(t,e),Me(t,e),We(t,e),Ee(t,e),Le(t,e),ze(t,r.executablePath??process.argv[1],e),Ie(t,e),Se(t,e);const o=await Ue(t,e);o!==void 0&&Fe(o,e),me(n,t,o?.usesAi===!0,e),await He(t,n,r,e),await Xe(t,n,o?.jurisdiction,r,e),he(n,o?.usesCimdWorkers===!0,e);const s={fail:0,info:0,pass:0,warn:0};for(const i of e)s[i.level]+=1;const c=s.fail>0?1:0;return{code:c,findings:e,ok:c===0,summary:s}},Ze={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},en=(r,t)=>{t.info("lunora doctor — project preflight");for(const a of r.findings){const o=`[${Ze[a.level]}] ${a.message}`;a.level==="fail"?t.error(o):a.level==="warn"?t.warn(o):t.info(o),a.fix!==void 0&&a.level!=="pass"&&t.info(` fix: ${a.fix}`)}const{fail:e,warn:n}=r.summary;e>0?t.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?t.warn(`0 failures, ${String(n)} warning(s).`):t.success("all checks passed.")},nn=async r=>{const{logger:t}=r,e=await Qe({...r});return en(e,t),e},bn=oe(async({cwd:r,format:t,logger:e,options:n})=>{if(n.fix===!0){const{path:o}=M(r),s=await xe({configPath:o,cwd:r,dryRun:n.dryRun===!0,logger:e});for(const c of s.applied)e.info(`fix: ${c}`);for(const c of s.skipped)e.warn(`not fixed: ${c}`)}const a=await nn({cwd:r,format:t,logger:e});return{code:a.code,data:{findings:a.findings,summary:a.summary}}});export{bn as execute,Qe as runDoctor,nn as runDoctorCommand};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{V as M}from"../packem_shared/cli-CPcfZdt0.mjs";import{d as A}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as h,readFileSync as N}from"node:fs";import{homedir as y}from"node:os";import{findWranglerFile as D}from"@lunora/config/cloudflare";import{join as c,relative as T}from"@visulima/path";import{stringify as I}from"smol-toml";import{h as P,u as F,i as R,r as H}from"../packem_shared/mcp-config-file-CcDTeXIq.mjs";import{detectPackageManager as W,execArgsFor as G}from"@lunora/config/cli";import{readLiveDevServerState as v,DEV_STATE_DIR as J}from"@lunora/config";import{resolveAdminToken as V}from"@lunora/config/studio-host";import{connectLocalStdio as z}from"@lunora/mcp";import{resolve as p}from"node:path";import{i as K}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),g=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),q=e=>e.transport==="http"?{httpUrl:e.url}:m(e),X=e=>e.transport==="http"?{serverUrl:e.url}:m(e),B=e=>({args:["-y","mcp-remote",e],command:"npx"}),Z=e=>e.transport==="http"?B(e.url):m(e),Q=e=>e.transport==="http"?{url:e.url}:m(e),Y=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},ee=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},re=({home:e,platform:r})=>{if(r==="darwin")return{global:c(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:c(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:c(e,".config","Claude","claude_desktop_config.json")}:{}},te=(e,r)=>I({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),f=[{buildEntry:g,paths:({projectRoot:e})=>({project:c(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:g,paths:({home:e,projectRoot:r})=>({global:c(e,".cursor","mcp.json"),project:c(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:g,paths:({projectRoot:e})=>({project:c(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:q,paths:({home:e,projectRoot:r})=>({global:c(e,".gemini","settings.json"),project:c(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:Z,paths:re,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:X,paths:({home:e})=>({global:c(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:Y,paths:({home:e,projectRoot:r})=>({global:c(e,".config","opencode","opencode.json"),project:c(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ee,paths:({home:e})=>({global:c(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:Q,paths:({home:e})=>({global:c(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:c(e,".codex","config.toml"),project:c(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:te}],$=f.map(e=>e.id),ne=e=>f.find(r=>r.id===e.toLowerCase()),oe=["global","project"],u=(e,r)=>{const t=T(r,e);return t.length>0&&!t.startsWith("..")?t:e},le=(e,r)=>{const t=e.paths(r);return oe.flatMap(n=>{const o=t[n];return o===void 0?[]:[{client:e,path:o,scope:n}]})},ae=(e,r,t,n)=>{const o=e.paths(r),l=t==="global"?"project":"global",a=o[t]??(n?void 0:o[l]);if(a!==void 0)return{client:e,path:a,scope:o[t]===void 0?l:t}},se=e=>f.filter(r=>Object.values(r.paths(e)).some(t=>h(t))),j=(e,r,t,n)=>{if(e.length===0)return r();const o=[];for(const l of e){const a=ne(l);if(a===void 0){t.error(`mcp ${n}: unknown client "${l}". Known clients: ${$.join(", ")}.`);return}o.push(a)}return o},ce=e=>e.client.format==="json",ie="https://lunora.sh/mcp",O="lunora-docs",C="lunora",de=e=>h(c(e,"lunora"))&&D(e)!==void 0,ue=e=>{const{args:r,command:t}=G(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},me=e=>({transport:"http",url:e}),fe=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),_=(e,r,t)=>ae(e,fe(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),pe=(e,r,t)=>{const n=_(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:o}=n,l=e.buildEntry(r.spec);if(t.print===!0){const i=u(o,t.cwd);return t.force!==!0&&P({key:e.key,name:r.name,path:o})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:o}):(t.logger.info(`${e.label} → ${i}
|
|
2
|
+
${JSON.stringify({[e.key]:{[r.name]:l}},void 0,4)}`),{action:"printed",path:o})}const a=F({entry:l,force:t.force===!0,key:e.key,name:r.name,path:o}),s=u(o,t.cwd);return a.action==="invalid"?t.logger.error(`${e.label}: ${s} is not valid JSON (${a.error??"unknown error"}) — left untouched.`):a.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${s} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${a.action==="created"?"created":"updated"} ${s} with "${r.name}".`),{action:a.action,path:o}},ge=(e,r,t)=>{const n=_(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${u(n,t.cwd)}
|
|
3
|
+
|
|
4
|
+
${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},ve=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:O,preferredScope:"global",spec:me(e.docsUrl??ie)}),e.docsOnly!==!0&&de(e.cwd)&&r.push({allowScopeFallback:!1,name:C,preferredScope:"project",spec:ue(W(e.cwd))}),r},he=e=>{const r=e.home??y(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of f){const o=n.paths({home:r,platform:t,projectRoot:e.cwd}),l=a=>{const s=o[a];return s===void 0?"—":u(s,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${l("project").padEnd(30)} global: ${l("global")}`)}return{code:0,written:[]}},ye=e=>e.docsOnly===!0&&e.localOnly===!0?"`--docs-only` and `--local-only` are mutually exclusive — pass at most one.":"`--local-only` was set but this directory is not a Lunora project (no `lunora/` directory and wrangler config).",be=(e,r,t)=>{const n=[];for(const o of e)for(const l of r){const a=o.format==="json"?pe(o,l,t):ge(o,l,t);a!==void 0&&n.push({action:a.action,client:o.id,path:a.path,server:l.name})}return n},we=e=>{const r=e.home??y(),t=e.platform??process.platform,n=j(e.clients,()=>se({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:d.USAGE,written:[]};if(n.length===0)return e.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${$.join(", ")}.`),{code:d.NOT_FOUND,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(a=>a.label).join(", ")}.`);const o=ve(e);if(o.length===0)return e.logger.error(`mcp install: nothing to install — ${ye(e)}`),{code:d.USAGE,written:[]};const l=be(n,o,{...e,home:r,platform:t});return l.some(a=>a.action==="created"||a.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:l.some(a=>a.action==="invalid")?1:0,written:l}},x=100,L=1e3,w=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Se=e=>({content:[{text:e,type:"text"}]}),ke=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?x:Math.min(L,Math.max(1,Math.floor(r)))},S=(e,r)=>{if(r===void 0)return;const t=p(e,J);return K(t,p(e,r))?p(e,r):void 0},Ee=(e,r)=>{const t=N(e,"utf8").split(`
|
|
5
|
+
`);return t.at(-1)===""&&t.pop(),t.slice(-r).join(`
|
|
6
|
+
`)},$e=e=>[{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Check the local dev server"},description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const r=v(e);return w(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:S(e,r.logFile),mode:r.mode,pid:r.pid,running:!0,startedAt:r.startedAt,studioUrl:r.studioUrl,url:r.url})}},{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Read the local dev server log"},description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(x)}, max ${String(L)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=v(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=S(e,t.logFile);if(n===void 0||!h(n))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const o=ke(r.lines),l=Ee(n,o);return Se(l.length===0?"(the dev server log is empty)":l)}}],je=new Set(["127.0.0.1","::1","localhost"]),U=e=>{try{const{hostname:r}=new URL(e);return je.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},k=e=>{const r=e.url??v(e.cwd)?.url;if(r===void 0||r.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:r};if(!U(r))return{url:r};const t=V(e.cwd);return t===void 0||t.length===0?{url:r}:{token:t,url:r}},Oe=async e=>{await new Promise(r=>{const t=()=>{r()};e.onclose=t,process.stdin.once("close",t),process.stdin.once("end",t)})},Ce=e=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url}
|
|
7
|
+
`;const t=!U(e.url)?"the project's admin token was NOT sent to this non-local url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${t})
|
|
8
|
+
`},_e=async(e,r=z)=>{const t=e.writeError??(l=>{process.stderr.write(l)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>k(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:$e(e.cwd),version:e.version})}catch(l){const a=l instanceof Error?l.message:String(l);return t(`lunora mcp serve: failed to start — ${a}
|
|
9
|
+
`),{code:1,deployment:void 0}}const o=k(e);return t(Ce(o)),await Oe(n),{code:0,deployment:o}},xe=e=>{const r=[];return e.localOnly!==!0&&r.push(O),e.docsOnly!==!0&&r.push(C),r},Le=(e,r,t,n)=>{const o=H({key:e.key,name:r,path:t}),l=u(t,n.cwd);return o.action==="removed"?n.logger.success(`${e.label}: removed "${r}" from ${l}.`):o.action==="invalid"&&n.logger.error(`${e.label}: ${l} is not valid JSON (${o.error??"unknown error"}) — left untouched.`),{action:o.action,path:t}},Ue=(e,r,t,n)=>{const o=R({key:e.key,name:r,path:t}),l=u(t,n.cwd);return o==="invalid"?(n.logger.error(`${e.label}: ${l} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:t}):o==="absent"?{action:"absent",path:t}:(n.logger.info(`${e.label}: would remove "${r}" from ${l}.`),{action:"removed",path:t})},Me=(e,r,t)=>e.flatMap(n=>le(n,r)).filter(ce).filter(n=>t===void 0||n.scope===t),Ae=e=>{const r=e.home??y(),t=e.platform??process.platform,n=j(e.clients,()=>f,e.logger,"uninstall");if(n===void 0)return{code:d.USAGE,removed:[]};const o=xe(e);if(o.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:d.USAGE,removed:[]};const l=[],a={home:r,platform:t,projectRoot:e.cwd};for(const s of Me(n,a,e.scope))for(const i of o){const b=e.print===!0?Ue(s.client,i,s.path,e):Le(s.client,i,s.path,e);b.action!=="absent"&&l.push({...b,client:s.client.id,server:i})}return l.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:l.some(s=>s.action==="invalid")?1:0,removed:l}},E=e=>e.global===!0?"global":e.project===!0?"project":void 0,Ne=async(e,r)=>{const{code:t}=await _e({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:M,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},Be=A(async({argument:e,cwd:r,logger:t,options:n})=>{const[o,...l]=e;if(o==="serve")return Ne(r,n);if(o==="uninstall"){const a=E(n),{code:s}=Ae({clients:l,cwd:r,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...a===void 0?{}:{scope:a}});return{code:s}}if(o==="install"){if(n.list===!0)return he({cwd:r,logger:t});const a=E(n),{code:s}=we({clients:l,cwd:r,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...a===void 0?{}:{scope:a},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:s}}return t.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:d.USAGE}});export{Be as execute};
|