@lunora/cli 1.0.0-alpha.21 → 1.0.0-alpha.211
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +33 -0
- package/README.md +1 -1
- package/__assets__/package-og.svg +1 -1
- package/dist/bin.mjs +2 -10
- package/dist/index.d.mts +745 -341
- package/dist/index.d.ts +745 -341
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/handler.mjs +1 -150
- package/dist/packem_chunks/handler10.mjs +4 -22
- package/dist/packem_chunks/handler11.mjs +2 -192
- package/dist/packem_chunks/handler12.mjs +1 -131
- package/dist/packem_chunks/handler13.mjs +1 -65
- package/dist/packem_chunks/handler14.mjs +1 -58
- package/dist/packem_chunks/handler15.mjs +1 -79
- package/dist/packem_chunks/handler16.mjs +3 -43
- package/dist/packem_chunks/handler17.mjs +1 -105
- package/dist/packem_chunks/handler18.mjs +1 -170
- package/dist/packem_chunks/handler19.mjs +7 -89
- package/dist/packem_chunks/handler2.mjs +2 -114
- package/dist/packem_chunks/handler20.mjs +1 -94
- package/dist/packem_chunks/handler21.mjs +2 -311
- package/dist/packem_chunks/handler22.mjs +3 -0
- package/dist/packem_chunks/handler23.mjs +3 -0
- package/dist/packem_chunks/handler24.mjs +1 -0
- package/dist/packem_chunks/handler25.mjs +99 -0
- package/dist/packem_chunks/handler26.mjs +10 -0
- package/dist/packem_chunks/handler3.mjs +1 -204
- package/dist/packem_chunks/handler4.mjs +1 -33
- package/dist/packem_chunks/handler5.mjs +1 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +3 -42
- package/dist/packem_chunks/handler8.mjs +1 -174
- package/dist/packem_chunks/handler9.mjs +1 -16
- package/dist/packem_chunks/planDevCommand.mjs +7 -500
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDeployCommand.mjs +1 -504
- package/dist/packem_chunks/runInitCommand.mjs +118 -1383
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/COMMANDS-BXbrW8dd.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Cf8ZymM1.mjs +1 -0
- package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +1 -0
- package/dist/packem_shared/admin-url-Cil3Or6N.mjs +1 -0
- package/dist/packem_shared/advisory-gate-Cl8IEFIj.mjs +1 -0
- package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
- package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
- package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
- package/dist/packem_shared/cli-C37AI4tr.mjs +3 -0
- package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
- package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
- package/dist/packem_shared/commands-BNKj7r1R.mjs +19 -0
- package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
- package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +5 -0
- package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
- package/dist/packem_shared/import-CdHdZRjj.mjs +12 -0
- package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
- package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
- package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
- package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
- package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
- package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
- package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
- package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
- package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
- package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
- package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +1 -0
- package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
- package/dist/packem_shared/schema-drift-gate-DARCKocg.mjs +1 -0
- package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
- package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
- package/dist/packem_shared/storage-wIUel5Az.mjs +1 -0
- package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
- package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
- package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
- package/package.json +39 -17
- package/skills/README.md +35 -17
- package/skills/lunora/SKILL.md +65 -9
- package/skills/lunora-functions/SKILL.md +38 -3
- package/skills/lunora-migration-helper/SKILL.md +70 -17
- package/skills/lunora-performance-audit/SKILL.md +36 -6
- package/skills/lunora-quickstart/SKILL.md +90 -24
- package/skills/lunora-realtime/SKILL.md +58 -30
- package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
- package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
- package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
- package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
- package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
- package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
- package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
- package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
- package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
- package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
- package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
- package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
- package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
- package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
- package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
- package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
- package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
- package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
- package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
- package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
- package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{mkdirSync as O,readFileSync as w,lstatSync as A,writeFileSync as D}from"node:fs";import{join as u,dirname as f}from"node:path";import{fileURLToPath as B}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}from"./api-spec-lYyq4vL6.mjs";import{T as s}from"./deploy-target-D9GPy_tq.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{createLogger as S}from"./createLogger-hGafwf-3.mjs";import{VisulimaError as U,renderError as M}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/handler23.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:`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","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 (deploy even with breaking schema drift and no migration)",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/handler24.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/handler21.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 (proceed even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},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/handler22.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 (local dev by default, --remote for production)",examples:[["lunora view","Open the studio for local dev"],["lunora view --remote","Open the deployed studio"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},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 U({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="",M(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},Ne=(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},Re=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Oe=1440*60*1e3,Ae=1500,De="0.0.0",Be=/^v/u,Ee=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Be,""),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,Ue=(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"),Me=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{}D(r,`${JSON.stringify(t)}
|
|
3
|
+
`,"utf8")}catch{}},Je=async(e,t)=>{try{const r=await e(Re(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===De||!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??Me(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ie(e.current),d=We(o),R=d?.tag??"latest",g=d!==void 0&&R===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(Ue(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(B(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],N=[...Ge,T,I],mt=N.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 N)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=Ne(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.")},gt=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,mt as R,C as V,gt as r};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{findLunoraSolution as i}from"@lunora/codegen";import{VisulimaError as s,renderError as a}from"@visulima/error";const d=n=>n.body.split(`
|
|
2
|
+
`).filter(e=>!e.startsWith("```")).join(`
|
|
3
|
+
`).replaceAll(/\*\*(.+?)\*\*/gu,"$1").replaceAll(/`([^`]+)`/gu,"$1"),l={filterStacktrace:()=>!1,hideErrorCodeView:!0},g=(n,e)=>{const r=n instanceof Error?n.message:String(n),o=i(r),t=new s({hint:o?[o.header,"",d(o)]:void 0,message:e===void 0?`codegen failed: ${r}`:`codegen failed (${e}): ${r}`,name:"CodegenError"});return t.stack="",a(t,l)},f=n=>{const e=i(n);if(e===void 0)return;const r=new s({hint:[d(e)],message:e.header,name:"Hint"});return r.stack="",a(r,l)};export{g as a,f as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger as n}from"./createLogger-hGafwf-3.mjs";import{P as t,a}from"./prompt-cancelled-C8Sj7OqI.mjs";const p=c=>async r=>{const s=n();try{const{code:e}=await c({argument:r.argument,cwd:r.process.cwd,logger:s,options:r.options});r.process.exit(e)}catch(e){if(e instanceof t){r.process.exit(a);return}s.error(e instanceof Error?e.message:String(e)),r.process.exit(1)}};export{p as d};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{existsSync as m,readFileSync as h,writeFileSync as $,mkdirSync as S,lstatSync as q}from"node:fs";import{join as l,relative as J,dirname as w}from"@visulima/path";import{DEV_VARS_FILE as U,parseDevVariableEntries as G,writeDevVariablesFileAtomically as H,installArgsFor as Y,detectPackageManager as z}from"@lunora/config";import{modify as F,applyEdits as T,parse as X}from"jsonc-parser";import{d as Q,s as j,e as Z,f as K,c as ee,g as ne}from"./resolve-DZAGzg67.mjs";import{b as te}from"./tui-prompts-Dd0pDuNr.mjs";import{collectCatalog as re,buildRegistryIndex as se}from"./buildRegistryIndex-Zi3bBqpc.mjs";import{findWranglerFile as ie,readWranglerJsonc as oe}from"@lunora/config/cloudflare";import{LunoraError as x}from"@lunora/errors";import{insertSchemaExtension as ae}from"./insertSchemaExtension-DY4pA8wE.mjs";import{createHash as ce}from"node:crypto";const C=e=>{if(!e.startsWith("workspace:"))return e;const n=e.slice(10);return n===""||n==="*"||n==="^"||n==="~"?Q():n},de=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),ue=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,fe=e=>{const n=l(e,"package.json");if(!m(n))return!1;try{const t=JSON.parse(h(n,"utf8"));return t.dependencies?.lunorash!==void 0||t.devDependencies?.lunorash!==void 0}catch{return!1}},le=e=>e.replaceAll(ue,(n,t,i,r)=>`${t}lunorash/${i}${r??""}${t}`),O=(e,n,t,i="dependencies",r=!1)=>{const s=Object.entries(e);if(s.length===0)return[];const o=l(n,"package.json");if(!m(o))return t.warn(`package.json not found at ${o} — skipping dependency updates`),[];let a=h(o,"utf8");const c=JSON.parse(a),d=[];for(const[u,f]of s){if(r&&de.has(u)){t.info(`dep provided by the lunorash umbrella, skipping: ${u}`);continue}if(c.dependencies?.[u]!==void 0||c.devDependencies?.[u]!==void 0){t.info(`dep already present: ${u}`);continue}const p=F(a,[i,u],C(f),{formattingOptions:{insertSpaces:!0,tabSize:4}});a=T(a,p),d.push(u)}return d.length>0&&($(o,a,"utf8"),t.success(`added ${String(d.length)} ${i==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${d.join(", ")}`)),d},pe=(e,n,t)=>{if(e.length===0)return[];const i=l(n,U),r=m(i)?h(i,"utf8"):"",s=new Set(G(r).map(d=>d.key)),o=[],a=[],c=[];for(const d of e)d.secret&&a.push(d.name),!s.has(d.name)&&(d.description&&c.push(`# ${d.description}`),c.push(`${d.name}=${d.secret?"":d.value??""}`),o.push(d.name));if(o.length>0){const d=r===""||r.endsWith(`
|
|
2
|
+
`)?r:`${r}
|
|
3
|
+
`;H(i,`${d}${c.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`),t.success(`scaffolded ${String(o.length)} env var(s) into .dev.vars: ${o.join(", ")}`)}return a.length>0&&t.info(`set secret value(s) locally in .dev.vars, then for production: ${a.map(d=>`wrangler secret put ${d}`).join("; ")}`),o},R=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"]),me=["binding","name","queue","pattern"],D=e=>{if(!(typeof e!="object"||e===null))for(const n of me){const t=e[n];if(typeof t=="string"&&t.length>0)return`${n}:${t}`}},he=(e,n,t,i)=>{const r=new Set(e.map(a=>JSON.stringify(a))),s=new Set(e.map(a=>D(a)).filter(a=>a!==void 0)),o=[];for(const a of n){if(r.has(JSON.stringify(a)))continue;const c=D(a);if(c!==void 0&&s.has(c)){i.warn(`${c.replace(":"," ")} already exists in ${t} — keeping the project's entry and skipping the registry item's. Reconcile by hand if the item needs different settings.`);continue}c!==void 0&&s.add(c),o.push(a)}return o},N=e=>Array.isArray(e),ge=(e,n)=>{let t=X(e);for(const i of n){if(typeof t!="object"||t===null)return;t=t[i]}return t},$e=(e,n)=>{const t=e[0];return t!==void 0&&R.has(t)?!0:(n.warn(`skipping binding "${e.join(".")}" — only resource bindings (${[...R].join(", ")}) may be written, not exec/entrypoint keys`),!1)},B=Symbol("skip-binding"),ve=(e,n,t)=>{const{value:i}=n;if(!N(i))return i;const r=ge(e,n.path);if(!N(r))return i;const s=he(r,i,n.path.join("."),t);return s.length===0?B:[...r,...s]},ye=(e,n,t)=>{if(e.length===0)return[];const r=["wrangler.jsonc","wrangler.json"].map(a=>l(n,a)).find(a=>m(a));if(!r)return t.warn("wrangler.jsonc not found — skipping binding updates"),[];let s=h(r,"utf8");const o=[];for(const a of e){if(!$e(a.path,t))continue;const c=ve(s,a,t);if(c===B)continue;const d=F(s,[...a.path],c,{formattingOptions:{insertSpaces:!0,tabSize:4}});d.length!==0&&(s=T(s,d),o.push(a.path.join(".")))}return o.length>0&&($(r,s,"utf8"),t.success(`applied ${String(o.length)} binding(s) to ${r}: ${o.join(", ")}`)),o},we=(e,n,t,i=!1)=>{const r=[],s=[];return e.deps&&r.push(...O(e.deps,n,t,"dependencies",i)),e.devDependencies&&r.push(...O(e.devDependencies,n,t,"devDependencies",i)),e.bindings&&s.push(...ye(e.bindings,n,t)),e.envVars&&pe(e.envVars,n,t),{bindings:s,deps:r}},ke=async(e,n)=>{const t=e.some(({manifest:d})=>Object.keys(d.deps??{}).length>0||Object.keys(d.devDependencies??{}).length>0),i=e.some(({manifest:d})=>(d.bindings??[]).length>0),r=n.source!==void 0&&n.source.length>0;if(!t&&!i&&!r||n.yes)return!0;const s=[];t&&s.push("add dependencies to package.json"),i&&s.push("write wrangler.jsonc bindings"),r&&s.push(`come from a non-default source (${String(n.source)})`);const o=s.join(", ");if(!process.stdin.isTTY&&n.confirm===void 0)return n.logger.error(`add: stdin is not a TTY and the requested items ${o} — re-run with --yes to confirm`),!1;const c=await(n.confirm??te)(`The requested items ${o}. Continue?`);return c||n.logger.info("add: aborted"),c},b=1,be=".lunora-registry.json",V=e=>l(e,"lunora",be),Se=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,y=e=>ce("sha256").update(e).digest("hex"),xe=e=>{const n=V(e);if(!m(n))return{items:{},version:b};try{const t=JSON.parse(h(n,"utf8"));if(Se(t))return{items:t.items,version:b}}catch{}return{items:{},version:b}},je=(e,n)=>{$(V(e),`${JSON.stringify(n,void 0,2)}
|
|
6
|
+
`,"utf8")},A=(e,n,t,i)=>{const r=e.items[n]??{files:{}};e.items[n]=r,r.files[t]=y(i)},Ee=(e,n,t)=>e.items[n]?.files[t],_=3,L=e=>e===""?[]:e.split(`
|
|
7
|
+
`),Oe=(e,n)=>{const t=L(e),i=L(n);let r=0;for(;r<t.length&&r<i.length&&t[r]===i[r];)r+=1;let s=t.length,o=i.length;for(;s>r&&o>r&&t[s-1]===i[o-1];)s-=1,o-=1;if(r===s&&r===o)return[];const a=[];for(let c=Math.max(0,r-_);c<r;c+=1)a.push(` ${t[c]??""}`);for(let c=r;c<s;c+=1)a.push(`- ${t[c]??""}`);for(let c=r;c<o;c+=1)a.push(`+ ${i[c]??""}`);for(let c=o;c<Math.min(i.length,o+_);c+=1)a.push(` ${i[c]??""}`);return a},Re=/\.[cm]?[jt]sx?$/u,E=(e,n,t,i)=>{const r=l(e,n.from);if(q(r).isSymbolicLink())throw new x("INTERNAL",`registry item "${i}": refusing to read "${n.from}" — it is a symlink, not a regular file`);const s=h(r,"utf8");return t&&Re.test(n.to)?le(s):s},De=(e,n,t,i,r,s,o)=>{const a=l(i,"lunora","schema.ts");if(s)return r.info(`~ would merge .extend(${n}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:a};const c=l(i,e.to);m(c)||(S(w(c),{recursive:!0}),$(c,E(t,e,o,n),"utf8"));const d=o?"lunorash/server":"@lunora/server",u=m(a)?h(a,"utf8"):`import { defineSchema } from "${d}";
|
|
8
|
+
|
|
9
|
+
export const schema = defineSchema({});
|
|
10
|
+
`,f=ae(u,n);if(f.ok)return S(w(a),{recursive:!0}),$(a,f.text,"utf8"),r.success(`merged .extend(${n}.extension) into lunora/schema.ts`),{kind:"written",path:a};if(f.reason==="already-applied")return r.warn(`lunora/schema.ts already extends "${n}" — skipping`),{kind:"skipped",path:a};throw f.reason==="invalid-identifier"?new x("INTERNAL",`schema-extension item "${n}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${n} }\` / \`.extend(${n}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new x("INTERNAL",`schema-extension merge failed for "${n}": ${f.reason}`)},Ne=(e,n,t,i,r)=>{const s=Oe(n,t);if(s.length===0){r.info(`= ${e.to} (unchanged)`);return}r.info(`${i?"~":"+"} ${e.to}`);for(const o of s)r.info(` ${o}`)},Ae=(e,n,t,i,r,s,o,a)=>{const c=l(i,e.to),d=E(t,e,a,n),u=m(c),f=u?h(c,"utf8"):"",p=M=>(S(w(c),{recursive:!0}),$(c,d,"utf8"),A(s,n,e.to,d),r.success(`${M}: ${e.to}`),{kind:"written",path:c});if(o.diff)return Ne(e,f,d,u,r),{kind:"skipped",path:c};if(!u)return p("write");const g=y(f);if(g===y(d))return A(s,n,e.to,d),r.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:c};if(o.overwrite)return p("overwrite");const v=Ee(s,n,e.to);return v===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:c}):v===g?p("update"):v===y(d)?(r.warn(`skip (locally edited): ${e.to}`),{kind:"skipped",path:c}):($(`${c}.new`,d,"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:c})},_e=(e,n,t,i,r,s,o={},a=!1)=>e.merge==="schema-extension"?De(e,n,t,i,r,o.diff===!0,a):Ae(e,n,t,i,r,s,o,a),P=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],Le=e=>{const n=ie(e);if(n===void 0)return;const{parsed:t}=oe(n);return typeof t?.main=="string"?t.main:void 0},Pe=e=>{const n=Le(e),t=n===void 0?P:[n,...P];for(const i of t){const r=l(e,i);if(!m(r))continue;const s=h(r,"utf8");if(!s.includes("createShardDO(")){if(i===n)break;continue}return{entryPath:r,main:i,source:s}}},Ie=(e,n,t)=>{const i=J(w(e),l(n,"lunora",t)).replaceAll("\\","/");return i.startsWith(".")?i:`./${i}`},Je=(e,n)=>{for(const t of e){const r=`Add \`export * from "${`./lunora/${t.module}.js`}"\` to your worker entry`,s=t.comment?` (${t.comment})`:"";n.warn(`${r}${s}`)}return 0},Fe=(e,n,t,i)=>{const r=[];for(const s of e){const o=Ie(n,t,s.module),a=o.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${a}\.js["']`,"u").test(i)||(s.comment&&r.push(`
|
|
11
|
+
// ${s.comment}`),r.push(`export * from "${o}.js";`))}return r},Te=(e,n,t,i)=>{if(e.length===0)return 0;const r=Pe(n);if(r===void 0)return Je(e,t);const s=Fe(e,r.entryPath,n,r.source);if(s.length===0)return 0;if(i){for(const a of s)a!==""&&t.info(`~ entrypoint: ${a}`);return s.length}const o=r.source.endsWith(`
|
|
12
|
+
`)?"":`
|
|
13
|
+
`;return $(r.entryPath,`${r.source}${o}${s.join(`
|
|
14
|
+
`)}
|
|
15
|
+
`,"utf8"),t.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${J(n,r.entryPath)}`),s.length},I=(e,n,t,i={})=>{const r=[],s=[],o=[],a=[],c=xe(n),d=fe(n);for(const{directory:u,manifest:f}of e){for(const g of f.files){const v=_e(g,f.name,u,n,t,c,i,d);(v.kind==="written"?r:s).push(v.path)}if(f.entrypointReexports!==void 0&&Te(f.entrypointReexports,n,t,i.diff===!0),i.diff)continue;const p=we(f,n,t,d);o.push(...p.deps),a.push(...p.bindings)}return!i.diff&&Object.keys(c.items).length>0&&je(n,c),{bindings:a,deps:o,skipped:s,written:r}},k=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),en=(e,n,t,i,r)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==n||!Array.isArray(s.value))return s;const o=s.value;return{...s,value:o.map(a=>typeof a=="object"&&a!==null&&a[t.key]===t.value?{...a,[i]:r}:a)}})}:e,W=(e,n)=>{const t=n.title??n.description;e.info(`plan: ${n.name}${t?` — ${t}`:""}`);for(const s of n.files)e.info(` file ${s.to} (${s.merge})`);const i=new Map,r=s=>{const o=i.get(s);if(o!==void 0)return o;const a=C(s);return i.set(s,a),a};for(const[s,o]of Object.entries(n.deps??{}))e.info(` dep ${s}@${r(o)}`);for(const[s,o]of Object.entries(n.devDependencies??{}))e.info(` dev ${s}@${r(o)}`);for(const s of n.bindings??[])e.info(` bind ${s.path.join(".")} = ${JSON.stringify(s.value)}`);for(const s of n.envVars??[]){const o=s.secret?" (secret)":` = ${JSON.stringify(s.value??"")}`;e.info(` env ${s.name}${o}`)}for(const s of n.entrypointReexports??[]){const o=`./lunora/${s.module}`,a=s.comment?` // ${s.comment}`:"";e.info(` entry ${o}${a}`)}},Ce=e=>{const n=e.map(({manifest:t})=>({bindings:(t.bindings??[]).map(i=>({path:i.path.join("."),value:i.value})),deps:Object.keys(t.deps??{}),devDependencies:Object.keys(t.devDependencies??{}),entrypointReexports:(t.entrypointReexports??[]).map(i=>({module:i.module,...i.comment?{comment:i.comment}:{}})),envVars:(t.envVars??[]).map(i=>({name:i.name,...i.secret?{secret:!0}:{value:i.value??""}})),files:t.files.map(i=>({merge:i.merge,to:i.to})),name:t.name,requires:t.requires??[],title:t.title}));process.stdout.write(`${JSON.stringify({items:n},void 0,2)}
|
|
16
|
+
`)},Be=e=>{try{const{args:n,command:t}=Y(z(e));return`${t} ${n.join(" ")}`}catch{return"<your-package-manager> install"}},Ve=(e,n,t,i,r,s)=>{r.success(`add complete: ${String(t)} written, ${String(i)} skipped`),r.info("next steps:"),r.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),n.length>0&&r.info(` ${Be(s)} # install newly-added dependencies`);for(const{manifest:o}of e)o.docs&&r.info(`${o.name}: ${o.docs}`)},We=async e=>{const n=k(),t=j("list",e);if(t)return e.logger.error(t),{...n,code:1};let i=()=>{};try{const r=await K(e);i=r.cleanup;const s=re(r.root);if(e.json)return process.stdout.write(`${JSON.stringify(s,void 0,2)}
|
|
17
|
+
`),n;e.logger.info(`available registry items (${String(s.length)}):`);for(const o of s)e.logger.info(` ${o.name}${o.description?` — ${o.description}`:""}`);return n}catch(r){return e.logger.error(`list failed: ${r instanceof Error?r.message:String(r)}`),{...n,code:1}}finally{i()}},nn=async e=>{const n=e.cwd??process.cwd(),t=k();if(e.list)return We(e);if(e.names.length===0)return e.logger.error("add requires at least one item name. Usage: lunora registry add <name> [...names]"),{...t,code:1};const i=j("add",e);if(i)return e.logger.error(i),{...t,code:1};let r=[];try{const{cleanups:s,items:o}=await Z(e.names,e);r=s;const{transformManifest:a}=e,c=a?o.map(g=>({...g,manifest:a(g.manifest)})):o;for(const{manifest:g}of c)W(e.logger,g);if(e.json&&Ce(c),e.dryRun)return e.logger.info("dry-run: stopping before any files are written"),t;if(e.diff)return I(c,n,e.logger,{diff:!0}),e.logger.info("diff: preview only — re-run without --diff to apply"),t;if(!await ke(c,e))return{...t,code:1};const{bindings:d,deps:u,skipped:f,written:p}=I(c,n,e.logger,{overwrite:e.overwrite});return Ve(c,u,p.length,f.length,e.logger,n),{bindings:d,code:0,deps:u,skipped:f,written:p}}catch(s){return e.logger.error(`add failed: ${s instanceof Error?s.message:String(s)}`),{...t,code:1}}finally{for(const s of r)s()}},tn=async e=>{const n=k();if(e.names.length===0)return e.logger.error("view requires an item name. Usage: lunora registry view <name>"),{...n,code:1};const t=j("view",e);if(t)return e.logger.error(t),{...n,code:1};const i=[];try{for(const r of e.names){const{cleanup:s,directory:o}=await ee(r,e);i.push(s);const a=ne(o,r);W(e.logger,a);for(const c of a.files){e.logger.info(`--- ${c.to} (${c.merge}) ---`);const d=E(o,c,!1,r);for(const u of d.split(`
|
|
18
|
+
`))e.logger.info(u)}}return n}catch(r){return e.logger.error(`view failed: ${r instanceof Error?r.message:String(r)}`),{...n,code:1}}finally{for(const r of i)r()}},rn=async e=>{const n=k(),t=e.from;if(t===void 0)return e.logger.error("registry build requires --from <registry root>"),{...n,code:1};if(!m(t))return e.logger.error(`registry root not found: ${t}`),{...n,code:1};const i=se(t),r=e.out??l(t,"index.json");if(e.check){const s=m(r)?JSON.parse(h(r,"utf8")):{items:[]};return JSON.stringify(s.items??[])!==JSON.stringify(i.items)?(e.logger.error(`registry: ${r} is stale — run \`lunora registry build\` to regenerate it`),{...n,code:1}):(e.logger.success(`registry: ${r} is up to date (${String(i.items.length)} items)`),n)}return $(r,`${JSON.stringify({$schema:"./schema/registry.schema.json",...i},void 0,4)}
|
|
19
|
+
`,"utf8"),e.logger.success(`registry: wrote ${r} (${String(i.items.length)} items)`),n};export{rn as a,tn as b,nn as r,en as s};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{STEP_BADGE_NAMES as u,LunoraReporter as i}from"@lunora/config";import{JsonReporter as a}from"@visulima/pail/reporter/json";import{createPail as p}from"@visulima/pail/server";let n,c=!1;const g=()=>{if(c)return!0;const r=process.env.LUNORA_LOG_JSON;return r==="1"||r==="true"},l=r=>new r,f=()=>[l(g()?a:i)],L=()=>{c||(c=!0,n=void 0)},d=Object.fromEntries(u.map(r=>[r,{label:r,logLevel:"informational"}])),o=()=>(n??=p({reporters:f(),scope:["lunora"],stderr:process.stderr,stdout:process.stdout,types:d}),n),P=()=>({debug:r=>{o().debug(r)},error:r=>{o().error(r)},info:r=>{o().info(r)},success:r=>{o().success(r)},warn:r=>{o().warn(r)}}),S=()=>{const r=(e,t)=>{process.stderr.write(`${e} ${t}
|
|
2
|
+
`)};return{debug:e=>{r("debug",e)},error:e=>{r("error",e)},info:e=>{r("info ",e)},success:e=>{r("ok ",e)},warn:e=>{r("warn ",e)}}},_=new Proxy({},{get(r,e){const t=o(),s=t[e];return typeof s=="function"?s.bind(t):s}}),E=(r,e)=>{o()[r](e)};export{P as createLogger,S as createStderrLogger,L as forceJsonLogging,E as logStep,_ as pail};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as S}from"node:child_process";const f=/[\s"%&<>^|]/u,w=/(\\*)"/gu,h=/(\\+)$/u,g=(t,s,a=process.platform)=>{if(a!=="win32"||t===process.execPath)return{args:[...s],command:t,shell:!1};const o=e=>e===""?'""':f.test(e)?`"${e.replaceAll(w,String.raw`$1$1\"`).replace(h,"$1$1")}"`:e;return{args:s.map(e=>o(e)),command:o(t),shell:!0}},_=t=>new Promise((s,a)=>{const o=typeof t.input=="string",e=t.captureStdout===!0,u=t.captureStdoutSilently===!0;let c="inherit";e||u?c="pipe":t.stdoutToStderr&&(c=2);const p=g(t.command,t.args),r=S(p.command,p.args,{cwd:t.cwd??process.cwd(),env:t.env?{...process.env,...t.env}:process.env,shell:p.shell,stdio:[o?"pipe":"inherit",c,t.captureStderr===!0?"pipe":"inherit"]});let i="",d="";t.captureStderr===!0&&r.stderr&&r.stderr.on("data",n=>{d+=n.toString("utf8"),process.stderr.write(n)}),(e||u)&&r.stdout&&r.stdout.on("data",n=>{i+=n.toString("utf8"),e&&process.stdout.write(n)}),r.on("error",n=>{a(n)}),r.on("exit",(n,l)=>{s({code:n??(l?1:0),stderr:t.captureStderr===!0?d:void 0,stdout:e||u?i:void 0})}),o&&r.stdin&&(r.stdin.on("error",()=>{}),r.stdin.end(t.input))}),A=(t=0)=>{const s=[];return{calls:s,spawner:o=>(s.push({descriptor:o}),Promise.resolve({code:t}))}};export{A as createRecordingSpawner,_ as defaultSpawner,g as spawnShellCompat};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{deployTargetIds as o,DEFAULT_DEPLOY_TARGET as n,resolveTargetOrThrow as s}from"@lunora/config";const a=(()=>{const r=o();return r.length>1?`${r.join(" | ")} (default ${n})`:r.join(" | ")})(),g={description:`Deploy target: ${a}. Also settable as "target" in lunora.json`,name:"target",type:String},i=(r,e)=>{try{return{target:s(r,e)}}catch(t){return{error:t instanceof Error?t.message:String(t)}}};export{g as T,i as r};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{quoteIdentifier as u,sqlAffinityForKind as y,frameworkColumnDdl as T,MAX_D1_TABLE_COLUMNS as a,columnRef as $,physicalIndexName as d}from"@lunora/d1/dialect";import{LunoraError as h}from"@lunora/errors";const R=e=>y(e),c=(e,n)=>{const s=[u(e),n.sqlType];return n.nullable||s.push("NOT NULL"),s.join(" ")},E=e=>{const n=Object.entries(e.columns).map(([i,r])=>` ${c(i,r)}`),s=T(),o=s.length+n.length;if(o>a)throw new h("VALIDATION_ERROR",`table "${e.name}" needs ${String(o)} columns, over D1's ${String(a)}-column limit — split the table, or move the extra fields into one object field`);const t=[...s.map(i=>` ${i}`),...n].join(`,
|
|
2
|
+
`);return`CREATE TABLE IF NOT EXISTS ${u(e.name)} (
|
|
3
|
+
${t}
|
|
4
|
+
);`},L=e=>`DROP TABLE IF EXISTS ${u(e)};`,O=(e,n,s)=>`ALTER TABLE ${u(e)} ADD COLUMN ${c(n,s)};`,m=(e,n)=>{const s=n.fields.map(t=>$(t)).join(", ");return`CREATE ${n.unique?"UNIQUE ":""}INDEX IF NOT EXISTS ${d(e,n.name)} ON ${u(e)} (${s});`},g=(e,n)=>`DROP INDEX IF EXISTS ${d(e,n)};`,I=(e,n,s,o,t)=>{s.sqlType!==o.sqlType&&t.push({kind:"columnTypeChange",summary:`column type change on ${e}.${n}: ${s.sqlType} → ${o.sqlType} (write SQL manually)`}),s.nullable!==o.nullable&&t.push({kind:"columnTypeChange",summary:`nullability change on ${e}.${n}: ${s.nullable?"NULL":"NOT NULL"} → ${o.nullable?"NULL":"NOT NULL"} (write SQL manually)`})},q=(e,n,s,o,t)=>{for(const[i,r]of Object.entries(s)){const l=n[i];if(l===void 0){o.push({kind:"addColumn",sql:O(e,i,r),summary:`ADD COLUMN ${e}.${i}`});continue}I(e,i,l,r,t)}for(const i of Object.keys(n))s[i]===void 0&&t.push({kind:"dropColumn",summary:`DROP COLUMN ${e}.${i} (SQLite drop-column requires careful migration — write SQL manually)`})},C=(e,n,s,o,t)=>{for(const[i,r]of Object.entries(s)){const l=n[i];if(l===void 0){o.push({kind:"createIndex",sql:m(e,r),summary:`CREATE INDEX ${i} ON ${e}`});continue}(!(l.fields.length===r.fields.length&&l.fields.every((f,p)=>f===r.fields[p]))||l.unique!==r.unique)&&t.push({kind:"indexRename",summary:`index ${i} changed on ${e} — drop+create manually if intentional`})}for(const i of Object.keys(n))s[i]===void 0&&o.push({kind:"dropIndex",sql:g(e,i),summary:`DROP INDEX ${i}`})},N=(e,n,s)=>{s.push({kind:"createTable",sql:E(n),summary:`CREATE TABLE ${e}`});for(const o of Object.values(n.indexes))s.push({kind:"createIndex",sql:m(e,o),summary:`CREATE INDEX ${o.name} ON ${e}`})},S=(e,n)=>{const s=e?.tables??{},o=[],t=[];for(const[i,r]of Object.entries(n.tables)){const l=s[i];if(l===void 0){N(i,r,o);continue}q(i,l.columns,r.columns,o,t),C(i,l.indexes,r.indexes,o,t)}for(const i of Object.keys(s))n.tables[i]===void 0&&o.push({kind:"dropTable",sql:L(i),summary:`DROP TABLE ${i}`});return{empty:o.length===0&&t.length===0,entries:o,unsupported:t}},k=(e,n,s)=>{const o=[`-- Lunora migration: ${e}`,`-- Generated at ${s}`,"-- This file was produced by `lunora migrate generate`. Review carefully before applying.",""];for(const t of n.entries)o.push(`-- ${t.summary}`,t.sql,"");if(n.unsupported.length>0){o.push("-- ---------------------------------------------------------------","-- The following deltas are NOT auto-generated in v0.1.","-- Write the appropriate SQL below by hand:","--");for(const t of n.unsupported)o.push(`-- * ${t.summary}`);o.push("-- ---------------------------------------------------------------","")}return n.empty&&o.push("-- No changes detected. Re-running `lunora migrate generate` will overwrite this file.",""),o.join(`
|
|
5
|
+
`)};export{S as diffSnapshots,O as renderAddColumn,m as renderCreateIndex,E as renderCreateTable,g as renderDropIndex,L as renderDropTable,k as renderMigrationFile,R as validatorKindToSqlType};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawnSync as r}from"node:child_process";const s=()=>{try{return r("docker",["info"],{stdio:"ignore"}).status===0}catch{return!1}},t=()=>{if(typeof process.env.BUILDKIT_HOST!="string"||process.env.BUILDKIT_HOST.length===0)return!1;try{return r("railpack",["--version"],{stdio:"ignore"}).status===0}catch{return!1}};export{t as a,s as i};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{createReadStream as N}from"node:fs";import{open as Ge,stat as R,readdir as O,realpath as te,readFile as $,mkdir as F,writeFile as fe,appendFile as We}from"node:fs/promises";import{r as Ye}from"./admin-token-rxXZbVMZ.mjs";import{r as Ke}from"./admin-url-Cil3Or6N.mjs";import{join as y,resolve as C,basename as p,dirname as he,relative as Xe,sep as qe}from"node:path";import{createInterface as j}from"node:readline";import Ze from"adm-zip";import{i as ge}from"./path-containment-CgxYZggb.mjs";import{Transform as Qe}from"node:stream";import{createInflateRaw as et,crc32 as tt}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{parse as rt}from"csv-parse/sync";import{parse as me}from"csv-parse";import{STORAGE_UPLOAD_MAX_BODY_BYTES as nt}from"@lunora/runtime";import{S as z,a as st,I as ot}from"./shared-D-zCOmgY.mjs";import{createHash as it}from"node:crypto";const at=67324752,A=30,ct=26,dt=28,re=0,lt=8,ut=async(e,t)=>{const r=await Ge(e,"r");try{const n=Buffer.alloc(A),{bytesRead:s}=await r.read(n,0,A,t);if(s<A||n.readUInt32LE(0)!==at)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+A+n.readUInt16LE(ct)+n.readUInt16LE(dt)}finally{await r.close()}},ne=e=>{let t=0;return new Qe({flush(r){if(t===e.header.crc){r();return}r(new Error(`${e.entryName} failed its CRC check — the archive is corrupt or truncated (expected ${String(e.header.crc)}, read ${String(t)})`))},transform(r,n,s){t=tt(r,t),s(void 0,r)}})},ft=async(e,t)=>{const{compressedSize:r,encrypted:n,method:s,offset:o}=t.header;if(n)throw new Error(`${t.entryName} is encrypted — decrypt the archive before importing`);if(s!==re&&s!==lt)throw new Error(`${t.entryName} uses unsupported compression method ${String(s)} — re-create the archive with standard deflate`);if(r===0){if(t.header.size>0||t.header.crc!==0)throw new Error(`${t.entryName} declares 0 compressed bytes but ${String(t.header.size)} uncompressed with CRC ${String(t.header.crc)} — the archive is corrupt`);return}const i=await ut(e,o),a=N(e,{end:i+r-1,start:i});if(s===re){const l=ne(t);return a.on("error",u=>l.destroy(u)),a.pipe(l)}const c=et(),d=ne(t);return a.on("error",l=>c.destroy(l)),c.on("error",l=>d.destroy(l)),a.pipe(c).pipe(d)},E="_storage",pe=e=>e.startsWith("_"),ht=e=>{for(const t of e.getEntries()){const n=t.entryName.replaceAll("\\","/").split("/");if(n.length>=2&&n[n.length-2]==="_storage")return n.slice(0,-1).join("/")}return"_storage"},gt=async e=>{const t=await R(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new Ze(e);return{kind:"zip",storagePrefix:ht(r),zip:r,zipPath:e}}},mt=async e=>{const t=[];for(const r of await O(e,{withFileTypes:!0})){if(!r.isDirectory())continue;const n=y(e,r.name,"documents.jsonl");(await R(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},pt=e=>{const t=[];for(const r of e.getEntries()){if(r.isDirectory)continue;const n=r.entryName.replaceAll("\\","/"),s=n.split("/");s.length>=2&&s[s.length-1]==="documents.jsonl"&&t.push({file:n,table:s[s.length-2]})}return t},yt=async e=>{const t=e.kind==="directory"?await mt(e.root):pt(e.zip);return t.length>0?t.toSorted((r,n)=>r.table.localeCompare(n.table)):void 0},M=async function*(e,t){if(e.kind==="directory"){for await(const o of j({crlfDelay:Number.POSITIVE_INFINITY,input:N(t.file,{encoding:"utf8"})}))yield o;return}const r=e.zip.getEntry(t.file);if(r===null)throw new Error(`missing ${t.file} in archive`);const n=await ft(e.zipPath,r);if(n===void 0)return;const s=j({crlfDelay:Number.POSITIVE_INFINITY,input:n});try{for await(const o of s)yield o}finally{s.close(),n.destroy()}},bt=async(e,t)=>{if(e.kind==="directory"){const n=await te(y(e.root,"_storage")),s=await te(C(n,t)).catch(()=>{});if(s===void 0||!ge(n,s))throw new Error(`blob ${t} resolves outside the snapshot's _storage directory`);return $(s)}const r=e.zip.readFile(`${e.storagePrefix}/${t}`);if(r===null)throw new Error(`missing blob ${t} in archive`);return Buffer.from(r)},x=207,wt=e=>{const t={conflicts:0,errors:[],failed:[],inserted:{},received:0,warnings:[]};let r=[],n=0;const s=a=>{for(const[c,d]of Object.entries(a.inserted??{}))t.inserted[c]=(t.inserted[c]??0)+d;t.errors.push(...a.errors??[]),t.failed.push(...a.failed??[]),t.conflicts+=a.conflicts??0,t.received+=a.received??0;for(const c of a.warnings??[])t.warnings.includes(c)||t.warnings.push(c)},o=async()=>{if(r.length===0)return;const a=r.join(`
|
|
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}},$t=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
|
+
`}},$e=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],St=e=>$e.includes(e),vt=/^\\x([\dA-Fa-f]*)$/,se=/^[+-]?\d+$/,Se=/[+-]\d{2}$/,ve=/(?:Z|[+-]\d{2}:\d{2})$/i,Ne=/^\+/,Nt=/e/i,Et=/e/i,Tt=e=>{const[t="0",r="0"]=e.split(Et),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},It=/^0+(?=\d)/,oe=e=>{const r=(Nt.test(e.trim())?Tt(e.trim()):e.trim()).replace(Ne,""),n=r.startsWith("-"),[s="0",o=""]=(n?r.slice(1):r).split("."),i=s.replace(It,"");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},At=(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=vt.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 At(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}},_t="auth.",Rt=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),Ot=String.raw`\N`,Te=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===Ot?null:e,Lt=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>p(t))),kt=async(e,t)=>be(e,t,{authFiles:Lt(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(_t),tableNameOf:r=>p(r,".csv")},async r=>O(r,{withFileTypes:!0})),xt=(e,t,r)=>{const n=t?.idColumn??"id",s=t?.types??{},o={};let i=!1;for(const[a,c]of Object.entries(e)){if(Rt.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},Ct=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=xt(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}},jt=async function*(e,t,r,n,s){yield*_e("supabase",s,t,r,n),yield*we(e,r,n,o=>Ct(o,t))},Pt=/^\d+$/,Ut=/[+-]\d{2}$/,P=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&Pt.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(Ut.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},Ft=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]}},zt=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]}},Mt=(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=Ft(n),i=zt(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}},Dt=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}},Bt=(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
|
+
`),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 rt(t,{cast:Te,columns:!0,skipEmptyLines:!0})},Jt=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},Vt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Ae(D(e,r)),s=await Jt(e,t.auth?.identitiesFile);return n.map(o=>Mt(o,s.get(o.id??"")??[]))},Ht=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=>Dt(i))},_e=async function*(e,t,r,n,s){if(r?.auth?.file===void 0)return;const o=e==="supabase"?await Vt(t,r):await Ht(t,r);n.info(`auth: ${String(o.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of Bt(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},Gt=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},Wt=(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")},Yt=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Gt(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},Kt=(e,t)=>typeof e=="string"?e:Wt(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 Yt(e.timestampValue,t);if(e.bytesValue!==void 0)return Kt(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)}`)},Xt=new Set(["createTime","fields","name","readTime","updateTime"]),qt=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},Zt=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>Xt.has(r))&&!qt(t)},U=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Oe(n,`${t}.${r}`)])),Qt=(e,t,r,n)=>{const s=Zt(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}},er=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})),tr=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()}},rr=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: [...] }\``)},nr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?tr(e.file):await rr(e.file);let s=0;for await(const o of n)yield Qt(o.raw,o.fallbackId,r,`${e.table}[${String(s)}]`),s+=1},sr=async function*(e,t,r,n,s){yield*_e("firebase",s,t,r,n),yield*we(e,r,n,o=>nr(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},or=(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(!St(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}},ir=(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`)}},ar=(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,or(n,`${t}: tables.${r}`)]))}},cr=(e,t)=>{const r=B(e,t),n=T(r,"keyPrefix",t),{auth:s,tables:o}=r;return ir(s,t),{auth:s,keyPrefix:n,tables:ar(o,t)}},ke=e=>y("lunora",`import-${e}.json`),dr=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 cr(i,s)},lr=8,ur=24*1048576,fr=1e3,hr=/^[\dA-F]{64}$/i,gr=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},mr=/^[\d+/A-Z]{43}=$/i,pr=e=>hr.test(e)?e.toLowerCase():mr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,yr=(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=pr(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"||!gr(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(yr(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=nt,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(fr)}${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},br=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},wr=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${z}?key=${encodeURIComponent(t)}${L(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,$r=async(e,t,r,n,s)=>{const o=`${e.baseUrl}${st}?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 wr(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?br(e,t,r,n):$r(e,t,r,n,s)},Sr=e=>{const t=[];let r=[],n=0;for(const s of e)r.length>0&&(r.length>=lr||n+s.size>ur)&&(t.push(r),r=[],n=0),r.push(s),n+=s.size;return r.length>0&&t.push(r),t},vr=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 bt(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 Sr(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*Nr(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*Er(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*Nr(e,o,s)}}const zn=["firebase","supabase"],Tr=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 dr(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 kt(e.file,n)}:{collections:await er(e.file,n),kind:"firebase",mapping:n}},Ir=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},Ar=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},_r=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return Tr(e,e.from,t);const r=await gt(e.file),n=r===void 0?void 0:await yt(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 Ir(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 Ar(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},_=y("lunora","import-convex.json"),Rr=(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}},Or=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 Rr(s,r)},Lr=(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})}},kr=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(Lr(a,t.table,o),n,t.table);for(const{column:d}of c)s.includes(d)||s.push(d)}return s},xr=async(e,t,r)=>{const n={};for(const s of t){if(pe(s.table))continue;const o=await kr(e,s,r);o.length>0&&(n[s.table]=o)}return n},Cr=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)}},jr=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 xr(e,t,i)};return await Cr(a,r,n),a},v=20,Pr=(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`)},Ur=(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),Fr=(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,zr=/^\\x[\dA-Fa-f]*$/,Mr=/^[+-]?\d+$/,Dr=/^[+-]?\d+\.\d+$/,Br=/^\{.*\}$/,Jr=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,Vr=[["bytea-base64",e=>zr.test(e)],["timestamp-ms",e=>Jr.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Mr.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>Dr.test(e)],[e=>e.every(t=>Br.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],Hr=e=>{if(e.length!==0){for(const[t,r]of Vr)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},Gr=(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)}},Wr=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(Gr(o,t),n+=1,n>=de)break;r.destroy();const s={};for(const[o,i]of t){const a=Hr(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)}},Yr=async(e,t,r)=>{const n={};for(const o of e){const i=await Wr(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},Kr=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`),Xr=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,Zr=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),Qr=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 Qr(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}},en=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)}/${Zr(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},tn=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:Xe(t,a).split(qe).join("/")})}};return await n(t),r},rn=async(e,t,r,n,s)=>{const o=await t.bytes(),i=it("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},nn=(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 Xr(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=nn(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 rn(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=/^\/+/,sn=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,on=/[#?]/u,an=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},cn=e=>{const t=sn.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(on)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},dn=(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=cn(e);return o===void 0?void 0:t.get(o)??t.get(o.replace(ue,""))},ln=500,un=9e5,fn=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}if(e.prod&&e.yes!==!0){e.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const t=Ke(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:r}=Ye({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}${ot}`,token:r}},hn=(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}:{}}),gn=(e,t,r,n)=>{switch(e.kind){case"convex":return Er(e.snapshot,e.tables,t.logger,r,n);case"firebase":return sr(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return jt(e.tables,e.mapping,t.logger,n,t.file);default:return N(t.file,{encoding:"utf8"})}},mn=async(e,t,r)=>{switch(e.kind){case"convex":return jr(e.snapshot,e.tables,t,r);case"firebase":return Kr(e.collections,t,r);case"supabase":return Yr(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},pn=async(e,t,r,n)=>{const s=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return le(e,await tn(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 en({serviceKey:i,url:c},e.fetchImpl,r.logger);return le(e,d,{cwd:n,keyPrefix:s,source:t.kind},r.logger)},yn=(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=dn(c,r);d===void 0?s.add(`${t}.${a}: ${c}`):i[a]=d}return i},bn=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:an(r);return $t({remapDocument:n===void 0||t===void 0?void 0:(s,o)=>yn(s,o,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},wn=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
|
+
`);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}},$n=async(e,t,r,n)=>{const s=await Or(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 vr(e,t.snapshot,o,s?.keyPrefix??"",n);return n.info(`storage map: ${String(i.size)} blobs mapped`),{mapping:s,storageIdMap:i}},Sn=async(e,t,r,n)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return $n(e,t,n,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const s=await pn(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}},vn=(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)},Mn=async e=>{const t=e.cwd??process.cwd(),r=await _r(e,t);if(r.kind==="invalid")return{body:void 0,code:1,inserted:0};if(e.scan===!0)return{body:void 0,code:await mn(r,t,e.logger)===void 0?1:0,inserted:0};const n=await fn(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??ln,d=await Sn({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=gn(r,e,u!==void 0,G),k=wt({batchSize:c,fetchImpl:o,maxBatchBytes:un,requestUrl:i,token:a}),ze=bn({report:w,source:r,storageColumns:m,storageIdMap:u,table:e.table,transferredPaths:h,unresolvedPaths:g}),W=await wn(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?Pr(e.logger,G,{conflicts:Y,inserted:q}):0,Je=u!==void 0&&Ur(e.logger,w,e.verify===!0),Ve=Fr(e.logger,g,e.verify===!0),Z=Object.values(q).reduce((S,He)=>S+He,0),Q=hn(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)),vn(e.logger,{conflicts:Y,errorCount:K.length,failed:ee,insertedTotal:Z,received:Me,warnings:De}),{body:Q,code:ee?1:0,inserted:Z}};export{ln as D,zn as I,xe as M,L as b,V as l,Mn as r,Ce as u};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{Project as p,SyntaxKind as i,Node as a}from"ts-morph";const x=/^[A-Za-z_$][\w$]*$/u,o=t=>`// lunora:add:${t}:start`,c=t=>`// lunora:add:${t}:end`,m=t=>`./${t}/schema`,g=t=>{for(const e of t)if(e.getExpression().getText()==="defineSchema")return e},E=t=>{let e=t;for(let n=e.getParent();n!==void 0;n=e.getParent())if(a.isPropertyAccessExpression(n)&&n.getExpression()===e)e=n;else if(a.isCallExpression(n)&&n.getExpression()===e)e=n;else break;return e},S=(t,e)=>{if(!x.test(e))return{ok:!1,reason:"invalid-identifier"};if(t.includes(o(e)))return{ok:!1,reason:"already-applied"};const r=new p({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("schema.ts",t,{overwrite:!0}),l=r.getDescendantsOfKind(i.CallExpression),s=g(l);if(!s)return{ok:!1,reason:"no-define-schema"};if(s.getArguments()[0]?.getKind()!==i.ObjectLiteralExpression)return{ok:!1,reason:"non-object-argument"};const d=E(s).getEnd(),f=`
|
|
2
|
+
${o(e)}
|
|
3
|
+
.extend(${e}.extension)
|
|
4
|
+
${c(e)}
|
|
5
|
+
`;r.insertText(d,f);const u=`${o(e)}
|
|
6
|
+
import { ${e} } from "${m(e)}";
|
|
7
|
+
${c(e)}
|
|
8
|
+
`;return r.insertText(0,u),{ok:!0,text:r.getFullText()}};export{S as insertSchemaExtension};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const n=(s,e)=>{for(const t of s)(t.status==="created"||t.status==="updated")&&e.success(`${t.status} ${t.path} — ${t.tool} now skips Lunora's generated files`),t.status==="failed"&&e.warn(`could not configure ${t.tool} to skip Lunora's generated files: ${t.message??"unknown error"}. Add the entries by hand, or re-run once the path is writable.`),t.status==="manual"&&t.snippet!==void 0&&e.warn(`${t.path} needs an entry so ${t.tool} skips Lunora's generated files — add:
|
|
2
|
+
${t.snippet}`)};export{n as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as i}from"node:child_process";import{platform as s}from"node:os";import{LunoraError as a}from"@lunora/errors";const d=()=>{const o=s();return o==="darwin"?{args:[],command:"open"}:o==="win32"?{args:["/c","start",""],command:"cmd"}:{args:[],command:"xdg-open"}},f=o=>o.replaceAll(/[!"%&()<>^|]/gu,n=>`%${(n.codePointAt(0)??0).toString(16).toUpperCase()}`),w=o=>new Promise((n,r)=>{const{args:e,command:c}=d(),p=s()==="win32"?f(o):o,t=i(c,[...e,p],{detached:!0,stdio:"ignore"});t.once("error",m=>{r(m)}),t.once("spawn",()=>{t.unref(),n()})}),L=async(o,n={})=>{let r;try{r=new URL(o)}catch{throw new a("INTERNAL",`Invalid URL: ${o}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new a("INTERNAL",`Refusing to open non-http(s) URL: ${o}`);await(n.opener??w)(o)};export{L as o};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createStderrLogger as r}from"./createLogger-hGafwf-3.mjs";const s=new Set(["json","pretty"]),i=(t,o)=>{if(o!==void 0&&!s.has(o))return`${t}: unknown --format "${o}" — expected pretty | json`},e=t=>t==="json",a=(t,o)=>e(t)?r():o,p=t=>{process.stdout.write(`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`)};export{e as i,a as l,p,i as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";const d=/[\r\n]/u,w=/^[A-Za-z_]\w*$/u,y=/^[A-Za-z0-9][\w-]*$/u,b=/^[\w.-]+(?:\/[\w.-]+)*$/u,I=(c,s)=>{if(typeof c!="object"||c===null)throw new r("INTERNAL",`registry.json for "${s}" is not an object`);const e=c,{name:n}=e;if(typeof n!="string"||n.length===0)throw new r("INTERNAL",`registry.json for "${s}" is missing a string "name"`);if(!y.test(n))throw new r("INTERNAL",`registry.json for "${s}": name "${n}" must match ${y.source} (letters, digits, "-", "_"; no path separators, "..", or code)`);const g=e.files;if(!Array.isArray(g))throw new TypeError(`registry.json for "${s}" is missing a "files" array`);const A=g.map((t,o)=>{if(typeof t!="object"||t===null)throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}] is not an object`);const i=t,{from:a}=i,{to:f}=i,{merge:p}=i;if(typeof a!="string"||typeof f!="string")throw new TypeError(`registry.json "${s}": files[${String(o)}] needs string "from" and "to"`);if(p!=="create-or-skip"&&p!=="schema-extension")throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}].merge must be "create-or-skip" or "schema-extension"`);for(const[v,l]of[["from",a],["to",f]])if(l.includes("..")||l.startsWith("/"))throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}].${v} "${l}" must be a relative path without ".."`);return{from:a,merge:p,to:f}}),u=t=>typeof t=="object"&&t!==null?t:void 0,h=u(e.deps),m=u(e.devDependencies),$=Array.isArray(e.requires)?e.requires.filter(t=>typeof t=="string"):void 0,E=Array.isArray(e.bindings)?e.bindings.filter(t=>{if(typeof t!="object"||t===null)return!1;const o=t;return Array.isArray(o.path)&&o.path.every(i=>typeof i=="string")}):void 0,j=Array.isArray(e.entrypointReexports)?e.entrypointReexports.filter(t=>typeof t=="object"&&t!==null&&typeof t.module=="string").map(t=>{if(t.module.includes("..")||t.module.startsWith("/")||!b.test(t.module))throw new r("INTERNAL",`registry.json "${s}": entrypointReexports[].module "${t.module}" must be a safe relative module path without path traversal or unsafe characters`);const o={module:t.module};if(typeof t.comment=="string"){if(d.test(t.comment))throw new r("INTERNAL",`registry.json "${s}": entrypointReexports[].comment must not contain a newline`);o.comment=t.comment}return o}):void 0,R=Array.isArray(e.envVars)?e.envVars.filter(t=>typeof t=="object"&&t!==null&&typeof t.name=="string").map(t=>{const o=typeof t.value=="string";if(!w.test(t.name))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].name must match ${w.source} (letters, digits, underscore; no "=" or newline)`);if(o&&d.test(t.value))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].value must not contain a newline`);if(typeof t.description=="string"&&d.test(t.description))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].description must not contain a newline`);return{...typeof t.description=="string"?{description:t.description}:{},name:t.name,secret:typeof t.secret=="boolean"?t.secret:!o,...o?{value:t.value}:{}}}):void 0;return{bindings:E,deps:h,description:typeof e.description=="string"?e.description:void 0,devDependencies:m,docs:typeof e.docs=="string"?e.docs:void 0,entrypointReexports:j,envVars:R,files:A,name:n,requires:$,title:typeof e.title=="string"?e.title:void 0}};export{I as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sep as t}from"node:path";const m=(s,i,e=t)=>i===s||i.startsWith(s.endsWith(e)?s:`${s}${e}`);export{m as i};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
const a=(e,t)=>{if(e.length===0)return;const l=e.map(r=>` [${r.level.toUpperCase()}] ${r.name} — ${r.message}
|
|
2
|
+
↳ ${r.remediation}`),n=e.filter(r=>r.level==="error"),o=`${String(e.length)} platform ${e.length===1?"diagnostic":"diagnostics"}:
|
|
3
|
+
${l.join(`
|
|
4
|
+
`)}`;if(n.length===0){t.warn(o);return}return t.error(o),n[0]?.message??"platform diagnostics reported an error"};export{a as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class e extends Error{constructor(){super("cancelled"),this.name="PromptCancelledError"}}const o=130;export{e as P,o as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as d,readFileSync as E,mkdtempSync as b,rmSync as w}from"node:fs";import{tmpdir as O}from"node:os";import{LunoraError as i}from"@lunora/errors";import{dirname as v,join as c}from"@visulima/path";import{downloadTemplate as B}from"giget";import{fileURLToPath as C}from"node:url";import U from"./parseManifest-CwPTKdtS.mjs";const D="alpha",S="main",k=new Set(["alpha","beta","next"]),G=/^[\w./@-]+$/,P=t=>!t.includes("..")&&G.test(t),f=()=>{try{let t=v(C(import.meta.url));for(let e=0;e<6;e+=1){const r=c(t,"package.json");if(d(r)){const s=JSON.parse(E(r,"utf8"));if(s.name==="@lunora/cli"&&typeof s.version=="string")return s.version}const n=v(t);if(n===t)break;t=n}}catch{}return"0.0.0"},R=t=>{if(t==="0.0.0")return D;const e=t.split("+")[0]??t,r=e.indexOf("-");if(r!==-1){const[n]=e.slice(r+1).split(".");if(n!==void 0&&k.has(n))return n}return S},$=t=>{if(t!==void 0&&t.length>0){if(!P(t))throw new i("INTERNAL",`invalid --ref "${t}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return t}return R(f())},l="anolilab/lunora",A=/^[0-9a-f]{40}$/iu,T=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,F=new RegExp(String.raw`^v?${T}$`,"u"),M=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${T}$`,"u"),V=t=>A.test(t)||F.test(t)||M.test(t),j=()=>{const t=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return t!==void 0&&t.length>0?{authorization:`Bearer ${t}`}:{}},x=async t=>{try{const e=await fetch(`https://api.github.com/repos/${l}/commits/${encodeURIComponent(t)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...j()},signal:AbortSignal.timeout(1e4)});if(!e.ok)return;const r=await e.json();return typeof r.sha=="string"&&A.test(r.sha)?r.sha:void 0}catch{return}},H=async(t,e)=>{const r=$(t);if(V(r))return r;const n=await x(r);return n===void 0?(e.warn(`could not pin ${l}#${r} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),r):(e.info(`pinned ${l}#${r} → ${n}`),n)},ct=(t=f())=>`@lunora/cli@${t}`,z="latest",it=(t=f())=>{const e=R(t);return e===S?z:e},K="https://registry.npmjs.org",W=()=>{const t=process.env.npm_config_registry,e=t!==void 0&&t.length>0?t:K;return e.endsWith("/")?e.slice(0,-1):e},Z=async(t,e)=>{try{const r=await fetch(`${W()}/${t.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return r.ok?(await r.json())["dist-tags"]?.[e]:void 0}catch{return}},ut=async(t,e)=>{const r=new Map;return await Promise.all([...new Set(t)].map(async n=>{const s=await Z(n,e);s!==void 0&&r.set(n,s)})),r},_="gh:anolilab/lunora/registry",y=/^[A-Za-z0-9][\w-]*$/u,q=t=>{if(!y.test(t))throw new i("INTERNAL",`invalid registry item name "${t}" — names must match ${y.source} (letters, digits, "-", "_"; no path separators or "..")`)},J=t=>t.includes("..")?!1:t.startsWith("gh:")||t.startsWith("github:")||t.startsWith("https://"),Y=t=>t.from===void 0&&t.source!==void 0&&t.source.length>0&&!t.allowUnsafeSource&&!J(t.source),lt=(t,e)=>Y(e)?`${t}: refusing --source ${String(e.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,N=async(t,e,r)=>{const n=b(c(O(),`lunora-${e}-fetch-`)),s=c(n,e);r.info(`fetching ${t}`);try{const a=await B(t,{cwd:n,dir:s,force:!0,install:!1,silent:!0});return r.info(a.commit?`resolved ${a.source} @ ${a.commit}`:`resolved ${a.source}`),{cleanup:()=>{w(n,{force:!0,recursive:!0})},directory:s}}catch(a){throw w(n,{force:!0,recursive:!0}),a}},p=new WeakMap,I=async t=>{const e=p.get(t);if(e!==void 0)return e;const r=t.source!==void 0&&t.source.length>0?Promise.resolve($(t.ref)):H(t.ref,t.logger);return p.set(t,r),r},Q=async(t,e,r=_)=>{if(q(t),e.from!==void 0){const s=c(e.from,t);if(!d(s))throw new i("INTERNAL",`registry item not found in local source: ${s}`);return{cleanup:()=>{},directory:s}}const n=e.source??r;return N(`${n}/${t}#${await I(e)}`,"item",e.logger)},dt=async t=>{if(t.from!==void 0){if(!d(t.from))throw new i("INTERNAL",`registry root not found: ${t.from}`);return{cleanup:()=>{},root:t.from}}const e=t.source??_,{cleanup:r,directory:n}=await N(`${e}#${await I(t)}`,"registry",t.logger);return{cleanup:r,root:n}},X=(t,e)=>{const r=JSON.parse(E(c(t,"registry.json"),"utf8"));return U(r,e)},ft=async(t,e)=>{const r=[],n=[],s=new Set,a=new Set,h=async o=>{if(s.has(o))return;if(a.has(o))throw new i("INTERNAL",`cyclic registry dependency detected at "${o}"`);a.add(o);const{cleanup:u,directory:g}=await Q(o,e);n.push(u);const m=X(g,o);for(const L of m.requires??[])await h(L);a.delete(o),s.add(o),r.push({directory:g,manifest:m})};try{for(const o of t)await h(o)}catch(o){for(const u of n)u();throw o}return{cleanups:n,items:r}};export{f as a,H as b,Q as c,it as d,ft as e,dt as f,X as g,ut as h,$ as i,ct as r,lt as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readLinkedProject as n}from"@lunora/config";const v=({cwd:e,env:i,url:o})=>{if(o!==void 0&&o!=="")return o;const r=n(e);if(!(r===void 0||r.env!==i))return r.workerUrl},d=({cwd:e,prod:i,url:o})=>{if(o!==void 0&&o!=="")return o;if(!i)return;const r=n(e);if(!(r===void 0||r.env!==void 0&&r.env!=="production"))return r.workerUrl};export{v as a,d as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as n,a as o,b as i}from"./commands-BNKj7r1R.mjs";import"./buildRegistryIndex-Zi3bBqpc.mjs";import"./resolve-DZAGzg67.mjs";export{n as runAddCommand,o as runBuildIndexCommand,i as runRegistryViewCommand};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{createWriteStream as y}from"node:fs";import{unlink as g}from"node:fs/promises";import{r as v}from"./admin-token-rxXZbVMZ.mjs";import{r as h}from"./admin-url-Cil3Or6N.mjs";import{E as b}from"./shared-D-zCOmgY.mjs";const p=e=>{if(e===void 0)return;const t=e.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t.length>0?t:void 0},w=async(e,t)=>{e.write(t)||await new Promise((o,s)=>{let n=r=>{};const i=()=>{e.removeListener("error",n),o()};n=r=>{e.removeListener("drain",i),s(r)},e.once("drain",i),e.once("error",n)})},x=async(e,t)=>{const o=e.getReader(),s=new TextDecoder;let n=0,i=0,r="",a=!1;try{for(;!a;){const l=await o.read();if(a=l.done,l.value===void 0)continue;n+=l.value.length,r+=s.decode(l.value,{stream:!0});let c=r.indexOf(`
|
|
2
|
+
`);for(;c!==-1;){i+=1;const d=`${r.slice(0,c)}
|
|
3
|
+
`;await w(t,d),r=r.slice(c+1),c=r.indexOf(`
|
|
4
|
+
`)}}return r.length>0&&(i+=1,await w(t,`${r}
|
|
5
|
+
`)),{bytes:n,rows:i}}finally{o.releaseLock()}},m=async(e,t)=>{if(t!==void 0){e.destroy();try{await g(t)}catch{}}},T=async(e,t,o)=>{await new Promise((n,i)=>{e.end(r=>{const a=r??o();a===void 0?n():i(a)})});const s=o();if(s!==void 0)throw await m(e,t),s},E=async e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{bytes:0,code:1,rows:0};const t=h(e.url,e.logger,e.cwd);if(t===void 0)return{bytes:0,code:1,rows:0};const{token:o}=v({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!o)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{bytes:0,code:1,rows:0};const s=`${t}${b}`,n=p(e.tables),i=e.fetchImpl??globalThis.fetch;if(typeof i!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");e.logger.info(`POST ${s} -> export${n?` (tables: ${n.join(",")})`:""}`);const r=await i(s,{body:JSON.stringify(n?{tables:n}:{}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},method:"POST"});if(!r.ok){const f=await r.text();return e.logger.error(`export failed: HTTP ${String(r.status)}: ${f}`),{bytes:0,code:1,rows:0}}if(!r.body)return e.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const a=e.out===void 0||e.out==="-"?void 0:e.out,l=a===void 0?process.stdout:y(a,{encoding:"utf8"});let c;a!==void 0&&l.on("error",f=>{c??=f});let d,u;try{({bytes:d,rows:u}=await x(r.body,l))}catch(f){throw await m(l,a),f}return a!==void 0&&(await T(l,a,()=>c),e.logger.success(`wrote ${String(u)} rows to ${a} (${String(d)} bytes)`)),{bytes:d,code:0,rows:u}};export{E as runExportCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as f,readFileSync as g,writeFileSync as m}from"node:fs";import{evaluateSchemaDrift as p,parseSchemaSnapshot as b,SchemaSnapshotParseError as S,serializeSchemaSnapshot as y}from"@lunora/codegen";const d="/_lunora/health",B="/_lunora/health/ready",k=(e,r=d)=>(e.endsWith("/")?e.slice(0,-1):e)+r,u=async(e,r,s)=>{let c={error:`health probe failed: no health path configured for ${e}`,url:e};for(const[i,h]of r.entries()){const n=k(e,h);let t;try{t=await s(n)}catch(o){const l=o instanceof Error?o.message:String(o);return{error:`health probe failed: could not reach ${n} (${l})`,url:n}}if(t.ok)return{url:n};if(c={error:`health probe failed: ${n} returned HTTP ${String(t.status)}`,url:n},t.status!==404||i===r.length-1)return c}return c},w=async e=>new Promise(r=>{setTimeout(r,e)}),O=async({attempts:e=1,baseUrl:r,delayMs:s=2e3,fetchImpl:c,paths:i=[d],sleep:h=w,timeoutMs:n=1e4})=>{const t=c??(a=>fetch(a,{signal:AbortSignal.timeout(n)})),o=Math.max(1,e);let l=await u(r,i,t);for(let a=1;a<o&&l.error!==void 0;a+=1)await h(s),l=await u(r,i,t);return l},H=e=>{if(!f(e))return{status:"absent"};let r;try{r=g(e,"utf8")}catch{return{status:"corrupt"}}try{const s=b(r);return s===void 0?{status:"corrupt"}:{snapshot:s,status:"ok"}}catch(s){if(s instanceof S)return{status:"corrupt"};throw s}},P=(e,r)=>{m(e,y(r),"utf8")},$=e=>{const r=`schema-drift gate: the committed baseline ${e.snapshotPath} is unreadable or malformed, so schema drift cannot be checked. Fix it (e.g. resolve a merge conflict in lunora/.lunora-schema.json), or pass --update-schema-baseline to regenerate it from the current schema.`;return e.updateBaseline&&!e.readOnly?(e.logger.warn(`schema baseline was unreadable; regenerating from the current schema on success (--update-schema-baseline): ${e.snapshotPath}`),{blocked:!1,changes:[],reason:r,rebless:e.rebless}):(e.readOnly||e.logger.error(r),{blocked:!0,changes:[],reason:r})},T=(e,r)=>(r.readOnly||r.logger.error(e.reason),r.updateBaseline&&!r.readOnly?(r.logger.warn(`schema baseline will be re-blessed despite breaking drift on success (--update-schema-baseline): ${r.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason,rebless:r.rebless}):{blocked:!0,changes:e.changes,reason:e.reason}),D=e=>{const{allowDrift:r,codegen:s,command:c,logger:i,readOnly:h=!1,updateBaseline:n=!1}=e,t=s.schemaSnapshotPath,o=H(t),l={logger:i,readOnly:h,rebless:()=>{P(t,s.schemaSnapshot)},snapshotPath:t,updateBaseline:n};if(o.status==="corrupt")return $(l);const a=p({allowDrift:r,baseline:o.status==="ok"?o.snapshot:void 0,command:c,current:s.schemaSnapshot});return a.blocked?T(a,l):a.changes.length>0?(h||i.info(a.reason),{blocked:!1,changes:a.changes,reason:a.reason,rebless:h?void 0:l.rebless}):{blocked:!1,changes:a.changes,reason:a.reason}};export{B as H,d as a,O as p,D as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{validatorKindToSqlType as a}from"./diffSnapshots-CIOFQN_a.mjs";const r=e=>e.kind==="optional"&&e.inner?{nullable:!0,sqlType:a(e.inner.kind)}:{nullable:!1,sqlType:a(e.kind)},u=e=>e==="global",f=e=>{const s={};for(const o of e.tables){if(!u(o.shardMode))continue;const l={};for(const[n,i]of Object.entries(o.shape))l[n]=r(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{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a="/_lunora/admin/export",o="/_lunora/admin/import",_="/_lunora/admin/storage",n="/_lunora/admin/storage/url";export{a as E,o as I,_ as S,n as a};
|