@lunora/cli 1.0.0-alpha.21 → 1.0.0-alpha.211
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 +1 -1
- package/__assets__/package-og.svg +1 -1
- package/dist/bin.mjs +2 -10
- package/dist/index.d.mts +745 -341
- package/dist/index.d.ts +745 -341
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/handler.mjs +1 -150
- package/dist/packem_chunks/handler10.mjs +4 -22
- package/dist/packem_chunks/handler11.mjs +2 -192
- package/dist/packem_chunks/handler12.mjs +1 -131
- package/dist/packem_chunks/handler13.mjs +1 -65
- package/dist/packem_chunks/handler14.mjs +1 -58
- package/dist/packem_chunks/handler15.mjs +1 -79
- package/dist/packem_chunks/handler16.mjs +3 -43
- package/dist/packem_chunks/handler17.mjs +1 -105
- package/dist/packem_chunks/handler18.mjs +1 -170
- package/dist/packem_chunks/handler19.mjs +7 -89
- package/dist/packem_chunks/handler2.mjs +2 -114
- package/dist/packem_chunks/handler20.mjs +1 -94
- package/dist/packem_chunks/handler21.mjs +2 -311
- package/dist/packem_chunks/handler22.mjs +3 -0
- package/dist/packem_chunks/handler23.mjs +3 -0
- package/dist/packem_chunks/handler24.mjs +1 -0
- package/dist/packem_chunks/handler25.mjs +99 -0
- package/dist/packem_chunks/handler26.mjs +10 -0
- package/dist/packem_chunks/handler3.mjs +1 -204
- package/dist/packem_chunks/handler4.mjs +1 -33
- package/dist/packem_chunks/handler5.mjs +1 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +3 -42
- package/dist/packem_chunks/handler8.mjs +1 -174
- package/dist/packem_chunks/handler9.mjs +1 -16
- package/dist/packem_chunks/planDevCommand.mjs +7 -500
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDeployCommand.mjs +1 -504
- package/dist/packem_chunks/runInitCommand.mjs +118 -1383
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/COMMANDS-BXbrW8dd.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Cf8ZymM1.mjs +1 -0
- package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +1 -0
- package/dist/packem_shared/admin-url-Cil3Or6N.mjs +1 -0
- package/dist/packem_shared/advisory-gate-Cl8IEFIj.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-Zi3bBqpc.mjs +1 -0
- package/dist/packem_shared/cli-C37AI4tr.mjs +3 -0
- package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
- package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
- package/dist/packem_shared/commands-BNKj7r1R.mjs +19 -0
- package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
- package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +5 -0
- package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
- package/dist/packem_shared/import-CdHdZRjj.mjs +12 -0
- package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
- package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
- package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
- package/dist/packem_shared/output-format-DfogXx0p.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/platform-diagnostics-uOXqysk3.mjs +4 -0
- package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
- package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
- package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
- package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +1 -0
- package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
- package/dist/packem_shared/schema-drift-gate-DARCKocg.mjs +1 -0
- package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
- package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
- package/dist/packem_shared/storage-wIUel5Az.mjs +1 -0
- package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
- package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
- package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
- package/package.json +39 -17
- package/skills/README.md +35 -17
- package/skills/lunora/SKILL.md +65 -9
- package/skills/lunora-functions/SKILL.md +38 -3
- package/skills/lunora-migration-helper/SKILL.md +70 -17
- package/skills/lunora-performance-audit/SKILL.md +36 -6
- package/skills/lunora-quickstart/SKILL.md +90 -24
- package/skills/lunora-realtime/SKILL.md +58 -30
- package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
- 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/command-BC30oSBW.mjs +0 -14
- package/dist/packem_shared/commands-hl0mRqqg.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/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-vJdgiR5t.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-B7hHSTZP.mjs +0 -84
- package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import{existsSync as T,readFileSync as O}from"node:fs";import{writeFile as I,mkdir as k}from"node:fs/promises";import{join as b}from"@visulima/path";import{d as B}from"../packem_shared/command-DwC11Cwe.mjs";import{createRequire as U}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as Y,detectPackageManager as q,parseSchema as F,applyAdditiveEdit as P}from"@lunora/config";const H=/^\//,K=(e,t)=>{try{const{args:n,command:r}=Y(q(e),[t],{dev:!0});return`${r} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${t}`}},L=(e,t,n)=>{const r=U(b(n,"noop.cjs"));try{r.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${t}\` driver to read this database, and it isn't installed.
|
|
2
|
+
|
|
3
|
+
Install it in your project:
|
|
4
|
+
|
|
5
|
+
${K(n,t)}`)}return r(e)},j=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},G=e=>{try{const t=new URL(e).pathname.replace(H,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},J=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=L("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,d)=>(await u.query(l,[...d])).rows,schema:n??"public"}}const a=L("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??G(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"]),Q={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()"},W={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,t)=>{const r=(t==="postgres"?Q:W)[e.dataType],s=e.references===void 0?r:`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,X=/[^\dA-Z]+(.)?/gi,z=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(V,t=>ee[t]??t),S=e=>M.test(e)?e:f(e),ne=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),te=e=>{const t=e.replaceAll(Z,"_");return t===""?"table":t},re=e=>{const n=e.replaceAll(X,(r,s)=>s?.toUpperCase()??"").replace(z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(t=>!h.has(t.name)),ae=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!h.has(n))},D=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.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}),se=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){r.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,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.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
|
+
`)},`},oe=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>se(a,e.dialect,r,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 "${t.serverImport}";
|
|
21
|
+
|
|
22
|
+
export default defineSchema({
|
|
23
|
+
${s}
|
|
24
|
+
});
|
|
25
|
+
`},ie=(e,t,n,r=new Set([e.name]),s=[])=>{const a=re(e.name),o=ae(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const d=i.get(l);if(d===void 0)return;const p=D({...d,nullable:!1},r,e.name,[]),{expression:y,known:A}=w(p,t);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${d.dataType}\`).`),` ${S(l)}: ${y},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${ne(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
|
+
`},ce=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:oe(e,t,n),path:"schema.ts"}];if(t.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=te(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:ie(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!_.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);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:me(i)}),!a.nullable&&t!==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 r},ue=(e,t,n)=>{const r=[],s=new Set(t?.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(!_.test(a.name)||!o.every(i=>_.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},de=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!_.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&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...le(i,c,{dialect:n,present:o,warnings:s}),...ue(i,c,s))}return{edits:r,warnings:s}},pe=(e,t,n)=>{const r=F(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=P(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,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ge=`
|
|
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`,fe=`
|
|
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`,ve=`
|
|
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'`,he=`
|
|
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`,be=`
|
|
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`,Ee=`
|
|
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`,_e=`
|
|
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`,ye=`
|
|
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 t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Ae=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Se=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},Ne=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?ge:be,[n]),e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[d,p]of E(s)){const y=new Map((m.get(d)??[]).map(v=>[g(v,"column_name"),{column:g(v,"foreign_column"),table:g(v,"foreign_table")}])),A=p.map(v=>{const R=g(v,"column_name"),$=y.get(R);return{...Ae(v,t),name:R,nullable:g(v,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Se(u.get(d)??[],t),name:d,primaryKey:(c.get(d)??[]).map(v=>g(v,"column_name"))})}return l.sort((d,p)=>d.name.localeCompare(p.name)),{dialect:t,tables:l}},we=e=>{try{const t=JSON.parse(O(b(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Re=async(e,t,n)=>{const r=b(t,e.path);return T(r)&&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 k(t,{recursive:!0}),await I(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},$e=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Le=async(e,t,n,r)=>{const s=pe(O(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const n=e.connection===void 0?j(e.url):e.dialect??"postgres",r=e.connection??await J(e.url,n,e.schema,t);let s;try{s=await Ne(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=$e(s,e);if(a.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:o,warnings:i}=ce({...s,tables:a},{procedures:e.procedures!==!1,serverImport:we(t)}),c=b(t,"lunora"),m=[],u=b(c,"schema.ts"),l=T(u)&&e.force!==!0,d=l?o.filter(p=>p.path!=="schema.ts"):o;l&&await Le(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const p of d)await Re(p,c,e)&&m.push(p.path);for(const p of i)e.logger.warn(p);return e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Be=B(async({cwd:e,logger:t,options:n})=>({code:(await Te({cwd:e,dryRun:n.dryRun===!0,force:n.force===!0,logger:t,procedures:n.procedures!==!1,schema:n.schema,tables:n.tables===void 0?void 0:n.tables.split(",").map(s=>s.trim()),url:n.url??process.env.DATABASE_URL})).code}));export{Be as execute,we as resolveServerImport,Te as runIntrospectCommand};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{V as R}from"../packem_shared/cli-C37AI4tr.mjs";import{d as T}from"../packem_shared/command-DwC11Cwe.mjs";import{existsSync as u,readFileSync as v,mkdirSync as D,realpathSync as I,statSync as J,writeFileSync as W,chmodSync as z,renameSync as G,unlinkSync as H}from"node:fs";import{homedir as b}from"node:os";import{findWranglerFile as V}from"@lunora/config/cloudflare";import{join as s,dirname as K,relative as q}from"@visulima/path";import{stringify as B}from"smol-toml";import{parse as X,modify as Z,applyEdits as Q}from"jsonc-parser";import{detectPackageManager as Y,execArgsFor as ee,readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as re}from"@lunora/config/studio-host";import{connectLocalStdio as te}from"@lunora/mcp";const f=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),h=e=>e.transport==="http"?{type:"http",url:e.url}:f(e),ne=e=>e.transport==="http"?{httpUrl:e.url}:f(e),oe=e=>e.transport==="http"?{serverUrl:e.url}:f(e),ae=e=>({args:["-y","mcp-remote",e],command:"npx"}),le=e=>e.transport==="http"?ae(e.url):f(e),ce=e=>e.transport==="http"?{url:e.url}:f(e),se=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}},ie=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...f(e)},de=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ue=(e,r)=>B({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),p=[{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:h,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:ne,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:le,paths:de,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:oe,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:ce,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ue}],O=p.map(e=>e.id),fe=e=>p.find(r=>r.id===e.toLowerCase()),C=(e,r)=>{let t=e,n;try{t=I(e),n=J(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{W(a,r,"utf8"),n!==void 0&&z(a,n),G(a,t)}catch(o){try{H(a)}catch{}throw o}},me={formattingOptions:{insertSpaces:!0,tabSize:4}},w=e=>{const r=[],t=X(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),S=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},x=e=>{if(!u(e.path))return"absent";let r;try{r=v(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=w(r);return t.length>0||!g(n)?"invalid":S(n,e.key,e.name)===void 0?"absent":"present"},ge=e=>x(e)==="present",M=(e,r,t,n,a)=>{try{const o=Z(e,[t,n],a,me);o.length>0&&C(r,Q(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},pe=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=u(o)?v(o,"utf8"):"";if(l.trim().length===0)return D(K(o),{recursive:!0}),C(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
|
|
2
|
+
`),{action:"created",path:o};const{errors:c,value:i}=w(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const m=i[n];if(m!==void 0&&!g(m))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(S(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const k=M(l,o,n,a,r);return k===void 0?{action:"updated",path:o}:{action:"invalid",error:k,path:o}},ve=e=>{const{key:r,name:t,path:n}=e;if(!u(n))return{action:"absent",path:n};let a;try{a=v(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=w(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(S(l,r,t)===void 0)return{action:"absent",path:n};const c=M(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},he=["global","project"],d=(e,r)=>{const t=q(r,e);return t.length>0&&!t.startsWith("..")?t:e},ye=(e,r)=>{const t=e.paths(r);return he.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},be=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},we=e=>p.filter(r=>Object.values(r.paths(e)).some(t=>u(t))),_=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=fe(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${O.join(", ")}.`);return}a.push(l)}return a},Se=e=>e.client.format==="json",ke="https://lunora.sh/mcp",L="lunora-docs",N="lunora",je=e=>u(s(e,"lunora"))&&V(e)!==void 0,$e=e=>{const{args:r,command:t}=ee(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Ee=e=>({transport:"http",url:e}),Oe=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),U=(e,r,t)=>be(e,Oe(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ce=(e,r,t)=>{const n=U(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:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=d(a,t.cwd);return t.force!==!0&&ge({key:e.key,name:r.name,path:a})?(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:a}):(t.logger.info(`${e.label} → ${i}
|
|
3
|
+
${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=pe({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=d(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},xe=(e,r,t)=>{const n=U(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 ${d(n,t.cwd)}
|
|
4
|
+
|
|
5
|
+
${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},Me=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:L,preferredScope:"global",spec:Ee(e.docsUrl??ke)}),e.docsOnly!==!0&&je(e.cwd)&&r.push({allowScopeFallback:!1,name:N,preferredScope:"project",spec:$e(Y(e.cwd))}),r},_e=e=>{const r=e.home??b(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of p){const a=n.paths({home:r,platform:t,projectRoot:e.cwd}),o=l=>{const c=a[l];return c===void 0?"—":d(c,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${o("project").padEnd(30)} global: ${o("global")}`)}return{code:0,written:[]}},Le=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).",Ne=(e,r,t)=>{const n=[];for(const a of e)for(const o of r){const l=a.format==="json"?Ce(a,o,t):xe(a,o,t);l!==void 0&&n.push({action:l.action,client:a.id,path:l.path,server:o.name})}return n},Ue=e=>{const r=e.home??b(),t=e.platform??process.platform,n=_(e.clients,()=>we({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:1,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: ${O.join(", ")}.`),{code:1,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(l=>l.label).join(", ")}.`);const a=Me(e);if(a.length===0)return e.logger.error(`mcp install: nothing to install — ${Le(e)}`),{code:1,written:[]};const o=Ne(n,a,{...e,home:r,platform:t});return o.some(l=>l.action==="created"||l.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:o.some(l=>l.action==="invalid")?1:0,written:o}},A=100,F=1e3,j=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ae=e=>({content:[{text:e,type:"text"}]}),Fe=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?A:Math.min(F,Math.max(1,Math.floor(r)))},Pe=(e,r)=>{const t=v(e,"utf8").split(`
|
|
6
|
+
`);return t.at(-1)===""&&t.pop(),t.slice(-r).join(`
|
|
7
|
+
`)},Re=e=>[{definition:{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=y(e);return j(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:r.logFile,mode:r.mode,pid:r.pid,running:!0,startedAt:r.startedAt,studioUrl:r.studioUrl,url:r.url})}},{definition:{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(A)}, max ${String(F)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=y(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};if(t.logFile===void 0||!u(t.logFile))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 n=Fe(r.lines),a=Pe(t.logFile,n);return Ae(a.length===0?"(the dev server log is empty)":a)}}],Te=new Set(["127.0.0.1","::1","localhost"]),P=e=>{try{const{hostname:r}=new URL(e);return Te.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},$=e=>{const r=e.url??y(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(e.url!==void 0&&!P(e.url))return{url:r};const t=re(e.cwd);return t===void 0||t.length===0?{url:r}:{token:t,url:r}},De=async e=>{await new Promise(r=>{const t=()=>{r()};e.onclose=t,process.stdin.once("close",t),process.stdin.once("end",t)})},Ie=(e,r)=>{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}
|
|
8
|
+
`;const n=r.url!==void 0&&!P(r.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} (${n})
|
|
9
|
+
`},Je=async(e,r=te)=>{const t=e.writeError??(o=>{process.stderr.write(o)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>$(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Re(e.cwd),version:e.version})}catch(o){const l=o instanceof Error?o.message:String(o);return t(`lunora mcp serve: failed to start — ${l}
|
|
10
|
+
`),{code:1,deployment:void 0}}const a=$(e);return t(Ie(a,e)),await De(n),{code:0,deployment:a}},We=e=>{const r=[];return e.localOnly!==!0&&r.push(L),e.docsOnly!==!0&&r.push(N),r},ze=(e,r,t,n)=>{const a=ve({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a.action==="removed"?n.logger.success(`${e.label}: removed "${r}" from ${o}.`):a.action==="invalid"&&n.logger.error(`${e.label}: ${o} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:t}},Ge=(e,r,t,n)=>{const a=x({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a==="invalid"?(n.logger.error(`${e.label}: ${o} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:t}):a==="absent"?{action:"absent",path:t}:(n.logger.info(`${e.label}: would remove "${r}" from ${o}.`),{action:"removed",path:t})},He=(e,r,t)=>e.flatMap(n=>ye(n,r)).filter(Se).filter(n=>t===void 0||n.scope===t),Ve=e=>{const r=e.home??b(),t=e.platform??process.platform,n=_(e.clients,()=>p,e.logger,"uninstall");if(n===void 0)return{code:1,removed:[]};const a=We(e);if(a.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:1,removed:[]};const o=[],l={home:r,platform:t,projectRoot:e.cwd};for(const c of He(n,l,e.scope))for(const i of a){const m=e.print===!0?Ge(c.client,i,c.path,e):ze(c.client,i,c.path,e);m.action!=="absent"&&o.push({...m,client:c.client.id,server:i})}return o.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:o.some(c=>c.action==="invalid")?1:0,removed:o}},E=e=>e.global===!0?"global":e.project===!0?"project":void 0,Ke=async(e,r)=>{const{code:t}=await Je({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:R,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},ar=T(async({argument:e,cwd:r,logger:t,options:n})=>{const[a,...o]=e;if(a==="serve")return Ke(r,n);if(a==="uninstall"){const l=E(n),{code:c}=Ve({clients:o,cwd:r,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l}});return{code:c}}if(a==="install"){if(n.list===!0)return _e({cwd:r,logger:t});const l=E(n),{code:c}=Ue({clients:o,cwd:r,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return t.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:1}});export{ar as execute};
|
|
@@ -1,204 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import { r as resolveAdminBaseUrl } from '../packem_shared/admin-url-4UzT-CI4.mjs';
|
|
5
|
-
import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
|
|
6
|
-
import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
|
|
7
|
-
import { runExportCommand, runImportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
|
|
8
|
-
|
|
9
|
-
const DEFAULT_BACKUP_DIR = ".lunora-backups";
|
|
10
|
-
const MANIFEST_FILE = "manifest.json";
|
|
11
|
-
const PITR_ENDPOINT_PATH = "/_lunora/admin/pitr";
|
|
12
|
-
const GET_PITR_BOOKMARK_OP = "__lunora_admin__:getPitrBookmark";
|
|
13
|
-
const PITR_RESTORE_OP = "__lunora_admin__:pitrRestore";
|
|
14
|
-
const isManifestEntry = (value) => typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.file === "string";
|
|
15
|
-
const readManifest = async (directory) => {
|
|
16
|
-
const path = join(directory, MANIFEST_FILE);
|
|
17
|
-
if (!existsSync(path)) {
|
|
18
|
-
return [];
|
|
19
|
-
}
|
|
20
|
-
let parsed;
|
|
21
|
-
try {
|
|
22
|
-
parsed = JSON.parse(await readFile(path, "utf8"));
|
|
23
|
-
} catch (error) {
|
|
24
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
25
|
-
throw new Error(`backup: ${path} exists but is not valid JSON (${message}) — refusing to overwrite it; fix or remove it manually`, { cause: error });
|
|
26
|
-
}
|
|
27
|
-
if (!Array.isArray(parsed)) {
|
|
28
|
-
throw new TypeError(`backup: ${path} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);
|
|
29
|
-
}
|
|
30
|
-
return parsed.filter(isManifestEntry);
|
|
31
|
-
};
|
|
32
|
-
const writeManifest = async (directory, entries) => {
|
|
33
|
-
await writeFile(join(directory, MANIFEST_FILE), `${JSON.stringify(entries, void 0, 2)}
|
|
34
|
-
`, "utf8");
|
|
35
|
-
};
|
|
36
|
-
const runBackupCreate = async (options, directory) => {
|
|
37
|
-
await mkdir(directory, { recursive: true });
|
|
38
|
-
const timestamp = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
|
|
39
|
-
const file = `lunora-backup-${timestamp.replaceAll(/[.:]/gu, "-")}.ndjson`;
|
|
40
|
-
const result = await runExportCommand({
|
|
41
|
-
fetchImpl: options.fetchImpl,
|
|
42
|
-
logger: options.logger,
|
|
43
|
-
out: join(directory, file),
|
|
44
|
-
prod: options.prod,
|
|
45
|
-
tables: options.tables,
|
|
46
|
-
token: options.token,
|
|
47
|
-
url: options.url
|
|
48
|
-
});
|
|
49
|
-
if (result.code !== 0) {
|
|
50
|
-
return { code: result.code };
|
|
51
|
-
}
|
|
52
|
-
const entry = { bytes: result.bytes, createdAt: timestamp, file, id: timestamp, rows: result.rows, tables: options.tables };
|
|
53
|
-
const manifest = await readManifest(directory);
|
|
54
|
-
manifest.push(entry);
|
|
55
|
-
await writeManifest(directory, manifest);
|
|
56
|
-
options.logger.success(`backup created: ${file} (${result.rows.toString()} rows, ${result.bytes.toString()} bytes)`);
|
|
57
|
-
return { code: 0, entry };
|
|
58
|
-
};
|
|
59
|
-
const runBackupList = async (options, directory) => {
|
|
60
|
-
const manifest = await readManifest(directory);
|
|
61
|
-
if (manifest.length === 0) {
|
|
62
|
-
options.logger.info(`no backups found in ${directory}`);
|
|
63
|
-
return { code: 0 };
|
|
64
|
-
}
|
|
65
|
-
for (const entry of manifest) {
|
|
66
|
-
options.logger.info(`${entry.id} ${entry.rows.toString()} rows ${entry.bytes.toString()} bytes ${entry.file}`);
|
|
67
|
-
}
|
|
68
|
-
return { code: 0 };
|
|
69
|
-
};
|
|
70
|
-
const runBackupRestore = async (options, directory) => {
|
|
71
|
-
const { target } = options;
|
|
72
|
-
if (target === void 0 || target.length === 0) {
|
|
73
|
-
options.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>");
|
|
74
|
-
return { code: 1 };
|
|
75
|
-
}
|
|
76
|
-
const manifest = await readManifest(directory);
|
|
77
|
-
const matched = manifest.find((entry) => entry.id === target);
|
|
78
|
-
const file = matched ? join(directory, matched.file) : target;
|
|
79
|
-
if (!existsSync(file)) {
|
|
80
|
-
options.logger.error(`backup not found: ${target}`);
|
|
81
|
-
return { code: 1 };
|
|
82
|
-
}
|
|
83
|
-
const result = await runImportCommand({
|
|
84
|
-
fetchImpl: options.fetchImpl,
|
|
85
|
-
file,
|
|
86
|
-
logger: options.logger,
|
|
87
|
-
prod: options.prod,
|
|
88
|
-
token: options.token,
|
|
89
|
-
url: options.url
|
|
90
|
-
});
|
|
91
|
-
return { code: result.code };
|
|
92
|
-
};
|
|
93
|
-
const resolvePitrRequest = (options) => {
|
|
94
|
-
const token = options.token ?? process.env.LUNORA_ADMIN_TOKEN;
|
|
95
|
-
if (!token) {
|
|
96
|
-
options.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");
|
|
97
|
-
return void 0;
|
|
98
|
-
}
|
|
99
|
-
if (options.prod && options.url === void 0) {
|
|
100
|
-
options.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");
|
|
101
|
-
return void 0;
|
|
102
|
-
}
|
|
103
|
-
if (options.restore === true && options.at === void 0 && options.bookmark === void 0) {
|
|
104
|
-
options.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");
|
|
105
|
-
return void 0;
|
|
106
|
-
}
|
|
107
|
-
if (options.restore === true && options.prod === true && options.yes !== true) {
|
|
108
|
-
options.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");
|
|
109
|
-
return void 0;
|
|
110
|
-
}
|
|
111
|
-
const baseUrl = resolveAdminBaseUrl(options.url, options.logger);
|
|
112
|
-
if (baseUrl === void 0) {
|
|
113
|
-
return void 0;
|
|
114
|
-
}
|
|
115
|
-
const fetchImpl = options.pitrFetch ?? globalThis.fetch;
|
|
116
|
-
if (typeof fetchImpl !== "function") {
|
|
117
|
-
throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");
|
|
118
|
-
}
|
|
119
|
-
return { fetchImpl, requestUrl: `${baseUrl}${PITR_ENDPOINT_PATH}`, token };
|
|
120
|
-
};
|
|
121
|
-
const buildPitrArgs = (options, isRestore) => {
|
|
122
|
-
const args = {};
|
|
123
|
-
if (options.at !== void 0) {
|
|
124
|
-
args.time = options.at;
|
|
125
|
-
}
|
|
126
|
-
if (isRestore && options.bookmark !== void 0) {
|
|
127
|
-
args.bookmark = options.bookmark;
|
|
128
|
-
}
|
|
129
|
-
if (isRestore && options.restart === true) {
|
|
130
|
-
args.restart = true;
|
|
131
|
-
}
|
|
132
|
-
return args;
|
|
133
|
-
};
|
|
134
|
-
const runBackupPitr = async (options) => {
|
|
135
|
-
const request = resolvePitrRequest(options);
|
|
136
|
-
if (request === void 0) {
|
|
137
|
-
return { code: 1 };
|
|
138
|
-
}
|
|
139
|
-
const isRestore = options.restore === true;
|
|
140
|
-
const functionPath = isRestore ? PITR_RESTORE_OP : GET_PITR_BOOKMARK_OP;
|
|
141
|
-
const args = buildPitrArgs(options, isRestore);
|
|
142
|
-
const action = isRestore ? "restore" : "bookmark";
|
|
143
|
-
options.logger.info(`POST ${request.requestUrl} -> pitr ${action}${options.shard === void 0 ? "" : ` (shard "${options.shard}")`}`);
|
|
144
|
-
const response = await request.fetchImpl(request.requestUrl, {
|
|
145
|
-
body: JSON.stringify({ args, functionPath, shardKey: options.shard }),
|
|
146
|
-
headers: { authorization: `Bearer ${request.token}`, "content-type": "application/json" },
|
|
147
|
-
method: "POST"
|
|
148
|
-
});
|
|
149
|
-
const text = await response.text();
|
|
150
|
-
let body;
|
|
151
|
-
try {
|
|
152
|
-
body = JSON.parse(text);
|
|
153
|
-
} catch {
|
|
154
|
-
body = text;
|
|
155
|
-
}
|
|
156
|
-
options.logger.info(JSON.stringify(body, void 0, 2));
|
|
157
|
-
return { code: response.ok ? 0 : 1 };
|
|
158
|
-
};
|
|
159
|
-
const runBackupCommand = async (options) => {
|
|
160
|
-
const cwd = options.cwd ?? process.cwd();
|
|
161
|
-
const directory = join(cwd, options.dir ?? DEFAULT_BACKUP_DIR);
|
|
162
|
-
try {
|
|
163
|
-
if (options.subcommand === "create") {
|
|
164
|
-
return await runBackupCreate(options, directory);
|
|
165
|
-
}
|
|
166
|
-
if (options.subcommand === "list") {
|
|
167
|
-
return await runBackupList(options, directory);
|
|
168
|
-
}
|
|
169
|
-
if (options.subcommand === "pitr") {
|
|
170
|
-
return await runBackupPitr(options);
|
|
171
|
-
}
|
|
172
|
-
return await runBackupRestore(options, directory);
|
|
173
|
-
} catch (error) {
|
|
174
|
-
options.logger.error(error instanceof Error ? error.message : String(error));
|
|
175
|
-
return { code: 1 };
|
|
176
|
-
}
|
|
177
|
-
};
|
|
178
|
-
const isBackupSubcommand = (value) => value === "create" || value === "list" || value === "pitr" || value === "restore";
|
|
179
|
-
const execute = defineHandler(({ argument, cwd, logger, options }) => {
|
|
180
|
-
const sub = argument[0];
|
|
181
|
-
if (!isBackupSubcommand(sub)) {
|
|
182
|
-
logger.error(`backup: unknown subcommand "${sub ?? ""}" — expected create | list | restore | pitr`);
|
|
183
|
-
return { code: 1 };
|
|
184
|
-
}
|
|
185
|
-
return runBackupCommand({
|
|
186
|
-
at: options.at,
|
|
187
|
-
bookmark: options.bookmark,
|
|
188
|
-
cwd,
|
|
189
|
-
dir: options.dir,
|
|
190
|
-
logger,
|
|
191
|
-
prod: options.prod === true,
|
|
192
|
-
restart: options.restart === true,
|
|
193
|
-
restore: options.restore === true,
|
|
194
|
-
shard: options.shard,
|
|
195
|
-
subcommand: sub,
|
|
196
|
-
tables: options.tables,
|
|
197
|
-
target: argument[1],
|
|
198
|
-
token: options.token,
|
|
199
|
-
url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url }),
|
|
200
|
-
yes: options.yes === true
|
|
201
|
-
});
|
|
202
|
-
});
|
|
203
|
-
|
|
204
|
-
export { execute, runBackupCommand };
|
|
1
|
+
import{d as i}from"../packem_shared/command-DwC11Cwe.mjs";import{i as l}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as m}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{execArgsFor as g,detectPackageManager as p}from"@lunora/config";const o=new Set(["build","delete","images","info","list","push"]),f=new Set(["build","push"]),h=async e=>{const[a,...t]=e.argument;if(a===void 0||!o.has(a))return e.logger.error(`lunora containers requires a subcommand: ${[...o].toSorted((u,d)=>u.localeCompare(d)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(f.has(a)&&!(e.dockerAvailable??l)())return e.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const r=["containers",a,...t];e.tag!==void 0&&r.push("--tag",e.tag),e.push===!0&&r.push("--push"),e.env!==void 0&&r.push("--env",e.env);const s=e.cwd??process.cwd(),c=g(p(s),"wrangler",r),n={args:c.args,command:c.command,cwd:s};return e.logger.info(`running ${n.command} ${n.args.join(" ")}`),{code:(await(e.spawner??m)(n)).code,descriptor:n}},D=i(async({argument:e,cwd:a,logger:t,options:r})=>({code:(await h({argument:e,cwd:a,env:r.env,logger:t,push:r.push===!0,tag:r.tag})).code}));export{D as execute,h as runContainersCommand};
|
|
@@ -1,33 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
|
|
3
|
-
import { runDeployCommand } from './runDeployCommand.mjs';
|
|
4
|
-
|
|
5
|
-
const DEFAULT_OUT_DIR = ".lunora/build";
|
|
6
|
-
const runBuildCommand = async (options) => {
|
|
7
|
-
const outDirectory = options.outDir ?? DEFAULT_OUT_DIR;
|
|
8
|
-
const result = await runDeployCommand({
|
|
9
|
-
apiSpec: options.apiSpec,
|
|
10
|
-
cwd: options.cwd,
|
|
11
|
-
dryRun: true,
|
|
12
|
-
format: options.format,
|
|
13
|
-
logger: options.logger,
|
|
14
|
-
outDir: outDirectory,
|
|
15
|
-
spawner: options.spawner
|
|
16
|
-
});
|
|
17
|
-
if (result.code === 0) {
|
|
18
|
-
options.logger.success(`build complete — bundle written to ${outDirectory}`);
|
|
19
|
-
}
|
|
20
|
-
return result;
|
|
21
|
-
};
|
|
22
|
-
const execute = defineHandler(async ({ cwd, logger, options }) => {
|
|
23
|
-
const result = await runBuildCommand({
|
|
24
|
-
apiSpec: parseApiSpec(options.apiSpec),
|
|
25
|
-
cwd,
|
|
26
|
-
format: options.format,
|
|
27
|
-
logger,
|
|
28
|
-
outDir: options.outDir
|
|
29
|
-
});
|
|
30
|
-
return { code: result.code };
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
export { execute, runBuildCommand };
|
|
1
|
+
import{d}from"../packem_shared/command-DwC11Cwe.mjs";import{defaultSpawner as a}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{execArgsFor as m,detectPackageManager as i}from"@lunora/config";const t=(e,r)=>(r!==void 0&&e.push("--env",r),e),u=e=>{const r=t(["deployments","list"],e.env);return e.json&&r.push("--json"),r},l=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:t(["versions","view",e.versionId],e.env)};case"list":return{args:u(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const r=t(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&r.push("--message",e.message),{args:r}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const r=t(["rollback"],e.env);return e.versionId!==void 0&&r.push(e.versionId),r.push("--yes"),e.message!==void 0&&r.push("--message",e.message),{args:r}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},v=async e=>{const{args:r,error:n}=l(e);if(n!==void 0||r===void 0)return e.logger.error(n??"deployments: nothing to run"),{code:1,descriptor:void 0,error:n};const s=e.cwd??process.cwd(),o=m(i(s),"wrangler",r),c={args:o.args,command:o.command,cwd:s};return e.logger.info(`${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??a)(c)).code,descriptor:c}},g=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",h=d(({argument:e,cwd:r,logger:n,options:s})=>{const o=e[0];return g(o)?v({cwd:r,env:s.env,json:s.json===!0,logger:n,message:s.message,subcommand:o,versionId:e[1],yes:s.yes===!0}):(n.error(`deployments: unknown subcommand "${o??""}" — expected list | inspect | rollback | promote`),{code:1})});export{h as execute,v as runDeploymentsCommand};
|
|
@@ -1,49 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { i as isDockerAvailable } from '../packem_shared/docker-hMQ97KSQ.mjs';
|
|
3
|
-
import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
|
|
4
|
-
|
|
5
|
-
const SUBCOMMANDS = /* @__PURE__ */ new Set(["build", "delete", "images", "info", "list", "push"]);
|
|
6
|
-
const NEEDS_DOCKER = /* @__PURE__ */ new Set(["build", "push"]);
|
|
7
|
-
const runContainersCommand = async (options) => {
|
|
8
|
-
const [subcommand, ...rest] = options.argument;
|
|
9
|
-
if (subcommand === void 0 || !SUBCOMMANDS.has(subcommand)) {
|
|
10
|
-
options.logger.error(
|
|
11
|
-
`lunora containers requires a subcommand: ${[...SUBCOMMANDS].toSorted((a, b) => a.localeCompare(b)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`
|
|
12
|
-
);
|
|
13
|
-
return { code: 1 };
|
|
14
|
-
}
|
|
15
|
-
if (NEEDS_DOCKER.has(subcommand) && !(options.dockerAvailable ?? isDockerAvailable)()) {
|
|
16
|
-
options.logger.error(
|
|
17
|
-
`containers ${subcommand} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`
|
|
18
|
-
);
|
|
19
|
-
return { code: 1 };
|
|
20
|
-
}
|
|
21
|
-
const args = ["exec", "wrangler", "containers", subcommand, ...rest];
|
|
22
|
-
if (options.tag !== void 0) {
|
|
23
|
-
args.push("--tag", options.tag);
|
|
24
|
-
}
|
|
25
|
-
if (options.push === true) {
|
|
26
|
-
args.push("--push");
|
|
27
|
-
}
|
|
28
|
-
if (options.env !== void 0) {
|
|
29
|
-
args.push("--env", options.env);
|
|
30
|
-
}
|
|
31
|
-
const descriptor = { args, command: "pnpm", cwd: options.cwd ?? process.cwd() };
|
|
32
|
-
options.logger.info(`running ${descriptor.command} ${descriptor.args.join(" ")}`);
|
|
33
|
-
const spawner = options.spawner ?? defaultSpawner;
|
|
34
|
-
const result = await spawner(descriptor);
|
|
35
|
-
return { code: result.code, descriptor };
|
|
36
|
-
};
|
|
37
|
-
const execute = defineHandler(async ({ argument, cwd, logger, options }) => {
|
|
38
|
-
const result = await runContainersCommand({
|
|
39
|
-
argument,
|
|
40
|
-
cwd,
|
|
41
|
-
env: options.env,
|
|
42
|
-
logger,
|
|
43
|
-
push: options.push === true,
|
|
44
|
-
tag: options.tag
|
|
45
|
-
});
|
|
46
|
-
return { code: result.code };
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
export { execute, runContainersCommand };
|
|
1
|
+
import{d as s}from"../packem_shared/command-DwC11Cwe.mjs";import{o as c}from"../packem_shared/open-url-EnKy--w-.mjs";const n="https://lunora.sh/docs",l=r=>{let e=0,t=r.length;for(;e<t&&r[e]==="/";)e+=1;for(;t>e&&r[t-1]==="/";)t-=1;return r.slice(e,t)},i=r=>{if(!r||r.length===0)return n;const e=l(r);return e.length===0?n:`${n}/${e}`},a=async r=>{const e=i(r.section);r.logger.info(`opening ${e}`);try{await c(e,{opener:r.opener})}catch(t){const o=t instanceof Error?t.message:String(t);return r.logger.error(`docs: failed to open URL: ${o}`),{code:1,url:e}}return{code:0,url:e}},m=s(({argument:r,logger:e})=>a({logger:e,section:r[0]}));export{m as execute,a as runDocsCommand};
|
|
@@ -1,91 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
|
|
3
|
-
|
|
4
|
-
const withEnv = (args, env) => {
|
|
5
|
-
if (env !== void 0) {
|
|
6
|
-
args.push("--env", env);
|
|
7
|
-
}
|
|
8
|
-
return args;
|
|
9
|
-
};
|
|
10
|
-
const buildListArgs = (options) => {
|
|
11
|
-
const args = withEnv(["exec", "wrangler", "deployments", "list"], options.env);
|
|
12
|
-
if (options.json) {
|
|
13
|
-
args.push("--json");
|
|
14
|
-
}
|
|
15
|
-
return args;
|
|
16
|
-
};
|
|
17
|
-
const buildArgs = (options) => {
|
|
18
|
-
switch (options.subcommand) {
|
|
19
|
-
case "inspect": {
|
|
20
|
-
if (options.versionId === void 0) {
|
|
21
|
-
return { error: "deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>" };
|
|
22
|
-
}
|
|
23
|
-
return { args: withEnv(["exec", "wrangler", "versions", "view", options.versionId], options.env) };
|
|
24
|
-
}
|
|
25
|
-
case "list": {
|
|
26
|
-
return { args: buildListArgs(options) };
|
|
27
|
-
}
|
|
28
|
-
case "promote": {
|
|
29
|
-
if (options.versionId === void 0) {
|
|
30
|
-
return { error: "deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes" };
|
|
31
|
-
}
|
|
32
|
-
if (!options.yes) {
|
|
33
|
-
return { error: "deployments promote shifts 100% of live traffic. Re-run with --yes to confirm." };
|
|
34
|
-
}
|
|
35
|
-
const args = withEnv(["exec", "wrangler", "versions", "deploy", `${options.versionId}@100%`, "--yes"], options.env);
|
|
36
|
-
if (options.message !== void 0) {
|
|
37
|
-
args.push("--message", options.message);
|
|
38
|
-
}
|
|
39
|
-
return { args };
|
|
40
|
-
}
|
|
41
|
-
case "rollback": {
|
|
42
|
-
if (!options.yes) {
|
|
43
|
-
return { error: "deployments rollback changes the live version. Re-run with --yes to confirm." };
|
|
44
|
-
}
|
|
45
|
-
const args = withEnv(["exec", "wrangler", "rollback"], options.env);
|
|
46
|
-
if (options.versionId !== void 0) {
|
|
47
|
-
args.push(options.versionId);
|
|
48
|
-
}
|
|
49
|
-
args.push("--yes");
|
|
50
|
-
if (options.message !== void 0) {
|
|
51
|
-
args.push("--message", options.message);
|
|
52
|
-
}
|
|
53
|
-
return { args };
|
|
54
|
-
}
|
|
55
|
-
default: {
|
|
56
|
-
return { error: `deployments: unknown subcommand "${options.subcommand}"` };
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
const runDeploymentsCommand = async (options) => {
|
|
61
|
-
const { args, error } = buildArgs(options);
|
|
62
|
-
if (error !== void 0 || args === void 0) {
|
|
63
|
-
options.logger.error(error ?? "deployments: nothing to run");
|
|
64
|
-
return { code: 1, descriptor: void 0, error };
|
|
65
|
-
}
|
|
66
|
-
const descriptor = { args, command: "pnpm", cwd: options.cwd ?? process.cwd() };
|
|
67
|
-
options.logger.info(`${descriptor.command} ${descriptor.args.join(" ")}`);
|
|
68
|
-
const spawner = options.spawner ?? defaultSpawner;
|
|
69
|
-
const result = await spawner(descriptor);
|
|
70
|
-
return { code: result.code, descriptor };
|
|
71
|
-
};
|
|
72
|
-
const isDeploymentsSubcommand = (value) => value === "list" || value === "inspect" || value === "rollback" || value === "promote";
|
|
73
|
-
const execute = defineHandler(({ argument, cwd, logger, options }) => {
|
|
74
|
-
const sub = argument[0];
|
|
75
|
-
if (!isDeploymentsSubcommand(sub)) {
|
|
76
|
-
logger.error(`deployments: unknown subcommand "${sub ?? ""}" — expected list | inspect | rollback | promote`);
|
|
77
|
-
return { code: 1 };
|
|
78
|
-
}
|
|
79
|
-
return runDeploymentsCommand({
|
|
80
|
-
cwd,
|
|
81
|
-
env: options.env,
|
|
82
|
-
json: options.json === true,
|
|
83
|
-
logger,
|
|
84
|
-
message: options.message,
|
|
85
|
-
subcommand: sub,
|
|
86
|
-
versionId: argument[1],
|
|
87
|
-
yes: options.yes === true
|
|
88
|
-
});
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
export { execute, runDeploymentsCommand };
|
|
1
|
+
import{existsSync as p,readFileSync as v,realpathSync as h}from"node:fs";import{join as u}from"node:path";import{isPlaceholderValue as w,DEV_VARS_FILE as g,parseDevVariableEntries as k,discoverSchemaInfo as x,inferLunoraBindings as b}from"@lunora/config";import{findWranglerFile as y,readWranglerJsonc as $,validateWranglerConfig as _,collectExportGaps as S}from"@lunora/config/cloudflare";import{i as N,m as A,c as R}from"../packem_shared/vectorize-metadata-DbziRKpX.mjs";import{d as L}from"../packem_shared/command-DwC11Cwe.mjs";import{v as E,i as I,p as D,l as j}from"../packem_shared/output-format-DfogXx0p.mjs";import{i as O}from"../packem_shared/path-containment-CgxYZggb.mjs";const V=o=>{const e=o.trim();if(e==="")return!0;const n=e.toLowerCase();return n.includes("replace")||n.startsWith("<")&&n.endsWith(">")},C=o=>{const e=y(o);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:n}=$(e);return{parsed:n,path:e}},F=(o,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(o===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const t=_(o).errors.find(r=>r.includes("SHARD"));t===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:t})},P=(o,e)=>{const{info:n}=x(o,"lunora");for(const a of n?.vectorMetadata??[]){const t=A(a.kind);if(t===void 0){e.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}e.push({code:"vector-metadata-index-required",fix:`wrangler ${R({index:a.index,property:a.property,type:t}).join(" ")}`,level:"info",message:`vector index "${a.index}" filters on metadata "${a.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},M=(o,e)=>{if(o===void 0)return;const n=(o.d1_databases??[]).filter(Boolean);for(const a of n){const t=typeof a.database_id=="string"?a.database_id:"";if(V(t)){const r=typeof a.binding=="string"&&a.binding.length>0?a.binding:"<unnamed>";e.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 "${r}" has a placeholder database_id ("${t||"<empty>"}").`})}}},W=(o,e)=>{if(o===void 0)return;const n=(o.send_email??[]).filter(Boolean);for(const a of n){const t=typeof a.destination_address=="string"?a.destination_address:"";if(t!==""&&w(t)){const r=typeof a.name=="string"&&a.name.length>0?a.name:"send_email";e.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${r}" has a placeholder destination_address ("${t}").`})}}},T=(o,e)=>{const n=u(o,g);if(!p(n))return;let a;try{a=v(n,"utf8")}catch{return}const t=k(a).filter(r=>N(r.key)&&w(r.value)).map(r=>r.key);t.length>0&&e.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${g} has unfilled secret value(s): ${t.join(", ")}.`})},z=o=>{const e=process.env.LUNORA_ADMIN_TOKEN;e===void 0||e.trim()===""?o.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."}):o.push({code:"admin-token-set",level:"pass",message:"LUNORA_ADMIN_TOKEN is set."})},K=async(o,e)=>{let n;try{n=await b({projectRoot:o})}catch{return}const a=S(n),t=[...n.containers.map(r=>({...r,kind:"container"})),...n.workflows.map(r=>({...r,kind:"workflow"})),...n.agents.map(r=>({...r,kind:"agent"}))];for(const r of t.filter(i=>i.exported))e.push({code:"declared-export-ok",level:"pass",message:`${r.kind} "${r.exportName}" is exported by the worker entry.`});for(const r of a)e.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${r.module}"\` to your worker entry (or re-run \`vis generate lunora-${r.kind}\`).`,level:"fail",message:`${r.kind} "${r.exportName}" is declared but ${r.className} is not exported by the worker entry.`})},J=/^[\^~><= ]+/u,U=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,B=o=>{const e=o.replace(J,"").trim(),n=U.exec(e);if(!n?.groups)return;const{channel:a,core:t,counter:r}=n.groups;return{channel:a??"",core:t??"",counter:r===void 0?void 0:Number.parseInt(r,10),raw:e}},G=(o,e)=>{const n=u(o,"package.json");if(!p(n))return;let a;try{a=JSON.parse(v(n,"utf8"))}catch{return}const t={...a.devDependencies,...a.dependencies},r=[];for(const[s,c]of Object.entries(t)){if(s!=="lunorash"&&!s.startsWith("@lunora/"))continue;const m=B(c);m&&r.push({name:s,version:m})}if(r.length<2)return;const i=s=>s.map(c=>`${c.name}@${c.version.raw}`).join(", "),l=new Set(r.map(s=>s.version.core)),f=new Set(r.map(s=>s.version.channel));if(l.size>1){e.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(l.size)} different versions: ${i(r)}.`});return}if(f.size>1){e.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 (${[...f].map(s=>s===""?"stable":s).join(" + ")}): ${i(r)}.`});return}const d=r.map(s=>s.version.counter).filter(s=>s!==void 0);if(d.length>1){const s=Math.min(...d),c=Math.max(...d);e.push({code:"version-counter-spread",level:"info",message:d.length===r.length&&s===c?`Lunora packages are all at ${[...f][0]??""}.${String(c)}.`:`Lunora pre-release counters span ${String(s)}–${String(c)}: ${i(r)}.`})}},H=[u("@lunora","cli"),"lunorash"],q=(o,e,n)=>{if(e===void 0)return;const a=[];for(const r of H){const i=u(o,"node_modules",r);if(p(i))try{a.push(h(i))}catch{}}if(a.length===0)return;let t;try{t=h(e)}catch{return}a.some(r=>O(r,t))||n.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${t}) is not the project's own install (${a.join(", ")}).`})},X=async o=>{const e=o.cwd??process.cwd(),n=[],{parsed:a,path:t}=C(e);F(a,t,n),M(a,n),W(a,n),T(e,n),z(n),G(e,n),P(e,n),q(e,o.executablePath??process.argv[1],n),await K(e,n);const r={fail:0,info:0,pass:0,warn:0};for(const l of n)r[l.level]+=1;const i=r.fail>0?1:0;return{code:i,findings:n,ok:i===0,summary:r}},Q={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Y=(o,e)=>{e.info("lunora doctor — project preflight");for(const t of o.findings){const r=`[${Q[t.level]}] ${t.message}`;t.level==="fail"?e.error(r):t.level==="warn"?e.warn(r):e.info(r),t.fix!==void 0&&t.level!=="pass"&&e.info(` fix: ${t.fix}`)}const{fail:n,warn:a}=o.summary;n>0?e.error(`${String(n)} failure(s), ${String(a)} warning(s).`):a>0?e.warn(`0 failures, ${String(a)} warning(s).`):e.success("all checks passed.")},Z=async o=>{const e=E("doctor",o.format);if(e!==void 0)return o.logger.error(e),{code:1,findings:[],ok:!1,summary:{fail:0,info:0,pass:0,warn:0}};const n=j(o.format,o.logger),a=await X({...o});return Y(a,n),I(o.format)&&D(a),a},ce=L(async({cwd:o,logger:e,options:n})=>({code:(await Z({cwd:o,format:n.format,logger:e})).code}));export{ce as execute,X as runDoctor,Z as runDoctorCommand};
|