@lunora/cli 1.0.0-alpha.217 → 1.0.0-alpha.218
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/dist/bin.mjs +1 -1
- package/dist/index.d.mts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +4 -1
- package/dist/packem_chunks/handler11.mjs +2 -4
- package/dist/packem_chunks/handler12.mjs +1 -2
- package/dist/packem_chunks/handler13.mjs +1 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +3 -1
- package/dist/packem_chunks/handler17.mjs +1 -3
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +7 -1
- package/dist/packem_chunks/handler2.mjs +2 -1
- package/dist/packem_chunks/handler20.mjs +1 -7
- package/dist/packem_chunks/handler21.mjs +3 -1
- package/dist/packem_chunks/handler22.mjs +3 -2
- package/dist/packem_chunks/handler23.mjs +1 -3
- package/dist/packem_chunks/handler24.mjs +2 -3
- package/dist/packem_chunks/handler25.mjs +99 -1
- package/dist/packem_chunks/handler26.mjs +10 -99
- package/dist/packem_chunks/handler3.mjs +1 -2
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +1 -1
- package/dist/packem_chunks/handler6.mjs +1 -1
- package/dist/packem_chunks/handler7.mjs +3 -1
- package/dist/packem_chunks/handler8.mjs +1 -3
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/planDevCommand.mjs +6 -6
- package/dist/packem_chunks/runDeployCommand.mjs +1 -0
- package/dist/packem_chunks/runInitCommand.mjs +89 -63
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +3 -3
- package/dist/packem_shared/{COMMANDS-Cf45cyJN.mjs → COMMANDS-BbQ3-hLn.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_IMPORT_BATCH_SIZE-CYq3UJmD.mjs → DEFAULT_IMPORT_BATCH_SIZE-BPQYMEmV.mjs} +1 -1
- package/dist/packem_shared/{buildRegistryIndex-BcJgAx76.mjs → buildRegistryIndex-DVmy8fHE.mjs} +1 -1
- package/dist/packem_shared/catalog-Cbzph90w.mjs +1 -0
- package/dist/packem_shared/cli-DOBnG22n.mjs +3 -0
- package/dist/packem_shared/commands-CLLQuHqU.mjs +15 -0
- package/dist/packem_shared/{diffSnapshots-Cnoe8Ob4.mjs → diffSnapshots-DtC5Cs4Z.mjs} +3 -3
- package/dist/packem_shared/{import-8FCB0cUX.mjs → import-DuHtoh4_.mjs} +7 -7
- package/dist/packem_shared/resolve-BWFT7RvE.mjs +5 -0
- package/dist/packem_shared/runAddCommand-BABRWlOb.mjs +1 -0
- package/dist/packem_shared/schemaIrToSnapshot-VpPguG3W.mjs +1 -0
- package/dist/packem_shared/{storage-D5s4vbtJ.mjs → storage-DlUnv7uG.mjs} +1 -1
- package/dist/packem_shared/vectorize-metadata-Br1QnnS8.mjs +1 -0
- package/package.json +11 -11
- package/skills/lunora-deploy/SKILL.md +42 -11
- package/skills/lunora-functions/SKILL.md +42 -14
- package/skills/lunora-migration-helper/SKILL.md +4 -4
- package/skills/lunora-performance-audit/SKILL.md +8 -5
- package/skills/lunora-quickstart/SKILL.md +3 -3
- package/skills/lunora-setup-auth/SKILL.md +23 -6
- package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
- package/skills/lunora-setup-mail/SKILL.md +34 -28
- package/skills/lunora-setup-scheduler/SKILL.md +15 -10
- package/skills/lunora-setup-storage/SKILL.md +182 -25
- package/dist/packem_chunks/handler27.mjs +0 -10
- package/dist/packem_shared/catalog-CJaormx0.mjs +0 -1
- package/dist/packem_shared/cli-CqNvbTR1.mjs +0 -3
- package/dist/packem_shared/commands-YfMX-Mto.mjs +0 -19
- package/dist/packem_shared/resolve-DZAGzg67.mjs +0 -1
- package/dist/packem_shared/runAddCommand-vE21wRIK.mjs +0 -1
- package/dist/packem_shared/runDeployCommand-o64lz-UD.mjs +0 -1
- package/dist/packem_shared/schemaIrToSnapshot-ogkcpHjM.mjs +0 -1
- package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{existsSync as m,mkdirSync as I,writeFileSync as h,mkdtempSync as
|
|
2
|
-
`,"utf8"),e.logger.success(`wrote ${f}`),l.unsupported.length>0&&e.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${
|
|
1
|
+
import{existsSync as m,mkdirSync as I,writeFileSync as h,mkdtempSync as R,rmSync as M,readFileSync as _}from"node:fs";import{tmpdir as N}from"node:os";import{discoverSchema as k,readPackageDependencies as x,discoverMigrations as C}from"@lunora/codegen";import{isInteractive as F,promptSelect as O,promptText as P}from"@lunora/config";import{LunoraError as w}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as b}from"ts-morph";import{r as D,t as z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as j,r as q}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as L}from"../packem_shared/command-DwC11Cwe.mjs";import{diffSnapshots as B,renderMigrationFile as H}from"../packem_shared/diffSnapshots-DtC5Cs4Z.mjs";import{r as G}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import W from"../packem_shared/schemaIrToSnapshot-VpPguG3W.mjs";import{readAndLogBody as J}from"./runRpcCommand.mjs";import{runExportCommand as V}from"../packem_shared/runExportCommand-Dq-SpjAe.mjs";import{r as Z}from"../packem_shared/import-DuHtoh4_.mjs";const u="__lunora_reproject__",K=e=>{if(!e.startsWith(u))return;const r=e.slice(u.length);return r===""?void 0:r},X=".snapshot.json",A=/[^\da-z]+/gu,E=(e,r)=>{let a=0,t=e.length;for(;a<t&&e[a]===r;)a+=1;for(;t>a&&e[t-1]===r;)t-=1;return e.slice(a,t)},Q=e=>{const r=E(e.toLowerCase().replaceAll(A,"_"),"_");return r===""?"auto":r},Y=e=>{const r=(a,t=2)=>a.toString().padStart(t,"0");return`${String(e.getUTCFullYear())}${r(e.getUTCMonth()+1)}${r(e.getUTCDate())}${r(e.getUTCHours())}${r(e.getUTCMinutes())}${r(e.getUTCSeconds())}`},ee=e=>{if(m(e))try{const r=_(e,"utf8"),a=JSON.parse(r);if(a.version!==1)throw new w("INTERNAL",`unsupported snapshot version: ${a.version}`);return a}catch(r){const a=r instanceof Error?r.message:String(r);throw new w("INTERNAL",`failed to read ${e}: ${a}`,{cause:r})}},re=e=>{const r=e.cwd??process.cwd(),a=c(r,"lunora","schema.ts");if(!m(a))return e.logger.error(`schema not found: ${a} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new b({skipAddingFilesFromTsConfig:!0}),n=k(t,a),s=W(n),o=c(r,"lunora","migrations"),i=c(o,X);let d;try{d=ee(i)}catch(g){return e.logger.error(g instanceof Error?g.message:String(g)),{code:1,empty:!0,migrationFile:""}}const l=B(d,s);if(l.empty)return e.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const v=(e.now??(()=>new Date))(),y=Q(e.name??"auto"),p=`${Y(v)}_${y}.sql`,f=c(o,p);I(o,{recursive:!0});const U=H(y,l,v.toISOString());return h(f,U,"utf8"),h(i,`${JSON.stringify(s,void 0,4)}
|
|
2
|
+
`,"utf8"),e.logger.success(`wrote ${f}`),l.unsupported.length>0&&e.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${p} and write the SQL manually`),{code:0,empty:!1,migrationFile:f}},te="migrations.ts",$=/^[A-Za-z_]\w*$/u,ae=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),S=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,ne=e=>`import { defineMigration } from "${x(e)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,oe="__lunora_admin__:runMigration",ie="__lunora_admin__:migrationStatus",se="/_lunora/migrate",ce=e=>E(e.trim().toLowerCase().replaceAll(A,"-"),"-"),de=e=>e.split("-").filter(r=>r.length>0).map((r,a)=>a===0?r:r.charAt(0).toUpperCase()+r.slice(1)).join(""),le=e=>{const r=c(e,"lunora","schema.ts");if(!m(r))return[];try{const a=new b({skipAddingFilesFromTsConfig:!0});return k(a,r).tables.map(t=>t.name)}catch{return[]}},ue=async e=>e.length>0?O("Which table does this migration iterate?",e.map(r=>({label:r,value:r}))):P("Target table for the migration: "),me=async(e,r)=>{if(r.table!==void 0)return r.table;const a=r.promptTable??(F()?ue:void 0);if(a===void 0){r.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const n=(await a(le(e)))?.trim();if(n===void 0||n===""){r.logger.error("no table selected — re-run with --table <table>");return}return n},fe=async e=>{const r=e.cwd??process.cwd(),a=ce(e.name);if(a==="")return e.logger.error(`invalid migration name: "${e.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=de(a);if(!$.test(t)||ae.has(t))return e.logger.error(`invalid migration name: "${e.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await me(r,e);if(n===void 0)return{code:1,file:""};if(!$.test(n))return e.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(r,"lunora"),o=c(s,te);let i=m(o)?_(o,"utf8"):"";if(i.includes(`id: "${a}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(i))return e.logger.error(`a migration with id "${a}" (export \`${t}\`) already exists in ${o}`),{code:1,file:""};const d=ne(r);i.trim()===""?i=`${d}
|
|
3
3
|
`:S.test(i)?i=i.replace(S,d):i=`${d}
|
|
4
4
|
${i}`;const l=`export const ${t} = defineMigration({
|
|
5
5
|
id: "${a}",
|
|
@@ -8,4 +8,4 @@ ${i}`;const l=`export const ${t} = defineMigration({
|
|
|
8
8
|
});`;return I(s,{recursive:!0}),h(o,`${i.trimEnd()}
|
|
9
9
|
|
|
10
10
|
${l}
|
|
11
|
-
`,"utf8"),e.logger.success(`scaffolded migration "${a}" in ${o}`),{code:0,file:o}},
|
|
11
|
+
`,"utf8"),e.logger.success(`scaffolded migration "${a}" in ${o}`),{code:0,file:o}},ge=(e,r)=>{const a=new b({skipAddingFilesFromTsConfig:!0});return C(a,c(e,"lunora")).find(n=>n.id===r)?.table},he=(e,r)=>{const a=K(r.id);if(a!==void 0)return a;if(r.id.startsWith(u)){r.logger.error(`"${r.id}" names no table — use ${u}<table>`);return}let t;try{t=ge(e,r.id)}catch(n){r.logger.error(n instanceof Error?n.message:String(n));return}if(t===void 0){r.logger.error(`migration "${r.id}" not found under lunora/ — declare it with defineMigration({ id: "${r.id}", ... })`);return}if(t===""){r.logger.error(`migration "${r.id}" must declare \`table\` as a static string literal`);return}return t},be=e=>{const r=e.cwd??process.cwd();if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}const a=he(r,e);if(a===void 0)return;const t=q(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:n}=D({cwd:r,token:e.token,url:t});if(!n){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}if((e.subcommand==="up"||e.subcommand==="down")&&z({prod:e.prod,url:t})&&!e.yes){e.logger.error(`migrate ${e.subcommand} runs the migration against ${t}, which is not local. Re-run with --yes to confirm.`);return}const s=e.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:s,requestUrl:`${t}${se}`,table:a,token:n}},ve=e=>{const r={id:e.id};return e.subcommand==="status"||(r.direction=e.subcommand,e.dryRun&&(r.dryRun=!0),e.batchSize!==void 0&&(r.batchSize=e.batchSize),e.maxBatches!==void 0&&(r.maxBatches=e.maxBatches)),r},ye=async e=>{const r=be(e);if(r===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:a,requestUrl:t,table:n,token:s}=r,o=e.subcommand==="status"?ie:oe,i=ve(e);e.logger.info(`POST ${t} -> ${e.subcommand} ${e.id} (table "${n}")`);const d=await a(t,{body:JSON.stringify({args:i,functionPath:o,table:n}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"});return{body:await J(d,e.logger),code:d.ok?0:1,requestUrl:t}},T=e=>e===void 0?void 0:j(e),pe=async e=>{const{logger:r}=e,a=T(e.fromUrl??e.toUrl),t=T(e.toUrl??e.fromUrl);if(a===t)return r.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const n=e.out===void 0?R(c(N(),"lunora-d1ps-")):void 0,s=e.out??c(n,"dump.ndjson");try{r.info(`Exporting .global() data from the D1 source (${a??"http://localhost:8787"}) …`);const o=await V({fetchImpl:e.fetchImpl,logger:r,out:s,prod:e.prod,tables:e.tables,token:e.fromToken,url:a});if(o.code!==0)return{code:o.code};r.info(`Exported ${String(o.rows)} row(s) (${String(o.bytes)} bytes).`),r.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const i=await Z({batchSize:e.batchSize,fetchImpl:e.fetchImpl,file:s,logger:r,prod:e.prod,token:e.toToken,url:t,yes:e.yes});return i.code!==0?{code:i.code}:(i.inserted===o.rows?r.info(`✓ Migrated ${String(o.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):r.warn(`Imported ${String(i.inserted)} of ${String(o.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{n!==void 0&&M(n,{force:!0,recursive:!0})}},De=L(({argument:e,cwd:r,logger:a,options:t})=>{const n=e[0];if(n==="generate")return re({cwd:r,logger:a,name:e[1]??t.name});if(n==="d1-to-hyperdrive")return pe({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:a,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url,yes:t.yes===!0});if(n==="create"){const s=e[1]??t.name;return s?fe({cwd:r,logger:a,name:s,table:t.table}):(a.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(n==="up"||n==="down"||n==="status"){const s=e[1]??t.name;return s?ye({batchSize:t.batchSize,cwd:r,dryRun:t.dryRun===!0,id:s,logger:a,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:G({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(a.error(`migrate ${n} requires a migration id. Usage: lunora migrate ${n} <id>`),{code:1})}return a.error(`unknown migrate subcommand: "${n??""}" — expected generate | create | up | down | status`),{code:1}});export{De as execute,fe as runMigrateCreateCommand,ye as runMigrateDataCommand,re as runMigrateGenerateCommand,pe as runMigrateToHyperdriveCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as a,R as s,V as C,r as N}from"./cli-
|
|
1
|
+
import{C as a,R as s,V as C,r as N}from"./cli-DOBnG22n.mjs";import"./createLogger-hGafwf-3.mjs";export{a as COMMANDS,s as REGISTERED_COMMAND_NAMES,C as VERSION,N as runCli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./admin-token-VdUnvnKW.mjs";import"./admin-url-BhF5ufg1.mjs";import{D as a,r as i}from"./import-
|
|
1
|
+
import"./admin-token-VdUnvnKW.mjs";import"./admin-url-BhF5ufg1.mjs";import{D as a,r as i}from"./import-DuHtoh4_.mjs";import"./shared-D-zCOmgY.mjs";export{a as DEFAULT_IMPORT_BATCH_SIZE,i as runImportCommand};
|
package/dist/packem_shared/{buildRegistryIndex-BcJgAx76.mjs → buildRegistryIndex-DVmy8fHE.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as l,c as o,l as r}from"./catalog-
|
|
1
|
+
import{b as l,c as o,l as r}from"./catalog-Cbzph90w.mjs";import"./parseManifest-CwPTKdtS.mjs";export{l as buildRegistryIndex,o as collectCatalog,r as listItemDirectories};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as a,readFileSync as o,readdirSync as p,statSync as d}from"node:fs";import{join as r}from"@visulima/path";import u from"./parseManifest-CwPTKdtS.mjs";const m=/[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/gu,n=i=>i.replaceAll(m,""),c=i=>p(i).filter(s=>{const t=r(i,s);return d(t).isDirectory()&&a(r(t,"registry.json"))}),y=i=>{const s=r(i,"index.json");if(a(s)){const t=JSON.parse(o(s,"utf8"));if(Array.isArray(t.items))return t.items.filter(e=>typeof e=="object"&&e!==null&&typeof e.name=="string").map(e=>({description:e.description===void 0?void 0:n(e.description),name:n(e.name)}))}return c(i).map(t=>{const e=JSON.parse(o(r(i,t,"registry.json"),"utf8"));return{description:e.description===void 0?void 0:n(e.description),name:n(t)}})},A=i=>({items:c(i).map(t=>{const e=u(JSON.parse(o(r(i,t,"registry.json"),"utf8")),t);return{...e.description===void 0?{}:{description:e.description},name:e.name,...e.title===void 0?{}:{title:e.title}}}).toSorted((t,e)=>t.name.localeCompare(e.name))});export{A as b,y as c,c as l,n as s};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{mkdirSync as O,readFileSync as w,lstatSync as A,writeFileSync as B}from"node:fs";import{join as u,dirname as f}from"node:path";import{fileURLToPath as D}from"node:url";import{resolveHint as E,isLunoraError as k,flattenHint as L,findSolutionByMessage as j}from"@lunora/errors";import{createCerebro as _}from"@visulima/cerebro";import I from"@visulima/cerebro/command/completion";import T from"@visulima/cerebro/command/version";import{A as p,T as s}from"./deploy-target-B0Xcb2jV.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{createLogger as S}from"./createLogger-hGafwf-3.mjs";import{VisulimaError as M,renderError as U}from"@visulima/error";import{homedir as W}from"node:os";import{addArgsFor as J,detectPackageManager as K}from"@lunora/config";const F={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},y="lunora.advisor.map.json",H={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${y})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${y})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},$={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[{description:"Emit a JSON report instead of human text",name:"json",type:Boolean}]},V={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a destructive step without prompting: a production pitr --restore, or backup prune",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},G={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},s]},q={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},z={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String}]},Y={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},s,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},Q={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},X={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},Z={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},ee={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"doctor",options:[{description:"Output format: pretty (default) or json",name:"format",type:String}]},te={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"]],group:"Data",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},re={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},oe={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"]],group:"Data",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ne={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ae={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},{description:"Emit JSON instead of human text",name:"json",type:Boolean},{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},ie={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Template: analog | astro | expo | next | nuxt | react-router | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},se={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},{description:"Emit a JSON report instead of human text",name:"json",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},le={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},pe={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},de={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},s,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},ce={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler26.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: expose the documentation tools (default)",name:"docs",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},ue={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/runMigrateGenerateCommand.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},me={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler13.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ge={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Emit JSON output (add plan / list)",name:"json",type:Boolean},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},he={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},fe={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},ye={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},ve={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${P.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},be={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},we={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},s]},ke={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},Se={filterStacktrace:()=>!1,hideErrorCodeView:!0},xe=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=E(k(e)?{code:e.code,hint:e.hint,message:r}:r),n=new M({hint:o===void 0?void 0:L(o).split(`
|
|
2
|
+
`),message:t.reason===void 0?r:`${t.reason}: ${r}`,name:e instanceof Error&&e.name.length>0?e.name:"Error"});return n.stack="",U(n,Se)},Ce=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,d=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+d),n=i}}return r[t.length]??0},Re=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Ce(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ne=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Oe=1440*60*1e3,Ae=1500,Be="0.0.0",De=/^v/u,Ee=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(De,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},v=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Le=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Le(a,i)}return 0},_e=(e,t)=>{const r=v(e),o=v(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return je(m(e).prerelease,m(t).prerelease)},Ie=e=>{const t=m(e).prerelease.split(".")[0]??"";return Ee.has(t)?t:"latest"},Te=(e,t)=>_e(t,e)>0,Pe=(e,t,r)=>t-e<r,Me=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=J(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},x=e=>u(e,"lunora-cli-update.json"),Ue=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:u(W(),".cache"),r=u(t,"lunora");try{O(r,{mode:448,recursive:!0})}catch{}return r},We=e=>{try{const t=JSON.parse(w(x(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},b=(e,t)=>{try{const r=x(e);try{if(A(r).isSymbolicLink())return}catch{}B(r,`${JSON.stringify(t)}
|
|
3
|
+
`,"utf8")}catch{}},Je=async(e,t)=>{try{const r=await e(Ne(t),{signal:AbortSignal.timeout(Ae)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Ke=(e,t,r)=>e===Be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Fe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ke(e.current,t,r))return;const o=e.cacheDir??Ue(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ie(e.current),d=We(o),N=d?.tag??"latest",g=d!==void 0&&N===i?d:void 0;let c=g?.latest;if(g===void 0||!Pe(g.checkedAt,n,a)){const h=await Je(e.fetchImpl??globalThis.fetch,i);h===void 0?b(o,{checkedAt:n,latest:e.current,tag:i}):(c=h,b(o,{checkedAt:n,latest:h,tag:i}))}c!==void 0&&Te(e.current,c)&&e.logger.warn(Me(e.current,c,i,e.manager))},He=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],$e=8,Ve=()=>{try{let e=f(D(import.meta.url));for(let t=0;t<$e;t+=1){try{const o=JSON.parse(w(u(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=f(e);if(r===e)break;e=r}}catch{}return"0.0.0"},C=Ve(),Ge=[ie,F,X,q,H,G,Y,z,me,pe,Q,de,ye,se,he,ue,oe,ne,be,le,V,re,we,ae,ee,te,$,ke,Z,ge,fe,ce,ve],R=[...Ge,T,I],ut=R.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),qe=e=>e.every(t=>typeof t=="string")?e.map(t=>l(t)):e.map(t=>typeof t=="string"?[l(t)]:t.map(r=>l(r))),ze=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:l(e.argument.description??"")}},...e.description===void 0?{}:{description:l(e.description)},...e.examples===void 0?{}:{examples:qe(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Ye=e=>{const t={value:0},r=_("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:C});for(const o of R)r.addCommand(ze(o));return{cli:r,exitCode:t}},Qe=/Command "(?<name>[^"]+)" not found/u,Xe=e=>{const t=S(),r=e instanceof Error?e.message:String(e),o=Qe.exec(r);if(!o?.groups){k(e)||j(r)!==void 0?t.error(xe(e)):t.error(r);return}const n=o.groups.name??"",a=Re(n,He);t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation.")},mt=async(e={})=>{const{cli:t,exitCode:r}=Ye(e);try{await t.run({shouldExitProcess:!1})}catch(n){return Xe(n),1}let o;try{o=K(process.cwd())}catch{}return await Fe({current:C,logger:S(),manager:o}),r.value};export{He as C,y as D,ut as R,C as V,mt as r};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{existsSync as h,readFileSync as v,writeFileSync as $,mkdirSync as b,lstatSync as M}from"node:fs";import{join as g,relative as F,dirname as k}from"@visulima/path";import{p as W,d as D,e as T,s as E,f as _,g as q,h as V,j as B,c as H,k as U}from"./resolve-BWFT7RvE.mjs";import{s as d,c as G,b as X}from"./catalog-Cbzph90w.mjs";import{findWranglerFile as Y,readWranglerJsonc as z}from"@lunora/config/cloudflare";import{LunoraError as R}from"@lunora/errors";import{insertSchemaExtension as Q}from"./insertSchemaExtension-DY4pA8wE.mjs";import{createHash as Z}from"node:crypto";import{installArgsFor as K,detectPackageManager as ee}from"@lunora/config";const S=1,te=".lunora-registry.json",I=e=>g(e,"lunora",te),re=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,w=e=>Z("sha256").update(e).digest("hex"),ne=e=>{const t=I(e);if(!h(t))return{items:{},version:S};try{const n=JSON.parse(v(t,"utf8"));if(re(n))return{items:n.items,version:S}}catch{}return{items:{},version:S}},se=(e,t)=>{$(I(e),`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`,"utf8")},N=(e,t,n,o)=>{const r=e.items[t]??{files:{}};e.items[t]=r,r.files[n]=w(o)},oe=(e,t,n)=>e.items[t]?.files[n],A=3,L=e=>e===""?[]:e.split(`
|
|
3
|
+
`),ie=(e,t)=>{const n=L(e),o=L(t);let r=0;for(;r<n.length&&r<o.length&&n[r]===o[r];)r+=1;let s=n.length,i=o.length;for(;s>r&&i>r&&n[s-1]===o[i-1];)s-=1,i-=1;if(r===s&&r===i)return[];const c=[];for(let a=Math.max(0,r-A);a<r;a+=1)c.push(` ${n[a]??""}`);for(let a=r;a<s;a+=1)c.push(`- ${n[a]??""}`);for(let a=r;a<i;a+=1)c.push(`+ ${o[a]??""}`);for(let a=i;a<Math.min(o.length,i+A);a+=1)c.push(` ${o[a]??""}`);return c},ae=/\.[cm]?[jt]sx?$/u,j=(e,t,n,o)=>{const r=g(e,t.from);if(M(r).isSymbolicLink())throw new R("INTERNAL",`registry item "${o}": refusing to read "${t.from}" — it is a symlink, not a regular file`);const s=v(r,"utf8");return n&&ae.test(t.to)?T(s):s},ce=(e,t,n,o,r,s,i)=>{const c=g(o,"lunora","schema.ts");if(s)return r.info(`~ would merge .extend(${t}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:c};const a=g(o,e.to);h(a)||(b(k(a),{recursive:!0}),$(a,j(n,e,i,t),"utf8"));const f=i?"lunorash/server":"@lunora/server",l=h(c)?v(c,"utf8"):`import { defineSchema } from "${f}";
|
|
4
|
+
|
|
5
|
+
export const schema = defineSchema({});
|
|
6
|
+
`,u=Q(l,t);if(u.ok)return b(k(c),{recursive:!0}),$(c,u.text,"utf8"),r.success(`merged .extend(${t}.extension) into lunora/schema.ts`),{kind:"written",path:c};if(u.reason==="already-applied")return r.warn(`lunora/schema.ts already extends "${t}" — skipping`),{kind:"skipped",path:c};throw u.reason==="invalid-identifier"?new R("INTERNAL",`schema-extension item "${t}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${t} }\` / \`.extend(${t}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new R("INTERNAL",`schema-extension merge failed for "${t}": ${u.reason}`)},de=(e,t,n,o,r)=>{const s=ie(t,n);if(s.length===0){r.info(`= ${e.to} (unchanged)`);return}r.info(`${o?"~":"+"} ${e.to}`);for(const i of s)r.info(` ${i}`)},ue=(e,t,n,o,r,s,i,c)=>{const a=g(o,e.to),f=j(n,e,c,t),l=h(a),u=l?v(a,"utf8"):"",m=J=>(b(k(a),{recursive:!0}),$(a,f,"utf8"),N(s,t,e.to,f),r.success(`${J}: ${e.to}`),{kind:"written",path:a});if(i.diff)return de(e,u,f,l,r),{kind:"skipped",path:a};if(!l)return m("write");const p=w(u);if(p===w(f))return N(s,t,e.to,f),r.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:a};if(i.overwrite)return m("overwrite");const y=oe(s,t,e.to);return y===void 0?(r.warn(`skip (exists, untracked): ${e.to} — refusing to overwrite a file lunora didn't add (use --overwrite to force)`),{kind:"skipped",path:a}):y===p?m("update"):y===w(f)?(r.warn(`skip (locally edited): ${e.to}`),{kind:"skipped",path:a}):($(`${a}.new`,f,"utf8"),r.warn(`conflict: ${e.to} has local edits and an upstream update — wrote ${e.to}.new (use --overwrite to take theirs)`),{kind:"skipped",path:a})},fe=(e,t,n,o,r,s,i={},c=!1)=>e.merge==="schema-extension"?ce(e,t,n,o,r,i.diff===!0,c):ue(e,t,n,o,r,s,i,c),O=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],le=e=>{const t=Y(e);if(t===void 0)return;const{parsed:n}=z(t);return typeof n?.main=="string"?n.main:void 0},me=e=>{const t=le(e),n=t===void 0?O:[t,...O];for(const o of n){const r=g(e,o);if(!h(r))continue;const s=v(r,"utf8");if(!s.includes("createShardDO(")){if(o===t)break;continue}return{entryPath:r,main:o,source:s}}},pe=(e,t,n)=>{const o=F(k(e),g(t,"lunora",n)).replaceAll("\\","/");return o.startsWith(".")?o:`./${o}`},ge=(e,t)=>{for(const n of e){const r=`Add \`export * from "${`./lunora/${n.module}.js`}"\` to your worker entry`,s=n.comment?` (${n.comment})`:"";t.warn(`${r}${s}`)}return 0},he=(e,t,n,o)=>{const r=[];for(const s of e){const i=pe(t,n,s.module),c=i.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${c}\.js["']`,"u").test(o)||(s.comment&&r.push(`
|
|
7
|
+
// ${s.comment}`),r.push(`export * from "${i}.js";`))}return r},$e=(e,t,n,o)=>{if(e.length===0)return 0;const r=me(t);if(r===void 0)return ge(e,n);const s=he(e,r.entryPath,t,r.source);if(s.length===0)return 0;if(o){for(const c of s)c!==""&&n.info(`~ entrypoint: ${c}`);return s.length}const i=r.source.endsWith(`
|
|
8
|
+
`)?"":`
|
|
9
|
+
`;return $(r.entryPath,`${r.source}${i}${s.join(`
|
|
10
|
+
`)}
|
|
11
|
+
`,"utf8"),n.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${F(t,r.entryPath)}`),s.length},P=(e,t,n,o={})=>{const r=[],s=[],i=[],c=[],a=ne(t),f=W(t);try{for(const{directory:l,manifest:u}of e){for(const p of u.files){const y=fe(p,u.name,l,t,n,a,o,f);(y.kind==="written"?r:s).push(y.path)}if(u.entrypointReexports!==void 0&&$e(u.entrypointReexports,t,n,o.diff===!0),o.diff)continue;const m=D(u,t,n,f);i.push(...m.deps),c.push(...m.bindings)}}finally{!o.diff&&Object.keys(a.items).length>0&&se(t,a)}return{bindings:c,deps:i,skipped:s,written:r}},x=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),Oe=(e,t,n,o,r)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==t||!Array.isArray(s.value))return s;const i=s.value;return{...s,value:i.map(c=>typeof c=="object"&&c!==null&&c[n.key]===n.value?{...c,[o]:r}:c)}})}:e,C=(e,t)=>{const n=t.title??t.description;e.info(`plan: ${d(t.name)}${n?` — ${d(n)}`:""}`);for(const s of t.files)e.info(` file ${d(s.to)} (${d(s.merge)})`);const o=new Map,r=s=>{const i=o.get(s);if(i!==void 0)return i;const c=B(s);return o.set(s,c),c};for(const[s,i]of Object.entries(t.deps??{}))e.info(` dep ${d(s)}@${d(r(i))}`);for(const[s,i]of Object.entries(t.devDependencies??{}))e.info(` dev ${d(s)}@${d(r(i))}`);for(const s of t.bindings??[])e.info(` bind ${d(s.path.join("."))} = ${d(JSON.stringify(s.value))}`);for(const s of t.envVars??[]){const i=s.secret?" (secret)":` = ${d(JSON.stringify(s.value??""))}`;e.info(` env ${d(s.name)}${i}`)}for(const s of t.entrypointReexports??[]){const i=`./lunora/${d(s.module)}`,c=s.comment?` // ${d(s.comment)}`:"";e.info(` entry ${i}${c}`)}},ye=e=>{const t=e.map(({manifest:n})=>({bindings:(n.bindings??[]).map(o=>({path:o.path.join("."),value:o.value})),deps:Object.keys(n.deps??{}),devDependencies:Object.keys(n.devDependencies??{}),entrypointReexports:(n.entrypointReexports??[]).map(o=>({module:o.module,...o.comment?{comment:o.comment}:{}})),envVars:(n.envVars??[]).map(o=>({name:o.name,...o.secret?{secret:!0}:{value:o.value??""}})),files:n.files.map(o=>({merge:o.merge,to:o.to})),name:n.name,requires:n.requires??[],title:n.title}));process.stdout.write(`${JSON.stringify({items:t},void 0,2)}
|
|
12
|
+
`)},ve=e=>{try{const{args:t,command:n}=K(ee(e));return`${n} ${t.join(" ")}`}catch{return"<your-package-manager> install"}},we=(e,t,n,o,r,s)=>{r.success(`add complete: ${String(n)} written, ${String(o)} skipped`),r.info("next steps:"),r.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),t.length>0&&r.info(` ${ve(s)} # install newly-added dependencies`);for(const{manifest:i}of e)i.docs&&r.info(`${d(i.name)}: ${d(i.docs)}`)},ke=async e=>{const t=x(),n=E("list",e);if(n)return e.logger.error(n),{...t,code:1};let o=()=>{};try{const r=await V(e);o=r.cleanup;const s=G(r.root);if(e.json)return process.stdout.write(`${JSON.stringify(s,void 0,2)}
|
|
13
|
+
`),t;e.logger.info(`available registry items (${String(s.length)}):`);for(const i of s)e.logger.info(` ${i.name}${i.description?` — ${i.description}`:""}`);return t}catch(r){return e.logger.error(d(`list failed: ${r instanceof Error?r.message:String(r)}`)),{...t,code:1}}finally{o()}},Pe=async e=>{const t=e.cwd??process.cwd(),n=x();if(e.list)return ke(e);if(e.names.length===0)return e.logger.error("add requires at least one item name. Usage: lunora registry add <name> [...names]"),{...n,code:1};const o=E("add",e);if(o)return e.logger.error(o),{...n,code:1};let r=[];try{const{cleanups:s,items:i}=await _(e.names,e);r=s;const{transformManifest:c}=e,a=c?i.map(p=>({...p,manifest:c(p.manifest)})):i;for(const{manifest:p}of a)C(e.logger,p);if(e.json&&ye(a),e.dryRun)return e.logger.info("dry-run: stopping before any files are written"),n;if(e.diff)return P(a,t,e.logger,{diff:!0}),e.logger.info("diff: preview only — re-run without --diff to apply"),n;if(!await q(a,e))return{...n,code:1};const{bindings:f,deps:l,skipped:u,written:m}=P(a,t,e.logger,{overwrite:e.overwrite});return we(a,l,m.length,u.length,e.logger,t),{bindings:f,code:0,deps:l,skipped:u,written:m}}catch(s){return e.logger.error(d(`add failed: ${s instanceof Error?s.message:String(s)}`)),{...n,code:1}}finally{for(const s of r)s()}},Fe=async e=>{const t=x();if(e.names.length===0)return e.logger.error("view requires an item name. Usage: lunora registry view <name>"),{...t,code:1};const n=E("view",e);if(n)return e.logger.error(n),{...t,code:1};const o=[];try{for(const r of e.names){const{cleanup:s,directory:i}=await H(r,e);o.push(s);const c=U(i,r);C(e.logger,c);for(const a of c.files){e.logger.info(`--- ${d(a.to)} (${d(a.merge)}) ---`);const f=j(i,a,!1,r);for(const l of f.split(`
|
|
14
|
+
`))e.logger.info(d(l))}}return t}catch(r){return e.logger.error(d(`view failed: ${r instanceof Error?r.message:String(r)}`)),{...t,code:1}}finally{for(const r of o)r()}},Ie=async e=>{const t=x(),n=e.from;if(n===void 0)return e.logger.error("registry build requires --from <registry root>"),{...t,code:1};if(!h(n))return e.logger.error(`registry root not found: ${n}`),{...t,code:1};const o=X(n),r=e.out??g(n,"index.json");if(e.check){const s=h(r)?JSON.parse(v(r,"utf8")):{items:[]};return JSON.stringify(s.items??[])!==JSON.stringify(o.items)?(e.logger.error(`registry: ${r} is stale — run \`lunora registry build\` to regenerate it`),{...t,code:1}):(e.logger.success(`registry: ${r} is up to date (${String(o.items.length)} items)`),t)}return $(r,`${JSON.stringify({$schema:"./schema/registry.schema.json",...o},void 0,4)}
|
|
15
|
+
`,"utf8"),e.logger.success(`registry: wrote ${r} (${String(o.items.length)} items)`),t};export{Ie as a,Fe as b,Pe as r,Oe as s};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{quoteIdentifier as a,sqlAffinityForKind as $,frameworkColumnDdl as y,MAX_D1_TABLE_COLUMNS as d,columnRef as
|
|
1
|
+
import{quoteIdentifier as a,sqlAffinityForKind as $,frameworkColumnDdl as y,OCC_VERSION_COLUMN as T,MAX_D1_TABLE_COLUMNS as d,columnRef as E,physicalIndexName as c}from"@lunora/d1/dialect";import{LunoraError as g}from"@lunora/errors";const v=e=>$(e),f=(e,n)=>{const o=[a(e),n.sqlType];return n.nullable||o.push("NOT NULL"),o.join(" ")},O=e=>{const n=Object.entries(e.columns).map(([s,r])=>` ${f(s,r)}`),o=[...y(),`${a(T)} INTEGER`],i=o.length+n.length;if(i>d)throw new g("VALIDATION_ERROR",`table "${e.name}" needs ${String(i)} columns, over D1's ${String(d)}-column limit — split the table, or move the extra fields into one object field`);const t=[...o.map(s=>` ${s}`),...n].join(`,
|
|
2
2
|
`);return`CREATE TABLE IF NOT EXISTS ${a(e.name)} (
|
|
3
3
|
${t}
|
|
4
|
-
);`},L=e=>`DROP TABLE IF EXISTS ${a(e)};`,
|
|
5
|
-
`)};export{A as diffSnapshots,
|
|
4
|
+
);`},L=e=>`DROP TABLE IF EXISTS ${a(e)};`,C=(e,n,o)=>`ALTER TABLE ${a(e)} ADD COLUMN ${f(n,o)};`,m=(e,n)=>{const o=n.fields.map(t=>E(t)).join(", ");return`CREATE ${n.unique?"UNIQUE ":""}INDEX IF NOT EXISTS ${c(e,n.name)} ON ${a(e)} (${o});`},I=(e,n)=>`DROP INDEX IF EXISTS ${c(e,n)};`,u=e=>e.field===void 0?void 0:JSON.stringify({...e.field,optional:void 0}),N=(e,n,o,i,t)=>{const s=u(o),r=u(i);if(o.sqlType!==i.sqlType)t.push({kind:"columnTypeChange",summary:`column type change on ${e}.${n}: ${o.sqlType} → ${i.sqlType} (write SQL manually)`});else if(s!==void 0&&r!==void 0&&s!==r){const l=o.field?.kind===i.field?.kind?`${String(i.field?.kind)} shape/constraints changed`:`${String(o.field?.kind)} → ${String(i.field?.kind)}`;t.push({kind:"columnTypeChange",summary:`column type change on ${e}.${n}: ${l} (write SQL manually)`})}o.nullable!==i.nullable&&t.push({kind:"columnTypeChange",summary:`nullability change on ${e}.${n}: ${o.nullable?"NULL":"NOT NULL"} → ${i.nullable?"NULL":"NOT NULL"} (write SQL manually)`})},S=(e,n,o,i,t)=>{for(const[s,r]of Object.entries(o)){const l=n[s];if(l===void 0){i.push({kind:"addColumn",sql:C(e,s,r),summary:`ADD COLUMN ${e}.${s}`});continue}N(e,s,l,r,t)}for(const s of Object.keys(n))o[s]===void 0&&t.push({kind:"dropColumn",summary:`DROP COLUMN ${e}.${s} (SQLite drop-column requires careful migration — write SQL manually)`})},q=(e,n,o,i,t)=>{for(const[s,r]of Object.entries(o)){const l=n[s];if(l===void 0){i.push({kind:"createIndex",sql:m(e,r),summary:`CREATE INDEX ${s} ON ${e}`});continue}(!(l.fields.length===r.fields.length&&l.fields.every((p,h)=>p===r.fields[h]))||l.unique!==r.unique)&&t.push({kind:"indexRename",summary:`index ${s} changed on ${e} — drop+create manually if intentional`})}for(const s of Object.keys(n))o[s]===void 0&&i.push({kind:"dropIndex",sql:I(e,s),summary:`DROP INDEX ${s}`})},k=(e,n,o)=>{o.push({kind:"createTable",sql:O(n),summary:`CREATE TABLE ${e}`});for(const i of Object.values(n.indexes))o.push({kind:"createIndex",sql:m(e,i),summary:`CREATE INDEX ${i.name} ON ${e}`})},A=(e,n)=>{const o=e?.tables??{},i=[],t=[];for(const[s,r]of Object.entries(n.tables)){const l=o[s];if(l===void 0){k(s,r,i);continue}S(s,l.columns,r.columns,i,t),q(s,l.indexes,r.indexes,i,t)}for(const s of Object.keys(o))n.tables[s]===void 0&&i.push({kind:"dropTable",sql:L(s),summary:`DROP TABLE ${s}`});return{empty:i.length===0&&t.length===0,entries:i,unsupported:t}},w=(e,n,o)=>{const i=[`-- Lunora migration: ${e}`,`-- Generated at ${o}`,"-- This file was produced by `lunora migrate generate`. Review carefully before applying.",""];for(const t of n.entries)i.push(`-- ${t.summary}`,t.sql,"");if(n.unsupported.length>0){i.push("-- ---------------------------------------------------------------","-- The following deltas are NOT auto-generated in v0.1.","-- Write the appropriate SQL below by hand:","--");for(const t of n.unsupported)i.push(`-- * ${t.summary}`);i.push("-- ---------------------------------------------------------------","")}return n.empty&&i.push("-- No changes detected. Re-running `lunora migrate generate` will overwrite this file.",""),i.join(`
|
|
5
|
+
`)};export{A as diffSnapshots,C as renderAddColumn,m as renderCreateIndex,O as renderCreateTable,I as renderDropIndex,L as renderDropTable,w as renderMigrationFile,v as validatorKindToSqlType};
|
|
@@ -2,11 +2,11 @@ import{createReadStream as N}from"node:fs";import{open as Ge,stat as R,readdir a
|
|
|
2
2
|
`);r=[],n=0;const c=await e.fetchImpl(e.requestUrl,{body:a,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!c.ok&&c.status!==x){const l=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`import batch failed (HTTP ${String(c.status)}): ${l}`)}const d=await c.json();s(d),c.status===x&&(d.failed??[]).length===0&&t.failed.push({message:`the endpoint answered ${String(x)} without naming the failed shards`,shardKey:"<unknown>",timedOut:!1})};return{flush:o,push:async a=>{const c=Buffer.byteLength(a)+1;r.length>0&&n+c>e.maxBatchBytes&&await o(),r.push(a),n+=c,r.length>=e.batchSize&&await o()},totals:t}},ye=(e,t,r,n)=>{const s=[],o=[];let i=0;const a=l=>n?.[r]?.includes(l)===!0,c=(l,u,h=!1)=>{if(Array.isArray(l))return l.map(g=>c(g,u,h));if(l!==null&&typeof l=="object"){const g=l;if(typeof g.$storage=="string"){const m=g.$storage,w=t.get(m);return w===void 0?(o.push({column:u,storageId:m,table:r}),l):(i+=1,w)}return Object.fromEntries(Object.entries(g).map(([m,w])=>[m,c(w,u)]))}return typeof l=="string"&&t.has(l)?a(u)?(i+=1,t.get(l)??l):(s.push({column:u,storageId:l,table:r}),l):(h&&typeof l=="string"&&l.length>0&&a(u)&&n!==void 0&&o.push({column:u,storageId:l,table:r}),l)},d=Object.fromEntries(Object.entries(e).map(([l,u])=>[l,c(u,l,!0)]));return{ambiguous:s,document:d,rewritten:i,unmigrated:o}},St=e=>{const{remapDocument:t,report:r,storageColumns:n,storageIdMap:s,table:o}=e,i=(d,l)=>{let u;try{u=JSON.parse(d)}catch(h){const g=h instanceof Error?h.message:String(h);throw new f("INTERNAL",`invalid JSON on line ${String(l)}: ${g}`,{cause:h})}return JSON.stringify({doc:u,table:o})},a=(d,l)=>{let u;try{u=JSON.parse(d)}catch(g){throw new f("INTERNAL",`line ${String(l)}: import envelope is not valid JSON — ${g instanceof Error?g.message:String(g)}`,{cause:g})}const h=u===null||typeof u!="object"||Array.isArray(u)?void 0:u;if(h===void 0||typeof h.table!="string")throw new f("INTERNAL",`line ${String(l)}: import envelope is missing a string \`table\``);return h},c=d=>{if(d.doc!==null&&typeof d.doc=="object"&&!Array.isArray(d.doc)){let l=d.doc;if(s!==void 0){const u=ye(l,s,d.table,n);l=u.document,r.rewritten+=u.rewritten,r.ambiguous.push(...u.ambiguous),r.unmigrated.push(...u.unmigrated)}return JSON.stringify({...d,doc:t===void 0?l:t(l,d.table)})}return JSON.stringify(d)};return(d,l)=>{const u=d.trim();if(u.length===0)return;if(o!==void 0)return i(u,l);const h=a(u,l);return s===void 0&&t===void 0?u:c(h)}},be=async(e,t,r,n)=>{const s=await n(e).catch(()=>{});if(s===void 0)throw new f("INTERNAL",`${e} is not a readable directory`);const o=new Map;for(const[d,l]of Object.entries(t?.tables??{}))l.file!==void 0&&o.set(p(l.file),d);const i=s.filter(d=>d.isFile()&&r.matches(d.name)&&!r.authFiles.has(d.name)).map(d=>({file:y(e,d.name),table:o.get(d.name)??r.tableNameOf(d.name)}));if(i.length===0)throw new f("INTERNAL",`${e} ${r.emptyMessage}`);const a=new Set(i.map(d=>p(d.file))),c=[...o].filter(([d])=>!a.has(d));if(c.length>0)throw new f("INTERNAL",`${e}: the mapping names ${String(c.length)} file(s) that are not importable from this directory — ${c.map(([d,l])=>`\`${d}\` (table \`${l}\`)`).join(", ")}. Check the name and that the file is one this source reads.`);return i.toSorted((d,l)=>d.table.localeCompare(l.table))},we=async function*(e,t,r,n){for(const s of e){r.has(s.table)||r.set(s.table,0),t.info(`reading ${p(s.file)} → ${s.table}`);for await(const o of n(s))r.set(s.table,(r.get(s.table)??0)+1),yield`${JSON.stringify({doc:o,table:s.table})}
|
|
3
3
|
`}},$e=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],vt=e=>$e.includes(e),Nt=/^\\x([\dA-Fa-f]*)$/,se=/^[+-]?\d+$/,Se=/[+-]\d{2}$/,ve=/(?:Z|[+-]\d{2}:\d{2})$/i,Ne=/^\+/,Et=/e/i,Tt=/e/i,It=e=>{const[t="0",r="0"]=e.split(Tt),n=Number(r),s=t.startsWith("-"),[o="0",i=""]=(s?t.slice(1):t).replace(Ne,"").split("."),a=`${o}${i}`,c=o.length+n;let d;return c<=0?d=`0.${"0".repeat(-c)}${a}`:c>=a.length?d=`${a}${"0".repeat(c-a.length)}`:d=`${a.slice(0,c)}.${a.slice(c)}`,s?`-${d}`:d},At=/^0+(?=\d)/,oe=e=>{const r=(Et.test(e.trim())?It(e.trim()):e.trim()).replace(Ne,""),n=r.startsWith("-"),[s="0",o=""]=(n?r.slice(1):r).split("."),i=s.replace(At,"");let a=o.length;for(;a>0&&o[a-1]==="0";)a-=1;const c=o.slice(0,a),d=c.length>0?`${i}.${c}`:i;return n&&Number(d)!==0?`-${d}`:d},b=(e,t,r,n)=>{throw new f("INTERNAL",`column \`${e}\`: cannot reshape ${JSON.stringify(r)} as \`${t}\` — ${n}`)},ie=(e,t,r)=>{const n=r.includes("T")?r:r.replace(" ","T"),s=Se.test(n)?`${n}:00`:n,o=ve.test(s)?s:`${s}Z`,i=Date.parse(o);return Number.isNaN(i)&&b(e,t,r,"not a date Postgres or ISO-8601 syntax can express"),i},_t=(e,t)=>{(!t.startsWith("{")||!t.endsWith("}"))&&b(e,"text-array",t,"not a Postgres array literal (expected `{…}`)");const r=t.slice(1,-1);if(r.length===0)return[];r.includes("{")&&b(e,"text-array",t,"nested arrays are not supported — map the column to `json` instead");const n=[];let s="",o=!1,i=!1,a=!1;const c=()=>{n.push(!i&&s==="NULL"?null:s),s="",i=!1};for(const d of r)a?(s+=d,a=!1):d==="\\"?a=!0:d==='"'?(o=!o,i=!0):d===","&&!o?c():s+=d;return c(),n},Ee=(e,t,r)=>{if(r===null)return null;switch(t){case"boolean":return["1","t","TRUE","true"].includes(r)?!0:["0","f","FALSE","false"].includes(r)?!1:b(e,t,r,"not a Postgres boolean literal");case"bytea-base64":{const n=Nt.exec(r);if(n===null)return b(e,t,r,"not `bytea` hex output (expected a leading `\\x`) — set `bytea_output = 'hex'` before dumping");const s=n[1];return s.length%2!==0?b(e,t,r,"has an odd number of hex digits, so the dump is truncated — re-export the column"):Buffer.from(s,"hex").toString("base64")}case"int8-string":return se.test(r)?r:b(e,t,r,"not an integer");case"json":try{return JSON.parse(r)}catch(n){return b(e,t,r,`invalid JSON — ${n instanceof Error?n.message:String(n)}`)}case"number":{const n=Number(r);if(r.trim().length===0||!Number.isFinite(n))return b(e,t,r,"not a finite number");if(se.test(r)){if(!Number.isSafeInteger(n))return b(e,t,r,"exceeds Number.MAX_SAFE_INTEGER — map this column to `int8-string` to keep it lossless")}else if(oe(String(n))!==oe(r))return b(e,t,r,"has more precision than a JS number holds — map this column to `int8-string` or `json` to keep it lossless");return n}case"text-array":return _t(e,r);case"timestamp-iso":{ie(e,t,r);const n=r.includes("T")?r:r.replace(" ","T"),s=Se.test(n)?`${n}:00`:n;return ve.test(s)?s:`${s}Z`}case"timestamp-ms":return ie(e,t,r);default:return r}},Rt="auth.",Ot=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),Lt=String.raw`\N`,Te=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===Lt?null:e,kt=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>p(t))),xt=async(e,t)=>be(e,t,{authFiles:kt(t),emptyMessage:"holds no .csv files — export each table with `COPY <table> TO STDOUT WITH CSV HEADER` first",matches:r=>r.toLowerCase().endsWith(".csv")&&!r.toLowerCase().startsWith(Rt),tableNameOf:r=>p(r,".csv")},async r=>O(r,{withFileTypes:!0})),Ct=(e,t,r)=>{const n=t?.idColumn??"id",s=t?.types??{},o={};let i=!1;for(const[a,c]of Object.entries(e)){if(Ot.has(a.toLowerCase()))throw new f("INTERNAL",`${r}.${a} is credential material — this looks like an auth dump being imported as a table. Name it under \`auth\` in the mapping instead; passwords are never migrated.`);const d=s[a],l=d===void 0?c:Ee(a,d,c);if(a===n){if(c===null)throw new f("INTERNAL",`id column \`${n}\` is NULL — every row needs an id to preserve`);o._id=c,i=!0}else{if(a==="_id")throw new f("INTERNAL",`${r}: source column \`_id\` collides with the reserved id field. Rename it in the source, or map it via \`tables.${r}.idColumn\` if it IS the id.`);o[a]=l}}if(!i)throw new f("INTERNAL",`${r}: no \`${n}\` column to preserve as the id (columns present: ${Object.keys(e).join(", ")}). Set \`tables.${r}.idColumn\` in the mapping.`);return o},jt=async function*(e,t){const r=t?.tables?.[e.table],n=N(e.file).pipe(me({cast:Te,columns:!0,relaxColumnCountLess:!1,skipEmptyLines:!0}));let s=0;const o=n[Symbol.asyncIterator]();for(;;){let i,a;try{if(i=await o.next(),i.done===!0)return;s+=1,a=Ct(i.value,r,e.table)}catch(c){throw new f("INTERNAL",`${p(e.file)} row ${String(s+1)}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}yield a}},Pt=async function*(e,t,r,n,s){yield*_e("supabase",s,t,r,n),yield*we(e,r,n,o=>jt(o,t))},Ut=/^\d+$/,Ft=/[+-]\d{2}$/,P=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&Ut.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(Ft.test(r)?`${r}:00`:r);return Number.isNaN(n)?void 0:n},Ie=e=>{if(typeof e=="string")try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}return e!==null&&typeof e=="object"?e:void 0},zt=e=>{const t=Ie(e);if(t!==void 0){for(const r of["name","full_name","user_name","preferred_username"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},Mt=e=>{const t=Ie(e);if(t!==void 0){for(const r of["avatar_url","picture"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},Dt=(e,t)=>{const{id:r}=e;if(typeof r!="string"||r.length===0)throw new f("INTERNAL","auth row is missing `id` — every user needs an id to preserve");const n=e.raw_user_meta_data,s={_id:r,email:e.email??null,emailVerified:typeof e.email_confirmed_at=="string"&&e.email_confirmed_at.length>0,id:r},o=zt(n),i=Mt(n),a=P(e.created_at),c=P(e.updated_at);return o!==void 0&&(s.name=o),i!==void 0&&(s.image=i),a!==void 0&&(s.createdAt=a),c!==void 0&&(s.updatedAt=c),{accounts:t.map(l=>{const u=typeof l.provider=="string"?l.provider:"unknown",h=typeof l.provider_id=="string"?l.provider_id:r,g=`${r}:${u}:${h}`;return{_id:g,accountId:h,id:g,providerId:u,userId:r}}),user:s}},Bt=e=>{const t=e.localId;if(typeof t!="string"||t.length===0)throw new f("INTERNAL","auth row is missing `localId` — every user needs an id to preserve");const r={_id:t,email:e.email??null,emailVerified:e.emailVerified===!0,id:t},n=P(e.createdAt);return typeof e.displayName=="string"&&(r.name=e.displayName),typeof e.photoUrl=="string"&&(r.image=e.photoUrl),n!==void 0&&(r.createdAt=n),{accounts:(e.providerUserInfo??[]).filter(o=>typeof o.providerId=="string"&&o.providerId!=="password").map(o=>{const i=o.providerId,a=o.rawId??o.federatedId??t,c=`${t}:${i}:${a}`;return{_id:c,accountId:a,id:c,providerId:i,userId:t}}),user:r}},Jt=(e,t)=>{const r=new Map,n=[],s=[];for(const{accounts:o,user:i}of e){const a=typeof i.email=="string"?i.email.toLowerCase():void 0;if(a!==void 0&&a.length>0){const c=r.get(a);c===void 0?r.set(a,String(i._id)):n.push(`${a} (ids ${c} and ${String(i._id)})`)}s.push(`${JSON.stringify({doc:i,table:"user"})}
|
|
4
4
|
`),t.set("user",(t.get("user")??0)+1);for(const c of o)s.push(`${JSON.stringify({doc:c,table:"account"})}
|
|
5
|
-
`),t.set("account",(t.get("account")??0)+1)}if(n.length>0)throw new f("INTERNAL",`auth import found ${String(n.length)} duplicate email(s), which would merge distinct users: ${n.slice(0,10).join("; ")}${n.length>10?" …":""}`);return s},D=(e,t)=>y(e,p(t)),Ae=async e=>{const t=await $(e,"utf8");return nt(t,{cast:Te,columns:!0,skipEmptyLines:!0})},Vt=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Ae(D(e,t))){const s=n.user_id;typeof s=="string"&&r.set(s,[...r.get(s)??[],n])}return r},Ht=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Ae(D(e,r)),s=await Vt(e,t.auth?.identitiesFile);return n.map(o=>Dt(o,s.get(o.id??"")??[]))},Gt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=D(e,r);let s;try{s=JSON.parse(await $(n,"utf8"))}catch(i){throw new f("INTERNAL",`${p(n)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}const o=Array.isArray(s)?s:s.users??[];if(!Array.isArray(o))throw new f("INTERNAL",`${p(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return o.map(i=>Bt(i))},_e=async function*(e,t,r,n,s){if(r?.auth?.file===void 0)return;const o=e==="supabase"?await Ht(t,r):await Gt(t,r);n.info(`auth: ${String(o.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of Jt(o,s))yield i},ae=/\.(?:nd)?json$/i,Re=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},Wt=e=>{const t=Number(e.seconds??0),r=e.nanos??0;return Number.isFinite(t)&&Number.isFinite(r)?t*1e3+Math.floor(r/1e6):Number.NaN},Yt=(e,t)=>{const r=Array.isArray(e)?e:e.data;if(!Array.isArray(r))throw new f("INTERNAL",`${t}: \`bytesValue\` ${JSON.stringify(e)} is neither base64 nor a byte array`);return Buffer.from(r).toString("base64")},Kt=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Wt(e);if(Number.isNaN(r))throw new f("INTERNAL",`${t}: \`timestampValue\` ${JSON.stringify(e)} is neither an RFC-3339 string nor a \`{ seconds, nanos }\` protobuf timestamp`);return r},Xt=(e,t)=>typeof e=="string"?e:Yt(e,t),Oe=(e,t)=>{if("nullValue"in e)return null;if(e.stringValue!==void 0)return e.stringValue;if(e.booleanValue!==void 0)return e.booleanValue;if(e.integerValue!==void 0){const r=String(e.integerValue),n=Number(r);return Number.isSafeInteger(n)?n:r}if(e.doubleValue!==void 0)return Number(e.doubleValue);if(e.timestampValue!==void 0)return Kt(e.timestampValue,t);if(e.bytesValue!==void 0)return Xt(e.bytesValue,t);if(e.geoPointValue!==void 0)return{latitude:e.geoPointValue.latitude??0,longitude:e.geoPointValue.longitude??0};if(e.referenceValue!==void 0)return Re(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>Oe(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return U(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},qt=new Set(["createTime","fields","name","readTime","updateTime"]),Zt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]?.endsWith("Value")===!0},Qt=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>qt.has(r))&&!Zt(t)},U=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Oe(n,`${t}.${r}`)])),er=(e,t,r,n)=>{const s=Qt(e),o=U(s?e.fields??{}:e,n),i=e.name??e.__name__,a=typeof i=="string"?Re(i):t;if(a===void 0)throw new f("INTERNAL",`${n}: no document id — expected a \`name\`/\`__name__\` resource path, or a document keyed by its id`);const c=r?.types??{};for(const[d,l]of Object.entries(c)){const u=o[d];if(u!==void 0){if(u!==null&&typeof u!="boolean"&&typeof u!="number"&&typeof u!="string")throw new f("INTERNAL",`${n}.${d}: a \`${l}\` reshape needs a scalar, but this field decoded to an object or array`);o[d]=Ee(d,l,u===null?null:String(u))}}return{...o,_id:a}},tr=async(e,t)=>be(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[p(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>ae.test(r),tableNameOf:r=>r.replace(ae,"")},async r=>O(r,{withFileTypes:!0})),rr=async function*(e){const t=j({crlfDelay:Number.POSITIVE_INFINITY,input:N(e,"utf8")});let r=0;try{for await(const n of t){r+=1;const s=n.trim();if(s.length!==0)try{yield{raw:JSON.parse(s)}}catch(o){throw new f("INTERNAL",`${p(e)} line ${String(r)}: invalid JSON — ${o instanceof Error?o.message:String(o)}`,{cause:o})}}}finally{t.close()}},nr=async e=>{const t=await $(e,"utf8");let r;try{r=JSON.parse(t)}catch(n){throw new f("INTERNAL",`${p(e)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(r!==null&&typeof r=="object"&&Array.isArray(r.documents))return r.documents.map(n=>({raw:n}));if(Array.isArray(r))return r.map(n=>({raw:n}));if(r!==null&&typeof r=="object")return Object.entries(r).map(([n,s])=>({fallbackId:n,raw:s}));throw new f("INTERNAL",`${p(e)}: expected an object, an array, or \`{ documents: [...] }\``)},sr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?rr(e.file):await nr(e.file);let s=0;for await(const o of n)yield er(o.raw,o.fallbackId,r,`${e.table}[${String(s)}]`),s+=1},or=async function*(e,t,r,n,s){yield*_e("firebase",s,t,r,n),yield*we(e,r,n,o=>sr(o,t))},I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),B=(e,t)=>{if(!I(e))throw new f("INTERNAL",`${t}: expected a JSON object`);return e},T=(e,t,r)=>{const n=e[t];if(n!==void 0&&typeof n!="string")throw new f("INTERNAL",`${r}: \`${t}\` must be a string`);return n},Le=(e,t,r)=>{const n=e[t];if(n!==void 0&&(!Array.isArray(n)||n.some(s=>typeof s!="string")))throw new f("INTERNAL",`${r}: \`${t}\` must be an array of column names`);return n},ir=(e,t)=>{const r=B(e,t),n=T(r,"file",t),s=T(r,"idColumn",t),o=Le(r,"storageColumns",t),{types:i}=r;if(i!==void 0){if(!I(i))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(i))if(!vt(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${$e.join(", ")}`)}return{file:n,idColumn:s,storageColumns:o,types:i}},ar=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`auth\` must be an object`);for(const r of["file","identitiesFile"])T(e,r,`${t}: auth`)}},cr=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`tables\` must be an object of table → mapping`);return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ir(n,`${t}: tables.${r}`)]))}},dr=(e,t)=>{const r=B(e,t),n=T(r,"keyPrefix",t),{auth:s,tables:o}=r;return ar(s,t),{auth:s,keyPrefix:n,tables:cr(o,t)}},ke=e=>y("lunora",`import-${e}.json`),lr=async(e,t,r)=>{const n=ke(t),s=y(e,n);let o;try{o=await $(s,"utf8")}catch(a){if(a.code==="ENOENT"){r.info(`no ${n} found — every column is copied through untouched (run with --scan to generate one)`);return}throw a}let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${s}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return dr(i,s)},ur=8,fr=24*1048576,hr=1e3,gr=/^[\dA-F]{64}$/i,mr=e=>{for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t)??0;if(r<32||r===127)return!1}return!0},pr=/^[\d+/A-Z]{43}=$/i,yr=e=>gr.test(e)?e.toLowerCase():pr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,br=(e,t)=>{const r=JSON.parse(e),n=r._id;if(typeof n!="string"||n.length===0||n.includes("/")||n.includes("\\"))throw new f("INTERNAL",`${t}: \`_id\` must be a path-free non-empty string`);if(typeof r.sha256!="string")throw new f("INTERNAL",`${t}: \`sha256\` is missing — re-export with \`npx convex export --include-file-storage\``);const s=yr(r.sha256);if(s===void 0)throw new f("INTERNAL",`${t}: \`sha256\` is neither base16 nor base64 SHA-256 (${r.sha256})`);if(typeof r.size!="number"||!Number.isInteger(r.size)||r.size<0)throw new f("INTERNAL",`${t}: \`size\` must be a non-negative integer`);if(r.contentType!==void 0&&(typeof r.contentType!="string"||!mr(r.contentType)))throw new f("INTERNAL",`${t}: \`contentType\` must be a string with no control characters`);return{contentType:typeof r.contentType=="string"?r.contentType:void 0,id:n,sha256:s,size:r.size}},J=async(e,t,r)=>{const n=[];try{let s=0;for await(const o of M(e,t)){const i=o.trim();s+=1,i.length>0&&n.push(br(i,`_storage/documents.jsonl line ${String(s)}`))}}catch(s){const o=s instanceof Error?s.message:String(s);throw r.error(`failed to read _storage metadata: ${o}`),s}return n},xe=st,L=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,V=async(e,t)=>{const r=[];let n;do{const s=`${e.baseUrl}${z}?prefix=${encodeURIComponent(t)}&limit=${String(hr)}${n===void 0?"":`&cursor=${encodeURIComponent(n)}`}${L(e)}`,o=await e.fetchImpl(s,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!o.ok){const c=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(o.status)}): ${c}`)}const i=await o.json();r.push(...i.objects??[]);const a=i.truncated===!0?i.cursor:void 0;if(a!==void 0&&a===n)throw new f("INTERNAL","storage list did not advance its cursor — refusing to page forever");n=a}while(n!==void 0);return r},wr=async(e,t,r,n)=>{const s=`${e.baseUrl}${z}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}${L(e)}`,o=await e.fetchImpl(s,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!o.ok){const a=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(o.status)}): ${a}`)}const i=await o.json();if(i.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${i.sha256??"none"}`);return t},$r=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${z}?key=${encodeURIComponent(t)}${L(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,Sr=async(e,t,r,n,s)=>{const o=`${e.baseUrl}${ot}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}${L(e)}`,i=await e.fetchImpl(o,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const m=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(xe)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(i.status)}): ${m}`)}const{url:a}=await i.json(),c=await e.fetchImpl(a,{body:new Uint8Array(r),headers:{"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!c.ok){const m=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${m}`)}const l=(await V(e,t)).find(m=>m.key===t);if(l===void 0)throw new f("INTERNAL",`post-upload verification failed: blob not found at key ${t}`);const u=l.size!==void 0&&l.size!==n.size,h=l.sha256!==void 0&&l.sha256.toLowerCase()!==n.sha256;if(u||h){const m=await $r(e,t);throw new f("INTERNAL",`post-upload verification failed: expected sha256=${n.sha256} size=${String(n.size)}, got sha256=${l.sha256??"none"} size=${String(l.size??"none")}${m?" (the object was removed)":` — AND the object could not be removed: delete ${t} by hand before re-running, or the next run will treat it as already migrated`}`)}const g=[l.size===void 0?"size":void 0,l.sha256===void 0?"sha256":void 0].filter(Boolean);return g.length>0&&s.warn(`blob ${t} went through the signed-PUT path and the host reports no ${g.join(" or ")} for it — that much of the write is unverified`),t},Ce=async(e,t,r,n,s)=>{if(r.length!==n.size)throw new f("INTERNAL",`blob ${n.id} is ${String(r.length)} bytes on disk but the export declares ${String(n.size)}`);return r.length<=xe?wr(e,t,r,n):Sr(e,t,r,n,s)},vr=e=>{const t=[];let r=[],n=0;for(const s of e)r.length>0&&(r.length>=ur||n+s.size>fr)&&(t.push(r),r=[],n=0),r.push(s),n+=s.size;return r.length>0&&t.push(r),t},Nr=async(e,t,r,n,s)=>{const o=await J(t,r,s),i=new Map,a=await V(e,n),c=new Map(a.map(u=>[u.key,u])),d=[];for(const u of o){const h=`${n}${u.sha256}`;c.get(h)?.size===u.size?i.set(u.id,h):d.push(u)}s.info(`migrating ${String(d.length)} storage blobs${i.size>0?` (${String(i.size)} already present)`:""}...`);const l=async u=>{try{const h=await wt(t,u.id);i.set(u.id,await Ce(e,`${n}${u.sha256}`,h,u,s))}catch(h){const g=h instanceof Error?h.message:String(h);throw s.error(`failed to upload blob ${u.id}: ${g}`),h}};for(const u of vr(d)){const g=(await Promise.allSettled(u.map(m=>l(m)))).find(m=>m.status==="rejected");if(g!==void 0)throw g.reason}return s.success(`migrated ${String(d.length)} storage blobs`),i};async function*Er(e,t,r){let n=0;for await(const s of M(e,t)){const o=s.trim();if(n+=1,o.length===0)continue;let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${t.table}/documents.jsonl line ${String(n)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}r.set(t.table,(r.get(t.table)??0)+1),yield`${JSON.stringify({doc:i,table:t.table})}
|
|
6
|
-
`}}async function*
|
|
7
|
-
`;await F(y(t,"lunora"),{recursive:!0});try{await fe(n,s,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(o){if(o.code!=="EEXIST")throw o;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(s)}},
|
|
8
|
-
`;await F(he(o),{recursive:!0});try{await fe(o,i,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${o} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${o} already exists — leaving it untouched. Candidate mapping:`),n.info(i)}},
|
|
9
|
-
`)){const a=i.trim();if(a.length!==0)try{const c=JSON.parse(a);typeof c.path=="string"&&typeof c.key=="string"?n.set(c.path,c):o+=1}catch{o+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${o>0?` (${String(o)} unreadable checkpoint line(s) ignored)`:""}`),n},
|
|
10
|
-
`,"utf8")},Pe=100,
|
|
5
|
+
`),t.set("account",(t.get("account")??0)+1)}if(n.length>0)throw new f("INTERNAL",`auth import found ${String(n.length)} duplicate email(s), which would merge distinct users: ${n.slice(0,10).join("; ")}${n.length>10?" …":""}`);return s},D=(e,t)=>y(e,p(t)),Ae=async e=>{const t=await $(e,"utf8");return nt(t,{cast:Te,columns:!0,skipEmptyLines:!0})},Vt=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Ae(D(e,t))){const s=n.user_id;typeof s=="string"&&r.set(s,[...r.get(s)??[],n])}return r},Ht=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Ae(D(e,r)),s=await Vt(e,t.auth?.identitiesFile);return n.map(o=>Dt(o,s.get(o.id??"")??[]))},Gt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=D(e,r);let s;try{s=JSON.parse(await $(n,"utf8"))}catch(i){throw new f("INTERNAL",`${p(n)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}const o=Array.isArray(s)?s:s.users??[];if(!Array.isArray(o))throw new f("INTERNAL",`${p(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return o.map(i=>Bt(i))},_e=async function*(e,t,r,n,s){if(r?.auth?.file===void 0)return;const o=e==="supabase"?await Ht(t,r):await Gt(t,r);n.info(`auth: ${String(o.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of Jt(o,s))yield i},ae=/\.(?:nd)?json$/i,Re=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},Wt=e=>{const t=Number(e.seconds??0),r=e.nanos??0;return Number.isFinite(t)&&Number.isFinite(r)?t*1e3+Math.floor(r/1e6):Number.NaN},Yt=(e,t)=>{const r=Array.isArray(e)?e:e.data;if(!Array.isArray(r))throw new f("INTERNAL",`${t}: \`bytesValue\` ${JSON.stringify(e)} is neither base64 nor a byte array`);return Buffer.from(r).toString("base64")},Kt=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Wt(e);if(Number.isNaN(r))throw new f("INTERNAL",`${t}: \`timestampValue\` ${JSON.stringify(e)} is neither an RFC-3339 string nor a \`{ seconds, nanos }\` protobuf timestamp`);return r},Xt=(e,t)=>typeof e=="string"?e:Yt(e,t),Oe=(e,t)=>{if("nullValue"in e)return null;if(e.stringValue!==void 0)return e.stringValue;if(e.booleanValue!==void 0)return e.booleanValue;if(e.integerValue!==void 0){const r=String(e.integerValue),n=Number(r);return Number.isSafeInteger(n)?n:r}if(e.doubleValue!==void 0)return Number(e.doubleValue);if(e.timestampValue!==void 0)return Kt(e.timestampValue,t);if(e.bytesValue!==void 0)return Xt(e.bytesValue,t);if(e.geoPointValue!==void 0)return{latitude:e.geoPointValue.latitude??0,longitude:e.geoPointValue.longitude??0};if(e.referenceValue!==void 0)return Re(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>Oe(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return U(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},qt=new Set(["createTime","fields","name","readTime","updateTime"]),Zt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]?.endsWith("Value")===!0},Qt=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>qt.has(r))&&!Zt(t)},U=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Oe(n,`${t}.${r}`)])),er=(e,t,r,n)=>{const s=Qt(e),o=U(s?e.fields??{}:e,n),i=e.name??e.__name__,a=typeof i=="string"?Re(i):t;if(a===void 0)throw new f("INTERNAL",`${n}: no document id — expected a \`name\`/\`__name__\` resource path, or a document keyed by its id`);const c=r?.types??{};for(const[d,l]of Object.entries(c)){const u=o[d];if(u!==void 0){if(u!==null&&typeof u!="boolean"&&typeof u!="number"&&typeof u!="string")throw new f("INTERNAL",`${n}.${d}: a \`${l}\` reshape needs a scalar, but this field decoded to an object or array`);o[d]=Ee(d,l,u===null?null:String(u))}}return{...o,_id:a}},tr=async(e,t)=>be(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[p(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>ae.test(r),tableNameOf:r=>r.replace(ae,"")},async r=>O(r,{withFileTypes:!0})),rr=async function*(e){const t=j({crlfDelay:Number.POSITIVE_INFINITY,input:N(e,"utf8")});let r=0;try{for await(const n of t){r+=1;const s=n.trim();if(s.length!==0)try{yield{raw:JSON.parse(s)}}catch(o){throw new f("INTERNAL",`${p(e)} line ${String(r)}: invalid JSON — ${o instanceof Error?o.message:String(o)}`,{cause:o})}}}finally{t.close()}},nr=async e=>{const t=await $(e,"utf8");let r;try{r=JSON.parse(t)}catch(n){throw new f("INTERNAL",`${p(e)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(r!==null&&typeof r=="object"&&Array.isArray(r.documents))return r.documents.map(n=>({raw:n}));if(Array.isArray(r))return r.map(n=>({raw:n}));if(r!==null&&typeof r=="object")return Object.entries(r).map(([n,s])=>({fallbackId:n,raw:s}));throw new f("INTERNAL",`${p(e)}: expected an object, an array, or \`{ documents: [...] }\``)},sr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?rr(e.file):await nr(e.file);let s=0;for await(const o of n)yield er(o.raw,o.fallbackId,r,`${e.table}[${String(s)}]`),s+=1},or=async function*(e,t,r,n,s){yield*_e("firebase",s,t,r,n),yield*we(e,r,n,o=>sr(o,t))},I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),B=(e,t)=>{if(!I(e))throw new f("INTERNAL",`${t}: expected a JSON object`);return e},T=(e,t,r)=>{const n=e[t];if(n!==void 0&&typeof n!="string")throw new f("INTERNAL",`${r}: \`${t}\` must be a string`);return n},Le=(e,t,r)=>{const n=e[t];if(n!==void 0&&(!Array.isArray(n)||n.some(s=>typeof s!="string")))throw new f("INTERNAL",`${r}: \`${t}\` must be an array of column names`);return n},ir=(e,t)=>{const r=B(e,t),n=T(r,"file",t),s=T(r,"idColumn",t),o=Le(r,"storageColumns",t),{types:i}=r;if(i!==void 0){if(!I(i))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(i))if(!vt(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${$e.join(", ")}`)}return{file:n,idColumn:s,storageColumns:o,types:i}},ar=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`auth\` must be an object`);for(const r of["file","identitiesFile"])T(e,r,`${t}: auth`)}},cr=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`tables\` must be an object of table → mapping`);return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ir(n,`${t}: tables.${r}`)]))}},dr=(e,t)=>{const r=B(e,t),n=T(r,"keyPrefix",t),{auth:s,tables:o}=r;return ar(s,t),{auth:s,keyPrefix:n,tables:cr(o,t)}},ke=e=>y("lunora",`import-${e}.json`),lr=async(e,t,r)=>{const n=ke(t),s=y(e,n);let o;try{o=await $(s,"utf8")}catch(a){if(a.code==="ENOENT"){r.info(`no ${n} found — every column is copied through untouched (run with --scan to generate one)`);return}throw a}let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${s}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return dr(i,s)},ur=async e=>{const t=[];let r;for(;;){const n=await e(r);if(t.push(...Array.isArray(n.records)?n.records:[]),n.truncated!==!0||typeof n.cursor!="string"||n.cursor.length===0)return t;if(n.cursor===r)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");r=n.cursor}},fr=8,hr=24*1048576,gr=1e3,mr=/^[\dA-F]{64}$/i,pr=e=>{for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t)??0;if(r<32||r===127)return!1}return!0},yr=/^[\d+/A-Z]{43}=$/i,br=e=>mr.test(e)?e.toLowerCase():yr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,wr=(e,t)=>{const r=JSON.parse(e),n=r._id;if(typeof n!="string"||n.length===0||n.includes("/")||n.includes("\\"))throw new f("INTERNAL",`${t}: \`_id\` must be a path-free non-empty string`);if(typeof r.sha256!="string")throw new f("INTERNAL",`${t}: \`sha256\` is missing — re-export with \`npx convex export --include-file-storage\``);const s=br(r.sha256);if(s===void 0)throw new f("INTERNAL",`${t}: \`sha256\` is neither base16 nor base64 SHA-256 (${r.sha256})`);if(typeof r.size!="number"||!Number.isInteger(r.size)||r.size<0)throw new f("INTERNAL",`${t}: \`size\` must be a non-negative integer`);if(r.contentType!==void 0&&(typeof r.contentType!="string"||!pr(r.contentType)))throw new f("INTERNAL",`${t}: \`contentType\` must be a string with no control characters`);return{contentType:typeof r.contentType=="string"?r.contentType:void 0,id:n,sha256:s,size:r.size}},J=async(e,t,r)=>{const n=[];try{let s=0;for await(const o of M(e,t)){const i=o.trim();s+=1,i.length>0&&n.push(wr(i,`_storage/documents.jsonl line ${String(s)}`))}}catch(s){const o=s instanceof Error?s.message:String(s);throw r.error(`failed to read _storage metadata: ${o}`),s}return n},xe=st,L=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,V=async(e,t)=>await ur(async r=>{const n=`${e.baseUrl}${z}?prefix=${encodeURIComponent(t)}&limit=${String(gr)}${r===void 0?"":`&cursor=${encodeURIComponent(r)}`}${L(e)}`,s=await e.fetchImpl(n,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!s.ok){const i=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(s.status)}): ${i}`)}const o=await s.json();return{cursor:o.cursor,records:o.objects,truncated:o.truncated}}),$r=async(e,t,r,n)=>{const s=`${e.baseUrl}${z}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}${L(e)}`,o=await e.fetchImpl(s,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!o.ok){const a=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(o.status)}): ${a}`)}const i=await o.json();if(i.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${i.sha256??"none"}`);return t},Sr=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${z}?key=${encodeURIComponent(t)}${L(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,vr=async(e,t,r,n,s)=>{const o=`${e.baseUrl}${ot}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}${L(e)}`,i=await e.fetchImpl(o,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const m=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(xe)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(i.status)}): ${m}`)}const{url:a}=await i.json(),c=await e.fetchImpl(a,{body:new Uint8Array(r),headers:{"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!c.ok){const m=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${m}`)}const l=(await V(e,t)).find(m=>m.key===t);if(l===void 0)throw new f("INTERNAL",`post-upload verification failed: blob not found at key ${t}`);const u=l.size!==void 0&&l.size!==n.size,h=l.sha256!==void 0&&l.sha256.toLowerCase()!==n.sha256;if(u||h){const m=await Sr(e,t);throw new f("INTERNAL",`post-upload verification failed: expected sha256=${n.sha256} size=${String(n.size)}, got sha256=${l.sha256??"none"} size=${String(l.size??"none")}${m?" (the object was removed)":` — AND the object could not be removed: delete ${t} by hand before re-running, or the next run will treat it as already migrated`}`)}const g=[l.size===void 0?"size":void 0,l.sha256===void 0?"sha256":void 0].filter(Boolean);return g.length>0&&s.warn(`blob ${t} went through the signed-PUT path and the host reports no ${g.join(" or ")} for it — that much of the write is unverified`),t},Ce=async(e,t,r,n,s)=>{if(r.length!==n.size)throw new f("INTERNAL",`blob ${n.id} is ${String(r.length)} bytes on disk but the export declares ${String(n.size)}`);return r.length<=xe?$r(e,t,r,n):vr(e,t,r,n,s)},Nr=e=>{const t=[];let r=[],n=0;for(const s of e)r.length>0&&(r.length>=fr||n+s.size>hr)&&(t.push(r),r=[],n=0),r.push(s),n+=s.size;return r.length>0&&t.push(r),t},Er=async(e,t,r,n,s)=>{const o=await J(t,r,s),i=new Map,a=await V(e,n),c=new Map(a.map(u=>[u.key,u])),d=[];for(const u of o){const h=`${n}${u.sha256}`;c.get(h)?.size===u.size?i.set(u.id,h):d.push(u)}s.info(`migrating ${String(d.length)} storage blobs${i.size>0?` (${String(i.size)} already present)`:""}...`);const l=async u=>{try{const h=await wt(t,u.id);i.set(u.id,await Ce(e,`${n}${u.sha256}`,h,u,s))}catch(h){const g=h instanceof Error?h.message:String(h);throw s.error(`failed to upload blob ${u.id}: ${g}`),h}};for(const u of Nr(d)){const g=(await Promise.allSettled(u.map(m=>l(m)))).find(m=>m.status==="rejected");if(g!==void 0)throw g.reason}return s.success(`migrated ${String(d.length)} storage blobs`),i};async function*Tr(e,t,r){let n=0;for await(const s of M(e,t)){const o=s.trim();if(n+=1,o.length===0)continue;let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${t.table}/documents.jsonl line ${String(n)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}r.set(t.table,(r.get(t.table)??0)+1),yield`${JSON.stringify({doc:i,table:t.table})}
|
|
6
|
+
`}}async function*Ir(e,t,r,n,s){for(const o of t){if(pe(o.table)){o.table===E&&!n&&r.warn(`skipping "${E}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}s.has(o.table)||s.set(o.table,0),yield*Tr(e,o,s)}}const Dn=["firebase","supabase"],Ar=async(e,t,r)=>{if(e.withStorage===!0&&t==="firebase"&&e.storageDir===void 0)return e.logger.error("--with-storage on Firebase needs --storage-dir — download the bucket first with `gcloud storage cp -r gs://<bucket> <dir>`."),{kind:"invalid"};if(e.table!==void 0)return e.logger.error(`--table cannot be combined with --from ${t} — each row's table comes from its source file.`),{kind:"invalid"};const n=await lr(r,t,e.logger),s=Object.values(n?.tables??{}).some(o=>(o.storageColumns??[]).length>0);return e.verify===!0&&e.withStorage!==!0&&s?(e.logger.error("--verify with `storageColumns` declared requires --with-storage — otherwise every storage path stays unmigrated and only row counts would be checked."),{kind:"invalid"}):t==="supabase"?{kind:"supabase",mapping:n,tables:await xt(e.file,n)}:{collections:await tr(e.file,n),kind:"firebase",mapping:n}},_r=async e=>{if(!await R(e.file).then(()=>!0,()=>!1))return!1;for(const[r,n]of[["--scan",e.scan],["--verify",e.verify],["--with-storage",e.withStorage]])if(n===!0)return e.logger.error(`${r} requires a Convex export directory or .zip snapshot — ${e.file} is not one.`),!0;return!1},Rr=async(e,t,r)=>{const n=t.find(o=>o.table===E);if(n===void 0)return r.logger.error("--verify cannot check file references: this export has no `_storage` table, so it was taken without `--include-file-storage`. Re-export with that flag and pass --with-storage, or drop --verify."),!0;const s=await J(e,n,r.logger);return s.length>0?(r.logger.error(`--verify on an export carrying ${String(s.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),!0):!1},Or=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return Ar(e,e.from,t);const r=await mt(e.file),n=r===void 0?void 0:await bt(r);return r!==void 0&&n===void 0?(e.logger.error(`${e.file} is a ${r.kind==="zip"?".zip":"directory"} but holds no <table>/documents.jsonl — expected a \`npx convex export --path\` snapshot, or pass an NDJSON file.`),{kind:"invalid"}):r===void 0||n===void 0?await _r(e)?{kind:"invalid"}:{kind:"ndjson"}:e.table!==void 0?(e.logger.error("--table cannot be combined with a Convex export directory — each row's table comes from its source directory."),{kind:"invalid"}):e.verify===!0&&e.withStorage!==!0&&await Rr(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},_=y("lunora","import-convex.json"),Lr=(e,t)=>{const r=B(e,t),n=T(r,"keyPrefix",t),s=r.storageColumns;if(s!==void 0){if(!I(s))throw new f("INTERNAL",`${t}: \`storageColumns\` must be an object of table → column names`);for(const o of Object.keys(s))Le(s,o,`${t}: storageColumns`)}return{keyPrefix:n,storageColumns:s}},kr=async(e,t)=>{const r=y(e,_);let n;try{n=await $(r,"utf8")}catch(o){if(o.code==="ENOENT"){t.info(`no ${_} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw o}let s;try{s=JSON.parse(n)}catch(o){throw new f("INTERNAL",`${r}: invalid JSON — ${o instanceof Error?o.message:String(o)}`,{cause:o})}return Lr(s,r)},xr=(e,t,r)=>{try{return JSON.parse(e)}catch(n){throw new f("INTERNAL",`${t}/documents.jsonl line ${String(r)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}},Cr=async(e,t,r)=>{const n=new Map([...r].map(i=>[i,i])),s=[];let o=0;for await(const i of M(e,t)){const a=i.trim();if(o+=1,a.length===0)continue;const{ambiguous:c}=ye(xr(a,t.table,o),n,t.table);for(const{column:d}of c)s.includes(d)||s.push(d)}return s},jr=async(e,t,r)=>{const n={};for(const s of t){if(pe(s.table))continue;const o=await Cr(e,s,r);o.length>0&&(n[s.table]=o)}return n},Pr=async(e,t,r)=>{const n=y(t,_),s=`${JSON.stringify(e,void 0,4)}
|
|
7
|
+
`;await F(y(t,"lunora"),{recursive:!0});try{await fe(n,s,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(o){if(o.code!=="EEXIST")throw o;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(s)}},Ur=async(e,t,r,n)=>{const s=t.find(c=>c.table===E);if(s===void 0){n.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const o=await J(e,s,n),i=new Set(o.map(c=>c.id));n.info(`found ${String(i.size)} storage ids`);const a={keyPrefix:"",storageColumns:await jr(e,t,i)};return await Pr(a,r,n),a},v=20,Fr=(e,t,r)=>{let n=0;if(r.conflicts===0)for(const[s,o]of t){const i=r.inserted[s]??0;i<o&&(n+=1,e.error(`verify: ${s} inserted ${String(i)} of ${String(o)} source rows (${String(o-i)} missing)`))}else{const s=[...t.values()].reduce((i,a)=>i+a,0),o=Object.values(r.inserted).reduce((i,a)=>i+a,0)+r.conflicts;o<s&&(n+=1,e.error(`verify: ${String(o)} of ${String(s)} source rows accounted for across all tables (${String(s-o)} missing; ${String(r.conflicts)} already present)`))}return n>0?e.error(`verify: ${String(n)} row-parity check(s) failed`):e.success("verify: all source rows accounted for"),n},ce=(e,t,r)=>{const n=new Set;for(const s of t){const o=`${s.table} ${s.column} ${s.storageId}`;n.has(o)||(n.add(o),n.size<=v&&e.warn(r(s)))}n.size>v&&e.warn(`… and ${String(n.size-v)} more`)},zr=(e,t,r)=>(e.info(`storage refs: ${String(t.rewritten)} rewritten, ${String(t.unmigrated.length)} unmigrated, ${String(t.ambiguous.length)} ambiguous`),ce(e,t.unmigrated,n=>`unmigrated storage reference ${n.table}.${n.column}: ${n.storageId} has no exported blob — re-export with \`npx convex export --include-file-storage\``),ce(e,t.ambiguous,n=>`unrewritten storage id in ${n.table}.${n.column}: ${n.storageId} — if that column holds storage references, add it to ${_} and re-import`),r&&t.unmigrated.length>0?(e.error(`verify: ${String(t.unmigrated.length)} storage reference(s) resolved to no migrated blob`),!0):!1),Mr=(e,t,r)=>{for(const n of[...t].slice(0,v))e.warn(`storage path never transferred: ${n} — left as-is`);return t.size>v&&e.warn(`… and ${String(t.size-v)} more untransferred storage paths`),r&&t.size>0},de=200,Dr=/^\\x[\dA-Fa-f]*$/,Br=/^[+-]?\d+$/,Jr=/^[+-]?\d+\.\d+$/,Vr=/^\{.*\}$/,Hr=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,Gr=[["bytea-base64",e=>Dr.test(e)],["timestamp-ms",e=>Hr.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Br.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>Jr.test(e)],[e=>e.every(t=>Vr.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],Wr=e=>{if(e.length!==0){for(const[t,r]of Gr)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},Yr=(e,t)=>{for(const[r,n]of Object.entries(e)){if(n.length===0)continue;const s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}},Kr=async e=>{const t=new Map,r=N(e).pipe(me({columns:!0,skipEmptyLines:!0,toLine:de+1}));let n=0;for await(const o of r)if(Yr(o,t),n+=1,n>=de)break;r.destroy();const s={};for(const[o,i]of t){const a=Wr(i);a!==void 0&&(s[o]=a)}return s},je=async(e,t,r,n)=>{const s=ke(r),o=y(t,s),i=`${JSON.stringify(e,void 0,4)}
|
|
8
|
+
`;await F(he(o),{recursive:!0});try{await fe(o,i,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${o} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${o} already exists — leaving it untouched. Candidate mapping:`),n.info(i)}},Xr=async(e,t,r)=>{const n={};for(const o of e){const i=await Kr(o.file);r.info(`${p(o.file)} → ${o.table}: ${String(Object.keys(i).length)} column(s) need a reshape`),n[o.table]={file:p(o.file),idColumn:"id",...Object.keys(i).length>0?{types:i}:{}}}const s={keyPrefix:"",tables:n};return await je(s,t,"supabase",r),s},qr=async(e,t,r)=>{const n={};for(const o of e)n[o.table]={file:p(o.file),storageColumns:[]};r.info(`found ${String(e.length)} collection(s) — Firestore values are self-describing, so only storage columns need declaring`);const s={keyPrefix:"",tables:n};return await je(s,t,"firebase",r),s},H=e=>y("lunora",`.import-storage-${e}.ndjson`),Zr=async(e,t,r)=>{const n=new Map;let s;try{s=await $(y(e,H(t)),"utf8")}catch(i){if(i.code==="ENOENT")return n;throw i}let o=0;for(const i of s.split(`
|
|
9
|
+
`)){const a=i.trim();if(a.length!==0)try{const c=JSON.parse(a);typeof c.path=="string"&&typeof c.key=="string"?n.set(c.path,c):o+=1}catch{o+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${o>0?` (${String(o)} unreadable checkpoint line(s) ignored)`:""}`),n},Qr=async(e,t,r)=>{const n=y(e,H(t));await F(he(n),{recursive:!0}),await We(n,`${JSON.stringify(r)}
|
|
10
|
+
`,"utf8")},Pe=100,en=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),tn=async(e,t,r,n,s)=>{const o=await r(`${e.url}/storage/v1/object/list/${encodeURIComponent(t)}`,{body:JSON.stringify({limit:Pe,offset:s,prefix:n}),headers:{authorization:`Bearer ${e.serviceKey}`,"content-type":"application/json"},method:"POST"});if(!o.ok){const i=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase storage list failed for bucket ${t} (HTTP ${String(o.status)}): ${i}`)}return await o.json()},Ue=async(e,t,r,n="")=>{const s=[];let o=0;for(;;){const i=await tn(e,t,r,n,o);for(const a of i){const c=n===""?a.name:`${n}/${a.name}`;a.id===null||a.id===void 0?s.push(...await Ue(e,t,r,c)):s.push({contentType:a.metadata?.mimetype,name:c})}if(i.length<Pe)return s;o+=i.length}},rn=async(e,t,r)=>{const n=await t(`${e.url}/storage/v1/bucket`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!n.ok){const i=await n.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase bucket list failed (HTTP ${String(n.status)}): ${i} — check the project URL and that the key is the service-role key, not the anon key`)}const s=await n.json(),o=[];for(const i of s){const a=await Ue(e,i.name,t);r.info(`supabase bucket ${i.name}: ${String(a.length)} object(s)`);for(const c of a){const d=`${i.name}/${c.name}`;o.push({contentType:c.contentType,bytes:async()=>{const l=await t(`${e.url}/storage/v1/object/${encodeURIComponent(i.name)}/${en(c.name)}`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!l.ok){const u=await l.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase download failed for ${d} (HTTP ${String(l.status)}): ${u}`)}if(l.arrayBuffer===void 0)throw new f("INTERNAL","the fetch implementation cannot read response bytes, which the storage transfer requires");return Buffer.from(await l.arrayBuffer())},path:d})}}return o},nn=async e=>{const t=C(e),r=[],n=async s=>{const o=await O(s,{withFileTypes:!0}).catch(()=>{});if(o===void 0)throw new f("INTERNAL",`${e} is not a readable directory — download the bucket first with \`gcloud storage cp -r gs://<bucket> <dir>\``);for(const i of o){const a=C(s,i.name);if(!ge(t,a))throw new f("INTERNAL",`${i.name} resolves outside ${e} — refusing to upload it`);i.isDirectory()?await n(a):i.isFile()&&r.push({bytes:async()=>$(a),path:qe(t,a).split(Ze).join("/")})}};return await n(t),r},sn=async(e,t,r,n,s)=>{const o=await t.bytes(),i=at("sha256").update(o).digest("hex"),a=`${r.keyPrefix}${i}`;if(n.get(a)?.size!==o.length){const c={contentType:t.contentType,id:t.path,sha256:i,size:o.length};await Ce(e,a,o,c,s)}return await Qr(r.cwd,r.source,{key:a,path:t.path,size:o.length}),a},on=(e,t)=>{const r=e>500?100:25;return n=>{if(n===e||n%r===0){const s=e===0?100:Math.round(n/e*100);t.info(`transferred ${String(n)}/${String(e)} object(s) (${String(s)}%)`)}}},le=async(e,t,r,n)=>{const s=new Map,o=await Zr(r.cwd,r.source,n),i=await V(e,r.keyPrefix),a=new Map(i.map(l=>[l.key,l]));o.size>0&&i.length===0&&n.warn(`the checkpoint records ${String(o.size)} transferred object(s) but the target holds none under \`${r.keyPrefix}\` — re-transferring (a different deployment, a wiped bucket, or a changed keyPrefix)`);const c=on(t.length,n);let d=0;n.info(`transferring ${String(t.length)} object(s) to R2...`);for(const l of t){const u=o.get(l.path);if(u!==void 0&&a.has(u.key)){s.set(l.path,u.key),d+=1,c(d);continue}try{const h=await sn(e,l,r,a,n);s.set(l.path,h)}catch(h){const g=h instanceof Error?h.message:String(h);throw n.error(`failed transferring ${l.path} after ${String(d)} object(s): ${g}`),n.error(`progress is saved — re-run the same command to continue from here (delete ${H(r.source)} to start over)`),h}d+=1,c(d)}return n.success(`transferred ${String(t.length)} object(s) to R2`),s},ue=/^\/+/,an=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,cn=/[#?]/u,dn=e=>{const t=new Map(e),r=new Map;for(const[n,s]of e){const o=n.indexOf("/");if(o===-1)continue;const i=n.slice(o+1);i.length===0||e.has(i)||r.set(i,r.has(i)?void 0:s)}for(const[n,s]of r)s!==void 0&&t.set(n,s);return t},ln=e=>{const t=an.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(cn)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},un=(e,t)=>{const r=t.get(e);if(r!==void 0)return r;const n=e.replace(ue,""),s=t.get(n);if(s!==void 0)return s;const o=ln(e);return o===void 0?void 0:t.get(o)??t.get(o.replace(ue,""))},fn=500,hn=9e5,gn=async e=>{if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}const t=Xe(e.url,e.logger,e.cwd);if(t===void 0)return;if(Ye({prod:e.prod,url:t})&&e.yes!==!0){e.logger.error(`import bulk-writes ${t}, which is not local. Re-run with --yes to confirm.`);return}const{token:r}=Ke({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}try{const s=await R(e.file);if(!s.isFile()&&!s.isDirectory()){e.logger.error(`not a file or directory: ${e.file}`);return}}catch(s){const o=s instanceof Error?s.message:String(s);e.logger.error(`failed to stat ${e.file}: ${o}`);return}const n=e.fetchImpl??globalThis.fetch;if(typeof n!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{baseUrl:t,fetchImpl:n,requestUrl:`${t}${it}`,token:r}},mn=(e,t,r)=>({conflicts:e.conflicts,errors:e.errors,...e.failed.length>0?{failed:e.failed}:{},inserted:e.inserted,received:e.received,...t===void 0?{}:{storage:{ambiguous:r.ambiguous,blobs:t.size,rewritten:r.rewritten,unmigrated:r.unmigrated}},...e.warnings.length>0?{warnings:e.warnings}:{}}),pn=(e,t,r,n)=>{switch(e.kind){case"convex":return Ir(e.snapshot,e.tables,t.logger,r,n);case"firebase":return or(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return Pt(e.tables,e.mapping,t.logger,n,t.file);default:return N(t.file,{encoding:"utf8"})}},yn=async(e,t,r)=>{switch(e.kind){case"convex":return Ur(e.snapshot,e.tables,t,r);case"firebase":return qr(e.collections,t,r);case"supabase":return Xr(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},bn=async(e,t,r,n)=>{const s=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return le(e,await nn(r.storageDir),{cwd:n,keyPrefix:s,source:t.kind},r.logger);if(t.kind==="firebase"){r.logger.error("--with-storage needs --storage-dir for a Firebase source: download the bucket first (`gcloud storage cp -r gs://<bucket> ./storage`), then point --storage-dir at it.");return}const o=process.env.SUPABASE_URL,i=process.env.SUPABASE_SERVICE_ROLE_KEY;if(o===void 0||i===void 0){r.logger.error("--with-storage needs SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in the environment (the service-role key, not the anon key), or --storage-dir pointing at an already-downloaded bucket.");return}let a=o.length;for(;a>0&&o[a-1]==="/";)a-=1;const c=o.slice(0,a);if(!c.startsWith("https://")){r.logger.error(`SUPABASE_URL must be https:// — refusing to send the service-role key over ${c.split(":")[0]??"an unknown scheme"}.`);return}const d=await rn({serviceKey:i,url:c},e.fetchImpl,r.logger);return le(e,d,{cwd:n,keyPrefix:s,source:t.kind},r.logger)},wn=(e,t,r,n,s)=>{const o=n.mapping?.tables?.[t]?.storageColumns??[];if(o.length===0)return e;const i={...e};for(const a of o){const c=i[a];if(typeof c!="string"||c.length===0)continue;const d=un(c,r);d===void 0?s.add(`${t}.${a}: ${c}`):i[a]=d}return i},$n=e=>{const t=e.source.kind==="supabase"||e.source.kind==="firebase"?e.source:void 0,{transferredPaths:r}=e,n=r===void 0||t===void 0?void 0:dn(r);return St({remapDocument:n===void 0||t===void 0?void 0:(s,o)=>wn(s,o,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},Sn=async(e,t,r,n)=>{let s="",o=0;const i=async a=>{o+=1;const c=t(a,o);c!==void 0&&await r.push(c)};try{for await(const a of e){s+=typeof a=="string"?a:a.toString("utf8");let c=s.indexOf(`
|
|
11
11
|
`);for(;c!==-1;)await i(s.slice(0,c)),s=s.slice(c+1),c=s.indexOf(`
|
|
12
|
-
`)}s.length>0&&await i(s),await r.flush();return}catch(a){return n.error(`import failed part-way through: ${a instanceof Error?a.message:String(a)}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)"),a}},
|
|
12
|
+
`)}s.length>0&&await i(s),await r.flush();return}catch(a){return n.error(`import failed part-way through: ${a instanceof Error?a.message:String(a)}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)"),a}},vn=async(e,t,r,n)=>{const s=await kr(r,n),o=t.tables.find(a=>a.table===E);if(o===void 0){n.error("--with-storage requires a Convex export with a `_storage` metadata table — re-export with `npx convex export --include-file-storage`.");return}const i=await Er(e,t.snapshot,o,s?.keyPrefix??"",n);return n.info(`storage map: ${String(i.size)} blobs mapped`),{mapping:s,storageIdMap:i}},Nn=async(e,t,r,n)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return vn(e,t,n,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const s=await bn(e,t,r,n);return s===void 0?void 0:{transferredPaths:s}}catch{r.logger.error("no rows were imported — fix the transfer and re-run; it will resume where it stopped");return}},En=(e,t)=>{for(const s of t.warnings)e.warn(s);const r=t.received-t.insertedTotal-t.conflicts-t.errorCount;r>0&&e.warn(`${String(r)} of ${String(t.received)} rows were neither inserted, conflicted, nor reported as errors`);const n=`imported ${String(t.insertedTotal)} of ${String(t.received)} rows (${String(t.conflicts)} conflicts, ${String(t.errorCount)} errors)`;t.failed?e.error(n):e.success(n)},Bn=async e=>{const t=e.cwd??process.cwd(),r=await Or(e,t);if(r.kind==="invalid")return{body:void 0,code:1,inserted:0};if(e.scan===!0)return{body:void 0,code:await yn(r,t,e.logger)===void 0?1:0,inserted:0};const n=await gn(e);if(n===void 0)return{body:void 0,code:1,inserted:0};const{baseUrl:s,fetchImpl:o,requestUrl:i,token:a}=n,c=e.batchSize??fn,d=await Nn({baseUrl:s,fetchImpl:o,token:a},r,e,t);if(d===void 0)return{body:void 0,code:1,inserted:0};const{mapping:l,storageIdMap:u,transferredPaths:h}=d,g=new Set,m=l?.storageColumns,w={ambiguous:[],rewritten:0,unmigrated:[]};e.logger.info(r.kind==="convex"?`POST ${i} -> import Convex export ${e.file} (${String(r.tables.length)} tables)`:`POST ${i} -> import ${e.file}`);const G=new Map,Fe=pn(r,e,u!==void 0,G),k=$t({batchSize:c,fetchImpl:o,maxBatchBytes:hn,requestUrl:i,token:a}),ze=$n({report:w,source:r,storageColumns:m,storageIdMap:u,table:e.table,transferredPaths:h,unresolvedPaths:g}),W=await Sn(Fe,ze,k,e.logger),{conflicts:Y,errors:K,failed:X,inserted:q,received:Me,warnings:De}=k.totals,Be=e.verify===!0&&W===void 0?Fr(e.logger,G,{conflicts:Y,inserted:q}):0,Je=u!==void 0&&zr(e.logger,w,e.verify===!0),Ve=Mr(e.logger,g,e.verify===!0),Z=Object.values(q).reduce((S,He)=>S+He,0),Q=mn(k.totals,u,w);for(const S of X)e.logger.error(`import: shard "${S.shardKey}" was never reached${S.timedOut?" (timed out)":""} — its rows were NOT written: ${S.message}`);const ee=W!==void 0||K.length>0||X.length>0||Be>0||Je||Ve;return e.logger.info(JSON.stringify(Q,void 0,2)),En(e.logger,{conflicts:Y,errorCount:K.length,failed:ee,insertedTotal:Z,received:Me,warnings:De}),{body:Q,code:ee?1:0,inserted:Z}};export{fn as D,Dn as I,xe as M,L as b,V as l,Bn as r,Ce as u};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{existsSync as l,readFileSync as p,writeFileSync as N,mkdtempSync as F,rmSync as w}from"node:fs";import{tmpdir as G}from"node:os";import{LunoraError as h}from"@lunora/errors";import{dirname as S,join as f}from"@visulima/path";import{downloadTemplate as M}from"giget";import{fileURLToPath as J}from"node:url";import{DEV_VARS_FILE as W,parseDevVariableEntries as z,writeDevVariablesFileAtomically as H}from"@lunora/config";import{modify as k,applyEdits as T,parse as K}from"jsonc-parser";import{b as q}from"./tui-prompts-Dd0pDuNr.mjs";import Y from"./parseManifest-CwPTKdtS.mjs";const Z="alpha",O="main",X=new Set(["alpha","beta","next"]),Q=/^[\w./@-]+$/,ee=e=>!e.includes("..")&&Q.test(e),y=()=>{try{let e=S(J(import.meta.url));for(let t=0;t<6;t+=1){const n=f(e,"package.json");if(l(n)){const r=JSON.parse(p(n,"utf8"));if(r.name==="@lunora/cli"&&typeof r.version=="string")return r.version}const s=S(e);if(s===e)break;e=s}}catch{}return"0.0.0"},D=e=>{if(e==="0.0.0")return Z;const t=e.split("+")[0]??e,n=t.indexOf("-");if(n!==-1){const[s]=t.slice(n+1).split(".");if(s!==void 0&&X.has(s))return s}return O},I=e=>{if(e!==void 0&&e.length>0){if(!ee(e))throw new h("INTERNAL",`invalid --ref "${e}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return e}return D(y())},L="anolilab/lunora",B=/^[0-9a-f]{40}$/iu,P=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,te=new RegExp(String.raw`^v?${P}$`,"u"),ne=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${P}$`,"u"),se=e=>B.test(e)||te.test(e)||ne.test(e),re=()=>{const e=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return e!==void 0&&e.length>0?{authorization:`Bearer ${e}`}:{}},oe=async(e,t=L)=>{try{const n=await fetch(`https://api.github.com/repos/${t}/commits/${encodeURIComponent(e)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...re()},signal:AbortSignal.timeout(1e4)});if(!n.ok)return;const s=await n.json();return typeof s.sha=="string"&&B.test(s.sha)?s.sha:void 0}catch{return}},ie=async(e,t,n)=>{if(se(t))return t;const s=await oe(t,e);return s===void 0?(n.warn(`could not pin ${e}#${t} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),t):(n.info(`pinned ${e}#${t} → ${s}`),s)},ae=async(e,t)=>ie(L,I(e),t),Ce=(e=y())=>`@lunora/cli@${e}`,ce="latest",ue=(e=y())=>{const t=D(e);return t===O?ce:t},de="https://registry.npmjs.org",fe=()=>{const e=process.env.npm_config_registry,t=e!==void 0&&e.length>0?e:de;return t.endsWith("/")?t.slice(0,-1):t},le=async(e,t)=>{try{const n=await fetch(`${fe()}/${e.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return n.ok?(await n.json())["dist-tags"]?.[t]:void 0}catch{return}},xe=async(e,t)=>{const n=new Map;return await Promise.all([...new Set(e)].map(async s=>{const r=await le(s,t);r!==void 0&&n.set(s,r)})),n},pe=e=>{if(!e.startsWith("workspace:"))return e;const t=e.slice(10);return t===""||t==="*"||t==="^"||t==="~"?ue():t},he=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),ge=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,Fe=e=>{const t=f(e,"package.json");if(!l(t))return!1;try{const n=JSON.parse(p(t,"utf8"));return n.dependencies?.lunorash!==void 0||n.devDependencies?.lunorash!==void 0}catch{return!1}},Ge=e=>e.replaceAll(ge,(t,n,s,r)=>`${n}lunorash/${s}${r??""}${n}`),$=(e,t,n,s="dependencies",r=!1)=>{const o=Object.entries(e);if(o.length===0)return[];const a=f(t,"package.json");if(!l(a))return n.warn(`package.json not found at ${a} — skipping dependency updates`),[];let i=p(a,"utf8");const u=JSON.parse(i),c=[];for(const[d,g]of o){if(r&&he.has(d)){n.info(`dep provided by the lunorash umbrella, skipping: ${d}`);continue}if(u.dependencies?.[d]!==void 0||u.devDependencies?.[d]!==void 0){n.info(`dep already present: ${d}`);continue}const x=k(i,[s,d],pe(g),{formattingOptions:{insertSpaces:!0,tabSize:4}});i=T(i,x),c.push(d)}return c.length>0&&(N(a,i,"utf8"),n.success(`added ${String(c.length)} ${s==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${c.join(", ")}`)),c},me=(e,t,n)=>{if(e.length===0)return[];const s=f(t,W),r=l(s)?p(s,"utf8"):"",o=new Set(z(r).map(c=>c.key)),a=[],i=[],u=[];for(const c of e)c.secret&&i.push(c.name),!o.has(c.name)&&(c.description&&u.push(`# ${c.description}`),u.push(`${c.name}=${c.secret?"":c.value??""}`),a.push(c.name));if(a.length>0){const c=r===""||r.endsWith(`
|
|
2
|
+
`)?r:`${r}
|
|
3
|
+
`;H(s,`${c}${u.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`),n.success(`scaffolded ${String(a.length)} env var(s) into .dev.vars: ${a.join(", ")}`)}return i.length>0&&n.info(`set secret value(s) locally in .dev.vars, then for production: ${i.map(c=>`wrangler secret put ${c}`).join("; ")}`),a},E=new Set(["ai","analytics_engine_datasets","browser","d1_databases","durable_objects","hyperdrive","kv_namespaces","mtls_certificates","queues","r2_buckets","send_email","services","vars","vectorize","version_metadata","workflows"]),ye=["binding","name","queue","pattern"],b=e=>{if(!(typeof e!="object"||e===null))for(const t of ye){const n=e[t];if(typeof n=="string"&&n.length>0)return`${t}:${n}`}},ve=(e,t,n,s)=>{const r=new Set(e.map(i=>JSON.stringify(i))),o=new Set(e.map(i=>b(i)).filter(i=>i!==void 0)),a=[];for(const i of t){if(r.has(JSON.stringify(i)))continue;const u=b(i);if(u!==void 0&&o.has(u)){s.warn(`${u.replace(":"," ")} already exists in ${n} — keeping the project's entry and skipping the registry item's. Reconcile by hand if the item needs different settings.`);continue}u!==void 0&&o.add(u),a.push(i)}return a},R=e=>Array.isArray(e),_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,s)=>{const r={};for(const[o,a]of Object.entries(t)){if(!Object.hasOwn(e,o)){r[o]=a;continue}JSON.stringify(e[o])!==JSON.stringify(a)&&s.warn(`${o} already exists in ${n} — keeping the project's value and skipping the registry item's. Reconcile by hand if the item needs different settings.`)}return r},Se=(e,t)=>{let n=K(e);for(const s of t){if(typeof n!="object"||n===null)return;n=n[s]}return n},$e=(e,t)=>{const n=e[0];return n!==void 0&&E.has(n)?!0:(t.warn(`skipping binding "${e.join(".")}" — only resource bindings (${[...E].join(", ")}) may be written, not exec/entrypoint keys`),!1)},m=Symbol("skip-binding"),Ee=(e,t,n)=>{const{value:s}=t,r=t.path.join("."),o=Se(e,t.path);if(R(s)){if(!R(o))return s;const a=ve(o,s,r,n);return a.length===0?m:[...o,...a]}if(_(s)){if(!_(o))return s;const a=we(o,s,r,n);return Object.keys(a).length===0?m:{...o,...a}}return s},be=(e,t,n)=>{if(e.length===0)return[];const r=["wrangler.jsonc","wrangler.json"].map(i=>f(t,i)).find(i=>l(i));if(!r)return n.warn("wrangler.jsonc not found — skipping binding updates"),[];let o=p(r,"utf8");const a=[];for(const i of e){if(!$e(i.path,n))continue;const u=Ee(o,i,n);if(u===m)continue;const c=k(o,[...i.path],u,{formattingOptions:{insertSpaces:!0,tabSize:4}});c.length!==0&&(o=T(o,c),a.push(i.path.join(".")))}return a.length>0&&(N(r,o,"utf8"),n.success(`applied ${String(a.length)} binding(s) to ${r}: ${a.join(", ")}`)),a},Me=(e,t,n,s=!1)=>{const r=[],o=[];return e.deps&&r.push(...$(e.deps,t,n,"dependencies",s)),e.devDependencies&&r.push(...$(e.devDependencies,t,n,"devDependencies",s)),e.bindings&&o.push(...be(e.bindings,t,n)),e.envVars&&me(e.envVars,t,n),{bindings:o,deps:r}},v=e=>e.source!==void 0&&e.source.length>0||e.from!==void 0&&e.from.length>0,Je=async(e,t)=>{const n=e.some(({manifest:c})=>Object.keys(c.deps??{}).length>0||Object.keys(c.devDependencies??{}).length>0),s=e.some(({manifest:c})=>(c.bindings??[]).length>0),r=v(t);if(!n&&!s&&!r||t.yes)return!0;const o=[];n&&o.push("add dependencies to package.json"),s&&o.push("write wrangler.jsonc bindings"),r&&o.push(`come from a custom registry source (${String(t.from??t.source)})`);const a=o.join(", ");if(!process.stdin.isTTY&&t.confirm===void 0)return t.logger.error(`add: stdin is not a TTY and the requested items ${a} — re-run with --yes to confirm`),!1;const u=await(t.confirm??q)(`The requested items ${a}. Continue?`);return u||t.logger.info("add: aborted"),u},U="gh:anolilab/lunora/registry",A=/^[A-Za-z0-9][\w-]*$/u,Re=e=>{if(!A.test(e))throw new h("INTERNAL",`invalid registry item name "${e}" — names must match ${A.source} (letters, digits, "-", "_"; no path separators or "..")`)},_e=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),Ae=e=>v(e)&&e.from===void 0&&!e.allowUnsafeSource&&!_e(e.source??""),We=(e,t)=>Ae(t)?`${e}: refusing --source ${String(t.source)} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`:void 0,V=async(e,t,n)=>{const s=F(f(G(),`lunora-${t}-fetch-`)),r=f(s,t);n.info(`fetching ${e}`);try{const o=await M(e,{cwd:s,dir:r,force:!0,install:!1,silent:!0});return n.info(o.commit?`resolved ${o.source} @ ${o.commit}`:`resolved ${o.source}`),{cleanup:()=>{w(s,{force:!0,recursive:!0})},directory:r}}catch(o){throw w(s,{force:!0,recursive:!0}),o}},j=new WeakMap,C=async e=>{const t=j.get(e);if(t!==void 0)return t;const n=v(e)?Promise.resolve(I(e.ref)):ae(e.ref,e.logger);return j.set(e,n),n},je=async(e,t,n=U)=>{if(Re(e),t.from!==void 0){const r=f(t.from,e);if(!l(r))throw new h("INTERNAL",`registry item not found in local source: ${r}`);return{cleanup:()=>{},directory:r}}const s=t.source??n;return V(`${s}/${e}#${await C(t)}`,"item",t.logger)},ze=async e=>{if(e.from!==void 0){if(!l(e.from))throw new h("INTERNAL",`registry root not found: ${e.from}`);return{cleanup:()=>{},root:e.from}}const t=e.source??U,{cleanup:n,directory:s}=await V(`${t}#${await C(e)}`,"registry",e.logger);return{cleanup:n,root:s}},Ne=(e,t)=>{const n=JSON.parse(p(f(e,"registry.json"),"utf8"));return Y(n,t)},He=async(e,t)=>{const n=[],s=[],r=new Set,o=new Set,a=async i=>{if(r.has(i))return;if(o.has(i))throw new h("INTERNAL",`cyclic registry dependency detected at "${i}"`);o.add(i);const{cleanup:u,directory:c}=await je(i,t);s.push(u);const d=Ne(c,i);for(const g of d.requires??[])await a(g);o.delete(i),r.add(i),n.push({directory:c,manifest:d})};try{for(const i of e)await a(i)}catch(i){for(const u of s)u();throw i}return{cleanups:s,items:n}};export{y as a,ae as b,je as c,Me as d,Ge as e,He as f,Je as g,ze as h,v as i,pe as j,Ne as k,xe as l,ie as m,ue as n,I as o,Fe as p,Ce as r,We as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./resolve-BWFT7RvE.mjs";import"./catalog-Cbzph90w.mjs";import{r as n,a as o,b as i}from"./commands-CLLQuHqU.mjs";export{n as runAddCommand,o as runBuildIndexCommand,i as runRegistryViewCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{buildSchemaSnapshot as u}from"@lunora/codegen";import{validatorKindToSqlType as r}from"./diffSnapshots-DtC5Cs4Z.mjs";const c=e=>e.kind==="optional"&&e.inner?{nullable:!0,sqlType:r(e.inner.kind)}:{nullable:!1,sqlType:r(e.kind)},f=e=>e.shardMode==="global"&&e.globalBackend!=="hyperdrive",b=e=>{const s={},d=u(e,[]);for(const o of e.tables){if(!f(o))continue;const l={};for(const[n,a]of Object.entries(o.shape)){const i=d.tables[o.name]?.fields[n];l[n]=i===void 0?c(a):{...c(a),field:i}}const t={};for(const n of o.indexes)t[n.name]={fields:[...n.fields],name:n.name,unique:n.unique??!1};s[o.name]={columns:l,indexes:t,name:o.name}}return{tables:s,version:1}};export{b as default};
|