@lunora/cli
Version:
The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands
14 lines • 60.1 kB
JavaScript
import{createReadStream as I}from"node:fs";import{open as yt,stat as F,readdir as M,realpath as we,readFile as T,mkdir as Z,writeFile as Le,appendFile as wt}from"node:fs/promises";import{S as Q,b as bt,I as $t,c as vt}from"./shared-CV7ESvuj.mjs";import{t as St,r as Nt}from"./admin-token-VdUnvnKW.mjs";import{r as Et,a as Tt}from"./admin-url-DJB8P6Jh.mjs";import{EXIT_CODE as v,isRefusal as At}from"./EXIT_CODE-DQVhSE-1.mjs";import{b as It}from"./tui-prompts-B3YwUhGw.mjs";import{join as w,resolve as G,basename as y,dirname as xe,relative as Rt,sep as _t}from"node:path";import{createInterface as W}from"node:readline";import Ot from"adm-zip";import{i as Ue}from"./path-containment-CgxYZggb.mjs";import{Transform as kt}from"node:stream";import{createInflateRaw as Lt,crc32 as xt}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{f as Ut}from"./export-rows-EzdNDYpa.mjs";import{parse as Ct}from"csv-parse/sync";import{parse as Ce}from"csv-parse";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Pt}from"@lunora/runtime";import{createHash as jt}from"node:crypto";const Ft=67324752,P=30,Mt=26,Dt=28,be=0,zt=8,Bt=async(e,t)=>{const r=await yt(e,"r");try{const n=Buffer.alloc(P),{bytesRead:o}=await r.read(n,0,P,t);if(o<P||n.readUInt32LE(0)!==Ft)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+P+n.readUInt16LE(Mt)+n.readUInt16LE(Dt)}finally{await r.close()}},$e=e=>{let t=0;return new kt({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=xt(r,t),o(void 0,r)}})},Jt=async(e,t)=>{const{compressedSize:r,encrypted:n,method:o,offset:s}=t.header;if(n)throw new Error(`${t.entryName} is encrypted — decrypt the archive before importing`);if(o!==be&&o!==zt)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 i=await Bt(e,s),a=I(e,{end:i+r-1,start:i});if(o===be){const l=$e(t);return a.on("error",u=>l.destroy(u)),a.pipe(l)}const c=Lt(),d=$e(t);return a.on("error",l=>c.destroy(l)),c.on("error",l=>d.destroy(l)),a.pipe(c).pipe(d)},A="_storage",Pe=e=>e.startsWith("_"),Vt=e=>{for(const t of e.getEntries()){const n=t.entryName.replaceAll("\\","/").split("/");if(n.length>=2&&n[n.length-2]==="_storage")return n.slice(0,-1).join("/")}return"_storage"},Ht=async e=>{const t=await F(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new Ot(e);return{kind:"zip",storagePrefix:Vt(r),zip:r,zipPath:e}}},qt=async e=>{const t=[];for(const r of await M(e,{withFileTypes:!0})){if(!r.isDirectory())continue;const n=w(e,r.name,"documents.jsonl");(await F(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},Gt=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},Wt=async e=>{const t=e.kind==="directory"?await qt(e.root):Gt(e.zip);return t.length>0?t.toSorted((r,n)=>r.table.localeCompare(n.table)):void 0},ee=async function*(e,t){if(e.kind==="directory"){for await(const s of W({crlfDelay:Number.POSITIVE_INFINITY,input:I(t.file,{encoding:"utf8"})}))yield s;return}const r=e.zip.getEntry(t.file);if(r===null)throw new Error(`missing ${t.file} in archive`);const n=await Jt(e.zipPath,r);if(n===void 0)return;const o=W({crlfDelay:Number.POSITIVE_INFINITY,input:n});try{for await(const s of o)yield s}finally{o.close(),n.destroy()}},Yt=async(e,t)=>{if(e.kind==="directory"){const n=await we(w(e.root,"_storage")),o=await we(G(n,t)).catch(()=>{});if(o===void 0||!Ue(n,o))throw new Error(`blob ${t} resolves outside the snapshot's _storage directory`);return T(o)}const r=e.zip.readFile(`${e.storagePrefix}/${t}`);if(r===null)throw new Error(`missing blob ${t} in archive`);return Buffer.from(r)},q=207,te=e=>{const t={conflicts:0,deleted:0,errors:[],failed:[],inserted:{},received:0,replaced:0,warnings:[]};let r=[],n=0;const o=a=>{for(const[c,d]of Object.entries(a.inserted??{}))t.inserted[c]=(t.inserted[c]??0)+d;t.errors.push(...a.errors??[]),t.failed.push(...a.failed??[]),t.conflicts+=a.conflicts??0,t.deleted+=a.deleted??0,t.received+=a.received??0,t.replaced+=a.replaced??0;for(const c of a.warnings??[])t.warnings.includes(c)||t.warnings.push(c)},s=async()=>{if(r.length===0)return;const a=r.join(`
`);r=[],n=0;const c=await e.fetchImpl(e.requestUrl,{body:a,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!c.ok&&c.status!==q){const l=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`import batch failed (HTTP ${String(c.status)}): ${l}`)}const d=await c.json();o(d),c.status===q&&(d.failed??[]).length===0&&t.failed.push({message:`the endpoint answered ${String(q)} without naming the failed shards`,shardKey:"<unknown>",timedOut:!1})};return{flush:s,push:async a=>{const c=Buffer.byteLength(a)+1;r.length>0&&n+c>e.maxBatchBytes&&await s(),r.push(a),n+=c,r.length>=e.batchSize&&await s()},totals:t}},Kt=["append","replace","require-empty","upsert"],Do=(e,t)=>e===void 0?t:Kt.find(r=>r===e),D=e=>e==="upsert"||e==="replace",ve=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,Xt=(e,t)=>{let r;try{r=JSON.parse(t)}catch{return}const n=ve(r),o=n?.table,s=ve(n?.doc)?._id;if(typeof o!="string")return;let i=e.get(o);i===void 0&&(i={duplicates:0,ids:new Set,rows:0,unkeyed:0},e.set(o,i)),i.rows+=1,typeof s=="string"?(i.ids.has(s)&&(i.duplicates+=1),i.ids.add(s)):i.unkeyed+=1},Zt=async(e,t,r,n=!0)=>{const o=new Map;if(r==="replace"){const i=[...t].find(([,a])=>a.unkeyed>0);if(i!==void 0)throw new f("INTERNAL",`--mode replace needs every row to carry an _id: ${String(i[1].unkeyed)} row(s) of ${i[0]} have none`)}for(const[i,a]of t)o.set(i,{add:a.rows-a.duplicates,delete:0,existing:a.duplicates,matched:0,source:a.rows,table:i,target:0});const s=[];return await Ut(e,[...t.keys()],i=>{const a=o.get(i.table);if(a===void 0)return;a.target+=1;const c=i.doc._id;typeof c=="string"&&t.get(i.table)?.ids.has(c)===!0?(a.existing+=1,a.matched+=1,a.add-=1):r==="replace"&&(a.delete+=1,n&&s.push(i))}),{deletions:s,tables:[...o.values()].toSorted((i,a)=>i.table.localeCompare(a.table))}},Qt=(e,t,r)=>{const n=D(r)?"replaced":"left unchanged";e.info(`import plan (--mode ${r}):`);for(const o of t.tables){const s=[`${String(o.add)} to add`,`${String(o.existing)} ${n}`];r==="replace"&&s.push(`${String(o.delete)} to delete`),e.info(` ${o.table}: ${String(o.source)} in file, ${String(o.target)} stored — ${s.join(", ")}`)}},er=(e,t)=>D(t)&&e.tables.some(r=>r.matched>0||r.delete>0),je=(e,t,r,n)=>{const o=[],s=[];let i=0;const a=l=>n?.[r]?.includes(l)===!0,c=(l,u,h=!1)=>{if(Array.isArray(l))return l.map(g=>c(g,u,h));if(l!==null&&typeof l=="object"){const g=l;if(typeof g.$storage=="string"){const p=g.$storage,m=t.get(p);return m===void 0?(s.push({column:u,storageId:p,table:r}),l):(i+=1,m)}return Object.fromEntries(Object.entries(g).map(([p,m])=>[p,c(m,u)]))}return typeof l=="string"&&t.has(l)?a(u)?(i+=1,t.get(l)??l):(o.push({column:u,storageId:l,table:r}),l):(h&&typeof l=="string"&&l.length>0&&a(u)&&n!==void 0&&s.push({column:u,storageId:l,table:r}),l)},d=Object.fromEntries(Object.entries(e).map(([l,u])=>[l,c(u,l,!0)]));return{ambiguous:o,document:d,rewritten:i,unmigrated:s}},Se=(e,t,r)=>{for(const n of r){const o=`${n.table}\0${n.column}\0${n.storageId}`;t.has(o)||(t.add(o),e.push(n))}},tr=e=>{const{remapDocument:t,report:r,storageColumns:n,storageIdMap:o,table:s}=e,i=new Set,a=new Set,c=(u,h)=>{let g;try{g=JSON.parse(u)}catch(p){const m=p instanceof Error?p.message:String(p);throw new f("INTERNAL",`invalid JSON on line ${String(h)}: ${m}`,{cause:p})}return JSON.stringify({doc:g,table:s})},d=(u,h)=>{let g;try{g=JSON.parse(u)}catch(m){throw new f("INTERNAL",`line ${String(h)}: import envelope is not valid JSON — ${m instanceof Error?m.message:String(m)}`,{cause:m})}const p=g===null||typeof g!="object"||Array.isArray(g)?void 0:g;if(p===void 0||typeof p.table!="string")throw new f("INTERNAL",`line ${String(h)}: import envelope is missing a string \`table\``);return p},l=u=>{if(u.doc!==null&&typeof u.doc=="object"&&!Array.isArray(u.doc)){let h=u.doc;if(o!==void 0){const g=je(h,o,u.table,n);h=g.document,r.rewritten+=g.rewritten,Se(r.ambiguous,i,g.ambiguous),Se(r.unmigrated,a,g.unmigrated)}return JSON.stringify({...u,doc:t===void 0?h:t(h,u.table)})}return JSON.stringify(u)};return(u,h)=>{const g=u.trim();if(g.length===0)return;if(s!==void 0)return c(g,h);const p=d(g,h);return o===void 0&&t===void 0?g:l(p)}},Fe=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 s=new Map;for(const[d,l]of Object.entries(t?.tables??{}))l.file!==void 0&&s.set(y(l.file),d);const i=o.filter(d=>d.isFile()&&r.matches(d.name)&&!r.authFiles.has(d.name)).map(d=>({file:w(e,d.name),table:s.get(d.name)??r.tableNameOf(d.name)}));if(i.length===0)throw new f("INTERNAL",`${e} ${r.emptyMessage}`);const a=new Set(i.map(d=>y(d.file))),c=[...s].filter(([d])=>!a.has(d));if(c.length>0)throw new f("INTERNAL",`${e}: the mapping names ${String(c.length)} file(s) that are not importable from this directory — ${c.map(([d,l])=>`\`${d}\` (table \`${l}\`)`).join(", ")}. Check the name and that the file is one this source reads.`);return i.toSorted((d,l)=>d.table.localeCompare(l.table))},Me=async function*(e,t,r,n){for(const o of e){r.has(o.table)||r.set(o.table,0),t.info(`reading ${y(o.file)} → ${o.table}`);for await(const s of n(o))r.set(o.table,(r.get(o.table)??0)+1),yield`${JSON.stringify({doc:s,table:o.table})}
`}},De=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],rr=e=>De.includes(e),nr=/^\\x([\dA-Fa-f]*)$/,Ne=/^[+-]?\d+$/,ze=/[+-]\d{2}$/,Be=/(?:Z|[+-]\d{2}:\d{2})$/i,Je=/^\+/,or=/e/i,sr=/e/i,ir=e=>{const[t="0",r="0"]=e.split(sr),n=Number(r),o=t.startsWith("-"),[s="0",i=""]=(o?t.slice(1):t).replace(Je,"").split("."),a=`${s}${i}`,c=s.length+n;let d;return c<=0?d=`0.${"0".repeat(-c)}${a}`:c>=a.length?d=`${a}${"0".repeat(c-a.length)}`:d=`${a.slice(0,c)}.${a.slice(c)}`,o?`-${d}`:d},ar=/^0+(?=\d)/,Ee=e=>{const r=(or.test(e.trim())?ir(e.trim()):e.trim()).replace(Je,""),n=r.startsWith("-"),[o="0",s=""]=(n?r.slice(1):r).split("."),i=o.replace(ar,"");let a=s.length;for(;a>0&&s[a-1]==="0";)a-=1;const c=s.slice(0,a),d=c.length>0?`${i}.${c}`:i;return n&&Number(d)!==0?`-${d}`:d},b=(e,t,r,n)=>{throw new f("INTERNAL",`column \`${e}\`: cannot reshape ${JSON.stringify(r)} as \`${t}\` — ${n}`)},Te=(e,t,r)=>{const n=r.includes("T")?r:r.replace(" ","T"),o=ze.test(n)?`${n}:00`:n,s=Be.test(o)?o:`${o}Z`,i=Date.parse(s);return Number.isNaN(i)&&b(e,t,r,"not a date Postgres or ISO-8601 syntax can express"),i},cr=(e,t)=>{(!t.startsWith("{")||!t.endsWith("}"))&&b(e,"text-array",t,"not a Postgres array literal (expected `{…}`)");const r=t.slice(1,-1);if(r.length===0)return[];r.includes("{")&&b(e,"text-array",t,"nested arrays are not supported — map the column to `json` instead");const n=[];let o="",s=!1,i=!1,a=!1;const c=()=>{n.push(!i&&o==="NULL"?null:o),o="",i=!1};for(const d of r)a?(o+=d,a=!1):d==="\\"?a=!0:d==='"'?(s=!s,i=!0):d===","&&!s?c():o+=d;return c(),n},Ve=(e,t,r)=>{if(r===null)return null;switch(t){case"boolean":return["1","t","TRUE","true"].includes(r)?!0:["0","f","FALSE","false"].includes(r)?!1:b(e,t,r,"not a Postgres boolean literal");case"bytea-base64":{const n=nr.exec(r);if(n===null)return b(e,t,r,"not `bytea` hex output (expected a leading `\\x`) — set `bytea_output = 'hex'` before dumping");const o=n[1];return o.length%2!==0?b(e,t,r,"has an odd number of hex digits, so the dump is truncated — re-export the column"):Buffer.from(o,"hex").toString("base64")}case"int8-string":return Ne.test(r)?r:b(e,t,r,"not an integer");case"json":try{return JSON.parse(r)}catch(n){return b(e,t,r,`invalid JSON — ${n instanceof Error?n.message:String(n)}`)}case"number":{const n=Number(r);if(r.trim().length===0||!Number.isFinite(n))return b(e,t,r,"not a finite number");if(Ne.test(r)){if(!Number.isSafeInteger(n))return b(e,t,r,"exceeds Number.MAX_SAFE_INTEGER — map this column to `int8-string` to keep it lossless")}else if(Ee(String(n))!==Ee(r))return b(e,t,r,"has more precision than a JS number holds — map this column to `int8-string` or `json` to keep it lossless");return n}case"text-array":return cr(e,r);case"timestamp-iso":{Te(e,t,r);const n=r.includes("T")?r:r.replace(" ","T"),o=ze.test(n)?`${n}:00`:n;return Be.test(o)?o:`${o}Z`}case"timestamp-ms":return Te(e,t,r);default:return r}},dr="auth.",lr=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),ur=String.raw`\N`,He=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===ur?null:e,fr=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>y(t))),hr=async(e,t)=>Fe(e,t,{authFiles:fr(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(dr),tableNameOf:r=>y(r,".csv")},async r=>M(r,{withFileTypes:!0})),gr=(e,t,r)=>{const n=t?.idColumn??"id",o=t?.types??{},s={};let i=!1;for(const[a,c]of Object.entries(e)){if(lr.has(a.toLowerCase()))throw new f("INTERNAL",`${r}.${a} is credential material — this looks like an auth dump being imported as a table. Name it under \`auth\` in the mapping instead; passwords are never migrated.`);const d=o[a],l=d===void 0?c:Ve(a,d,c);if(a===n){if(c===null)throw new f("INTERNAL",`id column \`${n}\` is NULL — every row needs an id to preserve`);s._id=c,i=!0}else{if(a==="_id")throw new f("INTERNAL",`${r}: source column \`_id\` collides with the reserved id field. Rename it in the source, or map it via \`tables.${r}.idColumn\` if it IS the id.`);s[a]=l}}if(!i)throw new f("INTERNAL",`${r}: no \`${n}\` column to preserve as the id (columns present: ${Object.keys(e).join(", ")}). Set \`tables.${r}.idColumn\` in the mapping.`);return s},pr=async function*(e,t){const r=t?.tables?.[e.table],n=I(e.file).pipe(Ce({cast:He,columns:!0,relaxColumnCountLess:!1,skipEmptyLines:!0}));let o=0;const s=n[Symbol.asyncIterator]();for(;;){let i,a;try{if(i=await s.next(),i.done===!0)return;o+=1,a=gr(i.value,r,e.table)}catch(c){throw new f("INTERNAL",`${y(e.file)} row ${String(o+1)}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}yield a}},mr=async function*(e,t,r,n,o){yield*We("supabase",o,t,r,n),yield*Me(e,r,n,s=>pr(s,t))},yr=/^\d+$/,wr=/[+-]\d{2}$/,Y=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&yr.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(wr.test(r)?`${r}:00`:r);return Number.isNaN(n)?void 0:n},qe=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},br=e=>{const t=qe(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]}},$r=e=>{const t=qe(e);if(t!==void 0){for(const r of["avatar_url","picture"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},vr=(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},s=br(n),i=$r(n),a=Y(e.created_at),c=Y(e.updated_at);return s!==void 0&&(o.name=s),i!==void 0&&(o.image=i),a!==void 0&&(o.createdAt=a),c!==void 0&&(o.updatedAt=c),{accounts:t.map(l=>{const u=typeof l.provider=="string"?l.provider:"unknown",h=typeof l.provider_id=="string"?l.provider_id:r,g=`${r}:${u}:${h}`;return{_id:g,accountId:h,id:g,providerId:u,userId:r}}),user:o}},Sr=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=Y(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(s=>typeof s.providerId=="string"&&s.providerId!=="password").map(s=>{const i=s.providerId,a=s.rawId??s.federatedId??t,c=`${t}:${i}:${a}`;return{_id:c,accountId:a,id:c,providerId:i,userId:t}}),user:r}},Nr=(e,t)=>{const r=new Map,n=[],o=[];for(const{accounts:s,user:i}of e){const a=typeof i.email=="string"?i.email.toLowerCase():void 0;if(a!==void 0&&a.length>0){const c=r.get(a);c===void 0?r.set(a,String(i._id)):n.push(`${a} (ids ${c} and ${String(i._id)})`)}o.push(`${JSON.stringify({doc:i,table:"user"})}
`),t.set("user",(t.get("user")??0)+1);for(const c of s)o.push(`${JSON.stringify({doc:c,table:"account"})}
`),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},re=(e,t)=>w(e,y(t)),Ge=async e=>{const t=await T(e,"utf8");return Ct(t,{cast:He,columns:!0,skipEmptyLines:!0})},Er=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Ge(re(e,t))){const o=n.user_id;typeof o=="string"&&r.set(o,[...r.get(o)??[],n])}return r},Tr=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Ge(re(e,r)),o=await Er(e,t.auth?.identitiesFile);return n.map(s=>vr(s,o.get(s.id??"")??[]))},Ar=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=re(e,r);let o;try{o=JSON.parse(await T(n,"utf8"))}catch(i){throw new f("INTERNAL",`${y(n)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}const s=Array.isArray(o)?o:o.users??[];if(!Array.isArray(s))throw new f("INTERNAL",`${y(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return s.map(i=>Sr(i))},We=async function*(e,t,r,n,o){if(r?.auth?.file===void 0)return;const s=e==="supabase"?await Tr(t,r):await Ar(t,r);n.info(`auth: ${String(s.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of Nr(s,o))yield i},Ae=/\.(?:nd)?json$/i,Ye=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},Ir=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},Rr=(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")},_r=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Ir(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},Or=(e,t)=>typeof e=="string"?e:Rr(e,t),Ke=(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 _r(e.timestampValue,t);if(e.bytesValue!==void 0)return Or(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 Ye(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>Ke(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return K(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},kr=new Set(["createTime","fields","name","readTime","updateTime"]),Lr=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},xr=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>kr.has(r))&&!Lr(t)},K=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ke(n,`${t}.${r}`)])),Ur=(e,t,r,n)=>{const o=xr(e),s=K(o?e.fields??{}:e,n),i=e.name??e.__name__,a=typeof i=="string"?Ye(i):t;if(a===void 0)throw new f("INTERNAL",`${n}: no document id — expected a \`name\`/\`__name__\` resource path, or a document keyed by its id`);const c=r?.types??{};for(const[d,l]of Object.entries(c)){const u=s[d];if(u!==void 0){if(u!==null&&typeof u!="boolean"&&typeof u!="number"&&typeof u!="string")throw new f("INTERNAL",`${n}.${d}: a \`${l}\` reshape needs a scalar, but this field decoded to an object or array`);s[d]=Ve(d,l,u===null?null:String(u))}}return{...s,_id:a}},Cr=async(e,t)=>Fe(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[y(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>Ae.test(r),tableNameOf:r=>r.replace(Ae,"")},async r=>M(r,{withFileTypes:!0})),Pr=async function*(e){const t=W({crlfDelay:Number.POSITIVE_INFINITY,input:I(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(s){throw new f("INTERNAL",`${y(e)} line ${String(r)}: invalid JSON — ${s instanceof Error?s.message:String(s)}`,{cause:s})}}}finally{t.close()}},jr=async e=>{const t=await T(e,"utf8");let r;try{r=JSON.parse(t)}catch(n){throw new f("INTERNAL",`${y(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",`${y(e)}: expected an object, an array, or \`{ documents: [...] }\``)},Fr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?Pr(e.file):await jr(e.file);let o=0;for await(const s of n)yield Ur(s.raw,s.fallbackId,r,`${e.table}[${String(o)}]`),o+=1},Mr=async function*(e,t,r,n,o){yield*We("firebase",o,t,r,n),yield*Me(e,r,n,s=>Fr(s,t))},k=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ne=(e,t)=>{if(!k(e))throw new f("INTERNAL",`${t}: expected a JSON object`);return e},O=(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},Xe=(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},Dr=(e,t)=>{const r=ne(e,t),n=O(r,"file",t),o=O(r,"idColumn",t),s=Xe(r,"storageColumns",t),{types:i}=r;if(i!==void 0){if(!k(i))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(i))if(!rr(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${De.join(", ")}`)}return{file:n,idColumn:o,storageColumns:s,types:i}},zr=(e,t)=>{if(e!==void 0){if(!k(e))throw new f("INTERNAL",`${t}: \`auth\` must be an object`);for(const r of["file","identitiesFile"])O(e,r,`${t}: auth`)}},Br=(e,t)=>{if(e!==void 0){if(!k(e))throw new f("INTERNAL",`${t}: \`tables\` must be an object of table → mapping`);return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Dr(n,`${t}: tables.${r}`)]))}},Jr=(e,t)=>{const r=ne(e,t),n=O(r,"keyPrefix",t),{auth:o,tables:s}=r;return zr(o,t),{auth:o,keyPrefix:n,tables:Br(s,t)}},Ze=e=>w("lunora",`import-${e}.json`),Vr=async(e,t,r)=>{const n=Ze(t),o=w(e,n);let s;try{s=await T(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 i;try{i=JSON.parse(s)}catch(a){throw new f("INTERNAL",`${o}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return Jr(i,o)},Hr=async e=>{const t=[];let r;for(;;){const n=await e(r);if(t.push(...Array.isArray(n.records)?n.records:[]),n.truncated!==!0||typeof n.cursor!="string"||n.cursor.length===0)return t;if(n.cursor===r)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");r=n.cursor}},qr=8,Gr=24*1048576,Wr=1e3,Yr=/^[\dA-F]{64}$/i,Kr=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},Xr=/^[\d+/A-Z]{43}=$/i,Zr=e=>Yr.test(e)?e.toLowerCase():Xr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,Qr=(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=Zr(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"||!Kr(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}},z=async(e,t,r)=>{const n=[];try{let o=0;for await(const s of ee(e,t)){const i=s.trim();o+=1,i.length>0&&n.push(Qr(i,`_storage/documents.jsonl line ${String(o)}`))}}catch(o){const s=o instanceof Error?o.message:String(o);throw r.error(`failed to read _storage metadata: ${s}`),o}return n},Qe=Pt,B=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,oe=async(e,t)=>await Hr(async r=>{const n=`${e.baseUrl}${Q}?prefix=${encodeURIComponent(t)}&limit=${String(Wr)}${r===void 0?"":`&cursor=${encodeURIComponent(r)}`}${B(e)}`,o=await e.fetchImpl(n,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!o.ok){const i=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(o.status)}): ${i}`)}const s=await o.json();return{cursor:s.cursor,records:s.objects,truncated:s.truncated}}),en=async(e,t,r,n)=>{const o=`${e.baseUrl}${Q}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}${B(e)}`,s=await e.fetchImpl(o,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!s.ok){const a=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(s.status)}): ${a}`)}const i=await s.json();if(i.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${i.sha256??"none"}`);return t},tn=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${Q}?key=${encodeURIComponent(t)}${B(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,rn=async(e,t,r,n,o)=>{const s=`${e.baseUrl}${bt}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}${B(e)}`,i=await e.fetchImpl(s,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const p=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(Qe)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(i.status)}): ${p}`)}const{url:a}=await i.json(),c=await e.fetchImpl(a,{body:new Uint8Array(r),headers:{"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!c.ok){const p=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${p}`)}const l=(await oe(e,t)).find(p=>p.key===t);if(l===void 0)throw new f("INTERNAL",`post-upload verification failed: blob not found at key ${t}`);const u=l.size!==void 0&&l.size!==n.size,h=l.sha256!==void 0&&l.sha256.toLowerCase()!==n.sha256;if(u||h){const p=await tn(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")}${p?" (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},et=async(e,t,r,n,o)=>{if(r.length!==n.size)throw new f("INTERNAL",`blob ${n.id} is ${String(r.length)} bytes on disk but the export declares ${String(n.size)}`);return r.length<=Qe?en(e,t,r,n):rn(e,t,r,n,o)},nn=e=>{const t=[];let r=[],n=0;for(const o of e)r.length>0&&(r.length>=qr||n+o.size>Gr)&&(t.push(r),r=[],n=0),r.push(o),n+=o.size;return r.length>0&&t.push(r),t},X=(e,t)=>`${e}${t.sha256}`,on=async(e,t,r,n)=>{const o=await z(e,t,n);return new Map(o.map(s=>[s.id,X(r,s)]))},sn=async(e,t,r,n,o)=>{const s=await z(t,r,o),i=new Map,a=await oe(e,n),c=new Map(a.map(u=>[u.key,u])),d=[];for(const u of s){const h=X(n,u);c.get(h)?.size===u.size?i.set(u.id,h):d.push(u)}o.info(`migrating ${String(d.length)} storage blobs${i.size>0?` (${String(i.size)} already present)`:""}...`);const l=async u=>{try{const h=await Yt(t,u.id);i.set(u.id,await et(e,X(n,u),h,u,o))}catch(h){const g=h instanceof Error?h.message:String(h);throw o.error(`failed to upload blob ${u.id}: ${g}`),h}};for(const u of nn(d)){const g=(await Promise.allSettled(u.map(p=>l(p)))).find(p=>p.status==="rejected");if(g!==void 0)throw g.reason}return o.success(`migrated ${String(d.length)} storage blobs`),i};async function*an(e,t,r){let n=0;for await(const o of ee(e,t)){const s=o.trim();if(n+=1,s.length===0)continue;let i;try{i=JSON.parse(s)}catch(a){throw new f("INTERNAL",`${t.table}/documents.jsonl line ${String(n)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}r.set(t.table,(r.get(t.table)??0)+1),yield`${JSON.stringify({doc:i,table:t.table})}
`}}async function*cn(e,t,r,n,o){for(const s of t){if(Pe(s.table)){s.table===A&&!n&&r.warn(`skipping "${A}" — 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(s.table)||o.set(s.table,0),yield*an(e,s,o)}}const zo=["firebase","supabase"],dn=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 Vr(r,t,e.logger),o=Object.values(n?.tables??{}).some(s=>(s.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 hr(e.file,n)}:{collections:await Cr(e.file,n),kind:"firebase",mapping:n}},ln=async e=>{if(!await F(e.file).then(()=>!0,()=>!1))return!1;for(const[r,n]of[["--scan",e.scan],["--verify",e.verify],["--with-storage",e.withStorage]])if(n===!0)return e.logger.error(`${r} requires a Convex export directory or .zip snapshot — ${e.file} is not one.`),!0;return!1},un=async(e,t,r)=>{const n=t.find(s=>s.table===A);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 z(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},fn=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return dn(e,e.from,t);const r=await Ht(e.file),n=r===void 0?void 0:await Wt(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 ln(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 un(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},j=w("lunora","import-convex.json"),hn=(e,t)=>{const r=ne(e,t),n=O(r,"keyPrefix",t),o=r.storageColumns;if(o!==void 0){if(!k(o))throw new f("INTERNAL",`${t}: \`storageColumns\` must be an object of table → column names`);for(const s of Object.keys(o))Xe(o,s,`${t}: storageColumns`)}return{keyPrefix:n,storageColumns:o}},gn=async(e,t)=>{const r=w(e,j);let n;try{n=await T(r,"utf8")}catch(s){if(s.code==="ENOENT"){t.info(`no ${j} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw s}let o;try{o=JSON.parse(n)}catch(s){throw new f("INTERNAL",`${r}: invalid JSON — ${s instanceof Error?s.message:String(s)}`,{cause:s})}return hn(o,r)},pn=(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})}},mn=async(e,t,r)=>{const n=new Map([...r].map(i=>[i,i])),o=[];let s=0;for await(const i of ee(e,t)){const a=i.trim();if(s+=1,a.length===0)continue;const{ambiguous:c}=je(pn(a,t.table,s),n,t.table);for(const{column:d}of c)o.includes(d)||o.push(d)}return o},yn=async(e,t,r)=>{const n={};for(const o of t){if(Pe(o.table))continue;const s=await mn(e,o,r);s.length>0&&(n[o.table]=s)}return n},wn=async(e,t,r)=>{const n=w(t,j),o=`${JSON.stringify(e,void 0,4)}
`;await Z(w(t,"lunora"),{recursive:!0});try{await Le(n,o,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(s){if(s.code!=="EEXIST")throw s;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(o)}},bn=async(e,t,r,n)=>{const o=t.find(c=>c.table===A);if(o===void 0){n.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const s=await z(e,o,n),i=new Set(s.map(c=>c.id));n.info(`found ${String(i.size)} storage ids`);const a={keyPrefix:"",storageColumns:await yn(e,t,i)};return await wn(a,r,n),a},E=20,$n=(e,t,r)=>{let n=0;if(r.conflicts===0)for(const[o,s]of t){const i=r.inserted[o]??0;i<s&&(n+=1,e.error(`verify: ${o} inserted ${String(i)} of ${String(s)} source rows (${String(s-i)} missing)`))}else{const o=[...t.values()].reduce((i,a)=>i+a,0),s=Object.values(r.inserted).reduce((i,a)=>i+a,0)+r.conflicts;s<o&&(n+=1,e.error(`verify: ${String(s)} of ${String(o)} source rows accounted for across all tables (${String(o-s)} 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},Ie=(e,t,r)=>{for(const n of t.slice(0,E))e.warn(r(n));t.length>E&&e.warn(`… and ${String(t.length-E)} more`)},tt=(e,t,r)=>(e.info(`storage refs: ${String(t.rewritten)} rewritten, ${String(t.unmigrated.length)} unmigrated, ${String(t.ambiguous.length)} ambiguous`),Ie(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\``),Ie(e,t.ambiguous,n=>`unrewritten storage id in ${n.table}.${n.column}: ${n.storageId} — if that column holds storage references, add it to ${j} 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),vn=(e,t,r)=>{for(const n of[...t].slice(0,E))e.warn(`storage path never transferred: ${n} — left as-is`);return t.size>E&&e.warn(`… and ${String(t.size-E)} more untransferred storage paths`),r&&t.size>0},Re=200,Sn=/^\\x[\dA-Fa-f]*$/,Nn=/^[+-]?\d+$/,En=/^[+-]?\d+\.\d+$/,Tn=/^\{.*\}$/,An=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,In=[["bytea-base64",e=>Sn.test(e)],["timestamp-ms",e=>An.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Nn.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>En.test(e)],[e=>e.every(t=>Tn.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],Rn=e=>{if(e.length!==0){for(const[t,r]of In)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},_n=(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)}},On=async e=>{const t=new Map,r=I(e).pipe(Ce({columns:!0,skipEmptyLines:!0,toLine:Re+1}));let n=0;for await(const s of r)if(_n(s,t),n+=1,n>=Re)break;r.destroy();const o={};for(const[s,i]of t){const a=Rn(i);a!==void 0&&(o[s]=a)}return o},rt=async(e,t,r,n)=>{const o=Ze(r),s=w(t,o),i=`${JSON.stringify(e,void 0,4)}
`;await Z(xe(s),{recursive:!0});try{await Le(s,i,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${s} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${s} already exists — leaving it untouched. Candidate mapping:`),n.info(i)}},kn=async(e,t,r)=>{const n={};for(const s of e){const i=await On(s.file);r.info(`${y(s.file)} → ${s.table}: ${String(Object.keys(i).length)} column(s) need a reshape`),n[s.table]={file:y(s.file),idColumn:"id",...Object.keys(i).length>0?{types:i}:{}}}const o={keyPrefix:"",tables:n};return await rt(o,t,"supabase",r),o},Ln=async(e,t,r)=>{const n={};for(const s of e)n[s.table]={file:y(s.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 rt(o,t,"firebase",r),o},se=e=>w("lunora",`.import-storage-${e}.ndjson`),xn=async(e,t,r)=>{const n=new Map;let o;try{o=await T(w(e,se(t)),"utf8")}catch(i){if(i.code==="ENOENT")return n;throw i}let s=0;for(const i of o.split(`
`)){const a=i.trim();if(a.length!==0)try{const c=JSON.parse(a);typeof c.path=="string"&&typeof c.key=="string"?n.set(c.path,c):s+=1}catch{s+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${s>0?` (${String(s)} unreadable checkpoint line(s) ignored)`:""}`),n},Un=async(e,t,r)=>{const n=w(e,se(t));await Z(xe(n),{recursive:!0}),await wt(n,`${JSON.stringify(r)}
`,"utf8")},nt=100,Cn=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),Pn=async(e,t,r,n,o)=>{const s=await r(`${e.url}/storage/v1/object/list/${encodeURIComponent(t)}`,{body:JSON.stringify({limit:nt,offset:o,prefix:n}),headers:{authorization:`Bearer ${e.serviceKey}`,"content-type":"application/json"},method:"POST"});if(!s.ok){const i=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase storage list failed for bucket ${t} (HTTP ${String(s.status)}): ${i}`)}return await s.json()},ot=async(e,t,r,n="")=>{const o=[];let s=0;for(;;){const i=await Pn(e,t,r,n,s);for(const a of i){const c=n===""?a.name:`${n}/${a.name}`;a.id===null||a.id===void 0?o.push(...await ot(e,t,r,c)):o.push({contentType:a.metadata?.mimetype,name:c})}if(i.length<nt)return o;s+=i.length}},jn=async(e,t,r)=>{const n=await t(`${e.url}/storage/v1/bucket`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!n.ok){const i=await n.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase bucket list failed (HTTP ${String(n.status)}): ${i} — check the project URL and that the key is the service-role key, not the anon key`)}const o=await n.json(),s=[];for(const i of o){const a=await ot(e,i.name,t);r.info(`supabase bucket ${i.name}: ${String(a.length)} object(s)`);for(const c of a){const d=`${i.name}/${c.name}`;s.push({contentType:c.contentType,bytes:async()=>{const l=await t(`${e.url}/storage/v1/object/${encodeURIComponent(i.name)}/${Cn(c.name)}`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!l.ok){const u=await l.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase download failed for ${d} (HTTP ${String(l.status)}): ${u}`)}if(l.arrayBuffer===void 0)throw new f("INTERNAL","the fetch implementation cannot read response bytes, which the storage transfer requires");return Buffer.from(await l.arrayBuffer())},path:d})}}return s},Fn=async e=>{const t=G(e),r=[],n=async o=>{const s=await M(o,{withFileTypes:!0}).catch(()=>{});if(s===void 0)throw new f("INTERNAL",`${e} is not a readable directory — download the bucket first with \`gcloud storage cp -r gs://<bucket> <dir>\``);for(const i of s){const a=G(o,i.name);if(!Ue(t,a))throw new f("INTERNAL",`${i.name} resolves outside ${e} — refusing to upload it`);i.isDirectory()?await n(a):i.isFile()&&r.push({bytes:async()=>T(a),path:Rt(t,a).split(_t).join("/")})}};return await n(t),r},Mn=async(e,t,r,n,o)=>{const s=await t.bytes(),i=jt("sha256").update(s).digest("hex"),a=`${r.keyPrefix}${i}`;if(n.get(a)?.size!==s.length){const c={contentType:t.contentType,id:t.path,sha256:i,size:s.length};await et(e,a,s,c,o)}return await Un(r.cwd,r.source,{key:a,path:t.path,size:s.length}),a},Dn=(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)}%)`)}}},_e=async(e,t,r,n)=>{const o=new Map,s=await xn(r.cwd,r.source,n),i=await oe(e,r.keyPrefix),a=new Map(i.map(l=>[l.key,l]));s.size>0&&i.length===0&&n.warn(`the checkpoint records ${String(s.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=Dn(t.length,n);let d=0;n.info(`transferring ${String(t.length)} object(s) to R2...`);for(const l of t){const u=s.get(l.path);if(u!==void 0&&a.has(u.key)){o.set(l.path,u.key),d+=1,c(d);continue}try{const h=await Mn(e,l,r,a,n);o.set(l.path,h)}catch(h){const g=h instanceof Error?h.message:String(h);throw n.error(`failed transferring ${l.path} after ${String(d)} object(s): ${g}`),n.error(`progress is saved — re-run the same command to continue from here (delete ${se(r.source)} to start over)`),h}d+=1,c(d)}return n.success(`transferred ${String(t.length)} object(s) to R2`),o},Oe=/^\/+/,zn=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,Bn=/[#?]/u,Jn=e=>{const t=new Map(e),r=new Map;for(const[n,o]of e){const s=n.indexOf("/");if(s===-1)continue;const i=n.slice(s+1);i.length===0||e.has(i)||r.set(i,r.has(i)?void 0:o)}for(const[n,o]of r)o!==void 0&&t.set(n,o);return t},Vn=e=>{const t=zn.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(Bn)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},Hn=(e,t)=>{const r=t.get(e);if(r!==void 0)return r;const n=e.replace(Oe,""),o=t.get(n);if(o!==void 0)return o;const s=Vn(e);return s===void 0?void 0:t.get(s)??t.get(s.replace(Oe,""))},qn=500,ie=9e5,Gn=async e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)"),{refused:v.USAGE};const t=Et(e.url,e.logger,e.cwd);if(t===void 0)return{refused:v.USAGE};if(St({prod:e.prod,url:t})&&e.yes!==!0&&e.dryRun!==!0)return e.logger.error(`import bulk-writes ${t}, which is not local. Re-run with --yes to confirm.`),{refused:v.USAGE};const{token:r}=Nt({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:v.AUTH};try{const o=await F(e.file);if(!o.isFile()&&!o.isDirectory())return e.logger.error(`not a file or directory: ${e.file}`),{refused:v.USAGE}}catch(o){const s=o instanceof Error?o.message:String(o);return e.logger.error(`failed to stat ${e.file}: ${s}`),{refused:v.NOT_FOUND}}const n=e.fetchImpl??Tt;return{baseUrl:t,fetchImpl:n,requestUrl:`${t}${$t}`,token:r}},ae=(e,t,r,n)=>({conflicts:e.conflicts,deleted:e.deleted,errors:e.errors,...e.failed.length>0?{failed:e.failed}:{},inserted:e.inserted,...n===void 0?{}:{plan:n.tables},received:e.received,replaced:e.replaced,...t===void 0?{}:{storage:{ambiguous:r.ambiguous.slice(0,E),ambiguousTotal:r.ambiguous.length,blobs:t.size,rewritten:r.rewritten,unmigrated:r.unmigrated.slice(0,E),unmigratedTotal:r.unmigrated.length}},...e.warnings.length>0?{warnings:e.warnings}:{}}),Wn=(e,t,r,n)=>{switch(e.kind){case"convex":return cn(e.snapshot,e.tables,t.logger,r,n);case"firebase":return Mr(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return mr(e.tables,e.mapping,t.logger,n,t.file);default:return I(t.file,{encoding:"utf8"})}},Yn=async(e,t,r)=>{switch(e.kind){case"convex":return bn(e.snapshot,e.tables,t,r);case"firebase":return Ln(e.collections,t,r);case"supabase":return kn(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},Kn=async(e,t,r,n)=>{const o=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return _e(e,await Fn(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 s=process.env.SUPABASE_URL,i=process.env.SUPABASE_SERVICE_ROLE_KEY;if(s===void 0||i===void 0){r.logger.error("--with-storage needs SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in the environment (the service-role key, not the anon key), or --storage-dir pointing at an already-downloaded bucket.");return}let a=s.length;for(;a>0&&s[a-1]==="/";)a-=1;const c=s.slice(0,a);if(!c.startsWith("https://")){r.logger.error(`SUPABASE_URL must be https:// — refusing to send the service-role key over ${c.split(":")[0]??"an unknown scheme"}.`);return}const d=await jn({serviceKey:i,url:c},e.fetchImpl,r.logger);return _e(e,d,{cwd:n,keyPrefix:o,source:t.kind},r.logger)},Xn=(e,t,r,n,o)=>{const s=n.mapping?.tables?.[t]?.storageColumns??[];if(s.length===0)return e;const i={...e};for(const a of s){const c=i[a];if(typeof c!="string"||c.length===0)continue;const d=Hn(c,r);d===void 0?o.add(`${t}.${a}: ${c}`):i[a]=d}return i},Zn=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:Jn(r);return tr({remapDocument:n===void 0||t===void 0?void 0:(o,s)=>Xn(o,s,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},Qn=async(e,t,r,n)=>{let o="",s=0;const i=async a=>{s+=1;const c=t(a,s);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(`
`);for(;c!==-1;)await i(o.slice(0,c)),o=o.slice(c+1),c=o.indexOf(`
`)}o.length>0&&await i(o),await r.flush();return}catch(a){const c=a instanceof Error?a.message:String(a);return r.totals.received===0?(n.error(`import failed before any batch was acknowledged: ${c}`),n.error("re-run the same command once the worker is reachable (existing rows conflict rather than duplicate)")):(n.error(`import failed part-way through: ${c}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)")),a}},eo=async(e,t,r)=>{if(t.withStorage!==!0||e.kind!=="convex")return{};const n=await gn(r,t.logger),o=e.tables.find(s=>s.table===A);if(o===void 0){t.logger.error("--with-storage requires a Convex export with a `_storage` metadata table — re-export with `npx convex export --include-file-storage`.");return}return{mapping:n,storageIdMap:await on(e.snapshot,o,n?.keyPrefix??"",t.logger)}},to=async(e,t,r,n)=>{const o=t.tables.find(i=>i.table===A);if(o===void 0)return;const s=await sn(e,t.snapshot,o,r.mapping?.keyPrefix??"",n);return n.info(`storage map: ${String(s.size)} blobs mapped`),{mapping:r.mapping,storageIdMap:s}},ro=async(e,t,r,n,o)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return to(e,t,o,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const s=await Kn(e,t,r,n);return s===void 0?void 0:{transferredPaths:s}}catch(s){r.logger.error(`storage transfer failed: ${s instanceof Error?s.message:String(s)}`),r.logger.error("no rows were imported — fix the error above and re-run; objects that did transfer are checkpointed and will be skipped");return}},no=(e,t)=>{for(const s of t.warnings)e.warn(s);const r=t.received-t.insertedTotal-t.replaced-t.conflicts-t.errorCount;r>0&&e.warn(`${String(r)} of ${String(t.received)} rows were neither inserted, replaced, conflicted, nor reported as errors`);const n=`${t.replaced>0?`${String(t.replaced)} replaced, `:""}${t.deleted>0?`${String(t.deleted)} deleted, `:""}`,o=`imported ${String(t.insertedTotal+t.replaced)} of ${String(t.received)} rows (${n}${String(t.conflicts)} conflicts, ${String(t.errorCount)} errors)`;t.failed?e.error(o):e.success(o)},oo=async(e,t,r)=>await Yn(e,t,r.logger)===void 0?{body:void 0,code:v.USAGE,error:"import --scan: the export could not be scanned",inserted:0}:{body:void 0,code:0,inserted:0},so="GLOBAL_DRY_RUN_UNSUPPORTED",io={error:()=>{},info:()=>{},success:()=>{},warn:()=>{}},ao=e=>({...e,logger:io}),ke=async(e,t,r,n,o)=>{const s=new Set,i={ambiguous:[],rewritten:0,unmigrated:[]},a=new Map,c=Wn(t,e,r.storageIdMap!==void 0,a),d=te({batchSize:n.batchSize,fetchImpl:n.fetchImpl,maxBatchBytes:ie,requestUrl:n.requestUrl,token:n.token}),l=Zn({report:i,source:t,storageColumns:r.mapping?.storageColumns,storageIdMap:r.storageIdMap,table:e.table,transferredPaths:r.transferredPaths,unresolvedPaths:s}),u=t.kind==="ndjson"&&e.table===void 0?vt():void 0,h=u===void 0?l:($,N)=>{if($.trim().length>0){let S;try{S=JSON.parse($)}catch{return l($,N)}if(!u.read(S))return}return l($,N)},p=await Qn(c,o===void 0?h:($,N)=>{const S=h($,N);return S!==void 0&&Xt(o,S),S},d,e.logger),m=p===void 0?u?.problem():void 0,L=m===void 0?p:new Error(`${e.file}: ${m}`);return{batcher:d,remapReport:i,sourceRows:a,streamFailure:L,unresolvedPaths:s}},R=e=>e instanceof Error?e.message:typeof e=="string"?e:"an unknown failure",st=e=>{const{conflicts:t,inserted:r}=e.batcher.totals;return t>0||Object.values(r).some(n=>n>0)},co=(e,t,r,n)=>{const o=ae(t.batcher.totals,n,t.remapReport),s=st(t);if(e.format!=="json"&&e.logger.info(JSON.stringify(o,void 0,2)),t.streamFailure!==void 0){const c=R(t.streamFailure);e.logger.error(t.batcher.totals.received===0?`import failed before any batch was acknowledged: ${c}`:`import failed while checking the rows: ${c}`),e.logger.error(s?"rows may already be written by the check; check the shard before running the command again":"no rows were written; re-run the same command once the worker is reachable")}for(const c of t.batcher.totals.failed)e.logger.error(`import: shard "${c.shardKey}" was never reached${c.timedOut?" (timed out)":""} — no rows were written: ${c.message}`);const i=Object.values(t.batcher.totals.inserted).reduce((c,d)=>c+d,0),a=s?`import: ${e.file} was refused, and rows may already be written: ${r}`:`import: ${e.file} was not written: ${r}`;return{body:o,code:1,data:{file:e.file,inserted:i,summary:o},error:a,inserted:i}},lo=(e,t)=>{if(e.streamFailure!==void 0)return`the check stopped early: ${R(e.streamFailure)}`;const{errors:r,failed:n}=e.batcher.totals;if(st(e))return"this worker wrote rows during its check, so it cannot check an import before writing, and some rows may already be written";if(n.length>0)return`${String(n.length)} shard(s) could not be reached to check`;const o=r.filter(i=>i.code!==so);if(o.length>0)return`${String(o.length)} row(s) would be refused`;const s=e.remapReport.unmigrated.length;return t&&s>0?`${String(s)} storage reference(s) resolve to no exported blob`:void 0},uo=(e,t)=>{e.verify===!0&&t.remapReport.unmigrated.length>0&&tt(e.logger,t.remapReport,!0)},fo=(e,t)=>{for(const r of t)e.error(`import: shard "${r.shardKey}" was never reached${r.timedOut?" (timed out)":""} — its rows were NOT written: ${r.message}`)},ho=async(e,t)=>{const r=D(t);try{const n=await e.fetchImpl(`${e.requestUrl}?dryRun=true${r?"&onConflict=replace":""}`,{body:`
`,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!n.ok)return`the worker at ${e.requestUrl} answered HTTP ${String(n.status)} to the check`;const o=await n.json();return o.dryRun!==!0?`the worker at ${e.requestUrl} predates ?dryRun=true, so it would write the file while checking it; deploy the current runtime and import again`:r&&o.onConflict!=="replace"?`the worker at ${e.requestUrl} predates ?onConflict=replace, so --mode ${t} would overwrite nothing; deploy the current runtime and import again`:t==="replace"&&typeof o.deleted!="number"?`the worker at ${e.requestUrl} cannot delete rows, so --mode replace could not remove the rows the file lacks; deploy the current runtime and import again`:void 0}catch(n){return`the worker at ${e.requestUrl} did not answer the check: ${R(n)}`}},go=(e,t)=>{const r=t?"onConflict=replace":void 0;return{check:`${e}?dryRun=true${r===void 0?"":`&${r}`}`,write:r===void 0?e:`${e}?${r}`}},po=async(e,t,r,n)=>{const o=(c,d)=>(e.logger.error(d),{stop:{body:void 0,code:c,error:d,inserted:0}});let s;try{s=await Zt({baseUrl:t.baseUrl,fetchImpl:t.fetchImpl,token:t.token},r,n,e.dryRun!==!0)}catch(c){return o(1,`import: ${e.file} was not written: ${R(c)}`)}Qt(e.logger,s,n);const i=s.tables.filter(c=>c.target>0);if(n==="require-empty"&&i.length>0){const c=i.map(d=>`${d.table} (${String(d.target)} rows)`).join(", ");return o(1,`import: ${e.file} was not written: --mode require-empty, and the target already holds ${c}. Use --mode replace to make those tables match the file.`)}if(e.dryRun===!0){const c=ae({conflicts:0,deleted:0,errors:[],failed:[],inserted:{},received:0,replaced:0,warnings:[]},void 0,{ambiguous:[],rewritten:0,unmigrated:[]},s);return e.logger.success("dry run: nothing was written"),{stop:{body:c,code:0,data:{file:e.file,inserted:0,summary:c},inserted:0}}}return!er(s,n)||e.yes===!0?{plan:s}:e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json")?o(v.USAGE,`import: --mode ${n} overwrites or deletes stored rows and cannot prompt here; re-run with --yes to confirm`):await(e.confirm??It)(`--mode ${n} overwrites or deletes the stored rows above. Continue?`)?{plan:s}:o(v.CANCELLED,"import: aborted, nothing was written")},mo=async(e,t,r)=>{const n=te({...t,maxBatchBytes:ie,requestUrl:`${t.requestUrl}?deletes=true`});try{for(const o of e.deletions){const s=o.doc._id;typeof s=="string"&&r.get(o.table)?.ids.has(s)===!0||await n.push(JSON.stringify({doc:o.doc,op:"delete",table:o.table}))}return await n.flush(),{batcher:n,failure:void 0}}catch(o){return{batcher:n,failure:o}}},yo=async(e,t,r)=>{if(e===void 0||t!=="replace"||e.deletions.length===0)return;const n=te({...r,maxBatchBytes:ie,requestUrl:`${r.requestUrl}?dryRun=true&deletes=true`});try{for(const s of e.deletions)await n.push(JSON.stringify({doc:s.doc,op:"delete",table:s.table}));await n.flush()}catch(s){return R(s)}if(n.totals.failed.length>0)return`${String(n.totals.failed.length)} shard(s) could not be reached to check the deletes`;const[o]=n.totals.errors;return o===void 0?void 0:`${String(n.totals.errors.length)} planned delete(s) refused, first: ${o.table} ${o.message}`},wo=async(e,t,r,n)=>{if(t===void 0||e.mode!=="replace"||t.deletions.length===0)return{failed:!1};const o=String(t.deletions.length),{totals:s}=r.batcher;if(r.streamFailure!==void 0||r.verifyFailed||s.errors.length>0||s.failed.length>0)return e.logger.error(`--mode replace: the write did not finish cleanly, so the ${o} stored row(s) the file lacks were NOT deleted; fix the errors and re-run the same command`),{failed:!0};e.logger.info(`--mode replace: deleting ${o} stored row(s) the file lacks`);const{batcher:i,failure:a}=await mo(t,n,r.written),{totals:c}=i;return a!==void 0||c.errors.length>0||c.failed.length>0?(e.logger.error(`--mode replace: deleting stopped part-way${a===void 0?"":` (${R(a)})`}; every file row is written, and re-running the same command deletes the rest`),{failed:!0,totals:c}):{failed:!1,totals:c}},bo=(e,t)=>t===void 0?e:{...e,deleted:e.deleted+t.deleted,errors:[...e.errors,...t.errors],failed:[...e.failed,...t.failed]},$o=async(e,t,r,n)=>(n==="append"||n==="upsert"&&e.yes===!0)&&e.dryRun!==!0?{plan:void 0}:po(e,t,r,n),Bo=async e=>{const t=e.cwd??process.cwd(),r=await fn(e,t);if(r.kind==="invalid")return{body:void 0,code:v.USAGE,error:`import: could not read ${e.file}`,inserted:0};if(e.scan===!0)return oo(r,t,e);const n=await Gn(e);if(At(n))return{body:void 0,code:n.refused,error:"import: could not resolve the worker URL and admin token",inserted:0};const{baseUrl:o,fetchImpl:s,token:i}=n,a=e.mode??"append",c=go(n.requestUrl,D(a)),{write:d}=c,u={batchSize:e.batchSize??qn,fetchImpl:s,requestUrl:n.requestUrl,token:i},h=await ho(u,a);if(h!==void 0)return{body:void 0,code:1,error:`import: ${e.file} was not written: ${h}`,inserted:0};const g=await eo(r,e,t);if(g===void 0)return{body:void 0,code:1,error:"import: the storage phase failed — no rows were written",inserted:0};const p=new Map,m=await ke(ao(e),r,g,{...u,requestUrl:c.check},p),L=lo(m,e.verify===!0);if(L!==void 0)return uo(e,m),co(e,m,L,void 0);const $=await $o(e,n,p,a);if("stop"in $)return $.stop;const N=$.plan,S=await yo(N,a,u);if(S!==void 0){const C=`import: ${e.file} was not written: the worker would refuse the deletes --mode replace needs (${S})`;return e.logger.error(C),{body:void 0,code:1,error:C,inserted:0}}const J=await ro({baseUrl:o,fetchImpl:s,token:i},r,e,t,g);if(J===void 0)return{body:void 0,code:1,error:"import: the storage phase failed — no rows were written",inserted:0};const{storageIdMap:ce}=J;e.logger.info(r.kind==="convex"?`POST ${d} -> import Convex export ${e.file} (${String(r.tables.length)} tables)`:`POST ${d} -> import ${e.file}`);const de=new Map,{batcher:_,remapReport:le,sourceRows:it,streamFailure:V,unresolvedPaths:at}=await ke(e,r,J,{...u,requestUrl:d},de),ct=e.verify===!0&&V===void 0?$n(e.logger,it,{conflicts:_.totals.conflicts+_.totals.replaced,inserted:_.totals.inserted}):0,dt=ce!==void 0&&tt(e.logger,le,e.verify===!0),lt=vn(e.logger,at,e.verify===!0),ue=ct>0||dt||lt,fe=await wo(e,N,{batcher:_,streamFailure:V,verifyFailed:ue,written:de},u),he=bo(_.totals,fe.totals),{conflicts:ut,deleted:ft,errors:ge,failed:pe,inserted:ht,received:gt,replaced:H,warnings:pt}=he,x=Object.values(ht).reduce((C,mt)=>C+mt,0),U=ae(he,ce,le,N);fo(e.logger,pe);const me=V!==void 0||ge.length>0||pe.length>0||ue||fe.failed;e.format!=="json"&&e.logger.info(JSON.stringify(U,void 0,2)),no(e.logger,{conflicts:ut,deleted:ft,errorCount:ge.length,failed:me,insertedTotal:x,received:gt,replaced:H,warnings:pt});const ye={file:e.file,inserted:x,summary:U};return me?{body:U,code:1,data:ye,error:`import: ${e.file} did not import cleanly`,inserted:x,replaced:H}:{body:U,code:0,data:ye,inserted:x,replaced:H}};export{qn as D,zo as I,Qe as M,Kt as a,B as b,oe as l,Do as p,Bo as r,et as u};