@lunora/cli 1.0.0-alpha.147 → 1.0.0-alpha.149
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +94 -1
- package/dist/index.d.ts +94 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -1
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +2 -2
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler25.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +2 -2
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +1 -1
- package/dist/packem_shared/{COMMANDS-DNQLU6rs.mjs → COMMANDS-DkO6XHZS.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Dqu4Zmi0.mjs +1 -0
- package/dist/packem_shared/cli-DYGVS96x.mjs +3 -0
- package/dist/packem_shared/import-DLyCq-2j.mjs +12 -0
- package/dist/packem_shared/{runExportCommand-DFpdjDoT.mjs → runExportCommand-BpE4AbuX.mjs} +1 -1
- package/dist/packem_shared/{shared-BF5QIWFD.mjs → shared-Ce9bKz5c.mjs} +1 -1
- package/package.json +12 -11
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C4qrFAn_.mjs +0 -8
- package/dist/packem_shared/cli-C-iz79JI.mjs +0 -3
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{f as s}from"./packem_shared/cli-
|
|
2
|
+
import{f as s}from"./packem_shared/cli-DYGVS96x.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
3
3
|
`),process.exit(1)}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { CodegenOptions, Finding, SchemaIR } from '@lunora/codegen';
|
|
2
2
|
import '@visulima/cerebro';
|
|
3
3
|
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, LintTool, LintIgnoreOutcome } from '@lunora/config';
|
|
4
|
+
import 'adm-zip';
|
|
4
5
|
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
6
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
6
7
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
@@ -100,6 +101,8 @@ type StreamingFetchLike = (input: string, init?: {
|
|
|
100
101
|
headers?: Record<string, string>;
|
|
101
102
|
method?: string;
|
|
102
103
|
}) => Promise<{
|
|
104
|
+
/** Optional: only the storage transfer reads raw bytes, and only real `fetch` needs to supply it. */
|
|
105
|
+
arrayBuffer?: () => Promise<ArrayBuffer>;
|
|
103
106
|
body: ReadableStream<Uint8Array> | null;
|
|
104
107
|
json: () => Promise<unknown>;
|
|
105
108
|
ok: boolean;
|
|
@@ -133,6 +136,63 @@ interface ExportCommandResult {
|
|
|
133
136
|
* the body in memory.
|
|
134
137
|
*/
|
|
135
138
|
declare const runExportCommand: (options: ExportCommandOptions) => Promise<ExportCommandResult>;
|
|
139
|
+
/** One row-scoped failure as the admin import endpoint reports it. */
|
|
140
|
+
interface ImportRowError {
|
|
141
|
+
code: string;
|
|
142
|
+
line: number;
|
|
143
|
+
message: string;
|
|
144
|
+
table: string;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The sources `--from` accepts.
|
|
148
|
+
*
|
|
149
|
+
* Only the two that cannot be detected. A Convex snapshot announces itself (a
|
|
150
|
+
* directory of `<table>/documents.jsonl`, or a `.zip` of one) and anything else
|
|
151
|
+
* is NDJSON, so naming those would advertise a control this does not implement:
|
|
152
|
+
* `--from ndjson` against a Convex export would have to either refuse it or
|
|
153
|
+
* silently import it as Convex, and the second is what an unhonoured flag
|
|
154
|
+
* actually did.
|
|
155
|
+
*/
|
|
156
|
+
declare const IMPORT_SOURCE_NAMES: readonly ["firebase", "supabase"];
|
|
157
|
+
type ImportSourceName = (typeof IMPORT_SOURCE_NAMES)[number];
|
|
158
|
+
/**
|
|
159
|
+
* The storage-reference rewrite: turning a Convex storage id into the
|
|
160
|
+
* content-hash R2 key its blob was migrated to.
|
|
161
|
+
*
|
|
162
|
+
* Split out of `./storage-mapping` (which owns the mapping *file*) because it
|
|
163
|
+
* has two callers that must never diverge — the import rewrite and `--scan`,
|
|
164
|
+
* which runs this same walk as a dry run to propose the mapping. A detector
|
|
165
|
+
* that proposed columns the rewrite would not touch, or missed ones it would,
|
|
166
|
+
* is worse than no detector.
|
|
167
|
+
*/
|
|
168
|
+
/** One reference the walk could not rewrite, with where it was found. */
|
|
169
|
+
interface UnresolvedStorageReference {
|
|
170
|
+
column: string;
|
|
171
|
+
storageId: string;
|
|
172
|
+
table: string;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* What a run's storage references resolved to. The two failure buckets are
|
|
176
|
+
* deliberately separate, because they are not the same problem and do not have
|
|
177
|
+
* the same remedy:
|
|
178
|
+
*
|
|
179
|
+
* `unmigrated` is a reference to a blob that does not exist — the export omitted
|
|
180
|
+
* it, or `--include-file-storage` was not passed. Nothing the operator writes in
|
|
181
|
+
* a mapping file can fix it, and the data is broken after import, so it fails
|
|
182
|
+
* `--verify`.
|
|
183
|
+
*
|
|
184
|
+
* `ambiguous` is a string that exactly matches a blob that *did* migrate, sitting
|
|
185
|
+
* in a column the mapping does not name. It may be a storage reference the
|
|
186
|
+
* mapping forgot, or it may be user text that happens to equal an id. Failing the
|
|
187
|
+
* run on a coincidence is not defensible, so it warns and names the column the
|
|
188
|
+
* operator would add to resolve it.
|
|
189
|
+
*/
|
|
190
|
+
interface StorageRemapReport {
|
|
191
|
+
ambiguous: UnresolvedStorageReference[];
|
|
192
|
+
/** Number of references rewritten to a content-hash key. */
|
|
193
|
+
rewritten: number;
|
|
194
|
+
unmigrated: UnresolvedStorageReference[];
|
|
195
|
+
}
|
|
136
196
|
/** Rows per HTTP request when importing. Convex uses ~500; same here. */
|
|
137
197
|
declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
|
|
138
198
|
interface ImportCommandOptions {
|
|
@@ -142,6 +202,13 @@ interface ImportCommandOptions {
|
|
|
142
202
|
fetchImpl?: StreamingFetchLike;
|
|
143
203
|
/** Source NDJSON file. Required. */
|
|
144
204
|
file: string;
|
|
205
|
+
/**
|
|
206
|
+
* Which reader to use. Omit to auto-detect between a Convex export snapshot
|
|
207
|
+
* and a plain NDJSON file; `supabase`/`firebase` must be explicit, because a
|
|
208
|
+
* directory of CSV or JSON has no signature that distinguishes it from
|
|
209
|
+
* anything else a user might point at.
|
|
210
|
+
*/
|
|
211
|
+
from?: ImportSourceName;
|
|
145
212
|
logger: Logger;
|
|
146
213
|
prod?: boolean;
|
|
147
214
|
/**
|
|
@@ -149,6 +216,11 @@ interface ImportCommandOptions {
|
|
|
149
216
|
* `lunora/import-convex.json`. Scan-only: nothing is imported.
|
|
150
217
|
*/
|
|
151
218
|
scan?: boolean;
|
|
219
|
+
/**
|
|
220
|
+
* Local directory of storage objects to migrate alongside the rows — how
|
|
221
|
+
* Firebase Cloud Storage arrives, after `gcloud storage cp -r`.
|
|
222
|
+
*/
|
|
223
|
+
storageDir?: string;
|
|
152
224
|
/**
|
|
153
225
|
* Wrap each line as `{table:<name>,doc:<line>}`. Use when the source NDJSON
|
|
154
226
|
* is bare docs from a single table — Convex's `convex import --table users`
|
|
@@ -172,8 +244,29 @@ interface ImportCommandOptions {
|
|
|
172
244
|
/** Confirm bulk-writing production. Required alongside `--prod`. */
|
|
173
245
|
yes?: boolean;
|
|
174
246
|
}
|
|
247
|
+
/**
|
|
248
|
+
* The JSON summary a run prints and returns — the same object either way, so a
|
|
249
|
+
* caller reading `body.conflicts` does not have to cast its way there.
|
|
250
|
+
*
|
|
251
|
+
* `undefined` on every path that imports nothing: a rejected source, a failed
|
|
252
|
+
* storage phase, or `--scan` (whose product is the mapping file it writes, not
|
|
253
|
+
* a return value).
|
|
254
|
+
*/
|
|
255
|
+
interface ImportSummary {
|
|
256
|
+
conflicts: number;
|
|
257
|
+
errors: ImportRowError[];
|
|
258
|
+
inserted: Record<string, number>;
|
|
259
|
+
received: number;
|
|
260
|
+
storage?: {
|
|
261
|
+
ambiguous: StorageRemapReport["ambiguous"];
|
|
262
|
+
blobs: number;
|
|
263
|
+
rewritten: number;
|
|
264
|
+
unmigrated: StorageRemapReport["unmigrated"];
|
|
265
|
+
};
|
|
266
|
+
warnings?: string[];
|
|
267
|
+
}
|
|
175
268
|
interface ImportCommandResult {
|
|
176
|
-
body:
|
|
269
|
+
body: ImportSummary | undefined;
|
|
177
270
|
code: number;
|
|
178
271
|
/** Total inserted rows across batches. */
|
|
179
272
|
inserted: number;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { CodegenOptions, Finding, SchemaIR } from '@lunora/codegen';
|
|
2
2
|
import '@visulima/cerebro';
|
|
3
3
|
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, LintTool, LintIgnoreOutcome } from '@lunora/config';
|
|
4
|
+
import 'adm-zip';
|
|
4
5
|
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
6
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
6
7
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
@@ -100,6 +101,8 @@ type StreamingFetchLike = (input: string, init?: {
|
|
|
100
101
|
headers?: Record<string, string>;
|
|
101
102
|
method?: string;
|
|
102
103
|
}) => Promise<{
|
|
104
|
+
/** Optional: only the storage transfer reads raw bytes, and only real `fetch` needs to supply it. */
|
|
105
|
+
arrayBuffer?: () => Promise<ArrayBuffer>;
|
|
103
106
|
body: ReadableStream<Uint8Array> | null;
|
|
104
107
|
json: () => Promise<unknown>;
|
|
105
108
|
ok: boolean;
|
|
@@ -133,6 +136,63 @@ interface ExportCommandResult {
|
|
|
133
136
|
* the body in memory.
|
|
134
137
|
*/
|
|
135
138
|
declare const runExportCommand: (options: ExportCommandOptions) => Promise<ExportCommandResult>;
|
|
139
|
+
/** One row-scoped failure as the admin import endpoint reports it. */
|
|
140
|
+
interface ImportRowError {
|
|
141
|
+
code: string;
|
|
142
|
+
line: number;
|
|
143
|
+
message: string;
|
|
144
|
+
table: string;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The sources `--from` accepts.
|
|
148
|
+
*
|
|
149
|
+
* Only the two that cannot be detected. A Convex snapshot announces itself (a
|
|
150
|
+
* directory of `<table>/documents.jsonl`, or a `.zip` of one) and anything else
|
|
151
|
+
* is NDJSON, so naming those would advertise a control this does not implement:
|
|
152
|
+
* `--from ndjson` against a Convex export would have to either refuse it or
|
|
153
|
+
* silently import it as Convex, and the second is what an unhonoured flag
|
|
154
|
+
* actually did.
|
|
155
|
+
*/
|
|
156
|
+
declare const IMPORT_SOURCE_NAMES: readonly ["firebase", "supabase"];
|
|
157
|
+
type ImportSourceName = (typeof IMPORT_SOURCE_NAMES)[number];
|
|
158
|
+
/**
|
|
159
|
+
* The storage-reference rewrite: turning a Convex storage id into the
|
|
160
|
+
* content-hash R2 key its blob was migrated to.
|
|
161
|
+
*
|
|
162
|
+
* Split out of `./storage-mapping` (which owns the mapping *file*) because it
|
|
163
|
+
* has two callers that must never diverge — the import rewrite and `--scan`,
|
|
164
|
+
* which runs this same walk as a dry run to propose the mapping. A detector
|
|
165
|
+
* that proposed columns the rewrite would not touch, or missed ones it would,
|
|
166
|
+
* is worse than no detector.
|
|
167
|
+
*/
|
|
168
|
+
/** One reference the walk could not rewrite, with where it was found. */
|
|
169
|
+
interface UnresolvedStorageReference {
|
|
170
|
+
column: string;
|
|
171
|
+
storageId: string;
|
|
172
|
+
table: string;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* What a run's storage references resolved to. The two failure buckets are
|
|
176
|
+
* deliberately separate, because they are not the same problem and do not have
|
|
177
|
+
* the same remedy:
|
|
178
|
+
*
|
|
179
|
+
* `unmigrated` is a reference to a blob that does not exist — the export omitted
|
|
180
|
+
* it, or `--include-file-storage` was not passed. Nothing the operator writes in
|
|
181
|
+
* a mapping file can fix it, and the data is broken after import, so it fails
|
|
182
|
+
* `--verify`.
|
|
183
|
+
*
|
|
184
|
+
* `ambiguous` is a string that exactly matches a blob that *did* migrate, sitting
|
|
185
|
+
* in a column the mapping does not name. It may be a storage reference the
|
|
186
|
+
* mapping forgot, or it may be user text that happens to equal an id. Failing the
|
|
187
|
+
* run on a coincidence is not defensible, so it warns and names the column the
|
|
188
|
+
* operator would add to resolve it.
|
|
189
|
+
*/
|
|
190
|
+
interface StorageRemapReport {
|
|
191
|
+
ambiguous: UnresolvedStorageReference[];
|
|
192
|
+
/** Number of references rewritten to a content-hash key. */
|
|
193
|
+
rewritten: number;
|
|
194
|
+
unmigrated: UnresolvedStorageReference[];
|
|
195
|
+
}
|
|
136
196
|
/** Rows per HTTP request when importing. Convex uses ~500; same here. */
|
|
137
197
|
declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
|
|
138
198
|
interface ImportCommandOptions {
|
|
@@ -142,6 +202,13 @@ interface ImportCommandOptions {
|
|
|
142
202
|
fetchImpl?: StreamingFetchLike;
|
|
143
203
|
/** Source NDJSON file. Required. */
|
|
144
204
|
file: string;
|
|
205
|
+
/**
|
|
206
|
+
* Which reader to use. Omit to auto-detect between a Convex export snapshot
|
|
207
|
+
* and a plain NDJSON file; `supabase`/`firebase` must be explicit, because a
|
|
208
|
+
* directory of CSV or JSON has no signature that distinguishes it from
|
|
209
|
+
* anything else a user might point at.
|
|
210
|
+
*/
|
|
211
|
+
from?: ImportSourceName;
|
|
145
212
|
logger: Logger;
|
|
146
213
|
prod?: boolean;
|
|
147
214
|
/**
|
|
@@ -149,6 +216,11 @@ interface ImportCommandOptions {
|
|
|
149
216
|
* `lunora/import-convex.json`. Scan-only: nothing is imported.
|
|
150
217
|
*/
|
|
151
218
|
scan?: boolean;
|
|
219
|
+
/**
|
|
220
|
+
* Local directory of storage objects to migrate alongside the rows — how
|
|
221
|
+
* Firebase Cloud Storage arrives, after `gcloud storage cp -r`.
|
|
222
|
+
*/
|
|
223
|
+
storageDir?: string;
|
|
152
224
|
/**
|
|
153
225
|
* Wrap each line as `{table:<name>,doc:<line>}`. Use when the source NDJSON
|
|
154
226
|
* is bare docs from a single table — Convex's `convex import --table users`
|
|
@@ -172,8 +244,29 @@ interface ImportCommandOptions {
|
|
|
172
244
|
/** Confirm bulk-writing production. Required alongside `--prod`. */
|
|
173
245
|
yes?: boolean;
|
|
174
246
|
}
|
|
247
|
+
/**
|
|
248
|
+
* The JSON summary a run prints and returns — the same object either way, so a
|
|
249
|
+
* caller reading `body.conflicts` does not have to cast its way there.
|
|
250
|
+
*
|
|
251
|
+
* `undefined` on every path that imports nothing: a rejected source, a failed
|
|
252
|
+
* storage phase, or `--scan` (whose product is the mapping file it writes, not
|
|
253
|
+
* a return value).
|
|
254
|
+
*/
|
|
255
|
+
interface ImportSummary {
|
|
256
|
+
conflicts: number;
|
|
257
|
+
errors: ImportRowError[];
|
|
258
|
+
inserted: Record<string, number>;
|
|
259
|
+
received: number;
|
|
260
|
+
storage?: {
|
|
261
|
+
ambiguous: StorageRemapReport["ambiguous"];
|
|
262
|
+
blobs: number;
|
|
263
|
+
rewritten: number;
|
|
264
|
+
unmigrated: StorageRemapReport["unmigrated"];
|
|
265
|
+
};
|
|
266
|
+
warnings?: string[];
|
|
267
|
+
}
|
|
175
268
|
interface ImportCommandResult {
|
|
176
|
-
body:
|
|
269
|
+
body: ImportSummary | undefined;
|
|
177
270
|
code: number;
|
|
178
271
|
/** Total inserted rows across batches. */
|
|
179
272
|
inserted: number;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as o,i as
|
|
1
|
+
import{d as o,i as a,f as n}from"./packem_shared/cli-DYGVS96x.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as C}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as E}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as D}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-BoSxdb2T.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as h,renderCreateTable as y,renderDropIndex as F,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as b}from"./packem_shared/diffSnapshots-BbwCuhoN.mjs";import{default as B}from"./packem_shared/schemaIrToSnapshot-Dahp39qH.mjs";import{createRecordingSpawner as U,defaultSpawner as W}from"./packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{default as N}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{R as V,S as j}from"./packem_shared/import-DLyCq-2j.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as z}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{I as X,F as $,E as rr}from"./packem_shared/commands-CG9qEtqR.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-BpE4AbuX.mjs";export{o as COMMANDS,V as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,a as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,W as defaultSpawner,v as diffSnapshots,D as insertSchemaExtension,c as pail,N as parseManifest,x as planDevCommand,_ as renderAddColumn,h as renderCreateIndex,y as renderCreateTable,F as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,n as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,C as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,E as runRpcCommand,B as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,b as validatorKindToSqlType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as p}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as u}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runExportCommand as d}from"../packem_shared/runExportCommand-
|
|
1
|
+
import{i as p}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as u}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runExportCommand as d}from"../packem_shared/runExportCommand-BpE4AbuX.mjs";const a=p(({argument:r,cwd:t,logger:e,options:o})=>d({cwd:t,logger:e,out:r[0]??o.out,prod:o.prod===!0,tables:o.tables,token:o.token,url:u({cwd:t,prod:o.prod===!0,url:o.url})}));export{a as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as
|
|
1
|
+
import{i as n}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as m}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{w as i,S as s}from"../packem_shared/import-DLyCq-2j.mjs";const f=n(({argument:a,cwd:r,logger:e,options:o})=>{const t=a[0];return t?o.from!==void 0&&!i.includes(o.from)?(e.error(`--from ${o.from} is not a known source. Expected one of: ${i.join(", ")}.`),{code:1}):s({batchSize:o.batchSize,cwd:r,file:t,from:o.from,logger:e,prod:o.prod===!0,scan:o.scan===!0,storageDir:o.storageDir,table:o.table,token:o.token,url:m({cwd:r,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,withStorage:o.withStorage===!0,yes:o.yes===!0}):(e.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{f as execute};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as $}from"node:fs/promises";import{tmpdir as j}from"node:os";import{discoverSchema as k,schemaFromIr as C}from"@lunora/codegen";import{seedPlan as x}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as z}from"ts-morph";import{d as F}from"../packem_shared/admin-token-BKmc3AUm.mjs";import{i as
|
|
1
|
+
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as $}from"node:fs/promises";import{tmpdir as j}from"node:os";import{discoverSchema as k,schemaFromIr as C}from"@lunora/codegen";import{seedPlan as x}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as z}from"ts-morph";import{d as F}from"../packem_shared/admin-token-BKmc3AUm.mjs";import{i as R}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as T}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{o as A}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{runResetCommand as I}from"./runResetCommand.mjs";import{S as N}from"../packem_shared/import-DLyCq-2j.mjs";const p=e=>e===""?!1:F(e),B=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,c=e=>({code:e,conflicts:0,generated:0,inserted:0,ndjson:""}),P=(e,r)=>{if(!y(r))return e.logger.error(`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`),c(1);if(e.reset===!0&&(e.prod===!0||!p(e.url)))return e.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),c(1)},U=async(e,r,o,t)=>{const l=await S(m(j(),"lunora-seed-")),a=m(l,"rows.ndjson");await v(a,e,"utf8");try{const n=await N({batchSize:t.batchSize,cwd:o,fetchImpl:t.fetchImpl,file:a,logger:t.logger,prod:t.prod,token:t.token,url:t.url}),d=n.body?.conflicts??0;return d>0&&t.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:n.code,conflicts:d,generated:r,inserted:n.inserted,ndjson:e}}finally{await $(l,{force:!0,recursive:!0}).catch(()=>{})}},_=(e,r)=>{if(e.table===void 0||r.tables.some(t=>t.name===e.table))return;const o=r.tables.map(t=>t.name).join(", ");return e.logger.error(`unknown table "${e.table}" — schema defines: ${o||"(no tables)"}`),c(1)},H=async(e,r)=>{if(!(!(e.prod===!0||!p(e.url))||e.yes===!0)){if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),c(1);if(!await(e.confirm??A)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),c(1)}},J=async e=>{const r=e.cwd??process.cwd(),o=m(r,"lunora","schema.ts"),t=P(e,o);if(t!==void 0)return t;const l=new z({skipAddingFilesFromTsConfig:!0}),a=k(l,o),n=_(e,a);if(n!==void 0)return n;const d=C(a),g=x(d,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const b of f)u.push(JSON.stringify({doc:b,table:h},B));const i=u.length>0?`${u.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`:"",s=u.length;if(
|
|
3
|
+
`:"",s=u.length;if(e.dryRun===!0)return i.length>0&&process.stdout.write(i),e.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(e.reset===!0){const f=await I({cwd:r,logger:e.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await H(e,s);return w!==void 0?w:U(i,s,r,e)},Z=R(async({cwd:e,logger:r,options:o})=>({code:(await J({batchSize:o.batchSize,count:o.count,cwd:e,dryRun:o.dryRun===!0,logger:r,prod:o.prod===!0,reset:o.reset===!0,now:o.now,seed:o.seed,table:o.table,token:o.token,url:T({cwd:e,prod:o.prod===!0,url:o.url}),yes:o.yes===!0})).code}));export{Z as execute,J as runSeedCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{writeFileSync as h,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as D,d as M,s as F,t as N}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{o as g}from"../packem_shared/cli-
|
|
1
|
+
import{writeFileSync as h,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as D,d as M,s as F,t as N}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{o as g}from"../packem_shared/cli-DYGVS96x.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(r,e)=>r.length>=e?r:r+" ".repeat(e-r.length),C=r=>`${r.id} (${r.visibility} ${r.kind})`,m=r=>{let e=0;for(const o of r)e=Math.max(e,o.id.length);return e},p=(r,e)=>` ${u(String(r.score),3)} ${l[r.coverage]} ${u(r.id,e)} ${r.visibility} ${r.kind}`,E=r=>{if(!r.comparable)return[` baseline not comparable (${r.reason}) — regenerate it; this run cannot verify anything`];if(!r.regressed)return[` no regression against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];const e=[` REGRESSED against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];for(const o of r.dropped)e.push(` ${o.id}: ${String(o.before)} → ${String(o.after)}`);for(const o of r.newFailing)e.push(` ${o}: now failing`);for(const o of r.worsened)e.push(` ${o}: more findings than the baseline`);return r.projectRegressed&&e.push(" project: new schema/config rules fired"),e},J=(r,e)=>{const o=r.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),n=m(o),t=[`advisor health ${String(r.score)}/100 — ${r.grade}`,` ${String(r.summary.clean)} clean · ${String(r.summary.warned)} warned · ${String(r.summary.failing)} failing · ${String(r.summary.exempt)} exempt (${String(r.summary.procedures)} procedures, ${String(r.summary.rulesFired)} rules fired)`];return r.project.checks.length>0&&t.push("",` project ${String(r.project.score)}/100 — ${r.project.checks.map(i=>i.name).join(", ")}`),o.length>0&&t.push("",...o.map(i=>p(i,n)),""," run with --all for every procedure, or --entry <file#export> for one"),e!==void 0&&t.push("",...E(e)),t.join(`
|
|
2
2
|
`)},O=r=>r.coverage==="exempt"?[` exempt: ${r.exemptReason===void 0||r.exemptReason===""?"no reason given":r.exemptReason}`]:r.checks.map(e=>{const o=e.occurrences>1?`, ×${String(e.occurrences)}`:"";return` ${e.name} (−${String(e.weight)}${o})`}),B=r=>{const e=new Map;for(const o of r){const n=e.get(o.file);n===void 0?e.set(o.file,[o]):n.push(o)}return[...e].toSorted(([o],[n])=>y(o,n))},P=r=>{const e=m(r.procedures),o=[`advisor health ${String(r.score)}/100 — ${r.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[n,t]of B(r.procedures)){o.push("",` ${n}`);for(const i of t)o.push(p(i,e),...O(i))}return o.join(`
|
|
3
3
|
`)},T=(r,e)=>{const o=r.procedures.find(t=>t.id===e);if(o===void 0){const t=r.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${e} in the map. Known ids:`,...t,r.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
4
|
`)}const n=[`${C(o)} — ${String(o.score)}/100, ${o.coverage}`,` weight in the global mean: ${String(o.weight)}`];if(o.checks.length===0)return n.push(""," no rule fired"),n.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as L}from"../packem_shared/cli-
|
|
1
|
+
import{i as L}from"../packem_shared/cli-DYGVS96x.mjs";import{i as J}from"../packem_shared/command-0l-ZPhIX.mjs";import{existsSync as p,readFileSync as h,mkdirSync as P,realpathSync as W,statSync as D,writeFileSync as T,chmodSync as z,renameSync as H,unlinkSync as I}from"node:fs";import{homedir as $}from"node:os";import{findWranglerFile as K}from"@lunora/config/cloudflare";import{join as s,dirname as q,relative as G}from"@visulima/path";import{l as V,M as Z}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{stringify as B}from"smol-toml";import{parse as Q,modify as X,applyEdits as Y}from"jsonc-parser";import{readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const u=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),v=o=>o.transport==="http"?{type:"http",url:o.url}:u(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:u(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:u(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):u(o),io=o=>o.transport==="http"?{url:o.url}:u(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...u(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>B({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),g=[{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:v,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],O=g.map(o=>o.id),uo=o=>g.find(t=>t.id===o.toLowerCase()),x=(o,t)=>{let e=o,r;try{e=W(o),r=D(e).mode}catch{}const a=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{T(a,t,"utf8"),r!==void 0&&z(a,r),H(a,e)}catch(n){try{I(a)}catch{}throw n}},mo={formattingOptions:{insertSpaces:!0,tabSize:4}},b=o=>{const t=[],e=Q(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},f=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),w=(o,t,e)=>{if(!f(o))return;const r=o[t];return f(r)?r[e]:void 0},C=o=>{if(!p(o.path))return"absent";let t;try{t=h(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=b(t);return e.length>0||!f(r)?"invalid":w(r,o.key,o.name)===void 0?"absent":"present"},fo=o=>C(o)==="present",E=(o,t,e,r,a)=>{try{const n=X(o,[e,r],a,mo);n.length>0&&x(t,Y(o,n));return}catch(n){return n instanceof Error?n.message:String(n)}},go=o=>{const{entry:t,force:e=!1,key:r,name:a,path:n}=o,i=p(n)?h(n,"utf8"):"";if(i.trim().length===0)return P(q(n),{recursive:!0}),x(n,`${JSON.stringify({[r]:{[a]:t}},void 0,4)}
|
|
2
2
|
`),{action:"created",path:n};const{errors:l,value:c}=b(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:n};if(!f(c))return{action:"invalid",error:"the file's root is not a JSON object",path:n};const m=c[r];if(m!==void 0&&!f(m))return{action:"invalid",error:`"${r}" is not an object`,path:n};if(w(c,r,a)!==void 0&&!e)return{action:"skipped",path:n};const j=E(i,n,r,a,t);return j===void 0?{action:"updated",path:n}:{action:"invalid",error:j,path:n}},ho=o=>{const{key:t,name:e,path:r}=o;if(!p(r))return{action:"absent",path:r};let a;try{a=h(r,"utf8")}catch(c){return{action:"invalid",error:c instanceof Error?c.message:String(c),path:r}}const{errors:n,value:i}=b(a);if(n.length>0)return{action:"invalid",error:`parse error at offset ${String(n[0]?.offset??0)}`,path:r};if(w(i,t,e)===void 0)return{action:"absent",path:r};const l=E(a,r,t,e,void 0);return l===void 0?{action:"removed",path:r}:{action:"invalid",error:l,path:r}},vo=["global","project"],d=(o,t)=>{const e=G(t,o);return e.length>0&&!e.startsWith("..")?e:o},yo=(o,t)=>{const e=o.paths(t);return vo.flatMap(r=>{const a=e[r];return a===void 0?[]:[{client:o,path:a,scope:r}]})},$o=(o,t,e,r)=>{const a=o.paths(t),n=e==="global"?"project":"global",i=a[e]??(r?void 0:a[n]);if(i!==void 0)return{client:o,path:i,scope:a[e]===void 0?n:e}},bo=o=>g.filter(t=>Object.values(t.paths(o)).some(e=>p(e))),R=(o,t,e,r)=>{if(o.length===0)return t();const a=[];for(const n of o){const i=uo(n);if(i===void 0){e.error(`mcp ${r}: unknown client "${n}". Known clients: ${O.join(", ")}.`);return}a.push(i)}return a},wo=o=>o.client.format==="json",jo="https://lunora.sh/mcp",U="lunora-docs",N="lunora",ko=o=>p(s(o,"lunora"))&&K(o)!==void 0,So=o=>{const{args:t,command:e}=Z(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},Oo=o=>({transport:"http",url:o}),xo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),_=(o,t,e)=>$o(o,xo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),Co=(o,t,e)=>{const r=_(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:a}=r,n=o.buildEntry(t.spec);if(e.print===!0){const c=d(a,e.cwd);return e.force!==!0&&fo({key:o.key,name:t.name,path:a})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(e.logger.info(`${o.label} → ${c}
|
|
3
3
|
${JSON.stringify({[o.key]:{[t.name]:n}},void 0,4)}`),{action:"printed",path:a})}const i=go({entry:n,force:e.force===!0,key:o.key,name:t.name,path:a}),l=d(a,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:a}},Eo=(o,t,e)=>{const r=_(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${d(r,e.cwd)}
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{existsSync as u}from"node:fs";import{mkdir as l,readFile as p,writeFile as m}from"node:fs/promises";import{join as n}from"node:path";import{LunoraError as f}from"@lunora/errors";import{u as g}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as k}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as w}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{runExportCommand as y}from"../packem_shared/runExportCommand-
|
|
2
|
-
`,"utf8")},
|
|
1
|
+
import{existsSync as u}from"node:fs";import{mkdir as l,readFile as p,writeFile as m}from"node:fs/promises";import{join as n}from"node:path";import{LunoraError as f}from"@lunora/errors";import{u as g}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as k}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as w}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{runExportCommand as y}from"../packem_shared/runExportCommand-BpE4AbuX.mjs";import{S as h}from"../packem_shared/import-DLyCq-2j.mjs";const $=".lunora-backups",d="manifest.json",S="/_lunora/admin/pitr",v="__lunora_admin__:getPitrBookmark",_="__lunora_admin__:pitrRestore",N=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string",c=async t=>{const o=n(t,d);if(!u(o))return[];let r;try{r=JSON.parse(await p(o,"utf8"))}catch(e){const a=e instanceof Error?e.message:String(e);throw new f("INTERNAL",`backup: ${o} exists but is not valid JSON (${a}) — refusing to overwrite it; fix or remove it manually`,{cause:e})}if(!Array.isArray(r))throw new TypeError(`backup: ${o} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(N)},O=async(t,o)=>{await m(n(t,d),`${JSON.stringify(o,void 0,2)}
|
|
2
|
+
`,"utf8")},A=async(t,o)=>{await l(o,{recursive:!0});const r=(t.now??(()=>new Date))().toISOString(),e=`lunora-backup-${r.replaceAll(/[.:]/gu,"-")}.ndjson`,a=await y({cwd:t.cwd,fetchImpl:t.fetchImpl,logger:t.logger,out:n(o,e),prod:t.prod,tables:t.tables,token:t.token,url:t.url});if(a.code!==0)return{code:a.code};const i={bytes:a.bytes,createdAt:r,file:e,id:r,rows:a.rows,tables:t.tables},s=await c(o);return s.push(i),await O(o,s),t.logger.success(`backup created: ${e} (${a.rows.toString()} rows, ${a.bytes.toString()} bytes)`),{code:0,entry:i}},E=async(t,o)=>{const r=await c(o);if(r.length===0)return t.logger.info(`no backups found in ${o}`),{code:0};for(const e of r)t.logger.info(`${e.id} ${e.rows.toString()} rows ${e.bytes.toString()} bytes ${e.file}`);return{code:0}},I=async(t,o)=>{const{target:r}=t;if(r===void 0||r.length===0)return t.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const e=(await c(o)).find(i=>i.id===r),a=e?n(o,e.file):r;return u(a)?{code:(await h({cwd:t.cwd,fetchImpl:t.fetchImpl,file:a,logger:t.logger,prod:t.prod,token:t.token,url:t.url,yes:t.yes})).code}:(t.logger.error(`backup not found: ${r}`),{code:1})},x=t=>{const o=t.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){t.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(t.restore===!0&&t.at===void 0&&t.bookmark===void 0){t.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(t.restore===!0&&t.prod===!0&&t.yes!==!0){t.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const r=g(t.url,t.logger,t.cwd);if(r===void 0)return;const e=t.pitrFetch??globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:e,requestUrl:`${r}${S}`,token:o}},T=(t,o)=>{const r={};return t.at!==void 0&&(r.time=t.at),o&&t.bookmark!==void 0&&(r.bookmark=t.bookmark),o&&t.restart===!0&&(r.restart=!0),r},q=async t=>{const o=x(t);if(o===void 0)return{code:1};const r=t.restore===!0,e=r?_:v,a=T(t,r),i=r?"restore":"bookmark";t.logger.info(`POST ${o.requestUrl} -> pitr ${i}${t.shard===void 0?"":` (shard "${t.shard}")`}`);const s=await o.fetchImpl(o.requestUrl,{body:JSON.stringify({args:a,functionPath:e,shardKey:t.shard}),headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},method:"POST"});return await b(s,t.logger),{code:s.ok?0:1}},L=async t=>{const o=t.cwd??process.cwd(),r=n(o,t.dir??$);try{return t.subcommand==="create"?await A(t,r):t.subcommand==="list"?await E(t,r):t.subcommand==="pitr"?await q(t):await I(t,r)}catch(e){return t.logger.error(e instanceof Error?e.message:String(e)),{code:1}}},R=t=>t==="create"||t==="list"||t==="pitr"||t==="restore",z=k(({argument:t,cwd:o,logger:r,options:e})=>{const a=t[0];return R(a)?L({at:e.at,bookmark:e.bookmark,cwd:o,dir:e.dir,logger:r,prod:e.prod===!0,restart:e.restart===!0,restore:e.restore===!0,shard:e.shard,subcommand:a,tables:e.tables,target:t[1],token:e.token,url:w({cwd:o,prod:e.prod===!0,url:e.url}),yes:e.yes===!0}):(r.error(`backup: unknown subcommand "${a??""}" — expected create | list | restore | pitr`),{code:1})});export{z as execute,L as runBackupCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as u,mkdirSync as S,writeFileSync as p,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as T,readPackageDependencies as A,discoverMigrations as E}from"@lunora/codegen";import{isInteractive as z,promptSelect as F,promptText as N}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as f}from"ts-morph";import{u as R}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as q}from"../packem_shared/command-0l-ZPhIX.mjs";import{diffSnapshots as O,renderMigrationFile as D}from"../packem_shared/diffSnapshots-BbwCuhoN.mjs";import{d as L}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import j from"../packem_shared/schemaIrToSnapshot-Dahp39qH.mjs";import{readAndLogBody as B}from"./runRpcCommand.mjs";import{runExportCommand as H}from"../packem_shared/runExportCommand-
|
|
1
|
+
import{existsSync as u,mkdirSync as S,writeFileSync as p,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as T,readPackageDependencies as A,discoverMigrations as E}from"@lunora/codegen";import{isInteractive as z,promptSelect as F,promptText as N}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as f}from"ts-morph";import{u as R}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as q}from"../packem_shared/command-0l-ZPhIX.mjs";import{diffSnapshots as O,renderMigrationFile as D}from"../packem_shared/diffSnapshots-BbwCuhoN.mjs";import{d as L}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import j from"../packem_shared/schemaIrToSnapshot-Dahp39qH.mjs";import{readAndLogBody as B}from"./runRpcCommand.mjs";import{runExportCommand as H}from"../packem_shared/runExportCommand-BpE4AbuX.mjs";import{S as P}from"../packem_shared/import-DLyCq-2j.mjs";const Z=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},J=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},K=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},Q=r=>{if(u(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new $("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new $("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},W=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!u(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new f({skipAddingFilesFromTsConfig:!0}),n=T(t,o),s=j(n),i=c(e,"lunora","migrations"),a=c(i,Z);let d;try{d=Q(a)}catch(g){return r.logger.error(g instanceof Error?g.message:String(g)),{code:1,empty:!0,migrationFile:""}}const l=O(d,s);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const h=(r.now??(()=>new Date))(),w=J(r.name??"auto"),b=`${K(h)}_${w}.sql`,m=c(i,b);S(i,{recursive:!0});const _=D(w,l,h.toISOString());return p(m,_,"utf8"),p(a,`${JSON.stringify(s,void 0,4)}
|
|
2
2
|
`,"utf8"),r.logger.success(`wrote ${m}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${b} and write the SQL manually`),{code:0,empty:!1,migrationFile:m}},Y="migrations.ts",y=/^[A-Za-z_]\w*$/u,G=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),v=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,V=r=>`import { defineMigration } from "${A(r)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,X="__lunora_admin__:runMigration",rr="__lunora_admin__:migrationStatus",er="/_lunora/migrate",tr=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),or=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),nr=r=>{const e=c(r,"lunora","schema.ts");if(!u(e))return[];try{const o=new f({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},ir=async r=>r.length>0?F("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):N("Target table for the migration: "),ar=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(z()?ir:void 0);if(o===void 0){e.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const t=(await o(nr(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},sr=async r=>{const e=r.cwd??process.cwd(),o=tr(r.name);if(o==="")return r.logger.error(`invalid migration name: "${r.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=or(o);if(!y.test(t)||G.has(t))return r.logger.error(`invalid migration name: "${r.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await ar(e,r);if(n===void 0)return{code:1,file:""};if(!y.test(n))return r.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(e,"lunora"),i=c(s,Y);let a=u(i)?k(i,"utf8"):"";if(a.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(a))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};const d=V(e);a.trim()===""?a=`${d}
|
|
3
3
|
`:v.test(a)?a=a.replace(v,d):a=`${d}
|
|
4
4
|
${a}`;const l=`export const ${t} = defineMigration({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as S,t as A,i as C,f as D}from"./cli-
|
|
1
|
+
import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as S,t as A,i as C,f as D}from"./cli-DYGVS96x.mjs";import"./detect-package-manager-DXDstphE.mjs";import"./createLogger-BoSxdb2T.mjs";export{S as COMMANDS,A as REGISTERED_COMMAND_NAMES,C as VERSION,D as runCli};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"node:fs";import"node:fs/promises";import"./admin-token-BKmc3AUm.mjs";import"./admin-url-Ca-KI3d_.mjs";import{R as I,S as T}from"./import-DLyCq-2j.mjs";import"./shared-Ce9bKz5c.mjs";export{I as DEFAULT_IMPORT_BATCH_SIZE,T as runImportCommand};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{mkdirSync as A,readFileSync as w,lstatSync as B,writeFileSync as D}from"node:fs";import{join as u,dirname as y}from"node:path";import{fileURLToPath as L}from"node:url";import{resolveHint as j,isLunoraError as S,flattenHint as E,findSolutionByMessage as C}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import $ from"@visulima/cerebro/command/completion";import T from"@visulima/cerebro/command/version";import{p}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{P,l as _}from"./detect-package-manager-DXDstphE.mjs";import{createLogger as k}from"./createLogger-BoSxdb2T.mjs";import{VisulimaError as U,renderError as M}from"@visulima/error";import{homedir as W}from"node:os";const J={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}]},f="lunora.advisor.map.json",K={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/handler21.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 ${f})`,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 ${f})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"no-write",type:Boolean}]},F={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}]},q={argument:{description:"create | list | restore <id|file> | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) 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 pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{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 production pitr --restore (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}]},H={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/handler4.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]},z={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]},V={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/handler5.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}]},G={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 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}]},Y={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/handler6.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}]},Q={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)"],["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 --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:"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:"Don't start the embedded studio server",name:"no-studio",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:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},X={argument:{description:"Optional path under the docs site (e.g. addons/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 addons/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"docs"},Z={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"]],group:"Project",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"doctor",options:[]},ee={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/handler9.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}]},te={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},re={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/handler10.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}]},oe={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/handler11.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}]},ne={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"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},ae={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 --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:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",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}]},ie={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/handler13.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}]},se={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/handler24.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 (default true; --no-procedures to skip)",name:"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}]},le={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/handler14.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}]},pe={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/handler22.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}]},de={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"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.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: 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)",name:"token",type:String}]},ce={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}]},ue={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/handler15.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}]},me={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/handler16.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}]},ge={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}]},he={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/handler17.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}]},fe={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/handler18.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}]},ve={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/handler19.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:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},s]},be={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/handler20.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},we={filterStacktrace:()=>!1,hideErrorCodeView:!0},Se=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=j(S(e)?{code:e.code,hint:e.hint,message:r}:r),n=new U({hint:o===void 0?void 0:E(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,we)},ke=(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},xe=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ke(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,Ne=1500,Ae="0.0.0",Be=/^v/u,De=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},Ee=(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)},Ce=e=>{const t=m(e).prerelease.split(".")[0]??"";return De.has(t)?t:"latest"},Ie=(e,t)=>Ee(t,e)>0,$e=(e,t,r)=>t-e<r,Te=(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}=P(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},x=e=>u(e,"lunora-cli-update.json"),Pe=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{A(r,{mode:448,recursive:!0})}catch{}return r},_e=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(B(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
|
|
3
|
+
`,"utf8")}catch{}},Ue=async(e,t)=>{try{const r=await e(Re(t),{signal:AbortSignal.timeout(Ne)});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}},Me=(e,t,r)=>e===Ae||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,We=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Me(e.current,t,r))return;const o=e.cacheDir??Pe(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ce(e.current),d=_e(o),N=d?.tag??"latest",g=d!==void 0&&N===i?d:void 0;let c=g?.latest;if(g===void 0||!$e(g.checkedAt,n,a)){const h=await Ue(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&&Ie(e.current,c)&&e.logger.warn(Te(e.current,c,i,e.manager))},Je=["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"],Ke=8,Fe=()=>{try{let e=y(L(import.meta.url));for(let t=0;t<Ke;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=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Fe(),qe=[ae,J,Q,z,K,H,G,V,ue,le,Y,pe,ye,ie,ge,ce,re,oe,fe,se,q,te,ve,ne,Z,ee,F,be,X,me,he,de],O=[...qe,T,$],dt=O.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),He=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:He(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Ve=e=>{const t={value:0},r=I("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:R});for(const o of O)r.addCommand(ze(o));return{cli:r,exitCode:t}},Ge=/Command "(?<name>[^"]+)" not found/u,Ye=e=>{const t=k(),r=e instanceof Error?e.message:String(e),o=Ge.exec(r);if(!o?.groups){S(e)||C(r)!==void 0?t.error(Se(e)):t.error(r);return}const n=o.groups.name??"",a=xe(n,Je);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.")},ct=async(e={})=>{const{cli:t,exitCode:r}=Ve(e);try{await t.run({shouldExitProcess:!1})}catch(n){return Ye(n),1}let o;try{o=_(process.cwd())}catch{}return await We({current:R,logger:k(),manager:o}),r.value};export{Je as d,ct as f,R as i,f as o,dt as t};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{createReadStream as N}from"node:fs";import{open as Be,stat as x,readdir as A,realpath as Z,readFile as y,mkdir as C,writeFile as ce,appendFile as De}from"node:fs/promises";import{l as We}from"./admin-token-BKmc3AUm.mjs";import{u as qe}from"./admin-url-Ca-KI3d_.mjs";import{join as m,resolve as j,sep as L,basename as p,dirname as le,relative as He}from"node:path";import{createInterface as O}from"node:readline";import Ke from"adm-zip";import{Transform as Ye}from"node:stream";import{createInflateRaw as Ge,crc32 as Ze}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{parse as Xe}from"csv-parse/sync";import{parse as de}from"csv-parse";import{n as z,e as Qe,t as et}from"./shared-Ce9bKz5c.mjs";import{createHash as tt}from"node:crypto";const rt=67324752,E=30,nt=26,ot=28,X=0,it=8,st=async(e,t)=>{const r=await Be(e,"r");try{const n=Buffer.alloc(E),{bytesRead:o}=await r.read(n,0,E,t);if(o<E||n.readUInt32LE(0)!==rt)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+E+n.readUInt16LE(nt)+n.readUInt16LE(ot)}finally{await r.close()}},Q=e=>{let t=0;return new Ye({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,o){t=Ze(r,t),o(void 0,r)}})},at=async(e,t)=>{const{compressedSize:r,encrypted:n,method:o,offset:i}=t.header;if(n)throw new Error(`${t.entryName} is encrypted — decrypt the archive before importing`);if(o!==X&&o!==it)throw new Error(`${t.entryName} uses unsupported compression method ${String(o)} — 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 s=await st(e,i),a=N(e,{end:s+r-1,start:s});if(o===X){const d=Q(t);return a.on("error",u=>d.destroy(u)),a.pipe(d)}const c=Ge(),l=Q(t);return a.on("error",d=>c.destroy(d)),c.on("error",d=>l.destroy(d)),a.pipe(c).pipe(l)},S="_storage",ue=e=>e.startsWith("_"),ct=e=>{for(const t of e.getEntries()){const r=t.entryName.replaceAll("\\","/").split("/");if(r.length>=2&&r[r.length-2]==="_storage")return r.slice(0,-1).join("/")}return"_storage"},lt=async e=>{const t=await x(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new Ke(e);return{kind:"zip",storagePrefix:ct(r),zip:r,zipPath:e}}},dt=async e=>{const t=[];for(const r of await A(e,{withFileTypes:!0})){if(!r.isDirectory())continue;const n=m(e,r.name,"documents.jsonl");(await x(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},ut=e=>{const t=[];for(const r of e.getEntries()){if(r.isDirectory)continue;const n=r.entryName.replaceAll("\\","/"),o=n.split("/");o.length>=2&&o[o.length-1]==="documents.jsonl"&&t.push({file:n,table:o[o.length-2]})}return t},ft=async e=>{const t=e.kind==="directory"?await dt(e.root):ut(e.zip);return t.length>0?t.toSorted((r,n)=>r.table.localeCompare(n.table)):void 0},P=async function*(e,t){if(e.kind==="directory"){for await(const i of O({crlfDelay:Number.POSITIVE_INFINITY,input:N(t.file,{encoding:"utf8"})}))yield i;return}const r=e.zip.getEntry(t.file);if(r===null)throw new Error(`missing ${t.file} in archive`);const n=await at(e.zipPath,r);if(n===void 0)return;const o=O({crlfDelay:Number.POSITIVE_INFINITY,input:n});try{for await(const i of o)yield i}finally{o.close(),n.destroy()}},gt=async(e,t)=>{if(e.kind==="directory"){const n=await Z(m(e.root,"_storage")),o=await Z(j(n,t)).catch(()=>{});if(o===void 0||o!==n&&!o.startsWith(n+L))throw new Error(`blob ${t} resolves outside the snapshot's _storage directory`);return y(o)}const r=e.zip.readFile(`${e.storagePrefix}/${t}`);if(r===null)throw new Error(`missing blob ${t} in archive`);return Buffer.from(r)},ht=e=>{const t={conflicts:0,errors:[],inserted:{},received:0,warnings:[]};let r=[],n=0;const o=s=>{for(const[a,c]of Object.entries(s.inserted??{}))t.inserted[a]=(t.inserted[a]??0)+c;t.errors.push(...s.errors??[]),t.conflicts+=s.conflicts??0,t.received+=s.received??0;for(const a of s.warnings??[])t.warnings.includes(a)||t.warnings.push(a)},i=async()=>{if(r.length===0)return;const s=r.join(`
|
|
2
|
+
`);r=[],n=0;const a=await e.fetchImpl(e.requestUrl,{body:s,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!a.ok){const c=await a.text().catch(()=>"<no body>");throw new f("INTERNAL",`import batch failed (HTTP ${String(a.status)}): ${c}`)}o(await a.json())};return{flush:i,push:async s=>{const a=Buffer.byteLength(s)+1;r.length>0&&n+a>e.maxBatchBytes&&await i(),r.push(s),n+=a,r.length>=e.batchSize&&await i()},totals:t}},fe=(e,t,r,n)=>{const o=[],i=[];let s=0;const a=d=>n?.[r]?.includes(d)===!0,c=(d,u,g=!1)=>{if(Array.isArray(d))return d.map(h=>c(h,u,g));if(d!==null&&typeof d=="object"){const h=d;if(typeof h.$storage=="string"){const b=h.$storage,$=t.get(b);return $===void 0?(i.push({column:u,storageId:b,table:r}),d):(s+=1,$)}return Object.fromEntries(Object.entries(h).map(([b,$])=>[b,c($,u)]))}return typeof d=="string"&&t.has(d)?a(u)?(s+=1,t.get(d)??d):(o.push({column:u,storageId:d,table:r}),d):(g&&typeof d=="string"&&d.length>0&&a(u)&&n!==void 0&&i.push({column:u,storageId:d,table:r}),d)},l=Object.fromEntries(Object.entries(e).map(([d,u])=>[d,c(u,d,!0)]));return{ambiguous:o,document:l,rewritten:s,unmigrated:i}},pt=e=>{const{remapDocument:t,report:r,storageColumns:n,storageIdMap:o,table:i}=e,s=(c,l)=>{let d;try{d=JSON.parse(c)}catch(u){const g=u instanceof Error?u.message:String(u);throw new f("INTERNAL",`invalid JSON on line ${String(l)}: ${g}`,{cause:u})}return JSON.stringify({doc:d,table:i})},a=(c,l)=>{let d;try{d=JSON.parse(c)}catch(u){throw new f("INTERNAL",`line ${String(l)}: import envelope is not valid JSON — ${u instanceof Error?u.message:String(u)}`,{cause:u})}if(typeof d.table!="string")throw new f("INTERNAL",`line ${String(l)}: import envelope is missing a string \`table\``);if(d.doc!==null&&typeof d.doc=="object"&&!Array.isArray(d.doc)){let u=d.doc;if(o!==void 0){const g=fe(u,o,d.table,n);u=g.document,r.rewritten+=g.rewritten,r.ambiguous.push(...g.ambiguous),r.unmigrated.push(...g.unmigrated)}d.doc=t===void 0?u:t(u,d.table)}return JSON.stringify(d)};return(c,l)=>{const d=c.trim();if(d.length!==0)return i!==void 0?s(d,l):o===void 0&&t===void 0?d:a(d,l)}},ge=async(e,t,r,n)=>{const o=await n(e).catch(()=>{});if(o===void 0)throw new f("INTERNAL",`${e} is not a readable directory`);const i=new Map;for(const[l,d]of Object.entries(t?.tables??{}))d.file!==void 0&&i.set(p(d.file),l);const s=o.filter(l=>l.isFile()&&r.matches(l.name)&&!r.authFiles.has(l.name)).map(l=>({file:m(e,l.name),table:i.get(l.name)??r.tableNameOf(l.name)}));if(s.length===0)throw new f("INTERNAL",`${e} ${r.emptyMessage}`);const a=new Set(s.map(l=>p(l.file))),c=[...i].filter(([l])=>!a.has(l));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(([l,d])=>`\`${l}\` (table \`${d}\`)`).join(", ")}. Check the name and that the file is one this source reads.`);return s.toSorted((l,d)=>l.table.localeCompare(d.table))},he=async function*(e,t,r,n){for(const o of e){r.has(o.table)||r.set(o.table,0),t.info(`reading ${p(o.file)} → ${o.table}`);for await(const i of n(o))r.set(o.table,(r.get(o.table)??0)+1),yield`${JSON.stringify({doc:i,table:o.table})}
|
|
3
|
+
`}},pe=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],mt=e=>pe.includes(e),wt=/^\\x([\dA-Fa-f]*)$/,ee=/^[+-]?\d+$/,me=/[+-]\d{2}$/,we=/(?:Z|[+-]\d{2}:\d{2})$/i,$e=/^\+/,$t=/e/i,yt=/e/i,bt=e=>{const[t="0",r="0"]=e.split(yt),n=Number(r),o=t.startsWith("-"),[i="0",s=""]=(o?t.slice(1):t).replace($e,"").split("."),a=`${i}${s}`,c=i.length+n;let l;return c<=0?l=`0.${"0".repeat(-c)}${a}`:c>=a.length?l=`${a}${"0".repeat(c-a.length)}`:l=`${a.slice(0,c)}.${a.slice(c)}`,o?`-${l}`:l},vt=/^0+(?=\d)/,te=e=>{const t=($t.test(e.trim())?bt(e.trim()):e.trim()).replace($e,""),r=t.startsWith("-"),[n="0",o=""]=(r?t.slice(1):t).split("."),i=n.replace(vt,"");let s=o.length;for(;s>0&&o[s-1]==="0";)s-=1;const a=o.slice(0,s),c=a.length>0?`${i}.${a}`:i;return r&&Number(c)!==0?`-${c}`:c},w=(e,t,r,n)=>{throw new f("INTERNAL",`column \`${e}\`: cannot reshape ${JSON.stringify(r)} as \`${t}\` — ${n}`)},re=(e,t,r)=>{const n=r.includes("T")?r:r.replace(" ","T"),o=me.test(n)?`${n}:00`:n,i=we.test(o)?o:`${o}Z`,s=Date.parse(i);return Number.isNaN(s)&&w(e,t,r,"not a date Postgres or ISO-8601 syntax can express"),s},Nt=(e,t)=>{(!t.startsWith("{")||!t.endsWith("}"))&&w(e,"text-array",t,"not a Postgres array literal (expected `{…}`)");const r=t.slice(1,-1);if(r.length===0)return[];r.includes("{")&&w(e,"text-array",t,"nested arrays are not supported — map the column to `json` instead");const n=[];let o="",i=!1,s=!1,a=!1;const c=()=>{n.push(!s&&o==="NULL"?null:o),o="",s=!1};for(const l of r)a?(o+=l,a=!1):l==="\\"?a=!0:l==='"'?(i=!i,s=!0):l===","&&!i?c():o+=l;return c(),n},ye=(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:w(e,t,r,"not a Postgres boolean literal");case"bytea-base64":{const n=wt.exec(r);if(n===null)return w(e,t,r,"not `bytea` hex output (expected a leading `\\x`) — set `bytea_output = 'hex'` before dumping");const o=n[1];return o.length%2!==0?w(e,t,r,"has an odd number of hex digits, so the dump is truncated — re-export the column"):Buffer.from(o,"hex").toString("base64")}case"int8-string":return ee.test(r)?r:w(e,t,r,"not an integer");case"json":try{return JSON.parse(r)}catch(n){return w(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 w(e,t,r,"not a finite number");if(ee.test(r)){if(!Number.isSafeInteger(n))return w(e,t,r,"exceeds Number.MAX_SAFE_INTEGER — map this column to `int8-string` to keep it lossless")}else if(te(String(n))!==te(r))return w(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 Nt(e,r);case"timestamp-iso":{re(e,t,r);const n=r.includes("T")?r:r.replace(" ","T"),o=me.test(n)?`${n}:00`:n;return we.test(o)?o:`${o}Z`}case"timestamp-ms":return re(e,t,r);default:return r}},St="auth.",Tt=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),It=String.raw`\N`,be=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===It?null:e,Et=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>p(t))),kt=async(e,t)=>ge(e,t,{authFiles:Et(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(St),tableNameOf:r=>p(r,".csv")},async r=>A(r,{withFileTypes:!0})),xt=(e,t,r)=>{const n=t?.idColumn??"id",o=t?.types??{},i={};let s=!1;for(const[a,c]of Object.entries(e)){if(Tt.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 l=o[a],d=l===void 0?c:ye(a,l,c);if(a===n){if(c===null)throw new f("INTERNAL",`id column \`${n}\` is NULL — every row needs an id to preserve`);i._id=c,s=!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.`);i[a]=d}}if(!s)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 i},At=async function*(e,t){const r=t?.tables?.[e.table],n=N(e.file).pipe(de({cast:be,columns:!0,relaxColumnCountLess:!1,skipEmptyLines:!0}));let o=0;const i=n[Symbol.asyncIterator]();for(;;){let s,a;try{if(s=await i.next(),s.done===!0)return;o+=1,a=xt(s.value,r,e.table)}catch(c){throw new f("INTERNAL",`${p(e.file)} row ${String(o+1)}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}yield a}},Rt=async function*(e,t,r,n,o){yield*Se("supabase",o,t,r,n),yield*he(e,r,n,i=>At(i,t))},jt=/^\d+$/,Lt=/[+-]\d{2}$/,_=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&jt.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(Lt.test(r)?`${r}:00`:r);return Number.isNaN(n)?void 0:n},ve=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},Ot=e=>{const t=ve(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]}},_t=e=>{const t=ve(e);if(t!==void 0){for(const r of["avatar_url","picture"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},Ct=(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,o={_id:r,email:e.email??null,emailVerified:typeof e.email_confirmed_at=="string"&&e.email_confirmed_at.length>0,id:r},i=Ot(n),s=_t(n),a=_(e.created_at),c=_(e.updated_at);return i!==void 0&&(o.name=i),s!==void 0&&(o.image=s),a!==void 0&&(o.createdAt=a),c!==void 0&&(o.updatedAt=c),{accounts:t.map(l=>{const d=typeof l.provider=="string"?l.provider:"unknown",u=typeof l.provider_id=="string"?l.provider_id:r,g=`${r}:${d}:${u}`;return{_id:g,accountId:u,id:g,providerId:d,userId:r}}),user:o}},zt=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=_(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,s=o.rawId??o.federatedId??t,a=`${t}:${i}:${s}`;return{_id:a,accountId:s,id:a,providerId:i,userId:t}}),user:r}},Pt=(e,t)=>{const r=new Map,n=[],o=[];for(const{accounts:i,user:s}of e){const a=typeof s.email=="string"?s.email.toLowerCase():void 0;if(a!==void 0&&a.length>0){const c=r.get(a);c===void 0?r.set(a,String(s._id)):n.push(`${a} (ids ${c} and ${String(s._id)})`)}o.push(`${JSON.stringify({doc:s,table:"user"})}
|
|
4
|
+
`),t.set("user",(t.get("user")??0)+1);for(const c of i)o.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 o},U=(e,t)=>m(e,p(t)),Ne=async e=>{const t=await y(e,"utf8");return Xe(t,{cast:be,columns:!0,skipEmptyLines:!0})},Ut=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Ne(U(e,t))){const o=n.user_id;typeof o=="string"&&r.set(o,[...r.get(o)??[],n])}return r},Jt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Ne(U(e,r)),o=await Ut(e,t.auth?.identitiesFile);return n.map(i=>Ct(i,o.get(i.id??"")??[]))},Ft=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=U(e,r);let o;try{o=JSON.parse(await y(n,"utf8"))}catch(s){throw new f("INTERNAL",`${p(n)}: invalid JSON — ${s instanceof Error?s.message:String(s)}`,{cause:s})}const i=Array.isArray(o)?o:o.users??[];if(!Array.isArray(i))throw new f("INTERNAL",`${p(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return i.map(s=>zt(s))},Se=async function*(e,t,r,n,o){if(r?.auth?.file===void 0)return;const i=e==="supabase"?await Jt(t,r):await Ft(t,r);n.info(`auth: ${String(i.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const s of Pt(i,o))yield s},ne=/\.(?:nd)?json$/i,Te=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},Vt=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},Mt=(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")},Bt=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Vt(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},Dt=(e,t)=>typeof e=="string"?e:Mt(e,t),Ie=(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 Bt(e.timestampValue,t);if(e.bytesValue!==void 0)return Dt(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 Te(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>Ie(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return Ee(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},Wt=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},Ht=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>Wt.has(r))&&!qt(t)},Ee=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ie(n,`${t}.${r}`)])),Kt=(e,t,r,n)=>{const o=Ht(e),i=Ee(o?e.fields??{}:e,n),s=e.name??e.__name__,a=typeof s=="string"?Te(s):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[l,d]of Object.entries(c)){const u=i[l];if(u!==void 0){if(u!==null&&typeof u!="boolean"&&typeof u!="number"&&typeof u!="string")throw new f("INTERNAL",`${n}.${l}: a \`${d}\` reshape needs a scalar, but this field decoded to an object or array`);i[l]=ye(l,d,u===null?null:String(u))}}return{...i,_id:a}},Yt=async(e,t)=>ge(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[p(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>ne.test(r),tableNameOf:r=>r.replace(ne,"")},async r=>A(r,{withFileTypes:!0})),Gt=async function*(e){const t=O({crlfDelay:Number.POSITIVE_INFINITY,input:N(e,"utf8")});let r=0;try{for await(const n of t){r+=1;const o=n.trim();if(o.length!==0)try{yield{raw:JSON.parse(o)}}catch(i){throw new f("INTERNAL",`${p(e)} line ${String(r)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}}}finally{t.close()}},Zt=async e=>{const t=await y(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,o])=>({fallbackId:n,raw:o}));throw new f("INTERNAL",`${p(e)}: expected an object, an array, or \`{ documents: [...] }\``)},Xt=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?Gt(e.file):await Zt(e.file);let o=0;for await(const i of n)yield Kt(i.raw,i.fallbackId,r,`${e.table}[${String(o)}]`),o+=1},Qt=async function*(e,t,r,n,o){yield*Se("firebase",o,t,r,n),yield*he(e,r,n,i=>Xt(i,t))},I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),J=(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},ke=(e,t,r)=>{const n=e[t];if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))throw new f("INTERNAL",`${r}: \`${t}\` must be an array of column names`);return n},er=(e,t)=>{const r=J(e,t),n=T(r,"file",t),o=T(r,"idColumn",t),i=ke(r,"storageColumns",t),{types:s}=r;if(s!==void 0){if(!I(s))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(s))if(!mt(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${pe.join(", ")}`)}return{file:n,idColumn:o,storageColumns:i,types:s}},tr=(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`)}},rr=(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,er(n,`${t}: tables.${r}`)]))}},nr=(e,t)=>{const r=J(e,t),n=T(r,"keyPrefix",t),{auth:o,tables:i}=r;return tr(o,t),{auth:o,keyPrefix:n,tables:rr(i,t)}},xe=e=>m("lunora",`import-${e}.json`),or=async(e,t,r)=>{const n=xe(t),o=m(e,n);let i;try{i=await y(o,"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 s;try{s=JSON.parse(i)}catch(a){throw new f("INTERNAL",`${o}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return nr(s,o)},ir=8,sr=24*1048576,ar=1e3,cr=/^[\dA-F]{64}$/i,lr=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},dr=/^[\d+/A-Z]{43}=$/i,ur=e=>cr.test(e)?e.toLowerCase():dr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,fr=(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 o=ur(r.sha256);if(o===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"||!lr(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:o,size:r.size}},F=async(e,t,r)=>{const n=[];try{let o=0;for await(const i of P(e,t)){const s=i.trim();o+=1,s.length>0&&n.push(fr(s,`_storage/documents.jsonl line ${String(o)}`))}}catch(o){const i=o instanceof Error?o.message:String(o);throw r.error(`failed to read _storage metadata: ${i}`),o}return n},Ae=32*1048576,V=async(e,t)=>{const r=[];let n;do{const o=`${e.baseUrl}${z}?prefix=${encodeURIComponent(t)}&limit=${String(ar)}${n===void 0?"":`&cursor=${encodeURIComponent(n)}`}`,i=await e.fetchImpl(o,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const c=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(i.status)}): ${c}`)}const s=await i.json();r.push(...s.objects??[]);const a=s.truncated===!0?s.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},gr=async(e,t,r,n)=>{const o=`${e.baseUrl}${z}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}`,i=await e.fetchImpl(o,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!i.ok){const a=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(i.status)}): ${a}`)}const s=await i.json();if(s.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${s.sha256??"none"}`);return t},hr=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${z}?key=${encodeURIComponent(t)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,pr=async(e,t,r,n,o)=>{const i=`${e.baseUrl}${Qe}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}`,s=await e.fetchImpl(i,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!s.ok){const h=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(Ae)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(s.status)}): ${h}`)}const{url:a}=await s.json(),c=await e.fetchImpl(a,{body:new Uint8Array(r),headers:{"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!c.ok){const h=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${h}`)}const l=(await V(e,t)).find(h=>h.key===t);if(l===void 0)throw new f("INTERNAL",`post-upload verification failed: blob not found at key ${t}`);const d=l.size!==void 0&&l.size!==n.size,u=l.sha256!==void 0&&l.sha256.toLowerCase()!==n.sha256;if(d||u){const h=await hr(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")}${h?" (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&&o.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},Re=async(e,t,r,n,o)=>{const i=`${n}${r.sha256}`;if(t.length!==r.size)throw new f("INTERNAL",`blob ${r.id} is ${String(t.length)} bytes on disk but the export declares ${String(r.size)}`);return t.length<=Ae?gr(e,i,t,r):pr(e,i,t,r,o)},mr=e=>{const t=[];let r=[],n=0;for(const o of e)r.length>0&&(r.length>=ir||n+o.size>sr)&&(t.push(r),r=[],n=0),r.push(o),n+=o.size;return r.length>0&&t.push(r),t},wr=async(e,t,r,n,o)=>{const i=await F(t,r,o),s=new Map,a=await V(e,n),c=new Map(a.map(u=>[u.key,u])),l=[];for(const u of i){const g=`${n}${u.sha256}`;c.get(g)?.size===u.size?s.set(u.id,g):l.push(u)}o.info(`migrating ${String(l.length)} storage blobs${s.size>0?` (${String(s.size)} already present)`:""}...`);const d=async u=>{try{const g=await gt(t,u.id);s.set(u.id,await Re(e,g,u,n,o))}catch(g){const h=g instanceof Error?g.message:String(g);throw o.error(`failed to upload blob ${u.id}: ${h}`),g}};for(const u of mr(l)){const g=(await Promise.allSettled(u.map(h=>d(h)))).find(h=>h.status==="rejected");if(g!==void 0)throw g.reason}return o.success(`migrated ${String(l.length)} storage blobs`),s};async function*$r(e,t,r){let n=0;for await(const o of P(e,t)){const i=o.trim();if(n+=1,i.length===0)continue;let s;try{s=JSON.parse(i)}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:s,table:t.table})}
|
|
6
|
+
`}}async function*yr(e,t,r,n,o){for(const i of t){if(ue(i.table)){i.table===S&&!n&&r.warn(`skipping "${S}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}o.has(i.table)||o.set(i.table,0),yield*$r(e,i,o)}}const Ln=["firebase","supabase"],br=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 or(r,t,e.logger),o=Object.values(n?.tables??{}).some(i=>(i.storageColumns??[]).length>0);return e.verify===!0&&e.withStorage!==!0&&o?(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 Yt(e.file,n),kind:"firebase",mapping:n}},vr=async e=>{if(!await x(e.file).then(()=>!0,()=>!1))return!1;for(const[t,r]of[["--scan",e.scan],["--verify",e.verify],["--with-storage",e.withStorage]])if(r===!0)return e.logger.error(`${t} requires a Convex export directory or .zip snapshot — ${e.file} is not one.`),!0;return!1},Nr=async(e,t,r)=>{const n=t.find(i=>i.table===S);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 o=await F(e,n,r.logger);return o.length>0?(r.logger.error(`--verify on an export carrying ${String(o.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),!0):!1},Sr=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return br(e,e.from,t);const r=await lt(e.file),n=r===void 0?void 0:await ft(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 vr(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 Nr(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},k=m("lunora","import-convex.json"),Tr=(e,t)=>{const r=J(e,t),n=T(r,"keyPrefix",t),o=r.storageColumns;if(o!==void 0){if(!I(o))throw new f("INTERNAL",`${t}: \`storageColumns\` must be an object of table → column names`);for(const i of Object.keys(o))ke(o,i,`${t}: storageColumns`)}return{keyPrefix:n,storageColumns:o}},Ir=async(e,t)=>{const r=m(e,k);let n;try{n=await y(r,"utf8")}catch(i){if(i.code==="ENOENT"){t.info(`no ${k} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw i}let o;try{o=JSON.parse(n)}catch(i){throw new f("INTERNAL",`${r}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}return Tr(o,r)},Er=(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(s=>[s,s])),o=[];let i=0;for await(const s of P(e,t)){const a=s.trim();if(i+=1,a.length===0)continue;const{ambiguous:c}=fe(Er(a,t.table,i),n,t.table);for(const{column:l}of c)o.includes(l)||o.push(l)}return o},xr=async(e,t,r)=>{const n={};for(const o of t){if(ue(o.table))continue;const i=await kr(e,o,r);i.length>0&&(n[o.table]=i)}return n},Ar=async(e,t,r)=>{const n=m(t,k),o=`${JSON.stringify(e,void 0,4)}
|
|
7
|
+
`;await C(m(t,"lunora"),{recursive:!0});try{await ce(n,o,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(i){if(i.code!=="EEXIST")throw i;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(o)}},Rr=async(e,t,r,n)=>{const o=t.find(c=>c.table===S);if(o===void 0){n.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const i=await F(e,o,n),s=new Set(i.map(c=>c.id));n.info(`found ${String(s.size)} storage ids`);const a={keyPrefix:"",storageColumns:await xr(e,t,s)};return await Ar(a,r,n),a},v=20,jr=(e,t,r)=>{let n=0;if(r.conflicts===0)for(const[o,i]of t){const s=r.inserted[o]??0;s<i&&(n+=1,e.error(`verify: ${o} inserted ${String(s)} of ${String(i)} source rows (${String(i-s)} missing)`))}else{const o=[...t.values()].reduce((s,a)=>s+a,0),i=Object.values(r.inserted).reduce((s,a)=>s+a,0)+r.conflicts;i<o&&(n+=1,e.error(`verify: ${String(i)} of ${String(o)} source rows accounted for across all tables (${String(o-i)} 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},oe=(e,t,r)=>{const n=new Set;for(const o of t){const i=`${o.table} ${o.column} ${o.storageId}`;n.has(i)||(n.add(i),n.size<=v&&e.warn(r(o)))}n.size>v&&e.warn(`… and ${String(n.size-v)} more`)},Lr=(e,t,r)=>(e.info(`storage refs: ${String(t.rewritten)} rewritten, ${String(t.unmigrated.length)} unmigrated, ${String(t.ambiguous.length)} ambiguous`),oe(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\``),oe(e,t.ambiguous,n=>`unrewritten storage id in ${n.table}.${n.column}: ${n.storageId} — if that column holds storage references, add it to ${k} 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),Or=(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},ie=200,_r=/^\\x[\dA-Fa-f]*$/,Cr=/^[+-]?\d+$/,zr=/^[+-]?\d+\.\d+$/,Pr=/^\{.*\}$/,Ur=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,Jr=[["bytea-base64",e=>_r.test(e)],["timestamp-ms",e=>Ur.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Cr.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>zr.test(e)],[e=>e.every(t=>Pr.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],Fr=e=>{if(e.length!==0){for(const[t,r]of Jr)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},Vr=(e,t)=>{for(const[r,n]of Object.entries(e)){if(n.length===0)continue;const o=t.get(r);o===void 0?t.set(r,[n]):o.push(n)}},Mr=async e=>{const t=new Map,r=N(e).pipe(de({columns:!0,skipEmptyLines:!0,toLine:ie+1}));let n=0;for await(const i of r)if(Vr(i,t),n+=1,n>=ie)break;r.destroy();const o={};for(const[i,s]of t){const a=Fr(s);a!==void 0&&(o[i]=a)}return o},je=async(e,t,r,n)=>{const o=xe(r),i=m(t,o),s=`${JSON.stringify(e,void 0,4)}
|
|
8
|
+
`;await C(le(i),{recursive:!0});try{await ce(i,s,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${i} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${i} already exists — leaving it untouched. Candidate mapping:`),n.info(s)}},Br=async(e,t,r)=>{const n={};for(const i of e){const s=await Mr(i.file);r.info(`${p(i.file)} → ${i.table}: ${String(Object.keys(s).length)} column(s) need a reshape`),n[i.table]={file:p(i.file),idColumn:"id",...Object.keys(s).length>0?{types:s}:{}}}const o={keyPrefix:"",tables:n};return await je(o,t,"supabase",r),o},Dr=async(e,t,r)=>{const n={};for(const i of e)n[i.table]={file:p(i.file),storageColumns:[]};r.info(`found ${String(e.length)} collection(s) — Firestore values are self-describing, so only storage columns need declaring`);const o={keyPrefix:"",tables:n};return await je(o,t,"firebase",r),o},M=e=>m("lunora",`.import-storage-${e}.ndjson`),Wr=async(e,t,r)=>{const n=new Map;let o;try{o=await y(m(e,M(t)),"utf8")}catch(s){if(s.code==="ENOENT")return n;throw s}let i=0;for(const s of o.split(`
|
|
9
|
+
`)){const a=s.trim();if(a.length!==0)try{const c=JSON.parse(a);typeof c.path=="string"&&typeof c.key=="string"?n.set(c.path,c):i+=1}catch{i+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${i>0?` (${String(i)} unreadable checkpoint line(s) ignored)`:""}`),n},qr=async(e,t,r)=>{const n=m(e,M(t));await C(le(n),{recursive:!0}),await De(n,`${JSON.stringify(r)}
|
|
10
|
+
`,"utf8")},Le=100,Hr=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),Kr=async(e,t,r,n,o)=>{const i=await r(`${e.url}/storage/v1/object/list/${encodeURIComponent(t)}`,{body:JSON.stringify({limit:Le,offset:o,prefix:n}),headers:{authorization:`Bearer ${e.serviceKey}`,"content-type":"application/json"},method:"POST"});if(!i.ok){const s=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase storage list failed for bucket ${t} (HTTP ${String(i.status)}): ${s}`)}return await i.json()},Oe=async(e,t,r,n="")=>{const o=[];let i=0;for(;;){const s=await Kr(e,t,r,n,i);for(const a of s){const c=n===""?a.name:`${n}/${a.name}`;a.id===null||a.id===void 0?o.push(...await Oe(e,t,r,c)):o.push({contentType:a.metadata?.mimetype,name:c})}if(s.length<Le)return o;i+=s.length}},Yr=async(e,t,r)=>{const n=await t(`${e.url}/storage/v1/bucket`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!n.ok){const s=await n.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase bucket list failed (HTTP ${String(n.status)}): ${s} — check the project URL and that the key is the service-role key, not the anon key`)}const o=await n.json(),i=[];for(const s of o){const a=await Oe(e,s.name,t);r.info(`supabase bucket ${s.name}: ${String(a.length)} object(s)`);for(const c of a){const l=`${s.name}/${c.name}`;i.push({contentType:c.contentType,bytes:async()=>{const d=await t(`${e.url}/storage/v1/object/${encodeURIComponent(s.name)}/${Hr(c.name)}`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!d.ok){const u=await d.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase download failed for ${l} (HTTP ${String(d.status)}): ${u}`)}if(d.arrayBuffer===void 0)throw new f("INTERNAL","the fetch implementation cannot read response bytes, which the storage transfer requires");return Buffer.from(await d.arrayBuffer())},path:l})}}return i},Gr=async e=>{const t=j(e),r=[],n=async o=>{const i=await A(o,{withFileTypes:!0}).catch(()=>{});if(i===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 s of i){const a=j(o,s.name);if(a!==t&&!a.startsWith(t+L))throw new f("INTERNAL",`${s.name} resolves outside ${e} — refusing to upload it`);s.isDirectory()?await n(a):s.isFile()&&r.push({bytes:async()=>y(a),path:He(t,a).split(L).join("/")})}};return await n(t),r},Zr=async(e,t,r,n,o)=>{const i=await t.bytes(),s=tt("sha256").update(i).digest("hex"),a=`${r.keyPrefix}${s}`;if(n.get(a)?.size!==i.length){const c={contentType:t.contentType,id:t.path,sha256:s,size:i.length};await Re(e,i,c,r.keyPrefix,o)}return await qr(r.cwd,r.source,{key:a,path:t.path,size:i.length}),a},Xr=(e,t)=>{const r=e>500?100:25;return n=>{if(n===e||n%r===0){const o=e===0?100:Math.round(n/e*100);t.info(`transferred ${String(n)}/${String(e)} object(s) (${String(o)}%)`)}}},se=async(e,t,r,n)=>{const o=new Map,i=await Wr(r.cwd,r.source,n),s=await V(e,r.keyPrefix),a=new Map(s.map(d=>[d.key,d]));i.size>0&&s.length===0&&n.warn(`the checkpoint records ${String(i.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=Xr(t.length,n);let l=0;n.info(`transferring ${String(t.length)} object(s) to R2...`);for(const d of t){const u=i.get(d.path);if(u!==void 0&&a.has(u.key)){o.set(d.path,u.key),l+=1,c(l);continue}try{const g=await Zr(e,d,r,a,n);o.set(d.path,g)}catch(g){const h=g instanceof Error?g.message:String(g);throw n.error(`failed transferring ${d.path} after ${String(l)} object(s): ${h}`),n.error(`progress is saved — re-run the same command to continue from here (delete ${M(r.source)} to start over)`),g}l+=1,c(l)}return n.success(`transferred ${String(t.length)} object(s) to R2`),o},ae=/^\/+/,Qr=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,en=/[#?]/u,tn=e=>{const t=new Map(e),r=new Map;for(const[n,o]of e){const i=n.indexOf("/");if(i===-1)continue;const s=n.slice(i+1);s.length===0||e.has(s)||r.set(s,r.has(s)?void 0:o)}for(const[n,o]of r)o!==void 0&&t.set(n,o);return t},rn=e=>{const t=Qr.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(en)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},nn=(e,t)=>{const r=t.get(e);if(r!==void 0)return r;const n=e.replace(ae,""),o=t.get(n);if(o!==void 0)return o;const i=rn(e);return i===void 0?void 0:t.get(i)??t.get(i.replace(ae,""))},on=500,sn=9e5,an=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=qe(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:r}=We({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 o=await x(e.file);if(!o.isFile()&&!o.isDirectory()){e.logger.error(`not a file or directory: ${e.file}`);return}}catch(o){const i=o instanceof Error?o.message:String(o);e.logger.error(`failed to stat ${e.file}: ${i}`);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}${et}`,token:r}},cn=(e,t,r)=>({conflicts:e.conflicts,errors:e.errors,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}:{}}),ln=(e,t,r,n)=>{switch(e.kind){case"convex":return yr(e.snapshot,e.tables,t.logger,r,n);case"firebase":return Qt(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return Rt(e.tables,e.mapping,t.logger,n,t.file);default:return N(t.file,{encoding:"utf8"})}},dn=async(e,t,r)=>{switch(e.kind){case"convex":return Rr(e.snapshot,e.tables,t,r);case"firebase":return Dr(e.collections,t,r);case"supabase":return Br(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},un=async(e,t,r,n)=>{const o=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return se(e,await Gr(r.storageDir),{cwd:n,keyPrefix:o,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 i=process.env.SUPABASE_URL,s=process.env.SUPABASE_SERVICE_ROLE_KEY;if(i===void 0||s===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=i.length;for(;a>0&&i[a-1]==="/";)a-=1;const c=i.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 l=await Yr({serviceKey:s,url:c},e.fetchImpl,r.logger);return se(e,l,{cwd:n,keyPrefix:o,source:t.kind},r.logger)},fn=(e,t,r,n,o)=>{const i=n.mapping?.tables?.[t]?.storageColumns??[];if(i.length===0)return e;const s={...e};for(const a of i){const c=s[a];if(typeof c!="string"||c.length===0)continue;const l=nn(c,r);l===void 0?o.add(`${t}.${a}: ${c}`):s[a]=l}return s},gn=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:tn(r);return pt({remapDocument:n===void 0||t===void 0?void 0:(o,i)=>fn(o,i,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},hn=async(e,t,r,n)=>{let o="",i=0;const s=async a=>{i+=1;const c=t(a,i);c!==void 0&&await r.push(c)};try{for await(const a of e){o+=typeof a=="string"?a:a.toString("utf8");let c=o.indexOf(`
|
|
11
|
+
`);for(;c!==-1;)await s(o.slice(0,c)),o=o.slice(c+1),c=o.indexOf(`
|
|
12
|
+
`)}o.length>0&&await s(o),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}},pn=async(e,t,r,n)=>{const o=await Ir(r,n),i=t.tables.find(a=>a.table===S);if(i===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 s=await wr(e,t.snapshot,i,o?.keyPrefix??"",n);return n.info(`storage map: ${String(s.size)} blobs mapped`),{mapping:o,storageIdMap:s}},mn=async(e,t,r,n)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return pn(e,t,n,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const o=await un(e,t,r,n);return o===void 0?void 0:{transferredPaths:o}}catch{r.logger.error("no rows were imported — fix the transfer and re-run; it will resume where it stopped");return}},wn=(e,t)=>{for(const o of t.warnings)e.warn(o);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)},On=async e=>{const t=e.cwd??process.cwd(),r=await Sr(e,t);if(r.kind==="invalid")return{body:void 0,code:1,inserted:0};if(e.scan===!0)return{body:void 0,code:await dn(r,t,e.logger)===void 0?1:0,inserted:0};const n=await an(e);if(n===void 0)return{body:void 0,code:1,inserted:0};const{baseUrl:o,fetchImpl:i,requestUrl:s,token:a}=n,c=e.batchSize??on,l=await mn({baseUrl:o,fetchImpl:i,token:a},r,e,t);if(l===void 0)return{body:void 0,code:1,inserted:0};const{mapping:d,storageIdMap:u,transferredPaths:g}=l,h=new Set,b=d?.storageColumns,$={ambiguous:[],rewritten:0,unmigrated:[]};e.logger.info(r.kind==="convex"?`POST ${s} -> import Convex export ${e.file} (${String(r.tables.length)} tables)`:`POST ${s} -> import ${e.file}`);const B=new Map,_e=ln(r,e,u!==void 0,B),R=ht({batchSize:c,fetchImpl:i,maxBatchBytes:sn,requestUrl:s,token:a}),Ce=gn({report:$,source:r,storageColumns:b,storageIdMap:u,table:e.table,transferredPaths:g,unresolvedPaths:h}),D=await hn(_e,Ce,R,e.logger),{conflicts:W,errors:q,inserted:H,received:ze,warnings:Pe}=R.totals,Ue=e.verify===!0&&D===void 0?jr(e.logger,B,{conflicts:W,inserted:H}):0,Je=u!==void 0&&Lr(e.logger,$,e.verify===!0),Fe=Or(e.logger,h,e.verify===!0),K=Object.values(H).reduce((Ve,Me)=>Ve+Me,0),Y=cn(R.totals,u,$),G=D!==void 0||q.length>0||Ue>0||Je||Fe;return e.logger.info(JSON.stringify(Y,void 0,2)),wn(e.logger,{conflicts:W,errorCount:q.length,failed:G,insertedTotal:K,received:ze,warnings:Pe}),{body:Y,code:G?1:0,inserted:K}};export{on as R,On as S,Ln as w};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createWriteStream as m}from"node:fs";import{unlink as g}from"node:fs/promises";import{l as y}from"./admin-token-BKmc3AUm.mjs";import{u as v}from"./admin-url-Ca-KI3d_.mjs";import{
|
|
1
|
+
import{createWriteStream as m}from"node:fs";import{unlink as g}from"node:fs/promises";import{l as y}from"./admin-token-BKmc3AUm.mjs";import{u as v}from"./admin-url-Ca-KI3d_.mjs";import{r as h}from"./shared-Ce9bKz5c.mjs";const b=o=>{if(o===void 0)return;const t=o.split(",").map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:void 0},w=async(o,t)=>{o.write(t)||await new Promise((e,a)=>{let i=r=>{};const s=()=>{o.removeListener("error",i),e()};i=r=>{o.removeListener("drain",s),a(r)},o.once("drain",s),o.once("error",i)})},$=async(o,t)=>{const e=o.getReader(),a=new TextDecoder;let i=0,s=0,r="",n=!1;try{for(;!n;){const c=await e.read();if(n=c.done,c.value===void 0)continue;i+=c.value.length,r+=a.decode(c.value,{stream:!0});let d=r.indexOf(`
|
|
2
2
|
`);for(;d!==-1;){s+=1;const l=`${r.slice(0,d)}
|
|
3
3
|
`;await w(t,l),r=r.slice(d+1),d=r.indexOf(`
|
|
4
4
|
`)}}return r.length>0&&(s+=1,await w(t,`${r}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const r="/_lunora/admin/export",a="/_lunora/admin/import",n="/_lunora/admin/storage",o="/_lunora/admin/storage/url";export{o as e,
|
|
1
|
+
const r="/_lunora/admin/export",a="/_lunora/admin/import",n="/_lunora/admin/storage",o="/_lunora/admin/storage/url";export{o as e,n,r,a as t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/cli",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.149",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -52,16 +52,16 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@bomb.sh/tab": "0.0.21",
|
|
55
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
56
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
57
|
-
"@lunora/codegen": "1.0.0-alpha.
|
|
58
|
-
"@lunora/config": "1.0.0-alpha.
|
|
59
|
-
"@lunora/container": "1.0.0-alpha.
|
|
60
|
-
"@lunora/d1": "1.0.0-alpha.
|
|
61
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
62
|
-
"@lunora/mcp": "1.0.0-alpha.
|
|
63
|
-
"@lunora/runtime": "1.0.0-alpha.
|
|
64
|
-
"@lunora/seed": "1.0.0-alpha.
|
|
55
|
+
"@lunora/advisor": "1.0.0-alpha.70",
|
|
56
|
+
"@lunora/bindings": "1.0.0-alpha.22",
|
|
57
|
+
"@lunora/codegen": "1.0.0-alpha.95",
|
|
58
|
+
"@lunora/config": "1.0.0-alpha.124",
|
|
59
|
+
"@lunora/container": "1.0.0-alpha.25",
|
|
60
|
+
"@lunora/d1": "1.0.0-alpha.67",
|
|
61
|
+
"@lunora/errors": "1.0.0-alpha.16",
|
|
62
|
+
"@lunora/mcp": "1.0.0-alpha.60",
|
|
63
|
+
"@lunora/runtime": "1.0.0-alpha.56",
|
|
64
|
+
"@lunora/seed": "1.0.0-alpha.65",
|
|
65
65
|
"@visulima/cerebro": "3.0.0",
|
|
66
66
|
"@visulima/error": "6.0.0",
|
|
67
67
|
"@visulima/fs": "5.0.5",
|
|
@@ -72,6 +72,7 @@
|
|
|
72
72
|
"@visulima/tui": "1.0.5",
|
|
73
73
|
"adm-zip": "0.6.0",
|
|
74
74
|
"cfonts": "^3.3.1",
|
|
75
|
+
"csv-parse": "6.1.0",
|
|
75
76
|
"giget": "3.3.1",
|
|
76
77
|
"jsonc-parser": "^3.3.1",
|
|
77
78
|
"magic-string": "^1.1.0",
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{createReadStream as U}from"node:fs";import{stat as b,readdir as K,readFile as N,realpath as R,mkdir as V,writeFile as Y}from"node:fs/promises";import{l as Q}from"./admin-token-BKmc3AUm.mjs";import{u as X}from"./admin-url-Ca-KI3d_.mjs";import{LunoraError as h}from"@lunora/errors";import{join as w,resolve as tt,sep as et}from"node:path";import{createInterface as rt}from"node:readline";import ot from"adm-zip";import{r as T,e as nt,n as it}from"./shared-BF5QIWFD.mjs";const st=t=>{const e={conflicts:0,errors:[],inserted:{},received:0,warnings:[]};let o=[],r=0;const n=s=>{for(const[a,d]of Object.entries(s.inserted??{}))e.inserted[a]=(e.inserted[a]??0)+d;e.errors.push(...s.errors??[]),e.conflicts+=s.conflicts??0,e.received+=s.received??0;for(const a of s.warnings??[])e.warnings.includes(a)||e.warnings.push(a)},i=async()=>{if(o.length===0)return;const s=o.join(`
|
|
2
|
-
`);o=[],r=0;const a=await t.fetchImpl(t.requestUrl,{body:s,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"<no body>");throw new h("INTERNAL",`import batch failed (HTTP ${String(a.status)}): ${d}`)}n(await a.json())};return{flush:i,push:async s=>{const a=Buffer.byteLength(s)+1;o.length>0&&r+a>t.maxBatchBytes&&await i(),o.push(s),r+=a,o.length>=t.batchSize&&await i()},totals:e}},at=t=>{for(const e of t.getEntries()){const o=e.entryName.replaceAll("\\","/").split("/");if(o.length>=2&&o[o.length-2]==="_storage")return o.slice(0,-1).join("/")}return"_storage"},ct=async t=>{const e=await b(t).catch(()=>{});if(e?.isDirectory())return{kind:"directory",root:t};if(e?.isFile()&&t.toLowerCase().endsWith(".zip")){const o=new ot(t);return{kind:"zip",storagePrefix:at(o),zip:o,zipPath:t}}},lt=async t=>{const e=[];for(const o of await K(t,{withFileTypes:!0})){if(!o.isDirectory())continue;const r=w(t,o.name,"documents.jsonl");(await b(r).catch(()=>{}))?.isFile()&&e.push({file:r,table:o.name})}return e},dt=t=>{const e=[];for(const o of t.getEntries()){if(o.isDirectory)continue;const r=o.entryName.replaceAll("\\","/"),n=r.split("/");n.length>=2&&n[n.length-1]==="documents.jsonl"&&e.push({file:r,table:n[n.length-2]})}return e},ft=async t=>{const e=t.kind==="directory"?await lt(t.root):dt(t.zip);return e.length>0?e.toSorted((o,r)=>o.table.localeCompare(r.table)):void 0},P=async function*(t,e){if(t.kind==="directory"){for await(const r of rt({crlfDelay:Number.POSITIVE_INFINITY,input:U(e.file,{encoding:"utf8"})}))yield r;return}const o=t.zip.readAsText(e.file);for(const r of o.split(`
|
|
3
|
-
`))yield r},gt=async(t,e)=>{if(t.kind==="directory"){const r=await R(w(t.root,"_storage")),n=await R(tt(r,e)).catch(()=>{});if(n===void 0||n!==r&&!n.startsWith(r+et))throw new Error(`blob ${e} resolves outside the snapshot's _storage directory`);return N(n)}const o=t.zip.readFile(`${t.storagePrefix}/${e}`);if(o===null)throw new Error(`missing blob ${e} in archive`);return Buffer.from(o)},ut=async(t,e)=>t.kind==="directory"?N(e.file,"utf8"):t.zip.readAsText(e.file),L=8,ht=1e3,pt=/^[\dA-F]{64}$/i,wt=/^[\d+/A-Z]{43}=$/i,mt=t=>pt.test(t)?t.toLowerCase():wt.test(t)?Buffer.from(t,"base64").toString("hex"):void 0,yt=(t,e)=>{const o=JSON.parse(t),r=o._id;if(typeof r!="string"||r.length===0||r.includes("/")||r.includes("\\"))throw new h("INTERNAL",`${e}: \`_id\` must be a path-free non-empty string`);if(typeof o.sha256!="string")throw new h("INTERNAL",`${e}: \`sha256\` is missing — re-export with \`npx convex export --include-file-storage\``);const n=mt(o.sha256);if(n===void 0)throw new h("INTERNAL",`${e}: \`sha256\` is neither base16 nor base64 SHA-256 (${o.sha256})`);if(typeof o.size!="number"||!Number.isInteger(o.size)||o.size<0)throw new h("INTERNAL",`${e}: \`size\` must be a non-negative integer`);return{contentType:typeof o.contentType=="string"?o.contentType:void 0,id:r,sha256:n,size:o.size}},I=async(t,e,o)=>{const r=[];try{const n=await ut(t,e);for(const[i,s]of n.split(`
|
|
4
|
-
`).entries()){const a=s.trim();a.length>0&&r.push(yt(a,`_storage/documents.jsonl line ${String(i+1)}`))}}catch(n){const i=n instanceof Error?n.message:String(n);throw o.error(`failed to read _storage metadata: ${i}`),n}return r},J=32*1048576,_=async(t,e)=>{const o=[];let r;do{const n=`${t.baseUrl}${T}?prefix=${encodeURIComponent(e)}&limit=${String(ht)}${r===void 0?"":`&cursor=${encodeURIComponent(r)}`}`,i=await t.fetchImpl(n,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!i.ok){const a=await i.text().catch(()=>"<no body>");throw new h("INTERNAL",`storage list failed (HTTP ${String(i.status)}): ${a}`)}const s=await i.json();o.push(...s.objects??[]),r=s.truncated===!0?s.cursor:void 0}while(r!==void 0);return o},$t=async(t,e,o,r)=>{const n=`${t.baseUrl}${T}?key=${encodeURIComponent(e)}&expectedSha256=${r.sha256}&expectedSize=${String(r.size)}`,i=await t.fetchImpl(n,{body:new Uint8Array(o),headers:{authorization:`Bearer ${t.token}`,"content-type":r.contentType??"application/octet-stream"},method:"PUT"});if(!i.ok){const a=await i.text().catch(()=>"<no body>");throw new h("INTERNAL",`blob upload failed (HTTP ${String(i.status)}): ${a}`)}const s=await i.json();if(s.sha256!==r.sha256)throw new h("INTERNAL",`blob upload verification failed: expected ${r.sha256}, got ${s.sha256??"none"}`);return e},bt=async(t,e)=>(await t.fetchImpl(`${t.baseUrl}${T}?key=${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${t.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,vt=async(t,e,o,r,n)=>{const i=`${t.baseUrl}${nt}?key=${encodeURIComponent(e)}&method=PUT&contentType=${encodeURIComponent(r.contentType??"application/octet-stream")}`,s=await t.fetchImpl(i,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const u=await s.text().catch(()=>"<no body>");throw new h("INTERNAL",`blob ${e} is ${String(r.size)} bytes, above the ${String(J)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(s.status)}): ${u}`)}const{url:a}=await s.json(),d=await t.fetchImpl(a,{body:new Uint8Array(o),headers:{"content-type":r.contentType??"application/octet-stream"},method:"PUT"});if(!d.ok){const u=await d.text().catch(()=>"<no body>");throw new h("INTERNAL",`signed PUT failed (HTTP ${String(d.status)}): ${u}`)}const f=(await _(t,e)).find(u=>u.key===e);if(f===void 0)throw new h("INTERNAL",`post-upload verification failed: blob not found at key ${e}`);const l=f.size!==void 0&&f.size!==r.size,c=f.sha256!==void 0&&f.sha256.toLowerCase()!==r.sha256;if(l||c){const u=await bt(t,e);throw new h("INTERNAL",`post-upload verification failed: expected sha256=${r.sha256} size=${String(r.size)}, got sha256=${f.sha256??"none"} size=${String(f.size??"none")}${u?" (the object was removed)":` — AND the object could not be removed: delete ${e} by hand before re-running, or the next run will treat it as already migrated`}`)}const g=[f.size===void 0?"size":void 0,f.sha256===void 0?"sha256":void 0].filter(Boolean);return g.length>0&&n.warn(`blob ${e} went through the signed-PUT path and the host reports no ${g.join(" or ")} for it — that much of the write is unverified`),e},St=async(t,e,o,r,n)=>{const i=`${r}${o.sha256}`;if(e.length!==o.size)throw new h("INTERNAL",`blob ${o.id} is ${String(e.length)} bytes on disk but the export declares ${String(o.size)}`);return e.length<=J?$t(t,i,e,o):vt(t,i,e,o,n)},xt=async(t,e,o,r,n)=>{const i=await I(e,o,n),s=new Map,a=await _(t,r),d=new Map(a.map(c=>[c.key,c])),f=[];for(const c of i){const g=`${r}${c.sha256}`;d.get(g)?.size===c.size?s.set(c.id,g):f.push(c)}n.info(`migrating ${String(f.length)} storage blobs${s.size>0?` (${String(s.size)} already present)`:""}...`);const l=async c=>{try{const g=await gt(e,c.id);s.set(c.id,await St(t,g,c,r,n))}catch(g){const u=g instanceof Error?g.message:String(g);throw n.error(`failed to upload blob ${c.id}: ${u}`),g}};for(let c=0;c<f.length;c+=L){const g=(await Promise.allSettled(f.slice(c,c+L).map(u=>l(u)))).find(u=>u.status==="rejected");if(g!==void 0)throw g.reason}return n.success(`migrated ${String(f.length)} storage blobs`),s},m="_storage",B=t=>t.startsWith("_");async function*Nt(t,e,o){let r=0;for await(const n of P(t,e)){const i=n.trim();if(r+=1,i.length===0)continue;let s;try{s=JSON.parse(i)}catch(a){throw new h("INTERNAL",`${e.table}/documents.jsonl line ${String(r)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}o.set(e.table,(o.get(e.table)??0)+1),yield`${JSON.stringify({doc:s,table:e.table})}
|
|
5
|
-
`}}async function*Tt(t,e,o,r,n){for(const i of e){if(B(i.table)){i.table===m&&!r&&o.warn(`skipping "${m}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}n.has(i.table)||n.set(i.table,0),yield*Nt(t,i,n)}}const It=async t=>{if(!await b(t.file).then(()=>!0,()=>!1))return!1;for(const[e,o]of[["--scan",t.scan],["--verify",t.verify],["--with-storage",t.withStorage]])if(o===!0)return t.logger.error(`${e} requires a Convex export directory or .zip snapshot — ${t.file} is not one.`),!0;return!1},kt=async t=>{const e=await ct(t.file),o=e===void 0?void 0:await ft(e);if(e!==void 0&&o===void 0)return t.logger.error(`${t.file} is a ${e.kind==="zip"?".zip":"directory"} but holds no <table>/documents.jsonl — expected a \`npx convex export --path\` snapshot, or pass an NDJSON file.`),{kind:"invalid"};if(e===void 0||o===void 0)return await It(t)?{kind:"invalid"}:{kind:"ndjson"};if(t.table!==void 0)return t.logger.error("--table cannot be combined with a Convex export directory — each row's table comes from its source directory."),{kind:"invalid"};const r=o.find(n=>n.table===m);if(t.verify===!0&&t.withStorage!==!0&&r!==void 0){const n=await I(e,r,t.logger);if(n.length>0)return t.logger.error(`--verify on an export carrying ${String(n.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),{kind:"invalid"}}return{kind:"convex",snapshot:e,tables:o}},$=w("lunora","import-convex.json"),Et=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new h("INTERNAL",`${e}: expected a JSON object`);const o=t;if(o.keyPrefix!==void 0&&typeof o.keyPrefix!="string")throw new h("INTERNAL",`${e}: \`keyPrefix\` must be a string`);const r=o.storageColumns;if(r!==void 0){if(r===null||typeof r!="object"||Array.isArray(r))throw new h("INTERNAL",`${e}: \`storageColumns\` must be an object of table → column names`);for(const[n,i]of Object.entries(r))if(!Array.isArray(i)||i.some(s=>typeof s!="string"))throw new h("INTERNAL",`${e}: \`storageColumns.${n}\` must be an array of column names`)}return{keyPrefix:o.keyPrefix,storageColumns:r}},zt=async(t,e)=>{const o=w(t,$);let r;try{r=await N(o,"utf8")}catch(i){if(i.code==="ENOENT"){e.info(`no ${$} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw i}let n;try{n=JSON.parse(r)}catch(i){throw new h("INTERNAL",`${o}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}return Et(n,o)},At=(t,e,o,r)=>{const n=[],i=[];let s=0;const a=l=>r?.[o]?.includes(l)===!0,d=(l,c)=>{if(Array.isArray(l))return l.map(g=>d(g,c));if(l!==null&&typeof l=="object"){const g=l;if(typeof g.$storage=="string"){const u=g.$storage,p=e.get(u);return p===void 0?(i.push({column:c,storageId:u,table:o}),l):(s+=1,p)}return Object.fromEntries(Object.entries(g).map(([u,p])=>[u,d(p,c)]))}return typeof l=="string"&&e.has(l)?a(c)?(s+=1,e.get(l)??l):(n.push({column:c,storageId:l,table:o}),l):l},f=Object.fromEntries(Object.entries(t).map(([l,c])=>[l,d(c,l)]));return{ambiguous:n,document:f,rewritten:s,unmigrated:i}},jt=(t,e,o)=>{try{return JSON.parse(t)}catch(r){throw new h("INTERNAL",`${e}/documents.jsonl line ${String(o)}: invalid JSON — ${r instanceof Error?r.message:String(r)}`,{cause:r})}},x=(t,e)=>typeof t=="string"?e.has(t):Array.isArray(t)?t.some(o=>x(o,e)):t!==null&&typeof t=="object"?typeof t.$storage=="string"?!1:Object.values(t).some(o=>x(o,e)):!1,Ot=async(t,e,o)=>{const r=[];let n=0;for await(const i of P(t,e)){const s=i.trim();if(n+=1,s.length!==0)for(const[a,d]of Object.entries(jt(s,e.table,n)))x(d,o)&&!r.includes(a)&&r.push(a)}return r},Rt=async(t,e,o)=>{const r={};for(const n of e){if(B(n.table))continue;const i=await Ot(t,n,o);i.length>0&&(r[n.table]=i)}return r},Lt=async(t,e,o)=>{const r=w(e,$),n=`${JSON.stringify(t,void 0,4)}
|
|
6
|
-
`;await V(w(e,"lunora"),{recursive:!0});try{await Y(r,n,{encoding:"utf8",flag:"wx"}),o.success(`wrote candidate mapping to ${r} — review it, then re-run without --scan`)}catch(i){if(i.code!=="EEXIST")throw i;o.warn(`${r} already exists — leaving it untouched. Candidate mapping:`),o.info(n)}},Ct=async(t,e,o,r)=>{const n=e.find(d=>d.table===m);if(n===void 0){r.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const i=await I(t,n,r),s=new Set(i.map(d=>d.id));r.info(`found ${String(s.size)} storage ids`);const a={keyPrefix:"",storageColumns:await Rt(t,e,s)};return await Lt(a,o,r),a},Ut=t=>{const{report:e,storageColumns:o,storageIdMap:r,table:n}=t,i=(a,d)=>{let f;try{f=JSON.parse(a)}catch(l){const c=l instanceof Error?l.message:String(l);throw new h("INTERNAL",`invalid JSON on line ${String(d)}: ${c}`,{cause:l})}return JSON.stringify({doc:f,table:n})},s=(a,d,f)=>{const l=JSON.parse(a);if(typeof l.table!="string")throw new h("INTERNAL",`line ${String(d)}: import envelope is missing a string \`table\``);if(l.doc!==null&&typeof l.doc=="object"&&!Array.isArray(l.doc)){const c=At(l.doc,f,l.table,o);l.doc=c.document,e.rewritten+=c.rewritten,e.ambiguous.push(...c.ambiguous),e.unmigrated.push(...c.unmigrated)}return JSON.stringify(l)};return(a,d)=>{const f=a.trim();if(f.length!==0)return n!==void 0?i(f,d):r===void 0?f:s(f,d,r)}},S=20,Pt=(t,e,o)=>{let r=0;if(o.conflicts===0)for(const[n,i]of e){const s=o.inserted[n]??0;s<i&&(r+=1,t.error(`verify: ${n} inserted ${String(s)} of ${String(i)} source rows (${String(i-s)} missing)`))}else{const n=[...e.values()].reduce((s,a)=>s+a,0),i=Object.values(o.inserted).reduce((s,a)=>s+a,0)+o.conflicts;i<n&&(r+=1,t.error(`verify: ${String(i)} of ${String(n)} source rows accounted for across all tables (${String(n-i)} missing; ${String(o.conflicts)} already present)`))}return r>0?t.error(`verify: ${String(r)} row-parity check(s) failed`):t.success("verify: all source rows accounted for"),r},C=(t,e,o)=>{const r=new Set;for(const n of e){const i=`${n.table} ${n.column} ${n.storageId}`;r.has(i)||(r.add(i),r.size<=S&&t.warn(o(n)))}r.size>S&&t.warn(`… and ${String(r.size-S)} more`)},Jt=(t,e,o)=>(t.info(`storage refs: ${String(e.rewritten)} rewritten, ${String(e.unmigrated.length)} unmigrated, ${String(e.ambiguous.length)} ambiguous`),C(t,e.unmigrated,r=>`unmigrated storage reference ${r.table}.${r.column}: ${r.storageId} has no exported blob — re-export with \`npx convex export --include-file-storage\``),C(t,e.ambiguous,r=>`unrewritten storage id in ${r.table}.${r.column}: ${r.storageId} — if that column holds storage references, add it to ${$} and re-import`),o&&e.unmigrated.length>0?(t.error(`verify: ${String(e.unmigrated.length)} storage reference(s) resolved to no migrated blob`),!0):!1),_t=500,Bt=9e5,Mt=async t=>{if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}if(t.prod&&t.yes!==!0){t.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const e=X(t.url,t.logger,t.cwd);if(e===void 0)return;const{token:o}=Q({cwd:t.cwd??process.cwd(),token:t.token,url:e});if(!o){t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}try{const n=await b(t.file);if(!n.isFile()&&!n.isDirectory()){t.logger.error(`not a file or directory: ${t.file}`);return}}catch(n){const i=n instanceof Error?n.message:String(n);t.logger.error(`failed to stat ${t.file}: ${i}`);return}const r=t.fetchImpl??globalThis.fetch;if(typeof r!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{baseUrl:e,fetchImpl:r,requestUrl:`${e}${it}`,token:o}},Dt=(t,e,o)=>({conflicts:t.conflicts,errors:t.errors,inserted:t.inserted,received:t.received,...e===void 0?{}:{storage:{ambiguous:o.ambiguous,blobs:e.size,rewritten:o.rewritten,unmigrated:o.unmigrated}},...t.warnings.length>0?{warnings:t.warnings}:{}}),Ft=async(t,e,o,r)=>{let n="",i=0;const s=async a=>{i+=1;const d=e(a,i);d!==void 0&&await o.push(d)};try{for await(const a of t){n+=typeof a=="string"?a:a.toString("utf8");let d=n.indexOf(`
|
|
7
|
-
`);for(;d!==-1;)await s(n.slice(0,d)),n=n.slice(d+1),d=n.indexOf(`
|
|
8
|
-
`)}n.length>0&&await s(n),await o.flush();return}catch(a){return r.error(`import failed part-way through: ${a instanceof Error?a.message:String(a)}`),r.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)"),a}},qt=async(t,e,o,r)=>{const n=await zt(o,r),i=e.tables.find(a=>a.table===m);if(i===void 0){r.error("--with-storage requires a Convex export with a `_storage` metadata table — re-export with `npx convex export --include-file-storage`.");return}const s=await xt(t,e.snapshot,i,n?.keyPrefix??"",r);return r.info(`storage map: ${String(s.size)} blobs mapped`),{mapping:n,storageIdMap:s}},Ht=(t,e)=>{for(const r of e.warnings)t.warn(r);const o=e.received-e.insertedTotal-e.conflicts-e.errorCount;o>0&&t.warn(`${String(o)} of ${String(e.received)} rows were neither inserted, conflicted, nor reported as errors`),t.success(`imported ${String(e.insertedTotal)} of ${String(e.received)} rows (${String(e.conflicts)} conflicts, ${String(e.errorCount)} errors)`)},ee=async t=>{const e=await kt(t);if(e.kind==="invalid")return{body:void 0,code:1,inserted:0};const o=t.cwd??process.cwd();if(t.scan===!0&&e.kind==="convex"){const y=await Ct(e.snapshot,e.tables,o,t.logger);return{body:y,code:y===void 0?1:0,inserted:0}}const r=await Mt(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{baseUrl:n,fetchImpl:i,requestUrl:s,token:a}=r,d=t.batchSize??_t,f=t.withStorage===!0&&e.kind==="convex"?await qt({baseUrl:n,fetchImpl:i,token:a},e,o,t.logger):{mapping:void 0,storageIdMap:void 0};if(f===void 0)return{body:void 0,code:1,inserted:0};const{mapping:l,storageIdMap:c}=f,g=l?.storageColumns,u={ambiguous:[],rewritten:0,unmigrated:[]};t.logger.info(e.kind==="convex"?`POST ${s} -> import Convex export ${t.file} (${String(e.tables.length)} tables)`:`POST ${s} -> import ${t.file}`);const p=new Map,M=e.kind==="convex"?Tt(e.snapshot,e.tables,t.logger,c!==void 0,p):U(t.file,{encoding:"utf8"}),v=st({batchSize:d,fetchImpl:i,maxBatchBytes:Bt,requestUrl:s,token:a}),D=Ut({report:u,storageColumns:g,storageIdMap:c,table:t.table}),k=await Ft(M,D,v,t.logger),{conflicts:E,errors:z,inserted:A,received:F,warnings:q}=v.totals,H=t.verify===!0&&k===void 0?Pt(t.logger,p,{conflicts:E,inserted:A}):0,W=c!==void 0&&Jt(t.logger,u,t.verify===!0),j=Object.values(A).reduce((y,G)=>y+G,0),O=Dt(v.totals,c,u);t.logger.info(JSON.stringify(O,void 0,2)),Ht(t.logger,{conflicts:E,errorCount:z.length,insertedTotal:j,received:F,warnings:q});const Z=k!==void 0||z.length>0||H>0||W;return{body:O,code:Z?1:0,inserted:j}};export{_t as DEFAULT_IMPORT_BATCH_SIZE,ee as runImportCommand};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{mkdirSync as B,readFileSync as w,lstatSync as A,writeFileSync as D}from"node:fs";import{join as u,dirname as y}from"node:path";import{fileURLToPath as L}from"node:url";import{resolveHint as j,isLunoraError as k,flattenHint as E,findSolutionByMessage as C}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import $ from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{p}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{P,l as T}from"./detect-package-manager-DXDstphE.mjs";import{createLogger as S}from"./createLogger-BoSxdb2T.mjs";import{VisulimaError as U,renderError as M}from"@visulima/error";import{homedir as W}from"node:os";const J={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}]},f="lunora.advisor.map.json",K={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/handler21.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 ${f})`,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 ${f})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"no-write",type:Boolean}]},F={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}]},q={argument:{description:"create | list | restore <id|file> | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) 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 pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{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 production pitr --restore (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}]},H={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/handler4.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]},z={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]},V={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/handler5.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}]},G={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 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}]},Y={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/handler6.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}]},Q={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)"],["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 --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:"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:"Don't start the embedded studio server",name:"no-studio",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:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},X={argument:{description:"Optional path under the docs site (e.g. addons/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 addons/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"docs"},Z={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"]],group:"Project",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"doctor",options:[]},ee={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/handler9.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}]},te={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},re={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/handler10.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}]},oe={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"]],group:"Data",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"import",options:[{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 Convex `_storage` blobs (verified upload)",name:"with-storage",type:Boolean},{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}]},ne={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"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},ae={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 --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:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",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}]},ie={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/handler13.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}]},se={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/handler24.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 (default true; --no-procedures to skip)",name:"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}]},le={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/handler14.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}]},pe={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/handler22.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}]},de={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"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.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: 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)",name:"token",type:String}]},ce={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}]},ue={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/handler15.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}]},me={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/handler16.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}]},ge={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}]},he={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/handler17.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}]},fe={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/handler18.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}]},ve={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/handler19.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:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},s]},be={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/handler20.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},we={filterStacktrace:()=>!1,hideErrorCodeView:!0},ke=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=j(k(e)?{code:e.code,hint:e.hint,message:r}:r),n=new U({hint:o===void 0?void 0:E(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,we)},Se=(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},xe=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Se(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,Ne=1500,Be="0.0.0",Ae=/^v/u,De=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Ae,""),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},Ee=(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)},Ce=e=>{const t=m(e).prerelease.split(".")[0]??"";return De.has(t)?t:"latest"},Ie=(e,t)=>Ee(t,e)>0,$e=(e,t,r)=>t-e<r,_e=(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}=P(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},x=e=>u(e,"lunora-cli-update.json"),Pe=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{B(r,{mode:448,recursive:!0})}catch{}return r},Te=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{}},Ue=async(e,t)=>{try{const r=await e(Re(t),{signal:AbortSignal.timeout(Ne)});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}},Me=(e,t,r)=>e===Be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,We=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Me(e.current,t,r))return;const o=e.cacheDir??Pe(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ce(e.current),d=Te(o),N=d?.tag??"latest",g=d!==void 0&&N===i?d:void 0;let c=g?.latest;if(g===void 0||!$e(g.checkedAt,n,a)){const h=await Ue(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&&Ie(e.current,c)&&e.logger.warn(_e(e.current,c,i,e.manager))},Je=["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"],Ke=8,Fe=()=>{try{let e=y(L(import.meta.url));for(let t=0;t<Ke;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=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Fe(),qe=[ae,J,Q,z,K,H,G,V,ue,le,Y,pe,ye,ie,ge,ce,re,oe,fe,se,q,te,ve,ne,Z,ee,F,be,X,me,he,de],O=[...qe,_,$],dt=O.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),He=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:He(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Ve=e=>{const t={value:0},r=I("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:R});for(const o of O)r.addCommand(ze(o));return{cli:r,exitCode:t}},Ge=/Command "(?<name>[^"]+)" not found/u,Ye=e=>{const t=S(),r=e instanceof Error?e.message:String(e),o=Ge.exec(r);if(!o?.groups){k(e)||C(r)!==void 0?t.error(ke(e)):t.error(r);return}const n=o.groups.name??"",a=xe(n,Je);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.")},ct=async(e={})=>{const{cli:t,exitCode:r}=Ve(e);try{await t.run({shouldExitProcess:!1})}catch(n){return Ye(n),1}let o;try{o=T(process.cwd())}catch{}return await We({current:R,logger:S(),manager:o}),r.value};export{Je as d,ct as f,R as i,f as o,dt as t};
|