@coreframe/scripts 0.2.47 → 0.2.49
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/coreframe.js +16 -16
- package/package.json +7 -7
package/dist/coreframe.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as e from"@alloc/cmd-ts";import{array as t,command as n,extendType as r,flag as i,multioption as a,number as o,oneOf as s,option as c,optional as l,positional as u,rest as d,restPositionals as f,string as p,subcommands as m}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as h,checkDeployMigrations as g,checkSchemaPush as _,collectDeployMigrationFiles as v,createLocalPostgresDb as
|
|
3
|
-
`)}function
|
|
2
|
+
import*as e from"@alloc/cmd-ts";import{array as t,command as n,extendType as r,flag as i,multioption as a,number as o,oneOf as s,option as c,optional as l,positional as u,rest as d,restPositionals as f,string as p,subcommands as m}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as h,checkDeployMigrations as g,checkSchemaPush as _,collectDeployMigrationFiles as v,createLocalPostgresDb as ee,createProjectPostgresDatabaseAdapter as y,createProjectSqliteDatabaseAdapter as b,createProjectSqliteDrizzleDatabase as x,ensureLocalDb as S,filterPendingMigrations as C,formatDbErrorMessage as w,formatMigrationList as T,formatMigrationScanFailures as te,migrateHeldMigrations as ne,migrateLocalDb as re,readAppliedMigrationNames as ie,reportLocalDatabaseInventory as ae,resetLocalDb as oe,runDrizzleKitCommand as se,scanDeployMigrationFiles as ce,seedLocalDb as le,setupLocalDb as ue,startProjectPostgres as E,startProjectTurso as de,stopProjectPostgres as fe}from"@coreframe/db";import{checkFlutterClient as D,classifyFlutterDevOutputLine as pe,ensureFlutterDevAssetDirectories as me,flutterPlatforms as O,generateFlutterNativeBridge as k,prepareFlutterClient as he,prepareFlutterDevOutput as ge,productionApiOrigin as A,runFlutterAcceptance as _e}from"@coreframe/flutter-tools";import j,{dirname as M,isAbsolute as ve,join as N,posix as ye,resolve as P,sep as be}from"node:path";import F from"nano-spawn";import{spawnSync as I}from"node:child_process";import{chmodSync as xe,existsSync as L,lstatSync as Se,mkdirSync as Ce,mkdtempSync as we,readFileSync as R,readlinkSync as Te,rmSync as Ee,symlinkSync as De,watch as Oe,writeFileSync as z}from"node:fs";import{homedir as ke,networkInterfaces as Ae,tmpdir as je}from"node:os";import*as B from"@clack/prompts";import{addAsset as Me,assetCatalogEntries as Ne,backupAssets as Pe,buildAssets as Fe,checkAssets as Ie,formatAssetProblems as Le,printAssetResult as Re,publishAssets as ze,readAssetCatalog as Be}from"@coreframe/assets";import{assertAssetCredentialProfile as Ve,configureAssetCredentials as He,createB2PrivateObjectStore as Ue}from"@coreframe/object-storage";import{access as We,chmod as Ge,copyFile as Ke,cp as qe,mkdir as V,mkdtemp as Je,readFile as H,readdir as Ye,rename as Xe,rm as U,stat as Ze,writeFile as W}from"node:fs/promises";import{importProjectDependency as Qe,importProjectModule as $e,normalizeWorkerEnvironment as et,primaryWorkerConfigPath as tt,readProjectConfig as G,wranglerEnvironmentNames as nt}from"@coreframe/config";import{createHash as rt,randomUUID as K}from"node:crypto";import q from"node:process";import{finished as it}from"node:stream/promises";import{createPrefixStream as at,supervise as ot}from"procband";import{createConnection as st,createServer as ct}from"node:net";import{inspectDevelopmentJobStates as lt}from"@coreframe/jobs";import{parse as ut,stringify as dt}from"yaml";import{accessTokenSigningSecretName as ft,clearAppliedPendingWorkerSecrets as pt,deployEnvironments as mt,discardPendingWorkerSecret as ht,discoverStagingUrl as gt,inspectWorkerEnvironment as _t,materializeBuiltClientDeployConfig as vt,materializeBuiltWorkerDeployConfig as yt,materializePrimaryWorkerTypeConfig as bt,parseDeclaredWorkerSecretEnv as xt,prepareAccessTokenSigningSecret as St,prepareReviewerDeploy as Ct,queueWorkerSecret as wt,queueWorkerSecrets as Tt,readDeclaredWorkerSecrets as Et,readPackageJson as Dt,readPendingWorkerSecretSnapshot as Ot,readPrimaryWorkerConfig as kt,reassignStagingHostname as At,releaseName as jt,resolveDeployConfig as Mt,resolveDeployD1Database as Nt,resolveReleaseVersion as Pt,rotateAccessTokenSigningSecret as Ft,runAfterWorkerDeploy as It,runPostDeployChecks as Lt,validateWorkerEnvironmentForDeploy as Rt,verifyAccessTokenSigningSecret as zt,writePackageVersion as Bt}from"@coreframe/deploy";import{inspect as Vt,parseEnv as Ht}from"node:util";import{once as Ut}from"node:events";import{connectDevSupervisor as Wt,createDevStartupTiming as Gt,devHttpsCertEnv as Kt,devHttpsKeyEnv as qt,isManagedDevCheckout as Jt,isPrimaryCheckout as Yt,prepareDevHttps as Xt}from"@coreframe/dev";import{devJobsEnv as Zt}from"@coreframe/dev-contracts/dev-jobs";import{managedDevEnv as Qt,managedDevFlutterRestartFileEnv as $t}from"@coreframe/dev-contracts/managed-dev";import{openScopedLogs as en}from"leylines";import{setTimeout as tn}from"node:timers/promises";import{determineAgent as nn}from"@vercel/detect-agent";import{runPreview as rn}from"@coreframe/preview";const an=`FLUTTER_XCODE_COREFRAME_BUNDLE_IDENTIFIER_SUFFIX`,on=`COREFRAME_FLUTTER_DEVELOPMENT`,sn=[`filtered`,`full`];function cn(e,{noCodesign:t=!1}={}){return{...e,[an]:`.dev`,[on]:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function ln(e=!1){return e?`debug`:`profile`}function un({device:e,mode:t,platform:n}){if(t===`profile`&&!e.physical)throw Error(`Flutter profile mode is unavailable on ${n===`ios`?`iOS simulator`:`Android emulator`}s. Re-run with --flutter-debug or select a physical device.`)}function dn({device:e,flutterDriver:t,mode:n,serverUrl:r,verbose:i}){return[`run`,`--machine`,`--${n}`,`-d`,e.id,`--dart-define=COREFRAME_DEV_SERVER_URL=${r}`,...t?[`--dart-define=ENABLE_FLUTTER_DRIVER=true`]:[],...i?[`--verbose`]:[]]}const fn=[`web`,...O];function pn(e=`web`,{apiOrigin:t,cwd:n=process.cwd(),profile:r=!1,simulator:i=!1}={}){if(bn(e,{profile:r,simulator:i}),e===`web`)return[Sn(`pnpm`,[`build`],n,{COREFRAME_PLATFORM:`web`})];let a=A(t);return[{kind:`prepare`,platform:e},Sn(`flutter`,mn(e,a,{profile:r,simulator:i}),P(n,`src-flutter`),{COREFRAME_API_ORIGIN:a})]}function mn(e,t,{noCodesign:n=e===`macos`,profile:r=!1,simulator:i=!1}={}){bn(e,{profile:r,simulator:i});let a=A(t);return[`build`,e===`android`?`apk`:e,r?`--profile`:`--release`,...i?[`--simulator`]:[],...n?[`--no-codesign`]:[],`--dart-define=COREFRAME_API_ORIGIN=${a}`]}function hn(e,{profile:t=!1}={}){let n=t?`profile`:`release`,r=P(e,`src-flutter/build/app/outputs/flutter-apk/app-${n}.apk`),i=JSON.stringify(r);return[`Android ${n} build succeeded.`,``,`Install it on a connected Android device:`,` 1. Enable Developer options and USB debugging, connect the device, and accept the authorization prompt.`,` 2. Verify the device is visible:`,` adb devices`,` 3. Install or update the APK:`,` adb install -r ${i}`,``,`If multiple devices are connected, use:`,` adb -s <device-id> install -r ${i}`].join(`
|
|
3
|
+
`)}function gn(e,{profile:t=!1,simulator:n=!1}={}){let r=t?`profile`:`release`,i=P(e,`src-flutter/build/ios/${n?`iphonesimulator`:`iphoneos`}/Runner.app`),a=JSON.stringify(i);return n?[`iOS Simulator ${r} build succeeded.`,``,`Install it on a booted iOS Simulator:`,` 1. Verify available simulators:`,` xcrun simctl list devices`,` 2. Install the app:`,` xcrun simctl install booted ${a}`,``,"If multiple simulators are available, replace `booted` with the simulator UDID."].join(`
|
|
4
4
|
`):[`iOS ${r} build succeeded.`,``,`Install it on a connected iOS device:`,` 1. Enable Developer Mode, connect the device, and trust this Mac if prompted.`,` 2. Verify the device is visible:`,` xcrun devicectl list devices`,` 3. Install the signed app:`,` xcrun devicectl device install app --device <device-id> ${a}`,``,`If multiple devices are connected, use the device UDID shown by devicectl.`].join(`
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
7
|
-
`)}async function vn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=me,runCommand:s=bn}={}){yn(r,{profile:i,simulator:a});let c={...n};delete c[rn],delete c[an],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:j(e??n.COREFRAME_API_ORIGIN);for(let e of fn(r,{apiOrigin:l,cwd:t,profile:i,simulator:a})){if(e.kind===`prepare`){if(!l)throw Error(`A production API origin is required for the Flutter ${e.platform} build.`);await o({apiOrigin:l,cwd:t,environment:c,platform:e.platform});continue}await s(e.command,e.args,{cwd:e.cwd,env:{...c,...e.environment}})}r===`android`?console.log(mn(t,{profile:i})):r===`ios`?console.log(hn(t,{profile:i,simulator:a})):r===`windows`?console.log(gn(t)):r===`linux`&&console.log(_n(t))}function yn(e,{profile:t,simulator:n}){if(t&&e===`web`)throw Error(`The --profile flag is only supported for Flutter build targets.`);if(n&&e!==`ios`)throw Error(`The --simulator flag is only supported for the iOS build target.`);if(t&&n)throw Error(`Flutter profile builds are not supported for the iOS simulator.`)}async function bn(e,t,{cwd:n,env:r}){await I(e,t,{cwd:n,env:r,stdio:`inherit`})}function xn(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const Sn=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return j(e)}}),Cn=n({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:u({type:l(s(dn)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:c({long:`api-origin`,type:l(Sn),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:i({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>vn({apiOrigin:e,platform:t,profile:n,simulator:r})});function wn(e){return e.apiKey??process.env.TYPESAFE_API_KEY??process.env.JEV_API_KEY}function Tn(e){return e.baseUrl??process.env.TYPESAFE_API_BASE??process.env.JEV_API_BASE??`https://jevtypesafeai.com/api/v1/decide`}function En(){return{resolvable:{type:`noul`,instructions:`Can these conflicting changes be mechanically combined without choosing between behaviors or losing either side's intent? Answer yes only when a resolution preserves both sides' semantics.`},strategy:{type:`choice`,instructions:`Which resolution strategy preserves both sides' intent?`,criteria:{keep_both:`both changes apply independently; concatenate or interleave them`,take_ours:`the ours side already supersedes or subsumes the theirs side`,take_theirs:`the theirs side already supersedes or subsumes the ours side`,combine_statements:`statements from both sides must be merged into shared code`}},risk:{type:`score`,instructions:`Risk that a mechanically produced resolution silently changes behavior, on an ordered scale.`,criteria:[`minimal`,`low`,`moderate`,`elevated`,`high`,`severe`]}}}async function Dn(e,t={}){let n=wn(t);if(!n)return{called:!1,approved:!1,reason:`jev_unavailable: no API key`};let r={state:e,questions:En()},i;try{let e=await(t.fetchImpl??fetch)(Tn(t),{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(r),signal:AbortSignal.timeout(t.timeoutMs??1e4)});if(!e.ok)return{called:!0,approved:!1,reason:`jev_unavailable: HTTP ${e.status}`};i=await e.json()}catch(e){return{called:!0,approved:!1,reason:`jev_unavailable: ${e instanceof Error?e.message:String(e)}`}}let a=i.answers?.resolvable?.noul;if(typeof a!=`number`||Number.isNaN(a))return{called:!0,approved:!1,reason:`jev_inconclusive: missing noul answer`,answers:i.answers};let o=t.noulThreshold??.8,s=t.confidenceThreshold??.7,c=i.answers?.strategy?.confidence??i.answers?.risk?.confidence;if(a<o)return{called:!0,approved:!1,reason:`jev_refused: resolvable ${a.toFixed(2)} < ${o}`,answers:i.answers};if(c!==void 0&&c<s)return{called:!0,approved:!1,reason:`jev_inconclusive: confidence ${c.toFixed(2)} < ${s}`,answers:i.answers};let l=i.answers?.strategy?.choice;return{called:!0,approved:!0,reason:`jev approved: resolvable ${a.toFixed(2)}${l?`, strategy ${l}`:``}`,answers:i.answers}}async function On(e,t={}){await Promise.all(e.map(async e=>{if(e.tier!==`judgment`)return;let n=await Dn({file:e.path,reasons:e.reasons,entities:e.entities,evidence:e.evidence},t);e.gate=n,e.decision=n.approved?`resolvable`:`escalate`,e.reasons.push(n.reason)}))}const kn=`safe`,An=`judgment`,Y=`unsafe`,jn=new Set([`both_added`,`rename_rename`,`rename_modify`]),Mn=new Set([`both_modified`,`modify_delete`,...jn]);function Nn(e,t,n){let r=L(t,n,{cwd:e,encoding:`utf8`});if(r.error)throw r.error;return r}function Pn(e,t=`git`){let n=Nn(e,t,[`ls-files`,`-u`,`-z`]);if(n.status!==0)throw Error(`git ls-files -u failed: ${n.stderr.trim()||n.stdout.trim()}`);let r=new Set;for(let e of n.stdout.split(`\0`)){if(!e)continue;let t=e.indexOf(` `);t!==-1&&r.add(e.slice(t+1))}return[...r]}function Fn(e,t,n=`weave`){let r=L(n,[`explain`,t,`--json`],{cwd:e,encoding:`utf8`});if(r.error)return{error:`weave unavailable: ${r.error.message}`};if(r.status!==0){let e=(r.stderr||r.stdout).toString().trim();return{error:`weave explain failed (${r.status}): ${e}`}}try{return{explain:JSON.parse(r.stdout)}}catch{return{error:`weave explain returned unparseable output`}}}function In(e,t,n,r=`git`){let i=Nn(e,r,[`show`,`:${t}:${n}`]);return i.status===0?i.stdout:void 0}function Ln(e){return e.collision??[]}function Rn(e){return Ln(e).length>0&&e.ours?.action===`modified`&&e.theirs?.action===`modified`}function zn(e){let t=e.kind??`unknown`,n=e.entity??`(file)`,r=[],i=(e,r)=>({entity:n,kind:t,tier:e,reasons:[r]});if(!Mn.has(t))return i(Y,`unrecognized conflict kind "${t}"`);if(jn.has(t))return i(Y,`${t}: divergent definitions of the same-named entity`);if(t===`modify_delete`){if((e.contested_hunks??0)===0){let i=e.repair?.kept_by;return r.push(`modify_delete with no contested hunks (decide_existence${i?`, kept_by=${i}`:``})`),{entity:n,kind:t,tier:An,reasons:r}}return i(Y,`modify_delete with contested hunks: deleted entity was also rewritten`)}let a=e.hunks??[];if(a.every(e=>Ln(e).length===0))return r.push(`both sides wrote adjacent lines only; no shared base statement rewritten`),{entity:n,kind:t,tier:kn,reasons:r};if(a.some(Rn))return i(Y,`collision on the same base statement: both sides rewrote it differently`);let o=a.reduce((e,t)=>e+Ln(t).length,0);return o<=3?(r.push(`contested collision bounded to ${o} statement(s)`),{entity:n,kind:t,tier:An,reasons:r}):i(Y,`contested collision spans ${o} base statements`)}const Bn={[kn]:0,[An]:1,[Y]:2};function Vn(e,t){if(t.error||!t.explain)return{path:e,tier:Y,decision:`escalate`,reasons:[t.error??`no analysis`],entities:[],analysisError:t.error};let n=(t.explain.conflicts??[]).map(zn),r=n.reduce((e,t)=>Bn[t.tier]>Bn[e]?t.tier:e,kn),i=n.flatMap(e=>e.reasons.map(t=>`${e.entity}: ${t}`));return{path:e,tier:r,decision:r===`safe`?`resolvable`:`escalate`,reasons:i,entities:n}}const Hn=12e3;function Un(e,t,n,r,i){let a={base:In(e,1,t,r),ours:In(e,2,t,r),theirs:In(e,3,t,r)},o=e=>e===void 0||e.length<=Hn?e:`${e.slice(0,Hn)}\n… truncated`,s={base:o(a.base),ours:o(a.ours),theirs:o(a.theirs)},c={};if(a.base&&(a.ours||a.theirs)){let e=Ce(P(Ae(),`coreframe-conflicts-`));try{let n=P(e,`base`);B(n,a.base);for(let r of[`ours`,`theirs`]){let o=a[r];if(!o)continue;let s=P(e,r);B(s,o);let l=L(i,[`patch`,`extract`,n,s,`--path`,t],{encoding:`utf8`});if(l.status===0)try{c[r]=JSON.parse(l.stdout)}catch{c[r]={error:`unparseable patch ops`}}}}catch{}finally{Te(e,{recursive:!0,force:!0})}}return{explain:n,stages:s,entityOps:c}}async function Wn(e){let t=e.gitBin??`git`,n=e.weaveBin??process.env.COREFRAME_WEAVE_BIN??`weave`,r=Pn(e.worktree,t).map(r=>{let i=Fn(e.worktree,r,n),a=Vn(r,i);return a.tier===`judgment`&&(a.evidence=Un(e.worktree,r,i.explain,t,n)),a}),i=r.filter(e=>e.tier===An);i.length>0&&await On(i,e.jev??{});let a={total:r.length,safe:r.filter(e=>e.tier===kn).length,judgment:r.filter(e=>e.tier===An).length,unsafe:r.filter(e=>e.tier===Y).length},o=r.every(e=>e.decision===`resolvable`)?`cheap-llm-resolvable`:`escalate`;return{worktree:e.worktree,recommendation:o,files:r,summary:a}}function Gn(e){for(let t of e.files){let e=t.decision===`resolvable`?` `:`!`;console.log(`${e} ${t.tier.padEnd(8)} ${t.decision.padEnd(10)} ${t.path}`);for(let e of t.reasons)console.log(` ${e}`)}let{summary:t}=e;console.log(`\n${t.total} conflicted file(s): ${t.safe} safe, ${t.judgment} judgment, ${t.unsafe} unsafe`),console.log(`recommendation: ${e.recommendation}`)}const Kn=m({name:`conflicts`,description:`Classify rebase/merge conflicts in a worktree as cheap-LLM-resolvable or escalate.`,cmds:{classify:n({name:`classify`,description:`Analyze unmerged index stages with weave and emit a per-conflict verdict. Judgment-tier conflicts are gated through the TypeSafe Jev decide API when TYPESAFE_API_KEY (or JEV_API_KEY) is set; any Jev failure escalates.`,args:{worktree:c({long:`worktree`,type:l(p),description:`Worktree to inspect. Defaults to the current directory.`}),json:i({long:`json`,description:`Print the full structured report instead of a summary.`,defaultValue:()=>!1})},handler:async({worktree:e,json:t})=>{let n=await Wn({worktree:e??process.cwd()});t?console.log(JSON.stringify(n,void 0,2)):Gn(n),n.recommendation!==`cheap-llm-resolvable`&&(process.exitCode=1)}})}}),qn=/^[a-f0-9]{64}$/,Jn=/^[a-f0-9]{40}$/,Yn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Xn(e){if(!qn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function Zn(e){if(!Jn.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function Qn(e,t){if(!Yn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function $n(e){return`projects/${Qn(e,`Project ID`)}/i18n/v1`}function er(e,t){return Xn(t),`${$n(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function tr(e,t){return Zn(t),`${$n(e)}/commits/${t}.json`}function nr(e,t){return rr(t),`${$n(e)}/releases/${encodeURIComponent(t)}.json`}function rr(e){if(!e.startsWith(`v`)||e.length<2||e.length>128||/\s/.test(e)||e.includes(`..`))throw Error(`Release tag "${e}" must be a valid v-prefixed tag.`);return e}function X(e,t){if(!t||t.startsWith(`/`)||t.includes(`\0`))throw Error(`Unsafe i18n artifact path "${t}".`);let n=F(e),r=F(n,t);if(r!==n&&!r.startsWith(`${n}${ye}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function Z(e,t,n){return`${e.directory}/${t}/${n}.json`}function ir(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function ar(e){await I(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function or({config:e,cwd:t,strict:n,temporaryDirectory:r}){let i=[];try{for(let n of e.locales)for(let a of e.catalogs){let o=X(t,Z(e,n,a)),s=await dr(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=P(r,`${n}-${a}.json`);await H(N(l),{recursive:!0}),await Ge(o,l),i.push({path:o,backup:l}),await fr(o,c)}await I(`pnpm`,[`exec`,`lingui`,`compile`,...n?[`--strict`]:[]],{cwd:t,stdio:`inherit`})}finally{try{for(let{path:e,backup:t}of i)await Ge(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await W(X(t,ir(e,n,r)),{force:!0})}}}async function sr({config:e,cwd:t}){let n=[];for(let r of e.locales)if(r!==e.sourceLocale)for(let i of e.catalogs){let a=await dr(X(t,Z(e,r,i)));for(let[e,t]of Object.entries(a)){if(t.obsolete||t.translation?.trim())continue;let a=t.message;if(typeof a!=`string`||!a)throw Error(`Missing source message metadata for ${r}:${e}.`);n.push({catalog:i,comments:t.comments?.filter(e=>typeof e==`string`)??[],context:t.context,id:e,locale:r,message:a,origins:t.origin?.map(([e,t])=>t?`${e}:${t}`:e)??[],placeholders:Object.keys(t.placeholders??{}).sort()})}}return n.sort((e,t)=>_r(e).localeCompare(_r(t)))}async function cr({config:e,cwd:t,messages:n,env:r=process.env}){if(n.length===0)return{translations:[],version:1};if(!e.generator)throw Error(`I18n preparation found ${n.length} missing translations, but no generator is configured.`);let i={messages:n,sourceLocale:e.sourceLocale,version:1};return pr(await mr({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function lr({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[_r(e),e])),a=new Map;for(let e of r.translations){let t=_r(e);if(!i.has(t))throw Error(`Translation generator returned unexpected entry ${e.locale}:${e.catalog}:${e.id}.`);if(a.has(t))throw Error(`Translation generator returned duplicate entry ${e.locale}:${e.catalog}:${e.id}.`);if(!e.translation.trim())throw Error(`Translation generator returned an empty entry ${e.locale}:${e.id}.`);a.set(t,e.translation)}let o=[...i.keys()].filter(e=>!a.has(e));if(o.length>0)throw Error(`Translation generator omitted ${o.length} required entries.`);let s=await Ze(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(_r(e));hr({compileMessage:s,id:e.id,locale:e.locale,source:e.message,translation:t})}for(let n of e.locales)if(n!==e.sourceLocale)for(let r of e.catalogs){let i=X(t,Z(e,n,r)),o=await dr(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(_r({catalog:r,id:e,locale:n}));if(i!==void 0){if(t.translation?.trim())throw Error(`Refusing to overwrite preserved translation ${n}:${e}.`);t.translation=i,s=!0}}s&&await fr(i,o)}}async function ur({config:e,cwd:t}){let n=await sr({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Ze(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await dr(X(t,Z(e,n,i)));for(let[e,t]of Object.entries(a))if(!t.obsolete){if(typeof t.message!=`string`||typeof t.translation!=`string`)throw Error(`Incomplete source metadata for active translation ${n}:${e}.`);hr({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function dr(e){let t=JSON.parse(await U(e,`utf8`));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Lingui rich JSON catalog must be an object: ${e}.`);for(let[n,r]of Object.entries(t)){if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Invalid Lingui rich JSON message ${n} in ${e}.`);let t=r;if(t.translation!==void 0&&typeof t.translation!=`string`)throw Error(`Invalid translation value for ${n} in ${e}.`);if(t.message!==void 0&&t.message!==null&&typeof t.message!=`string`)throw Error(`Invalid source message value for ${n} in ${e}.`);if(t.context!==void 0&&typeof t.context!=`string`)throw Error(`Invalid context value for ${n} in ${e}.`);if(t.obsolete!==void 0&&typeof t.obsolete!=`boolean`)throw Error(`Invalid obsolete marker for ${n} in ${e}.`);if(t.comments!==void 0&&(!Array.isArray(t.comments)||t.comments.some(e=>typeof e!=`string`)))throw Error(`Invalid comments for ${n} in ${e}.`);if(t.origin!==void 0&&(!Array.isArray(t.origin)||t.origin.some(e=>!Array.isArray(e)||typeof e[0]!=`string`||e[1]!==void 0&&typeof e[1]!=`number`)))throw Error(`Invalid origins for ${n} in ${e}.`);if(t.placeholders!==void 0&&(!t.placeholders||typeof t.placeholders!=`object`||Array.isArray(t.placeholders)))throw Error(`Invalid placeholders for ${n} in ${e}.`)}return t}async function fr(e,t){await H(N(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await G(n,`${JSON.stringify(t,null,2)}\n`),await Ye(n,e)}function pr(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Translation generator returned invalid JSON.`)}if(!t||typeof t!=`object`||t.version!==1||!Array.isArray(t.translations))throw Error(`Translation generator returned an invalid response envelope.`);for(let e of t.translations)if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.catalog!=`string`||typeof e.locale!=`string`||typeof e.translation!=`string`)throw Error(`Translation generator returned an invalid translation entry.`);return t}function mr({args:e,command:t,cwd:n,env:r,input:i}){return I(t,e,{cwd:n,env:r,stdio:[{string:i},`pipe`,`ignore`]}).then(({stdout:e})=>{if(Buffer.byteLength(e)>10*1024*1024)throw Error(`Translation generator output exceeded 10 MiB.`);return e}).catch(()=>{throw Error(`Translation generator exited unsuccessfully.`)})}function hr({compileMessage:e,id:t,locale:n,source:r,translation:i}){let a,o;try{a=e.compileMessageOrThrow(r),o=e.compileMessageOrThrow(i)}catch{throw Error(`Translation ${n}:${t} is not valid ICU MessageFormat.`)}let s=gr(a),c=gr(o);if(s.length!==c.length||s.some((e,t)=>e!==c[t]))throw Error(`Translation ${n}:${t} does not preserve source ICU placeholders.`)}function gr(e){let t=[];function n(e){for(let r of e){if(typeof r==`string`)continue;let[e,i=`argument`,a]=r;if(t.push(`${e}:${i}`),a&&typeof a==`object`&&!Array.isArray(a))for(let e of Object.values(a))Array.isArray(e)&&n(e)}}return n(e),t.sort()}function _r(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function vr(e){return nt(`sha256`).update(e).digest(`hex`)}async function yr(e){return vr(await U(e))}function br(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function xr({bucket:e,digest:t,projectId:n,source:r,store:i}){if(Xn(t),await yr(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=er(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${q()}.verify`;try{if(await i.download(e,a,o),await yr(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await W(o,{force:!0})}}async function Sr({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=br(n),o=P(i,`reference-${q()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await U(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await W(o,{force:!0})}await G(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await W(o,{force:!0})}let s=P(i,`reference-${q()}.verify.json`);try{if(await r.download(e,t,s),!(await U(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await W(s,{force:!0})}}async function Cr({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=br(t),o=vr(a),s=P(i,`manifest-${o}.json`);await G(s,a,{flag:`wx`});try{await xr({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await W(s,{force:!0})}return o}async function wr({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=P(r,`reference-${q()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await U(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return Zn(r.revision),Xn(r.snapshot),r}finally{await W(i,{force:!0})}}async function Tr({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await wr({bucket:e,key:tr(t,n),store:r,temporaryDirectory:i});if(a&&a.revision!==n)throw Error(`I18n commit reference does not match requested revision ${n}.`);return a}async function Er({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await Sr({bucket:e,key:tr(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await Sr({bucket:e,key:nr(t,i),reference:n,store:r,temporaryDirectory:a})}async function Dr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){Xn(n);let o=P(F(t),`v1`,`sha256`,n.slice(0,2),n);if(await kr(o,n)===!1){await H(N(o),{recursive:!0});let t=`${o}.${process.pid}.${q()}.tmp`;try{if(await i.download(e,er(r,n),t),await yr(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await W(o,{force:!0}),await Ye(t,o)}finally{await W(t,{force:!0})}}await H(N(a),{recursive:!0});let s=`${a}.${process.pid}.${q()}.tmp`;try{if(await Ge(o,s),await yr(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await W(a,{force:!0}),await Ye(s,a)}finally{await W(s,{force:!0})}}async function Or({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=P(a,`manifest-${n}.json`);await Dr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await U(o,`utf8`));if(s.version!==1||s.projectId!==r||typeof s.revision!=`string`||!Array.isArray(s.files)||!Array.isArray(s.catalogs)||s.catalogs.some(e=>typeof e!=`string`)||!Array.isArray(s.locales)||s.locales.some(e=>typeof e!=`string`)||typeof s.sourceLocale!=`string`||typeof s.generator!=`string`||typeof s.linguiVersion!=`string`)throw Error(`Invalid i18n snapshot manifest ${n}.`);Zn(s.revision),s.baseline!==void 0&&Xn(s.baseline);for(let e of s.files){if(!e||typeof e!=`object`||typeof e.path!=`string`||typeof e.digest!=`string`||typeof e.size!=`number`)throw Error(`Invalid file entry in i18n snapshot manifest ${n}.`);Xn(e.digest)}return s}async function kr(e,t){try{return(await Xe(e)).isFile()&&await yr(e)===t}catch{return!1}}async function Ar({cwd:e=process.cwd(),env:t=process.env}={}){let n=await K({cwd:e});if(!n.i18n)return;let r=t.COREFRAME_I18N_RELEASE_REVISION;if(r){if(Pr(Fr(n.i18n))===`multilingual`){await Nr({cwd:e,env:t,revision:r});return}console.log(`I18n source-only mode: building source catalogs for ${r}; no prepared translation snapshot is required.`)}await ar(e)}async function jr({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await K({cwd:e});if(!n.i18n)return;let r=Fr(n.i18n),i=X(e,r.directory);try{if(!(await Xe(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await ar(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Xe(X(e,Z(r,t,n)))).isFile())throw Error(`I18n catalog path is not a file: ${t}/${n}.json.`)}catch(t){if(t.code!==`ENOENT`)throw t;await ar(e);return}}async function Mr({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){rr(r),await Wr(e);let i=await Ur(e);await Gr(e,r,i);let a=await K({cwd:e});if(!a.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);let o=Fr(a.i18n);if(Pr(o)===`source-only`)return{mode:`source-only`,sourceLocale:o.sourceLocale};let s=await Ir({cwd:e,env:t,projectConfig:a,store:n}),c=await qe(P(Ae(),`coreframe-i18n-prepare-`));try{let n=await Tr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,revision:i,store:s.store,temporaryDirectory:c});if(n){let e=await Or({bucket:s.assets.sourceBucket,cacheRoot:s.cacheRoot,digest:n.snapshot,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return Hr(s,e,i),await Rr(s,e),await Er({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:n,store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!0,snapshot:n.snapshot}}return await Vr(s,c,async()=>{let n=await Lr(s,i,c);n||await Br(s),await ar(e);let a=await sr({config:s.config,cwd:e}),o=await cr({config:s.config,cwd:e,env:t,messages:a});await lr({config:s.config,cwd:e,missing:a,response:o}),await ur({config:s.config,cwd:e}),await or({config:s.config,cwd:e,strict:!0,temporaryDirectory:c});let l=await zr(s),u={...n?{baseline:n}:{},catalogs:s.config.catalogs,files:l,generator:a.length>0?s.config.generator?.id??`unconfigured`:`none`,linguiVersion:await Kr(e),locales:s.config.locales,projectId:s.assets.projectId,revision:i,sourceLocale:s.config.sourceLocale,version:1},d=await Cr({bucket:s.assets.sourceBucket,manifest:u,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return await Er({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:{revision:i,snapshot:d,version:1},store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!1,snapshot:d}})}finally{await W(c,{force:!0,recursive:!0})}}async function Nr({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await K({cwd:e});if(!i.i18n)return;let a=await Ir({cwd:e,env:t,store:r,projectConfig:i}),o=Zn(n??await Ur(e)),s=await qe(P(Ae(),`coreframe-i18n-materialize-`));try{let e=await Tr({bucket:a.assets.sourceBucket,projectId:a.assets.projectId,revision:o,store:a.store,temporaryDirectory:s});if(!e)throw Error(`No prepared i18n snapshot exists for commit ${o}. Push a v* tag for this commit and wait for the translation gate.`);let t=await Or({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return Hr(a,t,o),await Rr(a,t),{revision:o,snapshot:e.snapshot}}finally{await W(s,{force:!0,recursive:!0})}}function Pr(e){return e.locales.length===1&&e.locales[0]===e.sourceLocale?`source-only`:`multilingual`}function Fr(e){let t=Qn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>Qn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>Qn(e,`Catalog`)))];if(n.length===0||!n.includes(t))throw Error(`I18n locales must include the source locale.`);if(r.length===0)throw Error(`I18n configuration requires at least one catalog.`);if(e.generator&&(!e.generator.command.trim()||!e.generator.id.trim()))throw Error(`I18n generator command and ID must be non-empty.`);return{catalogs:r,directory:e.directory??`locales`,generator:e.generator,locales:n,sourceLocale:t}}async function Ir({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await K({cwd:e});if(!i.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);if(!i.assets)throw Error(`I18n snapshots require the existing private build bucket configured under assets.`);let a=i.assets;return{assets:a,cacheRoot:F(e,`.coreframe`,`i18n`,`cache`),config:Fr(i.i18n),cwd:F(e),env:t,store:r??He({config:a,env:t})}}async function Lr(e,t,n){let{stdout:r}=await I(`git`,[`rev-list`,`--first-parent`,`--skip=1`,t],{cwd:e.cwd,stdin:`ignore`});for(let t of r.split(/\r?\n/).filter(Boolean)){let r=await Tr({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:Zn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Or({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return Hr(e,i,t),await Rr(e,i),r.snapshot}}async function Rr(e,t){for(let n of t.files)if(await Dr({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:X(e.cwd,n.path)}),(await Xe(X(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function zr(e){let t=[];for(let n of e.config.locales)for(let r of e.config.catalogs){let i=Z(e.config,n,r),a=X(e.cwd,i),o=await yr(a);await xr({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Xe(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function Br(e){let{stdout:t}=await I(`git`,[`rev-parse`,`--show-prefix`],{cwd:e.cwd,stdin:`ignore`}),n=t.trim(),{stdout:r}=await I(`git`,[`log`,`-1`,`--format=%H`,`--diff-filter=AM`,`--`,`:(top)${`${n}${e.config.directory}/${e.config.sourceLocale}/${e.config.catalogs[0]}.po`}`],{cwd:e.cwd,stdin:`ignore`}),i=r.trim();if(!i)return!1;let a=(await Ze(`@lingui/format-po`,e.cwd)).formatter({lineNumbers:!1}),o=!1;for(let t of e.config.locales)for(let r of e.config.catalogs){let s=`${n}${`${e.config.directory}/${t}/${r}.po`}`;try{let{stdout:n}=await I(`git`,[`show`,`${i}:${s}`],{cwd:e.cwd,stdin:`ignore`});await fr(X(e.cwd,Z(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function Vr(e,t,n){let r=[];for(let n of e.config.locales)for(let i of e.config.catalogs){let a=Z(e.config,n,i),o=X(e.cwd,a);try{await Ue(o)}catch{continue}let s=P(t,`previous-catalogs`,a);await H(N(s),{recursive:!0}),await Ye(o,s),r.push({backup:s,path:o})}try{let e=await n();return await W(P(t,`previous-catalogs`),{force:!0,recursive:!0}),e}catch(t){for(let t of e.config.locales)for(let n of e.config.catalogs)await W(X(e.cwd,Z(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await H(N(t),{recursive:!0}),await Ye(e,t);throw t}}function Hr(e,t,n){if(t.revision!==n||t.projectId!==e.assets.projectId||t.sourceLocale!==e.config.sourceLocale||JSON.stringify(t.locales)!==JSON.stringify(e.config.locales)||JSON.stringify(t.catalogs)!==JSON.stringify(e.config.catalogs))throw Error(`I18n snapshot does not match commit or project configuration.`);let r=e.config.locales.flatMap(t=>e.config.catalogs.map(n=>Z(e.config,t,n))),i=t.files.map(e=>e.path);if(new Set(i).size!==i.length||JSON.stringify(i.sort())!==JSON.stringify(r.sort()))throw Error(`I18n snapshot has an incomplete or unexpected artifact set.`)}async function Ur(e){let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return Zn(t.trim())}async function Wr(e){let{stdout:t}=await I(`git`,[`status`,`--porcelain`],{cwd:e,stdin:`ignore`});if(t.trim())throw Error(`Tagged i18n preparation requires a clean Git tree.`)}async function Gr(e,t,n){let{stdout:r}=await I(`git`,[`rev-parse`,`${t}^{commit}`],{cwd:e,stdin:`ignore`});if(r.trim()!==n)throw Error(`Release tag ${t} does not point to checked-out commit ${n}.`)}async function Kr(e){let{stdout:t}=await I(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const qr=[`Use a B2 Multi-Bucket Application Key restricted to the configured private build-object and public generated-assets buckets.`,`Required capabilities: listAllBucketNames, readFiles, and writeFiles.`,`Deletion, bucket-management, and key-management capabilities are not needed.`].join(` `),Jr=r(p,{displayName:`widths`,description:`Comma-separated responsive variant widths.`,async from(e){let t=e.split(`,`).map(e=>Number(e));if(t.length===0||t.some(e=>!Number.isInteger(e)||e<=0)||t.some((e,n)=>n>0&&e<=t[n-1]))throw Error(`Widths must be positive, unique, strictly ascending integers.`);return t}}),Yr=r(p,{displayName:`profile`,async from(e){return Be(e)}}),Xr=r(p,{displayName:`pack`,description:`Asset pack name, such as training-videos.`,async from(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e))throw Error(`Asset pack names must use lowercase hyphen-separated segments.`);return e}}),Zr=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return j(e)}}),Qr=m({name:`assets`,cmds:{configure:n({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${qr}`,args:{profile:u({type:Yr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{V.note(qr,`Required B2 key access`);let t=await V.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(V.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await V.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(V.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await Ve({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:n({name:`add`,args:{file:u({type:p,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:c({long:`id`,type:p,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:c({long:`alt`,type:l(p),description:`Required alt text for raster image and SVG assets.`}),pack:c({long:`pack`,type:l(Xr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:c({long:`widths`,type:l(Jr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>Le(await je({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:n({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:c({long:`branch`,type:p,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await Ne({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:n({name:`build`,args:{id:c({long:`id`,type:l(p),description:`Build only one logical asset ID.`}),pack:c({long:`pack`,type:l(Xr),description:`Build only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>Le(await Pe({id:e,pack:n}),t,{kind:`build`})}),check:n({name:`check`,args:{fix:i({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:c({long:`pack`,type:l(Xr),description:`Check only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await Fe({fix:e,pack:n});Le(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:n({name:`publish`,args:{pack:c({long:`pack`,type:l(Xr),description:`Publish only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Re({pack:t});Le(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:n({name:`status`,args:{pack:c({long:`pack`,type:l(Xr),description:`Report status for only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Fe({pack:t});Le(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),$r=m({name:`flutter`,cmds:{acceptance:n({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Zr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>ge({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:n({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:i({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>A({check:e})}),prepare:n({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:u({type:s(k),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Zr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>me({apiOrigin:e,platform:t})}),check:n({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:u({type:s(k),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Zr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>O({apiOrigin:e,platform:t})})}}),ei=m({name:`i18n`,cmds:{build:n({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await Ar()}}),materialize:n({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:c({long:`revision`,type:l(p),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Nr({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:n({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot. Source-only projects skip translation preparation.`,args:{tag:c({long:`tag`,type:p,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await Mr({tag:e});if(t.mode===`source-only`){console.log(`Skipped i18n release preparation: the supported locales contain only the source locale "${t.sourceLocale}", so no translation snapshot is required.`);return}console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),ti=J.platform===`win32`?`react-router.cmd`:`react-router`,ni=J.platform===`win32`?`panda.cmd`:`panda`;async function ri(e=J.cwd()){await oi(e),await ai(e,[`typegen`])}async function ii(e=J.cwd(),t=J.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=M.resolve(e,`.coreframe/dashboard-build`),i=M.join(r,`client`),a=M.resolve(e,`dist/client/__dashboard`);await W(r,{force:!0,recursive:!0});let o=await K({cwd:e});if(o.deploy?.mode===`client`||o.dashboard?.enabled===!1){await W(a,{force:!0,recursive:!0});return}await si(e,ni,[`build`],t),await ai(e,[`build`,...n?[`--mode`,n]:[]],t),await W(a,{force:!0,recursive:!0}),await H(M.dirname(a),{recursive:!0}),await Ke(i,a,{recursive:!0})}async function ai(e,t,n=J.env){await si(e,ti,t,n)}async function oi(e){await W(M.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function si(e,t,n,r=J.env){await I(t,n,{cwd:M.resolve(e,`dashboard`),env:{...r,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const ci={access:Ue,chmod:We,mkdir:H,mkdtemp:qe,readFile:U,readFileSync:z,rm:W,writeFile:G},li={getAvailablePort:di},ui={homedir:Oe,kill:J.kill,networkInterfaces:ke,tmpdir:Ae};async function di(){let e=st();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,t)});let t=e.address();if(!t||typeof t==`string`)throw Error(`Could not allocate an available TCP port.`);return t.port}finally{e.listening&&await new Promise((t,n)=>{e.close(e=>e?n(e):t())})}}function fi({host:e=`127.0.0.1`,port:t,start:n}){let r,i=!1,a=!1,o=!1,s,c,l,u,d,f=new Set,p=new Promise((e,t)=>{u=e,d=t}),m=e=>{a||o||(o=!0,d(e))},h=()=>(s||=Promise.resolve().then(n).catch(e=>{throw m(e),e}),s),g=e=>{f.add(e),e.once(`close`,()=>f.delete(e)),e.pause(),_(e).catch(t=>{m(t),e.destroy()})},_=async e=>{let t=await h();if(a||e.destroyed)return;let n=await pi(t,()=>a);if(a||e.destroyed){n.destroy();return}f.add(n),n.once(`close`,()=>f.delete(n)),n.on(`error`,()=>e.destroy()),n.once(`close`,()=>e.destroy()),e.on(`error`,()=>n.destroy()),e.once(`close`,()=>n.destroy()),e.pipe(n),n.pipe(e)};return{close:async()=>l||(l=(async()=>{a=!0,o||(o=!0,u());for(let e of f)e.destroy();f.clear(),c&&!i&&await Promise.allSettled([c]),!(!r||!i)&&(await new Promise(e=>{r.close(()=>e())}),i=!1)})(),l),fail:m,listen:async()=>c||(r=st(g),c=new Promise((n,a)=>{let o=e=>{if(i){m(e);return}a(e)};r.once(`error`,o),r.once(`listening`,()=>{i=!0,r.off(`error`,o),r.on(`error`,m),n()}),r.listen(t,e)}),c),wait:()=>p}}async function pi(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await mi(e)}catch(e){if(r=e,Date.now()>=n)break;await new Promise(e=>setTimeout(e,50))}throw r instanceof Error?r:Error(`Could not connect to the dashboard.`)}function mi({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=ot({host:e,port:t}),a=e=>{i.off(`connect`,o),i.destroy(),r(e)},o=()=>{i.off(`error`,a),n(i)};i.once(`error`,a),i.once(`connect`,o)})}const hi=J.platform===`win32`?`react-router.cmd`:`react-router`;function gi(e){return R(M.resolve(e,`dashboard/dashboard.config.ts`))}function _i({cwd:e,env:t,port:n}){let r=t.PATH??t.Path??``,i,a,o=!1,s,c,l=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>{d()};return J.on(e,t),{handler:t,signal:e}}),u=async(e,t)=>{try{await e,o||a?.fail(Error(`The dashboard development server stopped unexpectedly.`))}catch(e){o||a?.fail(e)}finally{await t.outputTasks,t.stdout.end(),t.stderr.end(),await Promise.allSettled([rt(t.stdout),rt(t.stderr)]),i===e&&(i=void 0)}};a=fi({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await li.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=it({label:`dashboard`}),s=it({color:`red`,label:`dashboard`});a.pipe(J.stdout,{end:!1}),s.pipe(J.stderr,{end:!1});let l=I(hi,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:M.resolve(e,`dashboard`),env:{...t,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([yi(l.stdout,a),yi(l.stderr,s)]);return c=u(l,{outputTasks:d,stderr:s,stdout:a}),{host:`127.0.0.1`,port:n}}});let d=async()=>s||(s=(async()=>{o=!0,await a?.close(),i?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),await c;for(let{handler:e,signal:t}of l)J.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function vi({cwd:e=J.cwd(),env:t=J.env,port:n}){let r=_i({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function yi(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const bi=m({name:`dashboard`,cmds:{dev:n({name:`dev`,args:{port:c({long:`port`,type:o,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>vi({port:e})}),build:n({name:`build`,args:{mode:c({long:`mode`,type:l(p),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>ii(void 0,void 0,e)}),typegen:n({name:`typegen`,args:{},handler:()=>ri()})}});function xi(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}async function Si({all:e,cwd:t=process.cwd(),ids:n=[],matches:r=[],now:i=new Date}={}){let a=await Oi(t),o=await ki(a.config,t,async e=>a.module.developmentJobs.createStateAdmin(e).list()),s=ct({jobs:a.module.developmentJobs.jobs,now:i,records:o??[]}),c=Ei(s,{all:e,ids:n,matches:r},{defaultAll:!0});return{database:{dialect:a.dialect,state:o?`existing`:`missing`},jobs:s.filter(e=>c.has(e.id)),version:1}}async function Ci({all:e,breakLeases:t=!1,cwd:n=process.cwd(),dryRun:r=!1,ids:i=[],json:a=!1,matches:o=[],now:s=new Date,yes:c=!1}){let l=await Si({all:!0,cwd:n,now:s}),u=Ei(l.jobs,{all:e,ids:i,matches:o},{defaultAll:!1}),d=l.jobs.filter(e=>u.has(e.id)),f=d.filter(e=>e.lease===`active`);if(r)return{database:l.database,dryRun:!0,jobs:d.map(e=>({id:e.id,status:e.lease===`active`&&!t?`blocked-active-lease`:e.persisted?`would-reset`:`no-state`})),version:1};if(f.length>0&&!t)throw Error(`Cannot reset active development job ${Ni(f.map(e=>e.id))}. Wait for the lease to expire or pass --break-leases.`);if((t||e||o.length>0||d.length>1)&&!c){if(a||!process.stdin.isTTY)throw Error(`This reset requires --yes when prompts are unavailable.`);let e=await V.confirm({message:`Reset local development state for ${d.length} job${d.length===1?``:`s`}?`});if(V.isCancel(e)||!e)throw Error(`Development job state reset was cancelled.`)}if(l.database.state===`missing`)return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:`no-state`})),version:1};let p=await Oi(n),m=await ki(p.config,n,async e=>p.module.developmentJobs.createStateAdmin(e).reset({breakLeases:t,jobIds:[...u],now:s}));if(!m)throw Error(`The local database disappeared before development job state was reset.`);if(m.activeLeaseIds.length>0&&!t)throw Error(`Cannot reset active development job ${Ni(m.activeLeaseIds)}. Wait for the lease to expire or pass --break-leases.`);let h=new Set(m.resetIds);return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:h.has(e.id)?`reset`:`no-state`})),version:1}}function wi(e){let t=Mi(e.database);return e.jobs.length===0?`${t}No local development jobs are configured.`:`${t}${Pi([`Job`,`Status`,`Last success`,`Next eligible`,`Lease`],e.jobs.map(e=>[e.id,e.lease===`active`?`running`:e.registration===`orphaned`?`orphaned`:e.eligibility,ji(e.lastSucceededAt),ji(e.nextEligibleAt),e.lease===`none`?`-`:`${e.lease} until ${ji(e.leaseUntil)}`]))}`}function Ti(e){let t=Mi(e.database);return e.jobs.length===0?`${t}No local development job state matched.`:`${t}${Pi([`Job`,`Result`],e.jobs.map(e=>[e.id,e.status.replaceAll(`-`,` `)]))}`}function Ei(e,{all:t=!1,ids:n=[],matches:r=[]},{defaultAll:i}){if(t&&(n.length>0||r.length>0))throw Error(`Use --all or explicit job selectors, not both.`);if(!t&&n.length===0&&r.length===0){if(i)return new Set(e.map(e=>e.id));throw Error(`Select one or more jobs by ID or --match, or pass --all.`)}let a=new Set(e.map(e=>e.id)),o=n.filter(e=>!a.has(e));if(o.length>0)throw Error(`Unknown development job ${Ni(o)}.`);let s=new Set(t?a:n);for(let t of r){let n=Di(t),r=e.filter(e=>n.test(e.id));if(r.length===0)throw Error(`Development job pattern ${JSON.stringify(t)} matched no jobs.`);for(let e of r)s.add(e.id)}return s}function Di(e){if(!e)throw Error(`Development job patterns must not be empty.`);let t=[...e].map(e=>e===`*`?`.*`:e===`?`?`.`:e.replace(/[\\^$.[\]{}()+|]/gu,`\\$&`)).join(``);return RegExp(`^${t}$`,`u`)}async function Oi(e){let t=await K({cwd:e}),n=t.jobs?.entry;if(!n)throw Error(`coreframe.config.ts must configure jobs.entry before managing development job state.`);let r=await Qe(n,e);if(!r.developmentJobs||!Array.isArray(r.developmentJobs.jobs)||typeof r.developmentJobs.createStateAdmin!=`function`)throw Error(`${n} must export developmentJobs with jobs and createStateAdmin properties.`);return{config:t,dialect:t.database?.dialect??`postgres`,module:r}}async function ki(e,t,n){try{var r=xi();let a=e.database?.dialect??`postgres`,o=a===`sqlite`?M.resolve(t,`.coreframe/turso.db`):M.resolve(t,`.coreframe/postgres/PG_VERSION`);try{await Xe(o)}catch(e){if(Fi(e)&&e.code===`ENOENT`)return;throw e}if(a===`sqlite`)try{var i=xi();let r=await S({cwd:t,env:i.a(await ue({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Ai(n,r)}finally{r.$client.close()}}catch(e){i.e=e}finally{await i.d()}let s=await y({cwd:t,env:r.a(await D({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Ai(n,s)}finally{await s.$client.end()}}catch(e){r.e=e}finally{await r.d()}}async function Ai(e,t){try{return await e(t)}catch(e){throw Ii(e)?Error(`The local development job state table is missing. Run coreframe db migrate-local, then retry.`,{cause:e}):e}}function ji(e){return e?.toISOString()??`-`}function Mi(e){return e.state===`missing`?`Local ${e.dialect} database is missing; no database was created.\n\n`:``}function Ni(e){return e.map(e=>JSON.stringify(e)).join(`, `)}function Pi(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),r=e=>e.map((e,t)=>e.padEnd(n[t])).join(` `).trimEnd();return[r(e),r(n.map(e=>`-`.repeat(e))),...t.map(r)].join(`
|
|
8
|
-
`)}function Fi(e){return e instanceof Error&&`code`in e}function Ii(e){let t=e;for(;t instanceof Error;){let e=t.message.toLowerCase();if(e.includes(`coreframe_dev_job_state`)&&(e.includes(`does not exist`)||e.includes(`no such table`)))return!0;t=t.cause}return!1}const Li={ids:f({type:p,displayName:`job`,description:`Exact local development job IDs.`}),matches:a({type:t(p),long:`match`,description:`Select job IDs with an anchored * and ? glob. Repeat to add patterns.`,defaultValue:()=>[]})},Ri=m({name:`jobs`,cmds:{status:n({name:`status`,description:`Inspect local development job cooldown and lease state.`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1}),...Li},handler:async({ids:e,json:t,matches:n})=>{let r=await Si({ids:e,matches:n});console.log(t?JSON.stringify(r):wi(r))}}),reset:n({name:`reset`,description:`Make local development jobs eligible for their next startup check.`,args:{all:i({long:`all`,description:`Select every configured and orphaned development job.`,defaultValue:()=>!1}),breakLeases:i({long:`break-leases`,description:`Invalidate active job leases. The original invocation may keep running.`,defaultValue:()=>!1}),dryRun:i({long:`dry-run`,description:`Show the reset without changing local state.`,defaultValue:()=>!1}),json:i({long:`json`,description:`Print machine-readable JSON without prompting.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Confirm a multi-job, pattern, all-job, or lease-breaking reset.`,defaultValue:()=>!1}),...Li},handler:async({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o})=>{let s=await Ci({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o});console.log(i?JSON.stringify(s):Ti(s))}})}}),zi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Bi(e,t){let n=Hi(e,t);if(!Ui(n)||!Wi(n,[`description`,`requires`,`routes`,`verifier`])||!Ki(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Ki))||n.verifier!==void 0&&!Ki(n.verifier)||!Array.isArray(n.routes))throw Error(`${t} must contain a description string, routes array, and optional requires and verifier fields.`);let r=(n.requires??[]).map(e=>Vi(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Ui(e)||!Gi(e,[`path`,`router`,`when`])||!Ki(e.path)||!Ki(e.router)||!Ki(e.when))throw Error(`${t} route ${n+1} must contain router, path, and when strings.`);return{path:e.path,router:e.router,when:e.when}}),a=i.map(e=>`${e.router}\0${e.path}`);if(new Set(a).size!==a.length)throw Error(`${t} contains a duplicate router and path pair.`);return{description:n.description,requires:r,routes:i,verifier:n.verifier}}function Vi(e){if(!zi.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function Hi(e,t){try{return
|
|
5
|
+
`)}function _n(e){return[`Windows release build succeeded.`,``,`The unpackaged application bundle is at ${JSON.stringify(P(e,`src-flutter/build/windows/x64/runner/Release`))}.`,`Create and sign an installer with the Windows packaging workflow for distribution.`].join(`
|
|
6
|
+
`)}function vn(e){return[`Linux release build succeeded.`,``,`The application bundle is at ${JSON.stringify(P(e,`src-flutter/build/linux/x64/release/bundle`))}.`,`Package the bundle with the Linux distribution format used by your release process.`].join(`
|
|
7
|
+
`)}async function yn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=he,runCommand:s=xn}={}){bn(r,{profile:i,simulator:a});let c={...n};delete c[an],delete c[on],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:A(e??n.COREFRAME_API_ORIGIN);for(let e of pn(r,{apiOrigin:l,cwd:t,profile:i,simulator:a})){if(e.kind===`prepare`){if(!l)throw Error(`A production API origin is required for the Flutter ${e.platform} build.`);await o({apiOrigin:l,cwd:t,environment:c,platform:e.platform});continue}await s(e.command,e.args,{cwd:e.cwd,env:{...c,...e.environment}})}r===`android`?console.log(hn(t,{profile:i})):r===`ios`?console.log(gn(t,{profile:i,simulator:a})):r===`windows`?console.log(_n(t)):r===`linux`&&console.log(vn(t))}function bn(e,{profile:t,simulator:n}){if(t&&e===`web`)throw Error(`The --profile flag is only supported for Flutter build targets.`);if(n&&e!==`ios`)throw Error(`The --simulator flag is only supported for the iOS build target.`);if(t&&n)throw Error(`Flutter profile builds are not supported for the iOS simulator.`)}async function xn(e,t,{cwd:n,env:r}){await F(e,t,{cwd:n,env:r,stdio:`inherit`})}function Sn(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const Cn=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return A(e)}}),wn=n({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:u({type:l(s(fn)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:c({long:`api-origin`,type:l(Cn),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:i({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>yn({apiOrigin:e,platform:t,profile:n,simulator:r})});function Tn(e){return e.apiKey??process.env.TYPESAFE_API_KEY??process.env.JEV_API_KEY}function En(e){return e.baseUrl??process.env.TYPESAFE_API_BASE??process.env.JEV_API_BASE??`https://jevtypesafeai.com/api/v1/decide`}function Dn(){return{resolvable:{type:`noul`,instructions:`Can these conflicting changes be mechanically combined without choosing between behaviors or losing either side's intent? Answer yes only when a resolution preserves both sides' semantics.`},strategy:{type:`choice`,instructions:`Which resolution strategy preserves both sides' intent?`,criteria:{keep_both:`both changes apply independently; concatenate or interleave them`,take_ours:`the ours side already supersedes or subsumes the theirs side`,take_theirs:`the theirs side already supersedes or subsumes the ours side`,combine_statements:`statements from both sides must be merged into shared code`}},risk:{type:`score`,instructions:`Risk that a mechanically produced resolution silently changes behavior, on an ordered scale.`,criteria:[`minimal`,`low`,`moderate`,`elevated`,`high`,`severe`]}}}async function On(e,t={}){let n=Tn(t);if(!n)return{called:!1,approved:!1,reason:`jev_unavailable: no API key`};let r={state:e,questions:Dn()},i;try{let e=await(t.fetchImpl??fetch)(En(t),{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(r),signal:AbortSignal.timeout(t.timeoutMs??1e4)});if(!e.ok)return{called:!0,approved:!1,reason:`jev_unavailable: HTTP ${e.status}`};i=await e.json()}catch(e){return{called:!0,approved:!1,reason:`jev_unavailable: ${e instanceof Error?e.message:String(e)}`}}let a=i.answers?.resolvable?.noul;if(typeof a!=`number`||Number.isNaN(a))return{called:!0,approved:!1,reason:`jev_inconclusive: missing noul answer`,answers:i.answers};let o=t.noulThreshold??.8,s=t.confidenceThreshold??.7,c=i.answers?.strategy?.confidence??i.answers?.risk?.confidence;if(a<o)return{called:!0,approved:!1,reason:`jev_refused: resolvable ${a.toFixed(2)} < ${o}`,answers:i.answers};if(c!==void 0&&c<s)return{called:!0,approved:!1,reason:`jev_inconclusive: confidence ${c.toFixed(2)} < ${s}`,answers:i.answers};let l=i.answers?.strategy?.choice;return{called:!0,approved:!0,reason:`jev approved: resolvable ${a.toFixed(2)}${l?`, strategy ${l}`:``}`,answers:i.answers}}async function kn(e,t={}){await Promise.all(e.map(async e=>{if(e.tier!==`judgment`)return;let n=await On({file:e.path,reasons:e.reasons,entities:e.entities,evidence:e.evidence},t);e.gate=n,e.decision=n.approved?`resolvable`:`escalate`,e.reasons.push(n.reason)}))}const An=`safe`,jn=`judgment`,J=`unsafe`,Mn=new Set([`both_added`,`rename_rename`,`rename_modify`]),Nn=new Set([`both_modified`,`modify_delete`,...Mn]);function Pn(e,t,n){let r=I(t,n,{cwd:e,encoding:`utf8`});if(r.error)throw r.error;return r}function Fn(e,t=`git`){let n=Pn(e,t,[`ls-files`,`-u`,`-z`]);if(n.status!==0)throw Error(`git ls-files -u failed: ${n.stderr.trim()||n.stdout.trim()}`);let r=new Set;for(let e of n.stdout.split(`\0`)){if(!e)continue;let t=e.indexOf(` `);t!==-1&&r.add(e.slice(t+1))}return[...r]}function In(e,t,n=`weave`){let r=I(n,[`explain`,t,`--json`],{cwd:e,encoding:`utf8`});if(r.error)return{error:`weave unavailable: ${r.error.message}`};if(r.status!==0){let e=(r.stderr||r.stdout).toString().trim();return{error:`weave explain failed (${r.status}): ${e}`}}try{return{explain:JSON.parse(r.stdout)}}catch{return{error:`weave explain returned unparseable output`}}}function Ln(e,t,n,r=`git`){let i=Pn(e,r,[`show`,`:${t}:${n}`]);return i.status===0?i.stdout:void 0}function Rn(e){return e.collision??[]}function zn(e){return Rn(e).length>0&&e.ours?.action===`modified`&&e.theirs?.action===`modified`}function Bn(e){let t=e.kind??`unknown`,n=e.entity??`(file)`,r=[],i=(e,r)=>({entity:n,kind:t,tier:e,reasons:[r]});if(!Nn.has(t))return i(J,`unrecognized conflict kind "${t}"`);if(Mn.has(t))return i(J,`${t}: divergent definitions of the same-named entity`);if(t===`modify_delete`){if((e.contested_hunks??0)===0){let i=e.repair?.kept_by;return r.push(`modify_delete with no contested hunks (decide_existence${i?`, kept_by=${i}`:``})`),{entity:n,kind:t,tier:jn,reasons:r}}return i(J,`modify_delete with contested hunks: deleted entity was also rewritten`)}let a=e.hunks??[];if(a.every(e=>Rn(e).length===0))return r.push(`both sides wrote adjacent lines only; no shared base statement rewritten`),{entity:n,kind:t,tier:An,reasons:r};if(a.some(zn))return i(J,`collision on the same base statement: both sides rewrote it differently`);let o=a.reduce((e,t)=>e+Rn(t).length,0);return o<=3?(r.push(`contested collision bounded to ${o} statement(s)`),{entity:n,kind:t,tier:jn,reasons:r}):i(J,`contested collision spans ${o} base statements`)}const Vn={[An]:0,[jn]:1,[J]:2};function Hn(e,t){if(t.error||!t.explain)return{path:e,tier:J,decision:`escalate`,reasons:[t.error??`no analysis`],entities:[],analysisError:t.error};let n=(t.explain.conflicts??[]).map(Bn),r=n.reduce((e,t)=>Vn[t.tier]>Vn[e]?t.tier:e,An),i=n.flatMap(e=>e.reasons.map(t=>`${e.entity}: ${t}`));return{path:e,tier:r,decision:r===`safe`?`resolvable`:`escalate`,reasons:i,entities:n}}const Un=12e3;function Wn(e,t,n,r,i){let a={base:Ln(e,1,t,r),ours:Ln(e,2,t,r),theirs:Ln(e,3,t,r)},o=e=>e===void 0||e.length<=Un?e:`${e.slice(0,Un)}\n… truncated`,s={base:o(a.base),ours:o(a.ours),theirs:o(a.theirs)},c={};if(a.base&&(a.ours||a.theirs)){let e=we(N(je(),`coreframe-conflicts-`));try{let n=N(e,`base`);z(n,a.base);for(let r of[`ours`,`theirs`]){let o=a[r];if(!o)continue;let s=N(e,r);z(s,o);let l=I(i,[`patch`,`extract`,n,s,`--path`,t],{encoding:`utf8`});if(l.status===0)try{c[r]=JSON.parse(l.stdout)}catch{c[r]={error:`unparseable patch ops`}}}}catch{}finally{Ee(e,{recursive:!0,force:!0})}}return{explain:n,stages:s,entityOps:c}}async function Gn(e){let t=e.gitBin??`git`,n=e.weaveBin??process.env.COREFRAME_WEAVE_BIN??`weave`,r=Fn(e.worktree,t).map(r=>{let i=In(e.worktree,r,n),a=Hn(r,i);return a.tier===`judgment`&&(a.evidence=Wn(e.worktree,r,i.explain,t,n)),a}),i=r.filter(e=>e.tier===jn);i.length>0&&await kn(i,e.jev??{});let a={total:r.length,safe:r.filter(e=>e.tier===An).length,judgment:r.filter(e=>e.tier===jn).length,unsafe:r.filter(e=>e.tier===J).length},o=r.every(e=>e.decision===`resolvable`)?`cheap-llm-resolvable`:`escalate`;return{worktree:e.worktree,recommendation:o,files:r,summary:a}}function Kn(e){for(let t of e.files){let e=t.decision===`resolvable`?` `:`!`;console.log(`${e} ${t.tier.padEnd(8)} ${t.decision.padEnd(10)} ${t.path}`);for(let e of t.reasons)console.log(` ${e}`)}let{summary:t}=e;console.log(`\n${t.total} conflicted file(s): ${t.safe} safe, ${t.judgment} judgment, ${t.unsafe} unsafe`),console.log(`recommendation: ${e.recommendation}`)}const qn=m({name:`conflicts`,description:`Classify rebase/merge conflicts in a worktree as cheap-LLM-resolvable or escalate.`,cmds:{classify:n({name:`classify`,description:`Analyze unmerged index stages with weave and emit a per-conflict verdict. Judgment-tier conflicts are gated through the TypeSafe Jev decide API when TYPESAFE_API_KEY (or JEV_API_KEY) is set; any Jev failure escalates.`,args:{worktree:c({long:`worktree`,type:l(p),description:`Worktree to inspect. Defaults to the current directory.`}),json:i({long:`json`,description:`Print the full structured report instead of a summary.`,defaultValue:()=>!1})},handler:async({worktree:e,json:t})=>{let n=await Gn({worktree:e??process.cwd()});t?console.log(JSON.stringify(n,void 0,2)):Kn(n),n.recommendation!==`cheap-llm-resolvable`&&(process.exitCode=1)}})}}),Jn=/^[a-f0-9]{64}$/,Yn=/^[a-f0-9]{40}$/,Xn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Zn(e){if(!Jn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function Qn(e){if(!Yn.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function $n(e,t){if(!Xn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function er(e){return`projects/${$n(e,`Project ID`)}/i18n/v1`}function tr(e,t){return Zn(t),`${er(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function nr(e,t){return Qn(t),`${er(e)}/commits/${t}.json`}function rr(e,t){return ir(t),`${er(e)}/releases/${encodeURIComponent(t)}.json`}function ir(e){if(!e.startsWith(`v`)||e.length<2||e.length>128||/\s/.test(e)||e.includes(`..`))throw Error(`Release tag "${e}" must be a valid v-prefixed tag.`);return e}function Y(e,t){if(!t||t.startsWith(`/`)||t.includes(`\0`))throw Error(`Unsafe i18n artifact path "${t}".`);let n=P(e),r=P(n,t);if(r!==n&&!r.startsWith(`${n}${be}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function X(e,t,n){return`${e.directory}/${t}/${n}.json`}function ar(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function or(e){await F(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function sr({config:e,cwd:t,strict:n,temporaryDirectory:r}){let i=[];try{for(let n of e.locales)for(let a of e.catalogs){let o=Y(t,X(e,n,a)),s=await fr(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=N(r,`${n}-${a}.json`);await V(M(l),{recursive:!0}),await Ke(o,l),i.push({path:o,backup:l}),await pr(o,c)}await F(`pnpm`,[`exec`,`lingui`,`compile`,...n?[`--strict`]:[]],{cwd:t,stdio:`inherit`})}finally{try{for(let{path:e,backup:t}of i)await Ke(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await U(Y(t,ar(e,n,r)),{force:!0})}}}async function cr({config:e,cwd:t}){let n=[];for(let r of e.locales)if(r!==e.sourceLocale)for(let i of e.catalogs){let a=await fr(Y(t,X(e,r,i)));for(let[e,t]of Object.entries(a)){if(t.obsolete||t.translation?.trim())continue;let a=t.message;if(typeof a!=`string`||!a)throw Error(`Missing source message metadata for ${r}:${e}.`);n.push({catalog:i,comments:t.comments?.filter(e=>typeof e==`string`)??[],context:t.context,id:e,locale:r,message:a,origins:t.origin?.map(([e,t])=>t?`${e}:${t}`:e)??[],placeholders:Object.keys(t.placeholders??{}).sort()})}}return n.sort((e,t)=>vr(e).localeCompare(vr(t)))}async function lr({config:e,cwd:t,messages:n,env:r=process.env}){if(n.length===0)return{translations:[],version:1};if(!e.generator)throw Error(`I18n preparation found ${n.length} missing translations, but no generator is configured.`);let i={messages:n,sourceLocale:e.sourceLocale,version:1};return mr(await hr({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function ur({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[vr(e),e])),a=new Map;for(let e of r.translations){let t=vr(e);if(!i.has(t))throw Error(`Translation generator returned unexpected entry ${e.locale}:${e.catalog}:${e.id}.`);if(a.has(t))throw Error(`Translation generator returned duplicate entry ${e.locale}:${e.catalog}:${e.id}.`);if(!e.translation.trim())throw Error(`Translation generator returned an empty entry ${e.locale}:${e.id}.`);a.set(t,e.translation)}let o=[...i.keys()].filter(e=>!a.has(e));if(o.length>0)throw Error(`Translation generator omitted ${o.length} required entries.`);let s=await Qe(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(vr(e));gr({compileMessage:s,id:e.id,locale:e.locale,source:e.message,translation:t})}for(let n of e.locales)if(n!==e.sourceLocale)for(let r of e.catalogs){let i=Y(t,X(e,n,r)),o=await fr(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(vr({catalog:r,id:e,locale:n}));if(i!==void 0){if(t.translation?.trim())throw Error(`Refusing to overwrite preserved translation ${n}:${e}.`);t.translation=i,s=!0}}s&&await pr(i,o)}}async function dr({config:e,cwd:t}){let n=await cr({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Qe(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await fr(Y(t,X(e,n,i)));for(let[e,t]of Object.entries(a))if(!t.obsolete){if(typeof t.message!=`string`||typeof t.translation!=`string`)throw Error(`Incomplete source metadata for active translation ${n}:${e}.`);gr({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function fr(e){let t=JSON.parse(await H(e,`utf8`));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Lingui rich JSON catalog must be an object: ${e}.`);for(let[n,r]of Object.entries(t)){if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Invalid Lingui rich JSON message ${n} in ${e}.`);let t=r;if(t.translation!==void 0&&typeof t.translation!=`string`)throw Error(`Invalid translation value for ${n} in ${e}.`);if(t.message!==void 0&&t.message!==null&&typeof t.message!=`string`)throw Error(`Invalid source message value for ${n} in ${e}.`);if(t.context!==void 0&&typeof t.context!=`string`)throw Error(`Invalid context value for ${n} in ${e}.`);if(t.obsolete!==void 0&&typeof t.obsolete!=`boolean`)throw Error(`Invalid obsolete marker for ${n} in ${e}.`);if(t.comments!==void 0&&(!Array.isArray(t.comments)||t.comments.some(e=>typeof e!=`string`)))throw Error(`Invalid comments for ${n} in ${e}.`);if(t.origin!==void 0&&(!Array.isArray(t.origin)||t.origin.some(e=>!Array.isArray(e)||typeof e[0]!=`string`||e[1]!==void 0&&typeof e[1]!=`number`)))throw Error(`Invalid origins for ${n} in ${e}.`);if(t.placeholders!==void 0&&(!t.placeholders||typeof t.placeholders!=`object`||Array.isArray(t.placeholders)))throw Error(`Invalid placeholders for ${n} in ${e}.`)}return t}async function pr(e,t){await V(M(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await W(n,`${JSON.stringify(t,null,2)}\n`),await Xe(n,e)}function mr(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Translation generator returned invalid JSON.`)}if(!t||typeof t!=`object`||t.version!==1||!Array.isArray(t.translations))throw Error(`Translation generator returned an invalid response envelope.`);for(let e of t.translations)if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.catalog!=`string`||typeof e.locale!=`string`||typeof e.translation!=`string`)throw Error(`Translation generator returned an invalid translation entry.`);return t}function hr({args:e,command:t,cwd:n,env:r,input:i}){return F(t,e,{cwd:n,env:r,stdio:[{string:i},`pipe`,`ignore`]}).then(({stdout:e})=>{if(Buffer.byteLength(e)>10*1024*1024)throw Error(`Translation generator output exceeded 10 MiB.`);return e}).catch(()=>{throw Error(`Translation generator exited unsuccessfully.`)})}function gr({compileMessage:e,id:t,locale:n,source:r,translation:i}){let a,o;try{a=e.compileMessageOrThrow(r),o=e.compileMessageOrThrow(i)}catch{throw Error(`Translation ${n}:${t} is not valid ICU MessageFormat.`)}let s=_r(a),c=_r(o);if(s.length!==c.length||s.some((e,t)=>e!==c[t]))throw Error(`Translation ${n}:${t} does not preserve source ICU placeholders.`)}function _r(e){let t=[];function n(e){for(let r of e){if(typeof r==`string`)continue;let[e,i=`argument`,a]=r;if(t.push(`${e}:${i}`),a&&typeof a==`object`&&!Array.isArray(a))for(let e of Object.values(a))Array.isArray(e)&&n(e)}}return n(e),t.sort()}function vr(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function yr(e){return rt(`sha256`).update(e).digest(`hex`)}async function br(e){return yr(await H(e))}function xr(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function Sr({bucket:e,digest:t,projectId:n,source:r,store:i}){if(Zn(t),await br(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=tr(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${K()}.verify`;try{if(await i.download(e,a,o),await br(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await U(o,{force:!0})}}async function Cr({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=xr(n),o=N(i,`reference-${K()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await H(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await U(o,{force:!0})}await W(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await U(o,{force:!0})}let s=N(i,`reference-${K()}.verify.json`);try{if(await r.download(e,t,s),!(await H(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await U(s,{force:!0})}}async function wr({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=xr(t),o=yr(a),s=N(i,`manifest-${o}.json`);await W(s,a,{flag:`wx`});try{await Sr({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await U(s,{force:!0})}return o}async function Tr({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=N(r,`reference-${K()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await H(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return Qn(r.revision),Zn(r.snapshot),r}finally{await U(i,{force:!0})}}async function Er({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await Tr({bucket:e,key:nr(t,n),store:r,temporaryDirectory:i});if(a&&a.revision!==n)throw Error(`I18n commit reference does not match requested revision ${n}.`);return a}async function Dr({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await Cr({bucket:e,key:nr(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await Cr({bucket:e,key:rr(t,i),reference:n,store:r,temporaryDirectory:a})}async function Or({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){Zn(n);let o=N(P(t),`v1`,`sha256`,n.slice(0,2),n);if(await Ar(o,n)===!1){await V(M(o),{recursive:!0});let t=`${o}.${process.pid}.${K()}.tmp`;try{if(await i.download(e,tr(r,n),t),await br(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await U(o,{force:!0}),await Xe(t,o)}finally{await U(t,{force:!0})}}await V(M(a),{recursive:!0});let s=`${a}.${process.pid}.${K()}.tmp`;try{if(await Ke(o,s),await br(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await U(a,{force:!0}),await Xe(s,a)}finally{await U(s,{force:!0})}}async function kr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=N(a,`manifest-${n}.json`);await Or({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await H(o,`utf8`));if(s.version!==1||s.projectId!==r||typeof s.revision!=`string`||!Array.isArray(s.files)||!Array.isArray(s.catalogs)||s.catalogs.some(e=>typeof e!=`string`)||!Array.isArray(s.locales)||s.locales.some(e=>typeof e!=`string`)||typeof s.sourceLocale!=`string`||typeof s.generator!=`string`||typeof s.linguiVersion!=`string`)throw Error(`Invalid i18n snapshot manifest ${n}.`);Qn(s.revision),s.baseline!==void 0&&Zn(s.baseline);for(let e of s.files){if(!e||typeof e!=`object`||typeof e.path!=`string`||typeof e.digest!=`string`||typeof e.size!=`number`)throw Error(`Invalid file entry in i18n snapshot manifest ${n}.`);Zn(e.digest)}return s}async function Ar(e,t){try{return(await Ze(e)).isFile()&&await br(e)===t}catch{return!1}}async function jr({cwd:e=process.cwd(),env:t=process.env}={}){let n=await G({cwd:e});if(!n.i18n)return;let r=t.COREFRAME_I18N_RELEASE_REVISION;if(r){if(Fr(Ir(n.i18n))===`multilingual`){await Pr({cwd:e,env:t,revision:r});return}console.log(`I18n source-only mode: building source catalogs for ${r}; no prepared translation snapshot is required.`)}await or(e)}async function Mr({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await G({cwd:e});if(!n.i18n)return;let r=Ir(n.i18n),i=Y(e,r.directory);try{if(!(await Ze(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await or(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Ze(Y(e,X(r,t,n)))).isFile())throw Error(`I18n catalog path is not a file: ${t}/${n}.json.`)}catch(t){if(t.code!==`ENOENT`)throw t;await or(e);return}}async function Nr({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){ir(r),await Gr(e);let i=await Wr(e);await Kr(e,r,i);let a=await G({cwd:e});if(!a.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);let o=Ir(a.i18n);if(Fr(o)===`source-only`)return{mode:`source-only`,sourceLocale:o.sourceLocale};let s=await Lr({cwd:e,env:t,projectConfig:a,store:n}),c=await Je(N(je(),`coreframe-i18n-prepare-`));try{let n=await Er({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,revision:i,store:s.store,temporaryDirectory:c});if(n){let e=await kr({bucket:s.assets.sourceBucket,cacheRoot:s.cacheRoot,digest:n.snapshot,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return Ur(s,e,i),await zr(s,e),await Dr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:n,store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!0,snapshot:n.snapshot}}return await Hr(s,c,async()=>{let n=await Rr(s,i,c);n||await Vr(s),await or(e);let a=await cr({config:s.config,cwd:e}),o=await lr({config:s.config,cwd:e,env:t,messages:a});await ur({config:s.config,cwd:e,missing:a,response:o}),await dr({config:s.config,cwd:e}),await sr({config:s.config,cwd:e,strict:!0,temporaryDirectory:c});let l=await Br(s),u={...n?{baseline:n}:{},catalogs:s.config.catalogs,files:l,generator:a.length>0?s.config.generator?.id??`unconfigured`:`none`,linguiVersion:await qr(e),locales:s.config.locales,projectId:s.assets.projectId,revision:i,sourceLocale:s.config.sourceLocale,version:1},d=await wr({bucket:s.assets.sourceBucket,manifest:u,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return await Dr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:{revision:i,snapshot:d,version:1},store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!1,snapshot:d}})}finally{await U(c,{force:!0,recursive:!0})}}async function Pr({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await G({cwd:e});if(!i.i18n)return;let a=await Lr({cwd:e,env:t,store:r,projectConfig:i}),o=Qn(n??await Wr(e)),s=await Je(N(je(),`coreframe-i18n-materialize-`));try{let e=await Er({bucket:a.assets.sourceBucket,projectId:a.assets.projectId,revision:o,store:a.store,temporaryDirectory:s});if(!e)throw Error(`No prepared i18n snapshot exists for commit ${o}. Push a v* tag for this commit and wait for the translation gate.`);let t=await kr({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return Ur(a,t,o),await zr(a,t),{revision:o,snapshot:e.snapshot}}finally{await U(s,{force:!0,recursive:!0})}}function Fr(e){return e.locales.length===1&&e.locales[0]===e.sourceLocale?`source-only`:`multilingual`}function Ir(e){let t=$n(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>$n(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>$n(e,`Catalog`)))];if(n.length===0||!n.includes(t))throw Error(`I18n locales must include the source locale.`);if(r.length===0)throw Error(`I18n configuration requires at least one catalog.`);if(e.generator&&(!e.generator.command.trim()||!e.generator.id.trim()))throw Error(`I18n generator command and ID must be non-empty.`);return{catalogs:r,directory:e.directory??`locales`,generator:e.generator,locales:n,sourceLocale:t}}async function Lr({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await G({cwd:e});if(!i.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);if(!i.assets)throw Error(`I18n snapshots require the existing private build bucket configured under assets.`);let a=i.assets;return{assets:a,cacheRoot:P(e,`.coreframe`,`i18n`,`cache`),config:Ir(i.i18n),cwd:P(e),env:t,store:r??Ue({config:a,env:t})}}async function Rr(e,t,n){let{stdout:r}=await F(`git`,[`rev-list`,`--first-parent`,`--skip=1`,t],{cwd:e.cwd,stdin:`ignore`});for(let t of r.split(/\r?\n/).filter(Boolean)){let r=await Er({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:Qn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await kr({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return Ur(e,i,t),await zr(e,i),r.snapshot}}async function zr(e,t){for(let n of t.files)if(await Or({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:Y(e.cwd,n.path)}),(await Ze(Y(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function Br(e){let t=[];for(let n of e.config.locales)for(let r of e.config.catalogs){let i=X(e.config,n,r),a=Y(e.cwd,i),o=await br(a);await Sr({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Ze(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function Vr(e){let{stdout:t}=await F(`git`,[`rev-parse`,`--show-prefix`],{cwd:e.cwd,stdin:`ignore`}),n=t.trim(),{stdout:r}=await F(`git`,[`log`,`-1`,`--format=%H`,`--diff-filter=AM`,`--`,`:(top)${`${n}${e.config.directory}/${e.config.sourceLocale}/${e.config.catalogs[0]}.po`}`],{cwd:e.cwd,stdin:`ignore`}),i=r.trim();if(!i)return!1;let a=(await Qe(`@lingui/format-po`,e.cwd)).formatter({lineNumbers:!1}),o=!1;for(let t of e.config.locales)for(let r of e.config.catalogs){let s=`${n}${`${e.config.directory}/${t}/${r}.po`}`;try{let{stdout:n}=await F(`git`,[`show`,`${i}:${s}`],{cwd:e.cwd,stdin:`ignore`});await pr(Y(e.cwd,X(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function Hr(e,t,n){let r=[];for(let n of e.config.locales)for(let i of e.config.catalogs){let a=X(e.config,n,i),o=Y(e.cwd,a);try{await We(o)}catch{continue}let s=N(t,`previous-catalogs`,a);await V(M(s),{recursive:!0}),await Xe(o,s),r.push({backup:s,path:o})}try{let e=await n();return await U(N(t,`previous-catalogs`),{force:!0,recursive:!0}),e}catch(t){for(let t of e.config.locales)for(let n of e.config.catalogs)await U(Y(e.cwd,X(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await V(M(t),{recursive:!0}),await Xe(e,t);throw t}}function Ur(e,t,n){if(t.revision!==n||t.projectId!==e.assets.projectId||t.sourceLocale!==e.config.sourceLocale||JSON.stringify(t.locales)!==JSON.stringify(e.config.locales)||JSON.stringify(t.catalogs)!==JSON.stringify(e.config.catalogs))throw Error(`I18n snapshot does not match commit or project configuration.`);let r=e.config.locales.flatMap(t=>e.config.catalogs.map(n=>X(e.config,t,n))),i=t.files.map(e=>e.path);if(new Set(i).size!==i.length||JSON.stringify(i.sort())!==JSON.stringify(r.sort()))throw Error(`I18n snapshot has an incomplete or unexpected artifact set.`)}async function Wr(e){let{stdout:t}=await F(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return Qn(t.trim())}async function Gr(e){let{stdout:t}=await F(`git`,[`status`,`--porcelain`],{cwd:e,stdin:`ignore`});if(t.trim())throw Error(`Tagged i18n preparation requires a clean Git tree.`)}async function Kr(e,t,n){let{stdout:r}=await F(`git`,[`rev-parse`,`${t}^{commit}`],{cwd:e,stdin:`ignore`});if(r.trim()!==n)throw Error(`Release tag ${t} does not point to checked-out commit ${n}.`)}async function qr(e){let{stdout:t}=await F(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const Jr=[`Use a B2 Multi-Bucket Application Key restricted to the configured private build-object and public generated-assets buckets.`,`Required capabilities: listAllBucketNames, readFiles, and writeFiles.`,`Deletion, bucket-management, and key-management capabilities are not needed.`].join(` `),Yr=r(p,{displayName:`widths`,description:`Comma-separated responsive variant widths.`,async from(e){let t=e.split(`,`).map(e=>Number(e));if(t.length===0||t.some(e=>!Number.isInteger(e)||e<=0)||t.some((e,n)=>n>0&&e<=t[n-1]))throw Error(`Widths must be positive, unique, strictly ascending integers.`);return t}}),Xr=r(p,{displayName:`profile`,async from(e){return Ve(e)}}),Zr=r(p,{displayName:`pack`,description:`Asset pack name, such as training-videos.`,async from(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e))throw Error(`Asset pack names must use lowercase hyphen-separated segments.`);return e}}),Qr=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return A(e)}}),$r=m({name:`assets`,cmds:{configure:n({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${Jr}`,args:{profile:u({type:Xr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{B.note(Jr,`Required B2 key access`);let t=await B.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(B.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await B.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(B.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await He({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:n({name:`add`,args:{file:u({type:p,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:c({long:`id`,type:p,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:c({long:`alt`,type:l(p),description:`Required alt text for raster image and SVG assets.`}),pack:c({long:`pack`,type:l(Zr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:c({long:`widths`,type:l(Yr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>Re(await Me({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:n({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:c({long:`branch`,type:p,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await Pe({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:n({name:`build`,args:{id:c({long:`id`,type:l(p),description:`Build only one logical asset ID.`}),pack:c({long:`pack`,type:l(Zr),description:`Build only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>Re(await Fe({id:e,pack:n}),t,{kind:`build`})}),check:n({name:`check`,args:{fix:i({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:c({long:`pack`,type:l(Zr),description:`Check only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await Ie({fix:e,pack:n});Re(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:n({name:`publish`,args:{pack:c({long:`pack`,type:l(Zr),description:`Publish only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await ze({pack:t});Re(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:n({name:`status`,args:{pack:c({long:`pack`,type:l(Zr),description:`Report status for only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Ie({pack:t});Re(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),ei=m({name:`flutter`,cmds:{acceptance:n({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Qr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>_e({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:n({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:i({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>k({check:e})}),prepare:n({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:u({type:s(O),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Qr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>he({apiOrigin:e,platform:t})}),check:n({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:u({type:s(O),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Qr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>D({apiOrigin:e,platform:t})})}}),ti=m({name:`i18n`,cmds:{build:n({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await jr()}}),materialize:n({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:c({long:`revision`,type:l(p),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Pr({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:n({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot. Source-only projects skip translation preparation.`,args:{tag:c({long:`tag`,type:p,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await Nr({tag:e});if(t.mode===`source-only`){console.log(`Skipped i18n release preparation: the supported locales contain only the source locale "${t.sourceLocale}", so no translation snapshot is required.`);return}console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),ni=q.platform===`win32`?`react-router.cmd`:`react-router`,ri=q.platform===`win32`?`panda.cmd`:`panda`;async function ii(e=q.cwd()){await si(e),await oi(e,[`typegen`])}async function ai(e=q.cwd(),t=q.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=j.resolve(e,`.coreframe/dashboard-build`),i=j.join(r,`client`),a=j.resolve(e,`dist/client/__dashboard`);await U(r,{force:!0,recursive:!0});let o=await G({cwd:e});if(o.deploy?.mode===`client`||o.dashboard?.enabled===!1){await U(a,{force:!0,recursive:!0});return}await ci(e,ri,[`build`],t),await oi(e,[`build`,...n?[`--mode`,n]:[]],t),await U(a,{force:!0,recursive:!0}),await V(j.dirname(a),{recursive:!0}),await qe(i,a,{recursive:!0})}async function oi(e,t,n=q.env){await ci(e,ni,t,n)}async function si(e){await U(j.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function ci(e,t,n,r=q.env){await F(t,n,{cwd:j.resolve(e,`dashboard`),env:{...r,PATH:j.resolve(e,`node_modules/.bin`)+j.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const Z={access:We,chmod:Ge,mkdir:V,mkdtemp:Je,readFile:H,readFileSync:R,rm:U,writeFile:W},li={getAvailablePort:di},ui={homedir:ke,kill:q.kill,networkInterfaces:Ae,tmpdir:je};async function di(){let e=ct();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,t)});let t=e.address();if(!t||typeof t==`string`)throw Error(`Could not allocate an available TCP port.`);return t.port}finally{e.listening&&await new Promise((t,n)=>{e.close(e=>e?n(e):t())})}}function fi({host:e=`127.0.0.1`,port:t,start:n}){let r,i=!1,a=!1,o=!1,s,c,l,u,d,f=new Set,p=new Promise((e,t)=>{u=e,d=t}),m=e=>{a||o||(o=!0,d(e))},h=()=>(s||=Promise.resolve().then(n).catch(e=>{throw m(e),e}),s),g=e=>{f.add(e),e.once(`close`,()=>f.delete(e)),e.pause(),_(e).catch(()=>{e.destroy()})},_=async e=>{let t=await h();if(a||e.destroyed)return;let n=await pi(t,()=>a);if(a||e.destroyed){n.destroy();return}f.add(n),n.once(`close`,()=>f.delete(n)),n.on(`error`,()=>e.destroy()),n.once(`close`,()=>e.destroy()),e.on(`error`,()=>n.destroy()),e.once(`close`,()=>n.destroy()),e.pipe(n),n.pipe(e)};return{close:async()=>l||(l=(async()=>{a=!0,o||(o=!0,u());for(let e of f)e.destroy();f.clear(),c&&!i&&await Promise.allSettled([c]),!(!r||!i)&&(await new Promise(e=>{r.close(()=>e())}),i=!1)})(),l),fail:m,listen:async()=>c||(r=ct(g),c=new Promise((n,a)=>{let o=e=>{if(i){m(e);return}a(e)};r.once(`error`,o),r.once(`listening`,()=>{i=!0,r.off(`error`,o),r.on(`error`,m),n()}),r.listen(t,e)}),c),wait:()=>p}}async function pi(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await mi(e)}catch(e){if(r=e,Date.now()>=n)break;await new Promise(e=>setTimeout(e,50))}throw r instanceof Error?r:Error(`Could not connect to the dashboard.`)}function mi({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=st({host:e,port:t}),a=e=>{i.off(`connect`,o),i.destroy(),r(e)},o=()=>{i.off(`error`,a),n(i)};i.once(`error`,a),i.once(`connect`,o)})}const hi=q.platform===`win32`?`react-router.cmd`:`react-router`;function gi(e){return L(j.resolve(e,`dashboard/dashboard.config.ts`))}function _i({cwd:e,env:t,port:n}){let r=t.PATH??t.Path??``,i,a,o=!1,s,c,l=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>{d()};return q.on(e,t),{handler:t,signal:e}}),u=async(e,t)=>{try{await e,o||a?.fail(Error(`The dashboard development server stopped unexpectedly.`))}catch(e){o||a?.fail(e)}finally{await t.outputTasks,t.stdout.end(),t.stderr.end(),await Promise.allSettled([it(t.stdout),it(t.stderr)]),i===e&&(i=void 0)}};a=fi({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await li.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=at({label:`dashboard`}),s=at({color:`red`,label:`dashboard`});a.pipe(q.stdout,{end:!1}),s.pipe(q.stderr,{end:!1});let l=F(hi,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:j.resolve(e,`dashboard`),env:{...t,NODE_OPTIONS:[t.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:j.resolve(e,`node_modules/.bin`)+j.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([yi(l.stdout,a),yi(l.stderr,s)]);return c=u(l,{outputTasks:d,stderr:s,stdout:a}),{host:`127.0.0.1`,port:n}}});let d=async()=>s||(s=(async()=>{o=!0,await a?.close(),i?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),await c;for(let{handler:e,signal:t}of l)q.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function vi({cwd:e=q.cwd(),env:t=q.env,port:n}){let r=_i({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function yi(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const bi=m({name:`dashboard`,cmds:{dev:n({name:`dev`,args:{port:c({long:`port`,type:o,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>vi({port:e})}),build:n({name:`build`,args:{mode:c({long:`mode`,type:l(p),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>ai(void 0,void 0,e)}),typegen:n({name:`typegen`,args:{},handler:()=>ii()})}});function xi(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}async function Si({all:e,cwd:t=process.cwd(),ids:n=[],matches:r=[],now:i=new Date}={}){let a=await Oi(t),o=await ki(a.config,t,async e=>a.module.developmentJobs.createStateAdmin(e).list()),s=lt({jobs:a.module.developmentJobs.jobs,now:i,records:o??[]}),c=Ei(s,{all:e,ids:n,matches:r},{defaultAll:!0});return{database:{dialect:a.dialect,state:o?`existing`:`missing`},jobs:s.filter(e=>c.has(e.id)),version:1}}async function Ci({all:e,breakLeases:t=!1,cwd:n=process.cwd(),dryRun:r=!1,ids:i=[],json:a=!1,matches:o=[],now:s=new Date,yes:c=!1}){let l=await Si({all:!0,cwd:n,now:s}),u=Ei(l.jobs,{all:e,ids:i,matches:o},{defaultAll:!1}),d=l.jobs.filter(e=>u.has(e.id)),f=d.filter(e=>e.lease===`active`);if(r)return{database:l.database,dryRun:!0,jobs:d.map(e=>({id:e.id,status:e.lease===`active`&&!t?`blocked-active-lease`:e.persisted?`would-reset`:`no-state`})),version:1};if(f.length>0&&!t)throw Error(`Cannot reset active development job ${Ni(f.map(e=>e.id))}. Wait for the lease to expire or pass --break-leases.`);if((t||e||o.length>0||d.length>1)&&!c){if(a||!process.stdin.isTTY)throw Error(`This reset requires --yes when prompts are unavailable.`);let e=await B.confirm({message:`Reset local development state for ${d.length} job${d.length===1?``:`s`}?`});if(B.isCancel(e)||!e)throw Error(`Development job state reset was cancelled.`)}if(l.database.state===`missing`)return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:`no-state`})),version:1};let p=await Oi(n),m=await ki(p.config,n,async e=>p.module.developmentJobs.createStateAdmin(e).reset({breakLeases:t,jobIds:[...u],now:s}));if(!m)throw Error(`The local database disappeared before development job state was reset.`);if(m.activeLeaseIds.length>0&&!t)throw Error(`Cannot reset active development job ${Ni(m.activeLeaseIds)}. Wait for the lease to expire or pass --break-leases.`);let h=new Set(m.resetIds);return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:h.has(e.id)?`reset`:`no-state`})),version:1}}function wi(e){let t=Mi(e.database);return e.jobs.length===0?`${t}No local development jobs are configured.`:`${t}${Pi([`Job`,`Status`,`Last success`,`Next eligible`,`Lease`],e.jobs.map(e=>[e.id,e.lease===`active`?`running`:e.registration===`orphaned`?`orphaned`:e.eligibility,ji(e.lastSucceededAt),ji(e.nextEligibleAt),e.lease===`none`?`-`:`${e.lease} until ${ji(e.leaseUntil)}`]))}`}function Ti(e){let t=Mi(e.database);return e.jobs.length===0?`${t}No local development job state matched.`:`${t}${Pi([`Job`,`Result`],e.jobs.map(e=>[e.id,e.status.replaceAll(`-`,` `)]))}`}function Ei(e,{all:t=!1,ids:n=[],matches:r=[]},{defaultAll:i}){if(t&&(n.length>0||r.length>0))throw Error(`Use --all or explicit job selectors, not both.`);if(!t&&n.length===0&&r.length===0){if(i)return new Set(e.map(e=>e.id));throw Error(`Select one or more jobs by ID or --match, or pass --all.`)}let a=new Set(e.map(e=>e.id)),o=n.filter(e=>!a.has(e));if(o.length>0)throw Error(`Unknown development job ${Ni(o)}.`);let s=new Set(t?a:n);for(let t of r){let n=Di(t),r=e.filter(e=>n.test(e.id));if(r.length===0)throw Error(`Development job pattern ${JSON.stringify(t)} matched no jobs.`);for(let e of r)s.add(e.id)}return s}function Di(e){if(!e)throw Error(`Development job patterns must not be empty.`);let t=[...e].map(e=>e===`*`?`.*`:e===`?`?`.`:e.replace(/[\\^$.[\]{}()+|]/gu,`\\$&`)).join(``);return RegExp(`^${t}$`,`u`)}async function Oi(e){let t=await G({cwd:e}),n=t.jobs?.entry;if(!n)throw Error(`coreframe.config.ts must configure jobs.entry before managing development job state.`);let r=await $e(n,e);if(!r.developmentJobs||!Array.isArray(r.developmentJobs.jobs)||typeof r.developmentJobs.createStateAdmin!=`function`)throw Error(`${n} must export developmentJobs with jobs and createStateAdmin properties.`);return{config:t,dialect:t.database?.dialect??`postgres`,module:r}}async function ki(e,t,n){try{var r=xi();let a=e.database?.dialect??`postgres`,o=a===`sqlite`?j.resolve(t,`.coreframe/turso.db`):j.resolve(t,`.coreframe/postgres/PG_VERSION`);try{await Ze(o)}catch(e){if(Fi(e)&&e.code===`ENOENT`)return;throw e}if(a===`sqlite`)try{var i=xi();let r=await x({cwd:t,env:i.a(await de({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Ai(n,r)}finally{r.$client.close()}}catch(e){i.e=e}finally{await i.d()}let s=await ee({cwd:t,env:r.a(await E({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Ai(n,s)}finally{await s.$client.end()}}catch(e){r.e=e}finally{await r.d()}}async function Ai(e,t){try{return await e(t)}catch(e){throw Ii(e)?Error(`The local development job state table is missing. Run coreframe db migrate-local, then retry.`,{cause:e}):e}}function ji(e){return e?.toISOString()??`-`}function Mi(e){return e.state===`missing`?`Local ${e.dialect} database is missing; no database was created.\n\n`:``}function Ni(e){return e.map(e=>JSON.stringify(e)).join(`, `)}function Pi(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),r=e=>e.map((e,t)=>e.padEnd(n[t])).join(` `).trimEnd();return[r(e),r(n.map(e=>`-`.repeat(e))),...t.map(r)].join(`
|
|
8
|
+
`)}function Fi(e){return e instanceof Error&&`code`in e}function Ii(e){let t=e;for(;t instanceof Error;){let e=t.message.toLowerCase();if(e.includes(`coreframe_dev_job_state`)&&(e.includes(`does not exist`)||e.includes(`no such table`)))return!0;t=t.cause}return!1}const Li={ids:f({type:p,displayName:`job`,description:`Exact local development job IDs.`}),matches:a({type:t(p),long:`match`,description:`Select job IDs with an anchored * and ? glob. Repeat to add patterns.`,defaultValue:()=>[]})},Ri=m({name:`jobs`,cmds:{status:n({name:`status`,description:`Inspect local development job cooldown and lease state.`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1}),...Li},handler:async({ids:e,json:t,matches:n})=>{let r=await Si({ids:e,matches:n});console.log(t?JSON.stringify(r):wi(r))}}),reset:n({name:`reset`,description:`Make local development jobs eligible for their next startup check.`,args:{all:i({long:`all`,description:`Select every configured and orphaned development job.`,defaultValue:()=>!1}),breakLeases:i({long:`break-leases`,description:`Invalidate active job leases. The original invocation may keep running.`,defaultValue:()=>!1}),dryRun:i({long:`dry-run`,description:`Show the reset without changing local state.`,defaultValue:()=>!1}),json:i({long:`json`,description:`Print machine-readable JSON without prompting.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Confirm a multi-job, pattern, all-job, or lease-breaking reset.`,defaultValue:()=>!1}),...Li},handler:async({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o})=>{let s=await Ci({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o});console.log(i?JSON.stringify(s):Ti(s))}})}}),zi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Bi(e,t){let n=Hi(e,t);if(!Ui(n)||!Wi(n,[`description`,`requires`,`routes`,`verifier`])||!Ki(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Ki))||n.verifier!==void 0&&!Ki(n.verifier)||!Array.isArray(n.routes))throw Error(`${t} must contain a description string, routes array, and optional requires and verifier fields.`);let r=(n.requires??[]).map(e=>Vi(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Ui(e)||!Gi(e,[`path`,`router`,`when`])||!Ki(e.path)||!Ki(e.router)||!Ki(e.when))throw Error(`${t} route ${n+1} must contain router, path, and when strings.`);return{path:e.path,router:e.router,when:e.when}}),a=i.map(e=>`${e.router}\0${e.path}`);if(new Set(a).size!==a.length)throw Error(`${t} contains a duplicate router and path pair.`);return{description:n.description,requires:r,routes:i,verifier:n.verifier}}function Vi(e){if(!zi.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function Hi(e,t){try{return ut(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Ui(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wi(e,t){return Object.keys(e).every(e=>t.includes(e))}function Gi(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Ki(e){return typeof e==`string`&&e.length>0}const qi=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,Ji=`template`;function Yi(e=Ji){return`refs/remotes/${e}/tags`}function Q(e,t=Ji){return qi.test(e)?`${Yi(t)}/v${e}`:e.startsWith(`v`)&&qi.test(e.slice(1))?`${Yi(t)}/${e}`:e}function Xi(e){return e.startsWith(`refs/remotes/`)?e.slice(13):e}function Zi(e,t=Ji){return`${Q(e,t)}:template`}function Qi(e,t,n=Ji){return`${Zi(e,n)}/${t}`}function $i(e,t){return I(`git`,e,{cwd:t,encoding:`utf8`})}function ea(e,t){let n=$i(e,t);if(n.status!==0){let t=n.stderr.trim()||n.stdout.trim();throw Error(`Git command failed: git ${e.join(` `)}${t?`\n${t}`:``}`)}return n.stdout}function ta(e,t){let n=$i([`remote`,`get-url`,e],t);if(n.status===2)return null;if(n.status!==0){let t=n.stderr.trim()||n.stdout.trim();throw Error(`Could not inspect remote ${e}.${t?`\n${t}`:``}`)}return n.stdout.trim()}function na(e,t){$i([`config`,`--get`,`remote.${e}.tagOpt`],t).stdout.trim()!==`--no-tags`&&ea([`config`,`remote.${e}.tagOpt`,`--no-tags`],t);let n=$i([`config`,`--get-all`,`remote.${e}.fetch`],t),r=n.status===0?n.stdout.split(`
|
|
9
9
|
`).map(e=>e.trim()).filter(Boolean):[];for(let n of[`+refs/heads/*:refs/remotes/${e}/*`,`+refs/tags/*:${Yi(e)}/*`])r.includes(n)||ea([`config`,`--add`,`remote.${e}.fetch`,n],t)}function ra(e,t){return ea([`for-each-ref`,`--format=%(refname)`,t],e).split(`
|
|
10
|
-
`).map(e=>e.trim()).filter(Boolean)}function ia(e,t){return ea([`rev-parse`,`--verify`,`${e}^{commit}`],t).trim()}function aa(e,t){let n=`${Yi(e)}/`,r=new Set(ra(t,Yi(e)).map(e=>e.slice(n.length))),i=[],a=[];for(let e of ra(t,`refs/tags`)){let o=e.slice(10);if(r.has(o)){if(ia(e,t)!==ia(`${n}${o}`,t)){a.push(o);continue}ea([`update-ref`,`-d`,e],t),i.push(o)}}i.length>0&&console.log(`Removed ${i.length} copied ${e} tag(s) from refs/tags/ so they cannot be pushed to this repository's own remotes.`),a.length>0&&console.log(`Kept local tag(s) that share a name with ${e} tags but point at different commits: ${a.join(`, `)}`)}function oa({cwd:e=process.cwd(),fetch:t=!0,remote:n=Ji,url:r=`https://github.com/coreframe-js/coreframe.git`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);ea([`rev-parse`,`--show-toplevel`],e);let i=ta(n,e);if(i===null)ea([`remote`,`add`,n,r],e),console.log(`Added ${n} remote: ${r}`);else if(i===r)console.log(`${n} remote already points at ${r}`);else throw Error(`${n} remote points at ${i}, not ${r}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);na(n,e),t&&(ea([`fetch`,n,`--prune`],e),console.log(`Fetched ${n}.`)),aa(n,e)}function sa({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=da(e),a=ha(i,[`rev-parse`,`--show-toplevel`]),o=Q(r??fa(i),n);return oa({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,refLabel:Xi(o),repositoryRoot:a}}function ca(e,t,n){return la(e,t,n).toString(`utf8`)}function la(e,t,n){let r=`${t}:${n}`,i=
|
|
10
|
+
`).map(e=>e.trim()).filter(Boolean)}function ia(e,t){return ea([`rev-parse`,`--verify`,`${e}^{commit}`],t).trim()}function aa(e,t){let n=`${Yi(e)}/`,r=new Set(ra(t,Yi(e)).map(e=>e.slice(n.length))),i=[],a=[];for(let e of ra(t,`refs/tags`)){let o=e.slice(10);if(r.has(o)){if(ia(e,t)!==ia(`${n}${o}`,t)){a.push(o);continue}ea([`update-ref`,`-d`,e],t),i.push(o)}}i.length>0&&console.log(`Removed ${i.length} copied ${e} tag(s) from refs/tags/ so they cannot be pushed to this repository's own remotes.`),a.length>0&&console.log(`Kept local tag(s) that share a name with ${e} tags but point at different commits: ${a.join(`, `)}`)}function oa({cwd:e=process.cwd(),fetch:t=!0,remote:n=Ji,url:r=`https://github.com/coreframe-js/coreframe.git`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);ea([`rev-parse`,`--show-toplevel`],e);let i=ta(n,e);if(i===null)ea([`remote`,`add`,n,r],e),console.log(`Added ${n} remote: ${r}`);else if(i===r)console.log(`${n} remote already points at ${r}`);else throw Error(`${n} remote points at ${i}, not ${r}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);na(n,e),t&&(ea([`fetch`,n,`--prune`],e),console.log(`Fetched ${n}.`)),aa(n,e)}function sa({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=da(e),a=ha(i,[`rev-parse`,`--show-toplevel`]),o=Q(r??fa(i),n);return oa({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,refLabel:Xi(o),repositoryRoot:a}}function ca(e,t,n){return la(e,t,n).toString(`utf8`)}function la(e,t,n){let r=`${t}:${n}`,i=I(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${ga([`show`,r],i)}`);return i.stdout}function ua(e,t,n){let r=I(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(ga([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function da(e){let t=P(e);for(;;){let e=N(t,`package.json`),n=ma(e);if(n!==void 0&&pa(n,e).engines?.coreframe)return t;let r=M(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function fa(e){let t=N(e,`package.json`),n=ma(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=pa(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function pa(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ma(e){try{return R(e,`utf8`)}catch(e){if(_a(e)&&e.code===`ENOENT`)return;throw e}}function ha(e,t){let n=I(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(ga(t,n));return n.stdout.trim()}function ga(e,t){let n=t.stderr.toString(`utf8`).trim()||t.stdout.toString(`utf8`).trim();return`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`}function _a(e){return e instanceof Error&&`code`in e}const va=[{path:`package.json`,requirement:`retain the Coreframe Flutter JavaScript runtime used by src-flutter`,test:e=>e.includes(`"@coreframe/flutter-js"`)},{path:`coreframe.config.ts`,requirement:`enable web and at least one Flutter development platform`,test:Da},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:Oa},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:ka},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>Ea(e,[`configureShellQueryFocus`,`initializeShellClient`,`authSessionHint`,`authClient.signOut()`,`clearSession`])},{path:`src/web/entry.client.tsx`,requirement:`load the package-owned Flutter development tools only for non-browser development`,test:e=>Ea(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],ya=`src-flutter/lib/application.dart`,ba=`src/api/worker/auth-origin.ts`;function xa(e){let t=[];for(let n of va){let r=N(e,n.path);if(!L(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=R(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}let n=Sa(e,t),r=Ca(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${ya} loopbackPort (${n}) must match ${ba} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function Sa(e,t){let n=wa(e,ya,t);if(n===void 0)return;let r=n.match(/^\s*loopbackPort\s*:\s*(\d+)\s*,?\s*$/m)?.[1],i=n.match(/^\s*loopbackPort\s*:\s*([A-Za-z_]\w*)\s*,?\s*$/m)?.[1],a=i?n.match(RegExp(`^\\s*(?:static\\s+)?const\\s+${i}\\s*=\\s*(\\d+)\\s*;\\s*$`,`m`))?.[1]:void 0,o=Ta(r??a);return o===void 0&&t.push(`${ya} must configure loopbackPort as a fixed integer port.`),o}function Ca(e,t){let n=wa(e,ba,t);if(n===void 0)return;let r=Ta(n.match(/^\s*export\s+const\s+FLUTTER_LOOPBACK_ORIGIN\s*=\s*["']http:\/\/localhost:(\d+)["']\s*;?\s*$/m)?.[1]);return r===void 0&&t.push(`${ba} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function wa(e,t,n){let r=N(e,t);if(!L(r)){n.push(`${t} is missing; it must define the Flutter loopback origin contract.`);return}return R(r,`utf8`)}function Ta(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function Ea(e,t){return t.every(t=>e.includes(t))}function Da(e){let t=e.match(/\bplatforms\s*:\s*\[([\s\S]*?)\]/)?.[1];if(!t)return!1;let n=new Set([...t.matchAll(/(["'`])([^"'`]*)\1/g)].map(e=>e[2]));return n.has(`web`)&&[`ios`,`android`,`linux`,`macos`,`windows`].some(e=>n.has(e))}function Oa(e){try{let t=ut(e);if(!Aa(t)||!Aa(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return Aa(n)&&n.sdk===`flutter`}catch{return!1}}function ka(e){let t=/const\s+(\w+)\s*=\s*kDebugMode\s*&&\s*bool\.fromEnvironment\(\s*['"]ENABLE_FLUTTER_DRIVER['"]\s*\)/u.exec(e),n=e.indexOf(`enableFlutterDriverExtension()`),r=e.indexOf(`runCoreframeApplication(`),i=t?RegExp(`if\\s*\\(\\s*${t[1]}\\s*\\)\\s*\\{[^{}]*enableFlutterDriverExtension\\(\\)[^{}]*\\}`,`u`):void 0;return e.includes(`package:flutter_driver/driver_extension.dart`)&&i?.test(e)===!0&&n>=0&&r>=0&&n<r}function Aa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ja({name:e,...t}){let n=sa(t),r=`recipes/${e}/recipe.yaml`,i=Pa(Bi(ca(n.repositoryRoot,n.ref,r),r).verifier,n.projectRoot);if(i.length>0)throw Error(`Recipe ${e} verification failed:\n${i.map(e=>`- ${e}`).join(`
|
|
11
11
|
`)}`);return{name:e,ref:n.refLabel}}function Ma(e){console.log(`Verified Coreframe recipe ${e.name} from ${e.ref}.`)}function Na(e,t){for(let n of e){let e=`recipes/${n}/recipe.yaml`,r=Pa(Bi(ca(t.repositoryRoot,t.ref,e),e).verifier,t.projectRoot);if(r.length>0)throw Error(`Recipe ${n} is required but is not fully applied:\n${r.map(e=>`- ${e}`).join(`
|
|
12
|
-
`)}\nApply and verify ${n} before continuing.`)}}function Pa(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return xa(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function Fa({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){Vi(n);let a=sa({cwd:e,fetch:t,remote:r,target:i}),{projectRoot:o,ref:s,refLabel:c,repositoryRoot:l}=a,u=`recipes/${n}`,d=`${u}/recipe.yaml`,f=Bi(ca(l,s,d),d);Na(f.requires,a);let p=ca(l,s,`${u}/RECIPE.md`),m=ua(l,s,`${u}/files`),h=ua(l,s,`${u}/patches`),g=ua(l,s,`${u}/.agents`),_=new Map,v=new Map,y=[],b=[],x=[],S=[],C=[]
|
|
13
|
-
`)])),encoding:`utf8`});if(n.status!==0){let e=n.stderr.trim()||n.stdout.trim();throw Error(`Could not apply recipe patches.${e?`\n${e}`:``}`)}}function qa(e){return Ja(e)?.toString(`utf8`)}function Ja(e){try{return
|
|
14
|
-
`).map(e=>e.trim()).filter(Boolean)}const Fo=[`dependencies`,`devDependencies`];function Io(e){let t=
|
|
12
|
+
`)}\nApply and verify ${n} before continuing.`)}}function Pa(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return xa(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function Fa({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){Vi(n);let a=sa({cwd:e,fetch:t,remote:r,target:i}),{projectRoot:o,ref:s,refLabel:c,repositoryRoot:l}=a,u=`recipes/${n}`,d=`${u}/recipe.yaml`,f=Bi(ca(l,s,d),d);Na(f.requires,a);let p=ca(l,s,`${u}/RECIPE.md`),m=ua(l,s,`${u}/files`),h=ua(l,s,`${u}/patches`),g=ua(l,s,`${u}/.agents`),_=new Map,v=new Map,ee=[],y=[],b=[],x=[],S=[],C=[];for(let e of m){let t=e.slice(`${u}/files/`.length);if(Ha(t,`Recipe file ${e}`),t.startsWith(`.agents/`))throw Error(`Recipe file ${e} must be stored in the recipe's .agents directory.`);_.set(t,la(l,s,e)),v.set(t,e)}for(let e of g){let t=e.slice(`${u}/`.length);if(za(t,`Recipe asset ${e}`),_.has(t))throw Error(`Recipe declares ${t} as both a file and an agent asset.`);_.set(t,la(l,s,e)),v.set(t,e)}for(let e of h){let t=Ua(e,u);if(_.has(t))throw Error(`Recipe declares ${t} as both a file and a patch.`);let n=la(l,s,e);Wa(n.toString(`utf8`),t,e),Va(o,t),Ga(o,n,!1)?(ee.push({contents:n,destinationPath:t}),x.push(t)):Ga(o,n,!0)?S.push(t):b.push({destination:t,source:e})}let w=new Map;for(let[e,t]of _){let r=Ja(Va(o,e));if(r===void 0)w.set(e,t),y.push(e);else if(r.equals(t))S.push(e);else if(e.startsWith(`.agents/`))throw Error(`Recipe ${n} cannot replace modified ${e}. Reconcile that agent asset manually.`);else b.push({destination:e,source:v.get(e)})}let T=new Map;for(let e of f.routes){if(za(e.router,`Recipe route router`),Ba(e.path,`Recipe route path`),_.has(e.router))throw Error(`Recipe cannot replace its destination router ${e.router}.`);if(!_.has(e.path)&&!L(Va(o,e.path)))throw Error(`Recipe route target ${e.path} does not exist.`);let t=T.get(e.router)??La(Ya(Va(o,e.router),e.router),e.router);T.set(e.router,t);let r=t.routes.find(t=>t.path===e.path);if(r){if(r.when!==e.when)throw Error(`Recipe ${n} route ${e.path} conflicts with the existing trigger in ${e.router}.`);continue}t.routes.push({path:e.path,when:e.when})}for(let[e,t]of T){t.routes.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path));let n=Ya(Va(o,e),e),r=dt(t,{lineWidth:0});r===n?S.push(e):(w.set(e,r),C.push(e))}for(let{destinationPath:e}of ee)if(w.has(e))throw Error(`Recipe cannot both write and patch ${e}.`);for(let[e,t]of w){let n=Va(o,e);Ce(M(n),{recursive:!0}),z(n,t)}return ee.length>0&&Ka(o,ee.map(({contents:e})=>e)),{created:y.sort(),instructions:p,mergeRequired:b.sort((e,t)=>e.destination.localeCompare(t.destination)),name:n,patched:x.sort(),ref:c,unchanged:[...new Set(S)].sort(),updated:C.sort()}}function Ia(e){console.log(`Prepared Coreframe recipe ${e.name} from ${e.ref}.`);for(let t of e.created)console.log(`created: ${t}`);for(let t of e.updated)console.log(`updated: ${t}`);for(let t of e.patched)console.log(`patched: ${t}`);for(let t of e.mergeRequired)console.log(`merge-required: ${t.destination} (source: ${e.ref}:${t.source})`);for(let t of e.unchanged)console.log(`unchanged: ${t}`);console.log(`\nContinue by following ${e.ref}:recipes/${e.name}/RECIPE.md:\n`),console.log(e.instructions.trimEnd())}function La(e,t){let n=Ra(e,t);if(!Xa(n)||!Za(n,[`routes`,`rules`])||!Array.isArray(n.rules)||!n.rules.every(Qa)||!Array.isArray(n.routes))throw Error(`${t} must contain only string rules and a routes array.`);let r=n.routes.map((e,n)=>{if(!Xa(e)||!Za(e,[`path`,`when`])||!Qa(e.path)||!Qa(e.when))throw Error(`${t} route ${n+1} must contain path and when strings.`);return{path:e.path,when:e.when}}),i=r.map(e=>e.path);if(new Set(i).size!==i.length)throw Error(`${t} contains duplicate route paths.`);return{rules:n.rules,routes:r}}function Ra(e,t){try{return ut(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function za(e,t){if(!e.startsWith(`.agents/`))throw Error(`${t} must be a normalized project-relative path beneath .agents/.`);Ha(e,t)}function Ba(e,t){if(Ha(e,t),!/(?:^|\/)\.agents\/rules\/.+\.md$/u.test(e))throw Error(`${t} must point to a Markdown rule beneath an .agents/rules directory.`)}function Va(e,t){Ha(t,`Recipe destination`);let n=N(e,t),r=e;for(let e of t.split(`/`))if(r=N(r,e),L(r)&&Se(r).isSymbolicLink())throw Error(`Recipe destination ${t} crosses symbolic link ${r}.`);return n}function Ha(e,t){if(e.length===0||ve(e)||e===`..`||e.startsWith(`../`)||e.includes(`\\`)||ye.normalize(e)!==e)throw Error(`${t} must be a normalized project-relative path.`)}function Ua(e,t){let n=e.slice(`${t}/patches/`.length);if(!n.endsWith(`.patch`))throw Error(`Recipe patch ${e} must use a .patch suffix.`);let r=n.slice(0,-6);return Ha(r,`Recipe patch ${e}`),r}function Wa(e,t,n){let r=e.match(/^diff --git .+$/gmu)??[],i=e.match(/^--- .+$/gmu)??[],a=e.match(/^\+\+\+ .+$/gmu)??[];if(r.length!==1||r[0]!==`diff --git a/${t} b/${t}`||i.length!==1||a.length!==1||i[0]!==`--- a/${t}`||a[0]!==`+++ b/${t}`||/^(?:deleted file mode |GIT binary patch$|new file mode |rename from |rename to )/mu.test(e))throw Error(`Recipe patch ${n} must modify only ${t}.`)}function Ga(e,t,n){let r=[`apply`,`--check`,`--whitespace=nowarn`];return n&&r.push(`--reverse`),r.push(`-`),I(`git`,r,{cwd:e,input:t}).status===0}function Ka(e,t){let n=I(`git`,[`apply`,`--whitespace=nowarn`,`-`],{cwd:e,input:Buffer.concat(t.flatMap(e=>[e,Buffer.from(e.at(-1)===10?``:`
|
|
13
|
+
`)])),encoding:`utf8`});if(n.status!==0){let e=n.stderr.trim()||n.stdout.trim();throw Error(`Could not apply recipe patches.${e?`\n${e}`:``}`)}}function qa(e){return Ja(e)?.toString(`utf8`)}function Ja(e){try{return R(e)}catch(e){if($a(e)&&e.code===`ENOENT`)return;throw e}}function Ya(e,t){let n=qa(e);if(n===void 0)throw Error(`Required file ${t} does not exist.`);return n}function Xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Za(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Qa(e){return typeof e==`string`&&e.length>0}function $a(e){return e instanceof Error&&`code`in e}function eo(e={}){let{ref:t,refLabel:n,repositoryRoot:r}=sa(e),i=ua(r,t,`recipes`).filter(e=>/^recipes\/[^/]+\/recipe\.yaml$/u.test(e)).map(e=>{let n=e.split(`/`)[1];return Vi(n),{description:Bi(ca(r,t,e),e).description,name:n}});return i.sort((e,t)=>e.name.localeCompare(t.name)),{recipes:i,ref:n}}function to(e){console.log(`Coreframe recipes at ${e.ref}:`);for(let t of e.recipes)console.log(`${t.name} — ${t.description}`)}const no=`.agents/skills/coreframe-upgrade/SKILL.md`;function ro(e,t={}){return I(`git`,e,t)}function io(e){return e.stderr.toString(`utf8`).trim()||e.stdout.toString(`utf8`).trim()}function ao(e,t,n){let r=Qi(e,t,n),i=ro([`show`,r],{encoding:`utf8`});if(i.status!==0){let e=io(i);throw Error(`Could not read ${r}.${e?` ${e}`:``}`)}return i.stdout.toString()}function oo(){let e=ro([`rev-parse`,`--show-toplevel`],{encoding:`utf8`});if(e.status!==0){let t=io(e);throw Error(`Could not find git repository root.${t?` ${t}`:``}`)}return e.stdout.toString().trim()}function so(e,t){let n=we(N(je(),`coreframe-upgrade-skill-`)),r=N(n,`SKILL.md`);try{z(r,t);let n=io(ro([`--no-pager`,`diff`,`--no-index`,`--color=never`,`--`,e,r]));n&&console.log(n)}finally{Ee(n,{force:!0,recursive:!0})}}function co({apply:e,remote:t,target:n}){let r=N(oo(),no),i=Q(n,t);if(!L(r))throw Error(`Local ${no} does not exist.`);let a=R(r,`utf8`),o=ao(n,no,t),s=Xi(i);return a===o?(console.log(`Coreframe upgrade skill matches ${s}:template/${no}.`),0):e?(z(r,o),console.error(`Updated ${no} from ${s}:template. Reread it before continuing the upgrade.`),20):(console.error(`Coreframe upgrade skill differs from ${s}:template/${no}.`),console.error(`Run again with --apply to update it, then reread ${no} before continuing.`),so(r,o),20)}const lo=[{matches:e=>e===`drizzle`||e.startsWith(`drizzle/`),reason:`project-owned migration history`},{matches:e=>e===`drizzle-hold`||e.startsWith(`drizzle-hold/`),reason:`project-owned migration history`},{matches:e=>e===`src/web/routes.ts`||e.startsWith(`src/web/app/routes/`),reason:`downstream-owned demonstration routes`},{matches:e=>e===`pnpm-lock.yaml`||e===`src-flutter/pubspec.lock`,reason:`downstream-owned dependency lockfile`}],uo=[{matches:e=>e===`src-tauri`||e.startsWith(`src-tauri/`),reason:`legacy Tauri shell removed by breaking host migration`}],fo=new Set([`100644`,`100755`,`120000`]);function po(e,t={}){return I(`git`,e,t)}function mo(e){let t=po(e,{encoding:`utf8`});if(t.status!==0){let n=t.stderr.toString().trim()||t.stdout.toString().trim();throw Error(`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`)}return t.stdout.toString()}function ho(e){let t=po(e);if(t.status!==0){let n=t.stderr.toString(`utf8`).trim()||t.stdout.toString(`utf8`).trim();throw Error(`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`)}return t.stdout}function go(){return mo([`rev-parse`,`--show-toplevel`]).trim()}function _o(e){let t=N(e,`package.json`);if(!L(t))throw Error(`Missing --base <git-ref>, and package.json does not exist.`);let n=JSON.parse(R(t,`utf8`)).engines?.coreframe;if(typeof n!=`string`||n.length===0)throw Error(`Missing --base <git-ref>, and package.json engines.coreframe is not set.`);return n}function vo(e){let t=[],n=0;for(let r=0;r<e.length;r+=1)e[r]===0&&(t.push(e.subarray(n,r).toString(`utf8`)),n=r+1);return t.filter(e=>e.length>0)}function yo(e,t){let n=vo(ho([`diff`,`--name-status`,`-z`,`--no-renames`,Zi(e),Zi(t),`--`])),r=[];for(let e=0;e<n.length;e+=2){let t=n[e],i=n[e+1];if(!t||!i)throw Error(`Could not parse git diff --name-status output.`);r.push({path:i,status:t})}return r}function bo(e,t){let n=ho([`ls-tree`,`-z`,`-r`,Zi(e),`--`,t]);if(n.length===0)return null;let r=vo(n)[0],i=r.indexOf(` `);if(i===-1)throw Error(`Could not parse git ls-tree output for ${e}:${t}.`);let[a,o,s]=r.slice(0,i).split(` `);if(!a||!o||!s)throw Error(`Could not parse git ls-tree metadata for ${e}:${t}.`);return{mode:a,object:s,path:t,type:o}}function xo(e){return ho([`cat-file`,`blob`,e.object])}function So(e,t){let n=P(e,t),r=e.endsWith(be)?e:`${e}${be}`;if(n!==e&&!n.startsWith(r))throw Error(`Refusing to access path outside repository: ${t}`);return n}function Co(e){try{return Se(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}function wo(e){return(e.mode&73)!=0}function To(e){return e===null||e.type===`blob`&&fo.has(e.mode)}function Eo(e){return lo.find(t=>t.matches(e))?.reason}function Do(e){return uo.find(t=>t.matches(e))?.reason}function Oo(e,t,n){let r=So(e,t);if(n===null)return{matches:!Co(r)};if(!To(n))return{matches:!1,reason:`unsupported template entry mode ${n.mode} ${n.type}`};let i;try{i=Se(r)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{matches:!1,reason:`path is missing from worktree`};throw e}let a=xo(n);return n.mode===`120000`?i.isSymbolicLink()?{matches:Buffer.from(Te(r),`utf8`).equals(a)}:{matches:!1,reason:`worktree path is not a symlink`}:i.isFile()?(n.mode===`100755`?wo(i):!wo(i))?{matches:R(r).equals(a)}:{matches:!1,reason:`worktree executable bit differs from template`}:{matches:!1,reason:`worktree path is not a regular file`}}function ko(e){Co(e)&&Ee(e,{force:!0,recursive:!1})}function Ao(e,t,n){let r=So(e,t);if(n===null){ko(r);return}if(Ce(M(r),{recursive:!0}),n.mode===`120000`){ko(r),De(xo(n).toString(`utf8`),r);return}let i=Co(r)?Se(r):null;i&&!i.isFile()&&ko(r),z(r,xo(n)),xe(r,n.mode===`100755`?493:420)}function jo(e,t){return e===null&&t!==null?`add`:e!==null&&t===null?`delete`:`update`}function Mo(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t){let t=e.reason?` (${e.reason})`:``;console.log(` ${e.action}: ${e.path}${t}`)}console.log(``)}}function No(e){let t=go(),n=Q(e.base??_o(t),e.remote),r=Q(e.target,e.remote),i=yo(n,r),a=[],o=[],s=[],c=[];for(let e of i){let i=Eo(e.path);if(i){o.push({action:`ignored`,path:e.path,reason:i});continue}let l=bo(n,e.path),u=bo(r,e.path),d=jo(l,u),f=u===null?Do(e.path):void 0;if(f){a.push({action:d,path:e.path,reason:f,targetEntry:u});continue}if(!To(l)||!To(u)){s.push({action:d,path:e.path,reason:`unsupported template entry type`});continue}if(Oo(t,e.path,u).matches){c.push({action:`unchanged`,path:e.path});continue}let p=Oo(t,e.path,l);if(!p.matches){s.push({action:d,path:e.path,reason:p.reason??`downstream differs from base template`});continue}a.push({action:d,path:e.path,targetEntry:u})}if(e.apply)for(let e of a)Ao(t,e.path,e.targetEntry??null);console.log(`Coreframe template fast-forward: ${Xi(n)} -> ${Xi(r)}`),console.log(``),Mo(e.apply?`Applied clean template updates`:`Would apply clean template updates`,a),Mo(`Ignored downstream-owned paths`,o),Mo(`Skipped for agent review`,s),c.length>0&&console.log(`${c.length} changed template path(s) already matched the target state.`),i.length===0&&console.log(`No template file changes found in the requested range.`),!e.apply&&a.length>0&&(console.log(``),console.log(`Run with --apply to write the ${a.length} clean update(s).`))}function Po({base:e,cwd:t=process.cwd(),remote:n=Ji,target:r}){let i=[`for-each-ref`,`--sort=v:refname`,`--format=%(refname)`,`--merged`,Q(r,n)];e&&i.push(`--no-merged`,Q(e,n)),i.push(`${Yi(n)}/v[0-9]*`);let a=I(`git`,i,{cwd:t,encoding:`utf8`});if(a.status!==0){let e=a.stderr.trim()||a.stdout.trim();throw Error(`Git command failed: git ${i.join(` `)}${e?`\n${e}`:``}`)}return a.stdout.split(`
|
|
14
|
+
`).map(e=>e.trim()).filter(Boolean)}const Fo=[`dependencies`,`devDependencies`];function Io(e){let t=I(`git`,e,{encoding:`utf8`});if(t.status!==0){let n=t.stderr.trim()||t.stdout.trim();throw Error(`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`)}return t.stdout}function Lo(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}: ${e instanceof Error?e.message:e}`)}}function Ro(e,t,n){let r=`${Q(e,n)}:${t}`;return Lo(Io([`show`,r]),r)}function zo(e){return e.startsWith(`@coreframe/`)}function Bo(e){return e.startsWith(`file:`)||e.startsWith(`link:`)||e.startsWith(`workspace:`)}function Vo(e){return e.startsWith(`file:`)||e.startsWith(`link:`)}function Ho(e,t){let n=e.indexOf(`:`),r=e.slice(n+1),i=ye.normalize(ye.join(`template`,r,`package.json`));if(r.length===0||ye.isAbsolute(r)||i===`..`||i.startsWith(`../`))throw Error(`Invalid local template dependency for ${t}: ${e}`);return i}function Uo(e,t){let n=Ro(e,`template/package.json`,t),r=[],i=new Set;for(let a of Fo)for(let[o,s]of Object.entries(n[a]??{})){if(!zo(o)||!Vo(s))continue;if(i.has(o))throw Error(`Target template declares ${o} more than once.`);let n=Ho(s,o),c=Ro(e,n,t);if(c.name!==o||typeof c.version!=`string`)throw Error(`${Q(e,t)}:${n} must declare ${o} with a version.`);r.push({group:a,name:o,spec:`^${c.version}`}),i.add(o)}return r}function Wo(e,t){for(let n of Fo){let r=e[n]?.[t];if(r)return{group:n,spec:r}}}function Go(e,t,n){let r=t.match(/\n([\t ]+)"/u)?.[1]??` `,i=t.endsWith(`
|
|
15
15
|
`)?`
|
|
16
|
-
`:``;
|
|
17
|
-
`),`Pending Worker secret updates`),u?.accessTokenSigningSecret.provisioned&&
|
|
18
|
-
`);if(i)return i}return e instanceof Error?e.message:String(e)}async function ms(e,t,n){let r=await se(e);if(r.length!==0){if(t>0)throw Error(`Pending deploy migrations contain unsafe SQL. ${n}\n${ee(r)}`);V.log.warn(`Pending deploy migrations contain SQL that is unsafe for an existing deployment, but the target database has no applied migrations, so no deployed app version can depend on the current schema. Proceeding with deploy migrations.\n${ee(r)}`)}}async function hs(e){try{return await gs(e)}finally{await e.close?.()}}async function gs(e){let t=await v(),n=await re(e);return{appliedMigrations:n,pendingMigrations:w(t,n)}}async function _s(e,t){if(t.length===0)return V.log.info(`No pending deploy migrations.`),!1;if(V.note(E(t),`Pending deploy migrations`),e.runMigrations)return!0;if(e.skipMigrations)return!1;if(!process.stdout.isTTY)throw Error(`Pending migrations require --run-migrations or --skip-migrations in noninteractive deploys.`);let n=await V.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(V.isCancel(n))throw V.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function vs(){let{stdout:e}=await I(`git`,[`status`,`--porcelain`],{stdin:`ignore`});if(e.trim().length>0)throw Error(`Deploy requires a clean git tree.`);let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{stdin:`ignore`});return t.trim()}function ys(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function bs(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function xs(e,t,n=ht){return e.url?Ss(e.url,t):t===`staging`&&e.stagingHostname?Ss(await n(),t):Ss(void 0,t)}function Ss(e,t){if(!e)throw Error(`Missing ${t} deploy URL. Set DEPLOY_URL or deploy.environments.${t}.url in coreframe.config.ts.`);let n;try{n=new URL(e)}catch{throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`);return n.toString()}async function Cs(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await V.confirm({initialValue:!1,message:`Deploy to production?`});if(V.isCancel(t)||!t)throw V.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}async function ws(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Vt(await U(`.env`,`utf8`))}catch(e){throw Es(e)&&e.code===`ENOENT`?Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`):e}let i=r.DASHBOARD_PASSWORD?.trim();if(!i)throw Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`);return i}async function Ts(e){let t=await qe(P(Ae(),`coreframe-deploy-secrets-`)),n=P(t,`secrets.json`);return await G(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>W(t,{force:!0,recursive:!0})}}function Es(e){return e instanceof Error&&`code`in e}function Ds(e){return typeof e==`object`&&!!e}function Os(e,t,n,r,i){return{...e,CLOUDFLARE_ENV:t,DEPLOY_ENV:t,POSTHOG_RELEASE:n,POSTHOG_RELEASE_NAME:e.POSTHOG_RELEASE_NAME??r,POSTHOG_RELEASE_VERSION:e.POSTHOG_RELEASE_VERSION??i}}function ks(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function As(){let e=await Ms();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function js(e){let t=await Ms(),n=Ns();await ci.mkdir(M.dirname(n),{recursive:!0}),await ci.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function Ms(){try{let e=await ci.readFile(Ns(),`utf8`),t=JSON.parse(e);return Ps(t)?t:{}}catch{return{}}}function Ns(){return M.join(ui.homedir(),`.coreframe`,`preferences.json`)}function Ps(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Fs({env:e=J.env,interactive:t=J.stdin.isTTY===!0,platform:n,target:r}){let i=await Hs(n,e).catch(()=>[]),a=r?oc(i,r):void 0;if(a)return a;if(!r&&i.length>0)return Vs(i,n,t);let o=r?oc(await Ws(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return Gs(o,n,e,t);let s=await Us(n,e),c=r?oc(s,r):void 0;if(c)return c;if(!r&&s.length>0)return Vs(s,n,t);let l=n===`ios`?`iOS`:`Android`;throw Error(r?`Could not find a ${l} device matching "${r}".`:`No connected ${l} devices or available ${l} ${n===`ios`?`simulators`:`emulators`} were detected.`)}async function Is(e){let{device:t,host:n,interactive:r=J.stdin.isTTY===!0}=e;if(!t.physical&&n===void 0)return;if(typeof n==`string`&&n!==`0.0.0.0`&&n!==`::`)return n;let i=cc();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await zs();if(a&&i.includes(a))return a;if(i.length===1)return await Bs(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await V.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(V.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await Bs(o),o}async function Ls({device:e,env:t=J.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await $s(e.id,a,t)}catch{V.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:Rs(i,await Is({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function Rs(e,t,n){let r=t??(e===`android`?`10.0.2.2`:`127.0.0.1`);return`http://${r.includes(`:`)&&!r.startsWith(`[`)?`[${r}]`:r}:${n}`}async function zs(){return(await As()).mobileDevHost}async function Bs(e){try{await js({mobileDevHost:e})}catch(e){V.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function Vs(e,t,n){if(e.length===1)return e[0];if(!n)throw Error(`Multiple ${t===`ios`?`iOS`:`Android`} devices were detected. Pass a device name explicitly.`);let r=await V.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(V.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function Hs(e,t){return e===`android`?qs(t):Ys(t)}async function Us(e,t){return e===`android`?Js(t):Xs(t)}async function Ws(e){let{stdout:t}=await I(`flutter`,[`emulators`],{env:e});return t.split(/\r?\n/).flatMap(e=>{let[t,n,,r]=e.split(/\s*•\s*/).map(e=>e.trim());return t&&n&&(r===`android`||r===`ios`)?[{id:t,label:n,name:n,physical:!1,platform:r}]:[]})}async function Gs(e,t,n,r){let i=await Ks(t,n).catch(()=>[]),{stdout:a}=await I(`flutter`,[`emulators`,`--launch`,e.id],{env:n});if(/No emulator found|More than one emulator matches/i.test(a))throw Error(a.trim());let o=Date.now()+3e4;do{let a=await Ks(t,n).catch(()=>[]),o=oc(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return Vs(s,t,r);if(a.length===1)return a[0];await en(250)}while(Date.now()<o);let s=t===`ios`?`iOS simulator`:`Android emulator`;throw Error(`Flutter launched "${e.id}", but no ${s} became available.`)}async function Ks(e,t){return e===`ios`?Xs(t,`booted`):(await qs(t)).filter(e=>!e.physical)}async function qs(e){let t=await Qs(e,`platform-tools`,J.platform===`win32`?`adb.exe`:`adb`),{stdout:n}=await I(t,[`devices`],{env:e}),r=n.split(/\r?\n/).map(e=>e.match(/^(\S+)\s+device(?:\s|$)/)?.[1]).filter(e=>e!==void 0);return(await Promise.all(r.map(async n=>{let r=await tc(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await rc(t,e,n,r):await ic(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(lc)}async function Js(e){let{stdout:t}=await I(await Qs(e,`emulator`,J.platform===`win32`?`emulator.exe`:`emulator`),[`-list-avds`],{env:e});return t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!/^(INFO|WARNING|ERROR)\s+\|/.test(e)).map(e=>({id:e,label:e,name:e,physical:!1}))}async function Ys(e){let t=await ci.mkdtemp(M.join(ui.tmpdir(),`coreframe-ios-devices-`)),n=M.join(t,`devices.json`);try{return await ci.writeFile(n,``),await I(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await ci.readFile(n,`utf8`)).result?.devices??[]).filter(Zs).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(lc)}finally{await ci.rm(t,{force:!0,recursive:!0})}}async function Xs(e,t=`available`){let{stdout:n}=await I(`xcrun`,[`simctl`,`list`,`--json`,`devices`,t],{env:e}),r=JSON.parse(n);return Object.entries(r.devices??{}).filter(([e])=>e.includes(`iOS-`)).flatMap(([,e])=>e).flatMap(e=>e.name&&e.udid?[{id:e.udid,label:e.name,name:e.name,physical:!1}]:[]).sort(lc)}function Zs(e){return e.connectionProperties?.tunnelState!==`unavailable`&&typeof e.hardwareProperties?.platform==`string`&&(e.hardwareProperties.platform.includes(`iOS`)||e.hardwareProperties.platform.includes(`xrOS`))&&typeof e.deviceProperties?.name==`string`&&typeof e.hardwareProperties.productType==`string`&&typeof e.hardwareProperties.udid==`string`}async function Qs(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:ec(e);for(let e of i){let r=M.join(e,t,n);try{return await ci.access(r),r}catch{}}return n}async function $s(e,t,n){let r=await Qs(n,`platform-tools`,J.platform===`win32`?`adb.exe`:`adb`),{stdout:i}=await I(r,[`-s`,e,`reverse`,`tcp:0`,`tcp:${t}`],{env:n,timeout:3e3}),a=Number(i.trim());if(!Number.isInteger(a)||a<1||a>65535)throw Error(`ADB did not return a valid reverse TCP port.`);let o=`tcp:${a}`,s=!1;return{async close(){s||(s=!0,await I(r,[`-s`,e,`reverse`,`--remove`,o],{env:n,timeout:3e3}).catch(()=>void 0))},serverUrl:`http://127.0.0.1:${a}`,viteHost:`127.0.0.1`}}function ec(e){return J.platform===`darwin`?[M.join(ui.homedir(),`Library`,`Android`,`sdk`)]:J.platform===`win32`&&e.LOCALAPPDATA?[M.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[M.join(ui.homedir(),`Android`,`Sdk`)]}async function tc(e,t,n,r){return(await nc(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function nc(e,t,n){return(await I(e,n,{env:t,timeout:3e3})).stdout}async function rc(e,t,n,r){return nc(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function ic(e,t,n,r){return nc(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>ac(e)||r).catch(()=>r)}function ac(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function oc(e,t){let n=e.map(e=>({device:e,score:Math.max(sc(t,e.name),sc(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function sc(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(r===n)return 1e4;let i=r.indexOf(n);if(i>=0)return 5e3-i;let a=0,o=0;for(let e of n){let t=r.indexOf(e,o);if(t<0)return 0;a+=t===o?2:1,o=t+1}return a}function cc(){return[...new Set(Object.values(ui.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function lc(e,t){return e.label.localeCompare(t.label)}var uc=class{#e;#t=new Map;#n=new Set;#r;#i;#a;#o;#s=0;constructor({onEvent:e,verbose:t=!1,write:n}){this.#e=e,this.#r=t,this.#i=n}async handleLine(e){let t;try{t=JSON.parse(e)}catch{return $(e,`debug`)}if(!Array.isArray(t))return $(e,`debug`);let n=[];for(let e of t){if(!hc(e)){n.push(...$(JSON.stringify(e),`debug`));continue}if(e.id!==void 0&&(`result`in e||`error`in e)){this.#c(e);continue}if(typeof e.event!=`string`)continue;let t={event:e.event,params:hc(e.params)?e.params:{}};this.#l(t),await this.#e?.(t),n.push(...fc(t,this.#r))}return n}async restart({debounce:e=!1,fullRestart:t,reason:n}){let r=await this.#d();if(!r.supportsRestart)throw Error(`The running Flutter application does not support hot restart or reload.`);let i=await this.#u(`app.restart`,{appId:r.id,debounce:e,fullRestart:t,reason:n});if(!hc(i)||typeof i.code!=`number`)throw Error(`Flutter returned an invalid restart response.`);let a={code:i.code,message:typeof i.message==`string`?i.message:``};if(a.code!==0)throw Error(a.message||`Flutter restart failed with code ${a.code}.`);return a}async stop(){let e=await this.#d();if(await this.#u(`app.stop`,{appId:e.id})!==!0)throw Error(`Flutter did not stop the running application.`)}close(e=Error(`The Flutter machine connection closed.`)){if(this.#o)return;let t=_c(e);this.#o=t;for(let e of this.#t.values())e.reject(t);this.#t.clear(),this.#f(t)}#c(e){let t=String(e.id),n=this.#t.get(t);n&&(this.#t.delete(t),`error`in e?n.reject(Error(gc(e.error))):n.resolve(e.result))}#l({event:e,params:t}){let n=typeof t.appId==`string`?t.appId:void 0;if(e===`app.start`&&n){this.#a={id:n,started:!1,supportsRestart:t.supportsRestart===!0};return}if(e===`app.started`&&n&&this.#a?.id===n){let e={...this.#a,started:!0};this.#a=e;for(let t of this.#n)t.resolve(e);this.#n.clear();return}e===`app.stop`&&n&&this.#a?.id===n&&(this.#a=void 0,this.#f(Error(`The Flutter application stopped before it was ready.`)))}async#u(e,t){if(this.#o)throw this.#o;let n=String(++this.#s),r,i,a=new Promise((e,t)=>{r=t,i=e});this.#t.set(n,{reject:r,resolve:i});try{await this.#i(`${JSON.stringify([{id:n,method:e,params:t}])}\n`)}catch(e){this.#t.delete(n),r(_c(e))}return a}#d(){return this.#o?Promise.reject(this.#o):this.#a?.started?Promise.resolve(this.#a):new Promise((e,t)=>{this.#n.add({reject:t,resolve:e})})}#f(e){for(let t of this.#n)t.reject(e);this.#n.clear()}};async function*dc(e,t){try{for await(let n of e)yield*await t.handleLine(n)}catch(e){throw t.close(e),e}finally{t.close()}}function fc({event:e,params:t},n){if(e===`daemon.log`||e===`app.log`)return $(mc(t.log),t.error===!0?`error`:`debug`);if(e===`daemon.logMessage`){let e=pc(t.level);return!n&&e===`debug`?[]:[...$(mc(t.message),e),...n?$(mc(t.stackTrace),e):[]]}return e===`daemon.showMessage`?$(mc(t.message),pc(t.level)):e===`app.warning`?$(mc(t.warning),`warn`):e===`app.progress`&&t.finished!==!0?$(mc(t.message),`debug`):e===`app.stop`&&t.error!==void 0?$(gc(t.error),`error`):[]}function $(e,t){return e===void 0?[]:e.split(/\r?\n/u).map(e=>({level:t,message:e}))}function pc(e){return e===`error`?`error`:e===`warning`||e===`warn`?`warn`:`debug`}function mc(e){return typeof e==`string`&&e.length>0?e:void 0}function hc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gc(e){if(typeof e==`string`)return e;if(hc(e)&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function _c(e){return e instanceof Error?e:Error(gc(e))}async function vc(e,t){if(!e)return()=>void 0;Se(M.dirname(e),{recursive:!0}),B(e,``,{flag:`a`});let n;try{n=z(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=De(e,{persistent:!1},()=>{if(i)return;let a=++r;U(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function yc(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const bc=J.platform===`win32`?`portless.cmd`:`portless`,xc=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),Sc=/^Proxy is already running on port (\d+)\.$/,Cc=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function wc(e){let t=e.split(/(\r\n|\n)/),n=[];for(let e=0;e<t.length;){let r=t[e],i=t[e+2],a=r?.replace(xc,``).trim().match(Sc);if(a?.[1]!==void 0&&i!==void 0&&Cc.test(i.replace(xc,``).trim())){n.push(`Portless proxy is running on port ${a[1]}.`),t[e+1]!==void 0&&n.push(t[e+1]),e+=t[e+3]===void 0?3:4;continue}n.push(t[e]??``),e+=1}return n.join(``)}function Tc(e){let t=wc(e);t&&J.stdout.write(t.endsWith(`
|
|
19
|
-
`)?t:`${t}\n`)}async function Ec({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await tn()).isAgent?!1:Jt(e)}async function Dc({cwd:e,env:t,lan:n=!1}){let r=M.join(`node_modules`,`.bin`,bc),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await I(M.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});Tc(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Tc(e.stdout),e}}function Oc({host:e,lan:t=!1,port:n}){return[...t?[`--lan`]:[],`run`,...n===void 0?[]:[`--app-port`,String(n)],`react-router`,`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e]]}const kc=M.join(`.coreframe`,`dev`,`session.json`);async function Ac({appOrigin:e,cwd:t,device:n,flutterMcp:r,flutterMode:i,id:a,localOrigin:o,now:s=new Date,pid:c=process.pid,platform:l}){let u=M.resolve(t,kc),d=M.dirname(u),f={version:2,id:a,pid:c,projectRoot:M.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:M.resolve(t,`.leylines`,`logs.sqlite`),scopes:{browser:`browser`,...i===void 0?void 0:{flutter:`dev.flutter`},vite:`dev.vite`}},...i===void 0?void 0:{flutter:{mode:i,mcp:r,state:`starting`,...n===void 0?void 0:{device:n}}}},p=Promise.resolve(),m=()=>{let e=`${JSON.stringify(f,void 0,2)}\n`;return p=p.then(async()=>{await H(d,{recursive:!0});let t=M.join(d,`.session-${a}.json`);await G(t,e,{mode:384}),await We(t,384),await Ye(t,u)}),p};return await m(),{path:u,async recordFlutterEvent({event:e,params:t}){let n=f.flutter;if(!n)return;let r=Nc(t.appId),i;if(e===`daemon.connected`){let e=Pc(t.pid),r=Nc(t.version);i={...jc(n),state:`starting`,...e===void 0?void 0:{daemonPid:e},...r===void 0?void 0:{protocolVersion:r}}}else if(e===`app.start`&&r)i={...jc(n),appId:r,state:`starting`,supportsRestart:t.supportsRestart===!0};else if(e===`app.started`&&r===n.appId)i={...n,state:`running`};else if(e===`app.debugPort`&&r===n.appId){let e=Nc(t.wsUri);e&&(i={...n,vmServiceWsUri:e})}else if(e===`app.devTools`&&r===n.appId){let e=Nc(t.uri);e&&(i={...n,devToolsUri:e})}else if(e===`app.dtd`&&r===n.appId){let e=Nc(t.uri);e&&(i={...n,dtdUri:e})}else e===`app.stop`&&r===n.appId&&(i=Mc(n));i&&(f={...f,flutter:i},await m())},async recordFlutterExit(){!f.flutter||f.flutter.state===`stopped`||(f={...f,flutter:Mc(f.flutter)},await m())},async close(){await p;try{JSON.parse(await U(u,`utf8`)).id===a&&await W(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}function jc(e){return{mode:e.mode,mcp:e.mcp,...e.device===void 0?void 0:{device:e.device},...e.daemonPid===void 0?void 0:{daemonPid:e.daemonPid},...e.protocolVersion===void 0?void 0:{protocolVersion:e.protocolVersion}}}function Mc(e){return{...jc(e),state:`stopped`,...e.appId===void 0?void 0:{appId:e.appId},...e.supportsRestart===void 0?void 0:{supportsRestart:e.supportsRestart}}}function Nc(e){return typeof e==`string`?e:void 0}function Pc(e){return typeof e==`number`?e:void 0}const Fc=`extension:dev`;function Ic(e){if(!R(P(e,`src-webext/wxt.config.ts`)))throw Error("No WXT configuration found at src-webext/wxt.config.ts. Apply the wxt recipe or add that convention before running `coreframe dev webext`.");let t=P(e,`package.json`),n;try{n=JSON.parse(z(t,`utf8`))}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}if(!n||typeof n!=`object`||!(`scripts`in n)||!n.scripts||typeof n.scripts!=`object`||!(`extension:dev`in n.scripts)||typeof n.scripts[`extension:dev`]!=`string`)throw Error(`package.json must define scripts.${Fc} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function Lc({host:e,port:t}){let n=[...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)]];return[`run`,Fc,...n.length>0?[`--`,...n]:[]]}const Rc=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],zc=[`managed-dev-overlay`],Bc=M.resolve(`node_modules`,`.bin`),Vc=J.platform===`win32`?`pnpm.cmd`:`pnpm`,Hc=J.platform===`win32`?`portless.cmd`:`portless`,Uc=J.platform===`win32`?`react-router.cmd`:`react-router`,Wc=`Lost connection to device.`;async function Gc({cwd:e=J.cwd(),debug:t,device:n,env:r=J.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=J.stdin.isTTY===!0,lan:u=!1,managed:d=!1,noCodesign:f=!1,noManaged:p=!1,noDevJobs:m=!1,platform:h=`web`,verbose:g=!1,webPort:_}={}){let v=Wt({env:r}),y=r.PATH??r.Path??``,b=il(h)?h:void 0,x=cn(i||a),S=rl(_??r.COREFRAME_WEB_PORT),C,w,T,E,ee,te,ne,re,ae,oe,se,ce,le,D=!1,de,O=r;if(d&&p)throw Error(`Cannot use --managed and --no-managed together.`);if(t===`managed-dev-overlay`&&d)throw Error(`Cannot use --managed with --debug managed-dev-overlay.`);if(i&&b===void 0)throw Error(`The --flutter-debug option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(a&&b===void 0)throw Error(`The --flutter-mcp option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(f&&h!==`macos`)throw Error(`The --no-codesign option is only supported for macOS Flutter development.`);if(o===`full`&&b===void 0)throw Error(`The --flutter-output option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(h===`webext`){if(d||p||t!==void 0||g)throw Error(`Managed development, debug features, and verbose native output are only supported for the main web or native development platforms.`);Ic(e)}if(c&&h!==`web`)throw Error(`Local HTTPS is only supported for the web development platform.`);if(n!==void 0&&h!==`ios`&&h!==`android`)throw Error(`A device name or ID is only supported for iOS or Android development.`);let fe=await v.measure(`routing`,()=>Ec({cwd:e,env:r,platform:h}));fe&&await v.measure(`portless`,()=>Dc({cwd:e,env:r,lan:u}));let k=b===void 0?h===`web`?S??await li.getAvailablePort():h===`webext`?S:void 0:S??await li.getAvailablePort(),A,me=new Promise(e=>{A=e}),j=()=>{D||(D=!0,A(),w?.kill(`SIGTERM`),te?.kill(`SIGTERM`),ne?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),re?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ae?.close().catch(()=>void 0),C?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ge().catch(()=>void 0))},ge=()=>E?(ee??=E[Symbol.asyncDispose](),ee):Promise.resolve(),N=e=>{de??=e,j()},_e=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>N(e);return J.on(e,t),{handler:t,signal:e}}),P=async e=>{let t=at(e);w=t;try{await t.expectSuccess()}catch(e){if(!D)throw e}finally{w===t&&(w=void 0)}};try{se=b?$t({path:M.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await Fs({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&ln({device:_,mode:x,platform:i});let S=b?se?.logger({scope:`dev.flutter`,properties:{platform:b,..._?{deviceId:_.id}:void 0}}):void 0;oe=i&&_&&k!==void 0?await Ls({device:_,env:r,host:s,interactive:l,platform:i,port:k}):void 0;let w=oe?.viteHost??(b?i?!0:`127.0.0.1`:s),ee=k===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${k}`,de=b===void 0?ee:oe?.serverUrl??Rs(b,void 0,k),A={},ge=!1,N;[A,ge]=await Promise.all([v.measure(`config`,()=>K({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await qt(e))]),await v.measure(`i18n`,()=>jr({cwd:e,projectConfig:A})),N=h!==`webext`&&A.dashboard?.enabled!==!1&&gi(e)?await li.getAvailablePort():void 0;let _e=await v.measure(`https`,async()=>c&&!fe?Yt({cwd:e}):void 0),ve=yc(r,h);O={...ve,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Xt]:q()}:void 0,...b?{COREFRAME_PLATFORM:b,[Qt]:M.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,..._e?{[Gt]:_e.cert,[Kt]:_e.key}:void 0,...N?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${N}`}:void 0},ee!==void 0&&de!==void 0&&(ce=await Ac({appOrigin:de,cwd:e,device:_,flutterMcp:a,flutterMode:b===void 0?void 0:x,id:q(),localOrigin:ee,platform:h}));let F=async()=>{if(!N)return;let t=_i({cwd:e,env:O,port:N});ae=t;try{await t.listen(),await t.wait()}finally{await t.close(),ae===t&&(ae=void 0)}},ye=async()=>{let t=it({label:`web`}),n=it({color:`red`,label:`web`});t.pipe(J.stdout,{end:!1}),n.pipe(J.stderr,{end:!1}),ne=I(fe?Hc:Uc,fe?Oc({host:w,lan:u,port:k}):nl({host:w,port:k,strictPort:h===`web`||b!==void 0}),{cwd:e,env:{...O,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[O.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:Bc+M.delimiter+y},stdin:`inherit`});let r=Promise.allSettled([Qc(ne.stdout,t),Qc(ne.stderr,n)]);try{await ne;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!D)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([rt(t),rt(n)]),ne=void 0}},L=async()=>{let t=it({label:`webext`}),n=it({color:`red`,label:`webext`});t.pipe(J.stdout,{end:!1}),n.pipe(J.stderr,{end:!1}),re=I(Vc,Lc({host:s,port:k}),{cwd:e,env:O,stdin:`inherit`});let r=Promise.allSettled([Qc(re.stdout,t),Qc(re.stderr,n)]);try{await re;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!D)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([rt(t),rt(n)]),re=void 0}},be=async t=>{let n,r,i=!1,s,c=vc(O[Qt],()=>{if(D||!n||!r||s||x!==`debug`&&i)return;let e=n,t=r;s=(async()=>{if(x===`debug`){await t.restart({debounce:!0,fullRestart:!0,reason:`manual`});return}i=!0;try{await t.stop()}catch(t){let n=t instanceof Error?t.message:String(t);S?.write(`warn`,`Flutter stop failed; terminating it: ${n}`,{properties:{stream:`control`}}),J.stderr.write(`Flutter stop failed; terminating it: ${n}\n`),await e.nodeChildProcess.then(e=>e.kill(`SIGTERM`))}})().catch(e=>{let t=e instanceof Error?e.message:String(e);S?.write(`error`,`Flutter restart failed: ${t}`,{properties:{stream:`control`}}),J.stderr.write(`Flutter restart failed: ${t}\n`)}).finally(()=>{s=void 0})});try{for(;!D;){i=!1;let s=!1,c=h===`android`&&o===`filtered`&&!g?await he():void 0,u=I(`flutter`,un({device:_??{id:h},flutterDriver:a,mode:x,serverUrl:de,verbose:g}),{cwd:M.join(e,`src-flutter`),env:sn(ve,{noCodesign:f}),stdio:[`pipe`,`pipe`,`pipe`]}),d=new uc({onEvent:async e=>{Jc(e.params.message)&&(s=!0),await ce?.recordFlutterEvent(e)},verbose:g,write:async e=>{let t=await u.nodeChildProcess;if(!t.stdin)throw Error(`Flutter machine input is unavailable.`);t.stdin.write(e)===!1&&await Ht(t.stdin,`drain`)}}),p=e=>qc(dc(e,d),()=>s=!0);C=u,n=u,r=d;try{let e=!1;try{let e=c?c.capture(Zc(p(u),S,`output`)):Promise.all([Xc(p(u.stdout),J.stdout,S,`stdout`),Kc(u.stderr,J.stderr,S,`stderr`)]);await Promise.all([u,e])}catch{e=!0}if(i&&!D)continue;if(D)return;let n=l?await V.confirm({initialValue:!0,message:s?`${Wc} Restart Flutter?`:e?`Flutter failed. Retry?`:`Flutter exited unexpectedly. Restart Flutter?`}):!1;if(V.isCancel(n)||!n){if(!e&&!s){V.log.warn(`Flutter exited unexpectedly.`);return}V.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??me);return}}finally{C===u&&(C=void 0),n===u&&(n=void 0),r===d&&(r=void 0),d.close(),ce?.recordFlutterExit().catch(e=>{let t=e instanceof Error?e.message:String(e);S?.write(`error`,`Failed to record Flutter exit: ${t}`,{properties:{stream:`control`}})})}}}finally{(await c)()}},R=async()=>{if(h===`web`){await ye();return}let t=ye().then(()=>{if(!D)throw Error(`The Vite development server stopped while Flutter was still running.`)});await pe({cwd:e});try{await Promise.race([t,be(t)])}finally{j(),await Promise.allSettled([t,C]),C=void 0}},xe=async()=>{let t=at({name:`panda`,command:Vc,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:O});te=t;try{if(await t.expectSuccess(),!D)throw Error(`The Panda CSS watcher stopped while development was still running.`)}catch(e){if(!D)throw e}finally{te===t&&(te=void 0)}},Se=async()=>{if(h===`webext`){await L();return}let e=xe(),t=R(),n=N?F():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),D&&await t}finally{j(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(ge&&(O={...O,[Zt]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(le=await v.measure(`supervisor`,()=>Ut({cwd:e,env:r})))),D)return;if(h===`webext`){v.report(),await Se();return}if(A.database?.dialect===`sqlite`){if(await v.measure(`database`,async()=>{let t=await ue({config:A,cwd:e,env:r,tursoOutput:J.stdout,useSupervisorLease:!0});E=t,O={...O,...t.env}}),await v.measure(`schema`,()=>P({name:`db`,command:Vc,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),D)return;ie({cwd:e,env:O,dialect:`sqlite`})}if(tl(A)){let t=it({label:`postgres`});t.pipe(J.stdout,{end:!1});try{let n=await v.measure(`database`,()=>el({config:A,cwd:e,env:O,failIfRunning:!0,interactive:l,isStopping:()=>D,postgresOutput:t,useSupervisorLease:!0}));if(!n)return;T=n,O={...O,...n.env};try{D||await v.measure(`schema`,()=>P({name:`db`,command:Vc,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),D||(ie({cwd:e,env:O,dialect:`postgres`}),v.report(),await Se())}finally{await n[Symbol.asyncDispose](),T===n&&(T=void 0)}}finally{t.end()}return}v.report(),await Se()}finally{j(),await oe?.close(),oe=void 0;let e;try{await T?.[Symbol.asyncDispose]()}catch(t){e=t}finally{try{await ge()}finally{try{await ce?.close()}finally{le?.close(),se?.close();for(let{handler:e,signal:t}of _e)J.off(t,e)}}de&&(J.exitCode??=de===`SIGINT`?130:143)}$c(e)}}async function Kc(e,t,n,r){for await(let i of Yc(e,n,r))t.write(`${i}\n`)||await Ht(t,`drain`)}async function*qc(e,t){for await(let n of e)Jc(n.message)&&t(),yield n}function Jc(e){return typeof e==`string`&&e.trim()===Wc}async function*Yc(e,t,n){for await(let r of e){let e=fe(r);e.message&&t?.write(e.level,e.message,{properties:{stream:n}}),yield r}}async function Xc(e,t,n,r){for await(let i of Zc(e,n,r))t.write(`${i}\n`)||await Ht(t,`drain`)}async function*Zc(e,t,n){for await(let r of e)r.message&&t?.write(r.level,r.message,{properties:{stream:n}}),yield r.message}async function Qc(e,t){for await(let n of e)t.write(`${n}\n`)||await Ht(t,`drain`)}function $c(e){if(e)throw e}async function el({interactive:e,isStopping:t,...n}){try{return await D(n)}catch(r){if(!(r instanceof h)||!e)throw r;let i=await V.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(V.isCancel(i)||!i){V.cancel(`Keeping the existing PostgreSQL process.`);return}return await de(r),t()?void 0:D(n)}}function tl(e){return(e.database?.dialect??`postgres`)===`postgres`}function nl({host:e,port:t,strictPort:n=!1}){return[`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)],...n?[`--strictPort`]:[]]}function rl(e){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw Error(`COREFRAME_WEB_PORT must be a valid TCP port.`);return t}function il(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function al(e={}){let t=e.cwd??J.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await Ue(M.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Qe(n,t);if(!e.default||typeof e.default!=`object`)throw Error(`scripts/preview.ts must default-export preview hooks.`);for(let t of[`beforeBuild`,`afterBuild`])if(e.default[t]!==void 0&&typeof e.default[t]!=`function`)throw Error(`scripts/preview.ts ${t} must be a function.`);r=e.default}return nn({...e,cwd:t},r)}const ol=`worker-configuration.d.ts`;async function sl({check:e=!1,cwd:t=process.cwd()}={}){let n=await K({cwd:t}),r=await yt({coreframeConfig:n,cwd:t}),i=F(t,ol),a=F(t,`.coreframe-worker-types-${q()}.d.ts`);try{try{await I(`pnpm`,[`exec`,`wrangler`,`types`,a,`--config`,r.path,`--strict-vars=false`,`--include-runtime=false`],{cwd:t,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw cl(e),e}let o=ll(await U(a,`utf8`)),s=tt(r.config),c=$e(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${ul(c)}\n`;if(e){if(await U(i,`utf8`).catch(()=>``)!==l)throw Error(`${ol} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await U(i,`utf8`).catch(()=>``);return u!==l&&await G(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await W(a,{force:!0})}}function cl(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
|
|
16
|
+
`:``;z(e,`${JSON.stringify(n,null,r)}${i}`)}function Ko(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t)console.log(` ${e}`);console.log(``)}}function qo(e){let t=P(Io([`rev-parse`,`--show-toplevel`]).trim(),`package.json`),n=R(t,`utf8`),r=Lo(n,t),i=Q(e.target,e.remote),a=Uo(e.target,e.remote),o=new Set(a.map(({name:e})=>e)),s=[],c=[],l=[],u=0;for(let e of a){let t=Wo(r,e.name);if(!t){c.push(`missing: ${e.name} ${e.spec} (${e.group})`);continue}if(Bo(t.spec)){l.push(`linked: ${e.name} ${t.spec}`);continue}if(t.spec===e.spec){u+=1;continue}s.push({...e,currentGroup:t.group,currentSpec:t.spec})}let d=Fo.flatMap(e=>Object.entries(r[e]??{}).filter(([e])=>zo(e)&&!o.has(e)).map(([t,n])=>`review: ${t} ${n} (${e})`));if(e.apply&&s.length>0){for(let e of s)r[e.currentGroup][e.name]=e.spec;Go(t,n,r)}console.log(`Coreframe package sync: ${Xi(i)}`),console.log(``),Ko(e.apply?`Updated Coreframe packages`:`Would update Coreframe packages`,s.map(({currentSpec:e,name:t,spec:n})=>`update: ${t} ${e} -> ${n}`)),Ko(`Missing target Coreframe packages`,c),Ko(`Locally linked Coreframe packages`,l),Ko(`Downstream-only Coreframe packages`,d),u>0&&console.log(`${u} Coreframe package(s) already match the target versions.`),s.length===0?console.log(`No Coreframe package version updates found.`):e.apply||(console.log(``),console.log(`Run with --apply to write the ${s.length} package update(s).`))}const Jo={...p,displayName:`recipe`,description:`Coreframe recipe name, such as yam-db.`,async from(e){return Vi(e)}},Yo=m({name:`upgrade`,cmds:{"ensure-template-remote":n({name:`ensure-template-remote`,args:{remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Remote name to ensure.`}),url:c({long:`url`,type:l(p),description:`Template repository URL. Defaults to the upstream Coreframe repository.`}),noFetch:i({long:`no-fetch`,description:`Do not fetch the remote after ensuring it exists.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,url:n})=>oa({fetch:!e,remote:t,url:n})}),"check-skill-current":n({name:`check-skill-current`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),apply:i({long:`apply`,description:`Replace the local upgrade skill with the target version when it differs.`,defaultValue:()=>!1})},handler:({apply:e,remote:t,target:n})=>{process.exitCode=co({apply:e,remote:t,target:n})}}),"fast-forward-template-files":n({name:`fast-forward-template-files`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),base:c({long:`base`,type:l(p),description:`Previous Coreframe template git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),apply:i({long:`apply`,description:`Write clean fast-forwards to the worktree.`,defaultValue:()=>!1})},handler:({apply:e,base:t,remote:n,target:r})=>No({apply:e,base:t,remote:n,target:r})}),"list-template-versions":n({name:`list-template-versions`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),base:c({long:`base`,type:l(p),description:`Previous Coreframe template git ref. Omit to list every released version.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`})},handler:({base:e,remote:t,target:n})=>{for(let r of Po({base:e,remote:t,target:n}))console.log(r)}}),"sync-coreframe-packages":n({name:`sync-coreframe-packages`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),apply:i({long:`apply`,description:`Update existing published Coreframe dependency specifications.`,defaultValue:()=>!1})},handler:({apply:e,remote:t,target:n})=>qo({apply:e,remote:t,target:n})})}}),Xo=m({name:`recipes`,cmds:{apply:n({name:`apply`,args:{recipe:u({type:Jo,displayName:`recipe`,description:`Recipe to prepare and apply.`}),target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Ia(Fa({fetch:!e,name:t,remote:n,target:r}))}),list:n({name:`list`,args:{target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,target:n})=>to(eo({fetch:!e,remote:t,target:n}))}),verify:n({name:`verify`,args:{recipe:u({type:Jo,displayName:`recipe`,description:`Recipe adoption to verify.`}),target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Ma(ja({fetch:!e,name:t,remote:n,target:r}))})}}),Zo=m({name:`db`,cmds:{ensure:n({name:`ensure`,args:{},handler:S}),generate:n({name:`generate`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit generate.`})},handler:({args:e})=>se(`generate`,e)}),migrate:n({name:`migrate`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit migrate.`})},handler:({args:e})=>se(`migrate`,e)}),"migrate-held":n({name:`migrate-held`,args:{local:i({long:`local`,description:`Run held migrations against the Coreframe-managed local PostgreSQL database.`,defaultValue:()=>!1})},handler:({local:e})=>ne({target:e?`local`:`deployment`})}),"migrate-local":n({name:`migrate-local`,args:{},handler:re}),"migrations-check":n({name:`migrations-check`,args:{},handler:g}),reset:n({name:`reset`,args:{},handler:oe}),seed:n({name:`seed`,args:{},handler:()=>le()}),"schema-check":n({name:`schema-check`,args:{seed:i({long:`seed`,description:`Run the configured project seed against the throwaway database.`,defaultValue:()=>!1})},handler:({seed:e})=>_({seed:e})}),setup:n({name:`setup`,args:{},handler:()=>ue()}),studio:n({name:`studio`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit studio.`})},handler:({args:e})=>se(`studio`,e)})}}),Qo=`package.json`;async function $o(e=process.argv.slice(2),t=process.env){let n=ns(e);bs(n),await ts(t);let{packageJson:r,source:i}=await Dt(Qo),a=await G(),o=Mt(a.deploy,n.environment,t);xs(n,o.mode);let s=!!(t.POSTHOG_API_KEY&&t.POSTHOG_PROJECT_ID);!s&&(t.POSTHOG_API_KEY||t.POSTHOG_PROJECT_ID)&&B.log.warn(`PostHog source map upload is disabled because only one of POSTHOG_API_KEY or POSTHOG_PROJECT_ID is set.`);let c=await Ss(o,n.environment,()=>gt({env:t})),l=await Ct(o,a,c,t),u=o.mode===`full`?await is(n.environment,t,a):void 0,d=await ys(),f=a.i18n?Ir(a.i18n):void 0;f&&Fr(f)===`source-only`?B.log.info(`I18n source-only mode (${f.sourceLocale}): no prepared translation snapshot is required; source catalogs build directly.`):await Pr({env:t,revision:d});let p=d.slice(0,12),m=Pt(n.environment,r.version,p),h=jt(r.name,m),g={...ks(t,n.environment,h,r.name,m),...f?{COREFRAME_I18N_RELEASE_REVISION:d}:{}},_=n.environment===`production`,v=!1;B.intro(`Deploy ${h} to ${n.environment}`);let ee=Object.keys(u?.pendingWorkerSecrets.values??{}).sort();ee.length>0&&B.note(ee.join(`
|
|
17
|
+
`),`Pending Worker secret updates`),u?.accessTokenSigningSecret.provisioned&&B.log.info(`Provisioning Coreframe-managed access-token signing material.`),await ws(n);let y=o.mode===`full`?await as(a,n,t):{kind:`none`};try{_&&await Bt(Qo,r,m);let e=await Be(process.cwd(),{allowMissing:!0});if(a.assets||e.problems.length>0||Ne(e.catalog).length>0){let e={config:a.assets,env:g};B.log.step(`Building and validating managed assets`);let t=await Fe({...e,updateManifest:!1});if(!t.ok)throw Error(`Managed asset build failed.\n${Le(t.problems)}`);let n=await Ie(e);if(!n.ok)throw Error(`Managed asset validation failed.\n${Le(n.problems)}`);B.log.step(`Publishing managed assets`);let r=await ze(e);if(!r.ok)throw Error(`Managed asset publication failed.\n${Le(r.problems)}`)}B.log.step(s?`Running release build and uploading PostHog source maps`:`Running release build`),v=s,await F(`pnpm`,[`build`],{env:g,stdio:`inherit`}),v=!0;let t={...g};delete t.CLOUDFLARE_ENV,y.kind===`drizzle`?(B.log.step(`Running deploy-safe database migrations`),await F(`pnpm`,[`exec`,`drizzle-kit`,`migrate`],{env:g,stdio:`inherit`})):y.kind===`d1`&&(B.log.step(`Applying deploy-safe D1 migrations with Wrangler`),await F(`pnpm`,ds(n.environment,[`d1`,`migrations`,`apply`,y.database.binding,`--remote`]),{env:t,stdio:`inherit`})),B.log.step(o.mode===`full`?`Deploying Worker and static assets to Cloudflare`:`Deploying static assets to Cloudflare`);let i={...u?.dashboardPassword?{DASHBOARD_PASSWORD:u.dashboardPassword}:{},...u?.accessTokenSigningSecret.value?{[ft]:u.accessTokenSigningSecret.value}:{},...u?.pendingWorkerSecrets.values},d=Object.keys(i).length>0?await Es(i):void 0,f=o.mode===`full`?await yt({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:h}}}):await vt(process.cwd());try{let e=[`exec`,`wrangler`,`deploy`,`--config`,f.path,`--strict`,`--keep-vars`,`--tag`,h,`--message`,`Deploy ${h}`,...d?[`--secrets-file`,d.path]:[]];try{await es(e,t)}catch(n){let r=ms(n);if(!/\b10057\b/u.test(r)||!/no previous version exists/iu.test(r))throw n;B.log.info(`Initial Worker upload: retrying without binding inheritance.`);let i=Os(f.config.unsafe)?f.config.unsafe:{},a=Os(i.metadata)?i.metadata:{};await W(f.path,JSON.stringify({...f.config,keep_vars:!1,unsafe:{...i,metadata:{...a,keep_bindings:[]}}})),await es(e.filter(e=>e!==`--keep-vars`),t)}u&&(await pt(u.pendingWorkerSecrets),await zt({environment:n.environment}))}finally{await f.dispose(),await d?.dispose()}let p={environment:n.environment,releaseName:h,url:c,version:m};o.mode===`full`&&o.afterWorkerDeploy&&(B.log.step(`Running required after-Worker deploy hook`),await It(o,p)),l&&(B.log.step(`Provisioning and verifying deployment reviewer`),await l.run(p)),n.skipPostDeployChecks||(B.log.step(`Running post-deploy checks`),await Lt(o,p)),B.outro(`Deployed ${h} to ${n.environment}`)}catch(e){throw!v&&_&&await W(Qo,i),e}}async function es(e,t){try{let n=await F(`pnpm`,e,{env:t,stdin:`inherit`});process.stdout.write(n.stdout),process.stderr.write(n.stderr)}catch(e){throw Os(e)&&(typeof e.stdout==`string`&&process.stdout.write(e.stdout),typeof e.stderr==`string`&&process.stderr.write(e.stderr)),e}}async function ts(e){let t;try{t=await H(`.env.deploy`,`utf8`)}catch(e){if(Ds(e)&&e.code===`ENOENT`)return;throw e}for(let[n,r]of Object.entries(Ht(t)))e[n]===void 0&&(e[n]=r)}function ns(e){return{environment:rs(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function rs(e){if(e&&mt.includes(e))return e;throw Error(`Deploy environment must be one of: ${mt.join(`, `)}.`)}async function is(e,t,n){let r=await Ot({environment:e}),i=n.dashboard?.enabled===!1?void 0:r.values.DASHBOARD_PASSWORD??await Ts(t,e);return Rt(await _t({environment:e}),e,{availableNames:[...Object.keys(r.values),...i?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await St({environment:e}),dashboardPassword:i,pendingWorkerSecrets:r}}async function as(e,t,n){let r=e.database?.dialect??`postgres`,i=e.database?.d1Binding;if(i!==void 0&&r!==`sqlite`)throw Error(`database.d1Binding in coreframe.config.ts requires database.dialect "sqlite".`);if(r===`sqlite`&&i!==!1){let e=Nt({config:await os(i!==void 0),d1Binding:i,environment:t.environment,hasConnectionUrl:!!(n.TURSO_DATABASE_URL??n.DATABASE_URL)});if(e)return ss(e,t,n)}let a;switch(r){case`postgres`:a=await y({env:n});break;case`sqlite`:a=await b({env:n});break;default:throw Error(`Unsupported database dialect "${r}".`)}let{appliedMigrations:o,pendingMigrations:s}=await gs(a);return await hs(s,o.size,"Move unsafe statements to held migrations and apply them with `pnpm db migrate-held`."),await vs(t,s)?{kind:`drizzle`}:{kind:`none`}}async function os(e){try{return await kt()}catch(t){if(e)throw t;return{}}}async function ss(e,t,n){if(t.skipMigrations)return B.log.info(`Skipping D1 migration checks for binding "${e.binding}" (--skip-migrations). Apply pending migrations separately with \`wrangler d1 migrations apply ${e.binding} --remote --env ${t.environment}\`.`),{kind:`none`};let r=await v(),i=await cs(e,t.environment,n),a=r.filter(t=>{let n=us(t,e);return n===void 0||!i.has(n)}),o=a.filter(t=>us(t,e)===void 0);return o.length>0&&B.log.warn(`Deploy migrations are outside the D1 binding's migrations_dir and Wrangler will not apply them:\n${T(o)}`),await hs(a,i.size,`Move unsafe statements to held migrations and apply them to the D1 database for ${t.environment} separately.`),await vs(t,a)?{kind:`d1`,database:e}:{kind:`none`}}async function cs(e,t,n){let r=`select name from ${ps(e.migrationsTable)} order by id`,i;try{i=(await F(`pnpm`,ds(t,[`d1`,`execute`,e.binding,`--remote`,`--json`,`--command`,r]),{env:fs(n),stdin:`ignore`})).stdout}catch(n){let r=ms(n);if(/no such table|does not exist/iu.test(r))return new Set;throw Error(`Could not read applied D1 migrations for binding "${e.binding}" in ${t}. Check Wrangler credentials and the D1 binding configuration.\n${r}`)}return new Set(ls(i,e))}function ls(e,t){let n;try{n=JSON.parse(e)}catch{throw Error(`Could not parse Wrangler D1 migration output for binding "${t.binding}".`)}if(!Array.isArray(n))throw Error(`Could not parse Wrangler D1 migration output for binding "${t.binding}".`);let r=[];for(let e of n)if(!(!Os(e)||!Array.isArray(e.results)))for(let t of e.results)Os(t)&&typeof t.name==`string`&&r.push(t.name);return r}function us(e,t){let n=t.migrationsDir.replaceAll(`\\`,`/`).replace(/^\.\/|\/+$/gu,``),r=e.relativePath.split(be).join(`/`);return r.startsWith(`${n}/`)?r.slice(n.length+1):void 0}function ds(e,t){return[`exec`,`wrangler`,`--config`,tt,`--env`,e,...t]}function fs(e){let t={...e};return delete t.CLOUDFLARE_ENV,t}function ps(e){return`"${e.replaceAll(`"`,`""`)}"`}function ms(e){if(typeof e==`object`&&e){let{output:t,stdout:n,stderr:r}=e,i=[t,n,r].filter(e=>typeof e==`string`&&e.length>0).join(`
|
|
18
|
+
`);if(i)return i}return e instanceof Error?e.message:String(e)}async function hs(e,t,n){let r=await ce(e);if(r.length!==0){if(t>0)throw Error(`Pending deploy migrations contain unsafe SQL. ${n}\n${te(r)}`);B.log.warn(`Pending deploy migrations contain SQL that is unsafe for an existing deployment, but the target database has no applied migrations, so no deployed app version can depend on the current schema. Proceeding with deploy migrations.\n${te(r)}`)}}async function gs(e){try{return await _s(e)}finally{await e.close?.()}}async function _s(e){let t=await v(),n=await ie(e);return{appliedMigrations:n,pendingMigrations:C(t,n)}}async function vs(e,t){if(t.length===0)return B.log.info(`No pending deploy migrations.`),!1;if(B.note(T(t),`Pending deploy migrations`),e.runMigrations)return!0;if(e.skipMigrations)return!1;if(!process.stdout.isTTY)throw Error(`Pending migrations require --run-migrations or --skip-migrations in noninteractive deploys.`);let n=await B.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(B.isCancel(n))throw B.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function ys(){let{stdout:e}=await F(`git`,[`status`,`--porcelain`],{stdin:`ignore`});if(e.trim().length>0)throw Error(`Deploy requires a clean git tree.`);let{stdout:t}=await F(`git`,[`rev-parse`,`HEAD`],{stdin:`ignore`});return t.trim()}function bs(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function xs(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function Ss(e,t,n=gt){return e.url?Cs(e.url,t):t===`staging`&&e.stagingHostname?Cs(await n(),t):Cs(void 0,t)}function Cs(e,t){if(!e)throw Error(`Missing ${t} deploy URL. Set DEPLOY_URL or deploy.environments.${t}.url in coreframe.config.ts.`);let n;try{n=new URL(e)}catch{throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`);return n.toString()}async function ws(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await B.confirm({initialValue:!1,message:`Deploy to production?`});if(B.isCancel(t)||!t)throw B.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}async function Ts(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Ht(await H(`.env`,`utf8`))}catch(e){throw Ds(e)&&e.code===`ENOENT`?Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`):e}let i=r.DASHBOARD_PASSWORD?.trim();if(!i)throw Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`);return i}async function Es(e){let t=await Je(N(je(),`coreframe-deploy-secrets-`)),n=N(t,`secrets.json`);return await W(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>U(t,{force:!0,recursive:!0})}}function Ds(e){return e instanceof Error&&`code`in e}function Os(e){return typeof e==`object`&&!!e}function ks(e,t,n,r,i){return{...e,CLOUDFLARE_ENV:t,DEPLOY_ENV:t,POSTHOG_RELEASE:n,POSTHOG_RELEASE_NAME:e.POSTHOG_RELEASE_NAME??r,POSTHOG_RELEASE_VERSION:e.POSTHOG_RELEASE_VERSION??i}}async function As(){let e=await Ms();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function js(e){let t=await Ms(),n=Ns();await Z.mkdir(j.dirname(n),{recursive:!0}),await Z.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function Ms(){try{let e=await Z.readFile(Ns(),`utf8`),t=JSON.parse(e);return Ps(t)?t:{}}catch{return{}}}function Ns(){return j.join(ui.homedir(),`.coreframe`,`preferences.json`)}function Ps(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Fs({env:e=q.env,interactive:t=q.stdin.isTTY===!0,platform:n,target:r}){let i=await Hs(n,e).catch(()=>[]),a=r?oc(i,r):void 0;if(a)return a;if(!r&&i.length>0)return Vs(i,n,t);let o=r?oc(await Ws(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return Gs(o,n,e,t);let s=await Us(n,e),c=r?oc(s,r):void 0;if(c)return c;if(!r&&s.length>0)return Vs(s,n,t);let l=n===`ios`?`iOS`:`Android`;throw Error(r?`Could not find a ${l} device matching "${r}".`:`No connected ${l} devices or available ${l} ${n===`ios`?`simulators`:`emulators`} were detected.`)}async function Is(e){let{device:t,host:n,interactive:r=q.stdin.isTTY===!0}=e;if(!t.physical&&n===void 0)return;if(typeof n==`string`&&n!==`0.0.0.0`&&n!==`::`)return n;let i=cc();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await zs();if(a&&i.includes(a))return a;if(i.length===1)return await Bs(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await B.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(B.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await Bs(o),o}async function Ls({device:e,env:t=q.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await $s(e.id,a,t)}catch{B.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:Rs(i,await Is({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function Rs(e,t,n){let r=t??(e===`android`?`10.0.2.2`:`127.0.0.1`);return`http://${r.includes(`:`)&&!r.startsWith(`[`)?`[${r}]`:r}:${n}`}async function zs(){return(await As()).mobileDevHost}async function Bs(e){try{await js({mobileDevHost:e})}catch(e){B.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function Vs(e,t,n){if(e.length===1)return e[0];if(!n)throw Error(`Multiple ${t===`ios`?`iOS`:`Android`} devices were detected. Pass a device name explicitly.`);let r=await B.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(B.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function Hs(e,t){return e===`android`?qs(t):Ys(t)}async function Us(e,t){return e===`android`?Js(t):Xs(t)}async function Ws(e){let{stdout:t}=await F(`flutter`,[`emulators`],{env:e});return t.split(/\r?\n/).flatMap(e=>{let[t,n,,r]=e.split(/\s*•\s*/).map(e=>e.trim());return t&&n&&(r===`android`||r===`ios`)?[{id:t,label:n,name:n,physical:!1,platform:r}]:[]})}async function Gs(e,t,n,r){let i=await Ks(t,n).catch(()=>[]),{stdout:a}=await F(`flutter`,[`emulators`,`--launch`,e.id],{env:n});if(/No emulator found|More than one emulator matches/i.test(a))throw Error(a.trim());let o=Date.now()+3e4;do{let a=await Ks(t,n).catch(()=>[]),o=oc(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return Vs(s,t,r);if(a.length===1)return a[0];await tn(250)}while(Date.now()<o);let s=t===`ios`?`iOS simulator`:`Android emulator`;throw Error(`Flutter launched "${e.id}", but no ${s} became available.`)}async function Ks(e,t){return e===`ios`?Xs(t,`booted`):(await qs(t)).filter(e=>!e.physical)}async function qs(e){let t=await Qs(e,`platform-tools`,q.platform===`win32`?`adb.exe`:`adb`),{stdout:n}=await F(t,[`devices`],{env:e}),r=n.split(/\r?\n/).map(e=>e.match(/^(\S+)\s+device(?:\s|$)/)?.[1]).filter(e=>e!==void 0);return(await Promise.all(r.map(async n=>{let r=await tc(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await rc(t,e,n,r):await ic(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(lc)}async function Js(e){let{stdout:t}=await F(await Qs(e,`emulator`,q.platform===`win32`?`emulator.exe`:`emulator`),[`-list-avds`],{env:e});return t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!/^(INFO|WARNING|ERROR)\s+\|/.test(e)).map(e=>({id:e,label:e,name:e,physical:!1}))}async function Ys(e){let t=await Z.mkdtemp(j.join(ui.tmpdir(),`coreframe-ios-devices-`)),n=j.join(t,`devices.json`);try{return await Z.writeFile(n,``),await F(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await Z.readFile(n,`utf8`)).result?.devices??[]).filter(Zs).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(lc)}finally{await Z.rm(t,{force:!0,recursive:!0})}}async function Xs(e,t=`available`){let{stdout:n}=await F(`xcrun`,[`simctl`,`list`,`--json`,`devices`,t],{env:e}),r=JSON.parse(n);return Object.entries(r.devices??{}).filter(([e])=>e.includes(`iOS-`)).flatMap(([,e])=>e).flatMap(e=>e.name&&e.udid?[{id:e.udid,label:e.name,name:e.name,physical:!1}]:[]).sort(lc)}function Zs(e){return e.connectionProperties?.tunnelState!==`unavailable`&&typeof e.hardwareProperties?.platform==`string`&&(e.hardwareProperties.platform.includes(`iOS`)||e.hardwareProperties.platform.includes(`xrOS`))&&typeof e.deviceProperties?.name==`string`&&typeof e.hardwareProperties.productType==`string`&&typeof e.hardwareProperties.udid==`string`}async function Qs(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:ec(e);for(let e of i){let r=j.join(e,t,n);try{return await Z.access(r),r}catch{}}return n}async function $s(e,t,n){let r=await Qs(n,`platform-tools`,q.platform===`win32`?`adb.exe`:`adb`),{stdout:i}=await F(r,[`-s`,e,`reverse`,`tcp:0`,`tcp:${t}`],{env:n,timeout:3e3}),a=Number(i.trim());if(!Number.isInteger(a)||a<1||a>65535)throw Error(`ADB did not return a valid reverse TCP port.`);let o=`tcp:${a}`,s=!1;return{async close(){s||(s=!0,await F(r,[`-s`,e,`reverse`,`--remove`,o],{env:n,timeout:3e3}).catch(()=>void 0))},serverUrl:`http://127.0.0.1:${a}`,viteHost:`127.0.0.1`}}function ec(e){return q.platform===`darwin`?[j.join(ui.homedir(),`Library`,`Android`,`sdk`)]:q.platform===`win32`&&e.LOCALAPPDATA?[j.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[j.join(ui.homedir(),`Android`,`Sdk`)]}async function tc(e,t,n,r){return(await nc(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function nc(e,t,n){return(await F(e,n,{env:t,timeout:3e3})).stdout}async function rc(e,t,n,r){return nc(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function ic(e,t,n,r){return nc(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>ac(e)||r).catch(()=>r)}function ac(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function oc(e,t){let n=e.map(e=>({device:e,score:Math.max(sc(t,e.name),sc(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function sc(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(r===n)return 1e4;let i=r.indexOf(n);if(i>=0)return 5e3-i;let a=0,o=0;for(let e of n){let t=r.indexOf(e,o);if(t<0)return 0;a+=t===o?2:1,o=t+1}return a}function cc(){return[...new Set(Object.values(ui.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function lc(e,t){return e.label.localeCompare(t.label)}var uc=class{#e;#t=new Map;#n=new Set;#r;#i;#a;#o;#s=0;constructor({onEvent:e,verbose:t=!1,write:n}){this.#e=e,this.#r=t,this.#i=n}async handleLine(e){let t;try{t=JSON.parse(e)}catch{return $(e,`debug`)}if(!Array.isArray(t))return $(e,`debug`);let n=[];for(let e of t){if(!hc(e)){n.push(...$(JSON.stringify(e),`debug`));continue}if(e.id!==void 0&&(`result`in e||`error`in e)){this.#c(e);continue}if(typeof e.event!=`string`)continue;let t={event:e.event,params:hc(e.params)?e.params:{}};this.#l(t),await this.#e?.(t),n.push(...fc(t,this.#r))}return n}async restart({debounce:e=!1,fullRestart:t,reason:n}){let r=await this.#d();if(!r.supportsRestart)throw Error(`The running Flutter application does not support hot restart or reload.`);let i=await this.#u(`app.restart`,{appId:r.id,debounce:e,fullRestart:t,reason:n});if(!hc(i)||typeof i.code!=`number`)throw Error(`Flutter returned an invalid restart response.`);let a={code:i.code,message:typeof i.message==`string`?i.message:``};if(a.code!==0)throw Error(a.message||`Flutter restart failed with code ${a.code}.`);return a}async stop(){let e=await this.#d();if(await this.#u(`app.stop`,{appId:e.id})!==!0)throw Error(`Flutter did not stop the running application.`)}close(e=Error(`The Flutter machine connection closed.`)){if(this.#o)return;let t=_c(e);this.#o=t;for(let e of this.#t.values())e.reject(t);this.#t.clear(),this.#f(t)}#c(e){let t=String(e.id),n=this.#t.get(t);n&&(this.#t.delete(t),`error`in e?n.reject(Error(gc(e.error))):n.resolve(e.result))}#l({event:e,params:t}){let n=typeof t.appId==`string`?t.appId:void 0;if(e===`app.start`&&n){this.#a={id:n,started:!1,supportsRestart:t.supportsRestart===!0};return}if(e===`app.started`&&n&&this.#a?.id===n){let e={...this.#a,started:!0};this.#a=e;for(let t of this.#n)t.resolve(e);this.#n.clear();return}e===`app.stop`&&n&&this.#a?.id===n&&(this.#a=void 0,this.#f(Error(`The Flutter application stopped before it was ready.`)))}async#u(e,t){if(this.#o)throw this.#o;let n=String(++this.#s),r,i,a=new Promise((e,t)=>{r=t,i=e});this.#t.set(n,{reject:r,resolve:i});try{await this.#i(`${JSON.stringify([{id:n,method:e,params:t}])}\n`)}catch(e){this.#t.delete(n),r(_c(e))}return a}#d(){return this.#o?Promise.reject(this.#o):this.#a?.started?Promise.resolve(this.#a):new Promise((e,t)=>{this.#n.add({reject:t,resolve:e})})}#f(e){for(let t of this.#n)t.reject(e);this.#n.clear()}};async function*dc(e,t){try{for await(let n of e)yield*await t.handleLine(n)}catch(e){throw t.close(e),e}finally{t.close()}}function fc({event:e,params:t},n){if(e===`daemon.log`||e===`app.log`)return $(mc(t.log),t.error===!0?`error`:`debug`);if(e===`daemon.logMessage`){let e=pc(t.level);return!n&&e===`debug`?[]:[...$(mc(t.message),e),...n?$(mc(t.stackTrace),e):[]]}return e===`daemon.showMessage`?$(mc(t.message),pc(t.level)):e===`app.warning`?$(mc(t.warning),`warn`):e===`app.progress`&&t.finished!==!0?$(mc(t.message),`debug`):e===`app.stop`&&t.error!==void 0?$(gc(t.error),`error`):[]}function $(e,t){return e===void 0?[]:e.split(/\r?\n/u).map(e=>({level:t,message:e}))}function pc(e){return e===`error`?`error`:e===`warning`||e===`warn`?`warn`:`debug`}function mc(e){return typeof e==`string`&&e.length>0?e:void 0}function hc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gc(e){if(typeof e==`string`)return e;if(hc(e)&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function _c(e){return e instanceof Error?e:Error(gc(e))}async function vc(e,t){if(!e)return()=>void 0;Ce(j.dirname(e),{recursive:!0}),z(e,``,{flag:`a`});let n;try{n=R(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=Oe(e,{persistent:!1},()=>{if(i)return;let a=++r;H(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function yc(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const bc=q.platform===`win32`?`portless.cmd`:`portless`,xc=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),Sc=/^Proxy is already running on port (\d+)\.$/,Cc=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function wc(e){let t=e.split(/(\r\n|\n)/),n=[];for(let e=0;e<t.length;){let r=t[e],i=t[e+2],a=r?.replace(xc,``).trim().match(Sc);if(a?.[1]!==void 0&&i!==void 0&&Cc.test(i.replace(xc,``).trim())){n.push(`Portless proxy is running on port ${a[1]}.`),t[e+1]!==void 0&&n.push(t[e+1]),e+=t[e+3]===void 0?3:4;continue}n.push(t[e]??``),e+=1}return n.join(``)}function Tc(e){let t=wc(e);t&&q.stdout.write(t.endsWith(`
|
|
19
|
+
`)?t:`${t}\n`)}async function Ec({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await nn()).isAgent?!1:Yt(e)}async function Dc({cwd:e,env:t,lan:n=!1}){let r=j.join(`node_modules`,`.bin`,bc),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await F(j.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});Tc(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Tc(e.stdout),e}}function Oc({host:e,lan:t=!1,port:n}){return[...t?[`--lan`]:[],`run`,...n===void 0?[]:[`--app-port`,String(n)],`react-router`,`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e]]}const kc=j.join(`.coreframe`,`dev`,`session.json`);async function Ac({appOrigin:e,cwd:t,device:n,flutterMcp:r,flutterMode:i,id:a,localOrigin:o,now:s=new Date,pid:c=process.pid,platform:l}){let u=j.resolve(t,kc),d=j.dirname(u),f={version:2,id:a,pid:c,projectRoot:j.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:j.resolve(t,`.leylines`,`logs.sqlite`),scopes:{browser:`browser`,...i===void 0?void 0:{flutter:`dev.flutter`},vite:`dev.vite`}},...i===void 0?void 0:{flutter:{mode:i,mcp:r,state:`starting`,...n===void 0?void 0:{device:n}}}},p=Promise.resolve(),m=()=>{let e=`${JSON.stringify(f,void 0,2)}\n`;return p=p.then(async()=>{await V(d,{recursive:!0});let t=j.join(d,`.session-${a}.json`);await W(t,e,{mode:384}),await Ge(t,384),await Xe(t,u)}),p};return await m(),{path:u,async recordFlutterEvent({event:e,params:t}){let n=f.flutter;if(!n)return;let r=Nc(t.appId),i;if(e===`daemon.connected`){let e=Pc(t.pid),r=Nc(t.version);i={...jc(n),state:`starting`,...e===void 0?void 0:{daemonPid:e},...r===void 0?void 0:{protocolVersion:r}}}else if(e===`app.start`&&r)i={...jc(n),appId:r,state:`starting`,supportsRestart:t.supportsRestart===!0};else if(e===`app.started`&&r===n.appId)i={...n,state:`running`};else if(e===`app.debugPort`&&r===n.appId){let e=Nc(t.wsUri);e&&(i={...n,vmServiceWsUri:e})}else if(e===`app.devTools`&&r===n.appId){let e=Nc(t.uri);e&&(i={...n,devToolsUri:e})}else if(e===`app.dtd`&&r===n.appId){let e=Nc(t.uri);e&&(i={...n,dtdUri:e})}else e===`app.stop`&&r===n.appId&&(i=Mc(n));i&&(f={...f,flutter:i},await m())},async recordFlutterExit(){!f.flutter||f.flutter.state===`stopped`||(f={...f,flutter:Mc(f.flutter)},await m())},async close(){await p;try{JSON.parse(await H(u,`utf8`)).id===a&&await U(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}function jc(e){return{mode:e.mode,mcp:e.mcp,...e.device===void 0?void 0:{device:e.device},...e.daemonPid===void 0?void 0:{daemonPid:e.daemonPid},...e.protocolVersion===void 0?void 0:{protocolVersion:e.protocolVersion}}}function Mc(e){return{...jc(e),state:`stopped`,...e.appId===void 0?void 0:{appId:e.appId},...e.supportsRestart===void 0?void 0:{supportsRestart:e.supportsRestart}}}function Nc(e){return typeof e==`string`?e:void 0}function Pc(e){return typeof e==`number`?e:void 0}const Fc=`extension:dev`;function Ic(e){if(!L(N(e,`src-webext/wxt.config.ts`)))throw Error("No WXT configuration found at src-webext/wxt.config.ts. Apply the wxt recipe or add that convention before running `coreframe dev webext`.");let t=N(e,`package.json`),n;try{n=JSON.parse(R(t,`utf8`))}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}if(!n||typeof n!=`object`||!(`scripts`in n)||!n.scripts||typeof n.scripts!=`object`||!(`extension:dev`in n.scripts)||typeof n.scripts[`extension:dev`]!=`string`)throw Error(`package.json must define scripts.${Fc} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function Lc({host:e,port:t}){let n=[...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)]];return[`run`,Fc,...n.length>0?[`--`,...n]:[]]}const Rc=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],zc=[`managed-dev-overlay`],Bc=j.resolve(`node_modules`,`.bin`),Vc=q.platform===`win32`?`pnpm.cmd`:`pnpm`,Hc=q.platform===`win32`?`portless.cmd`:`portless`,Uc=q.platform===`win32`?`react-router.cmd`:`react-router`,Wc=`Lost connection to device.`;async function Gc({cwd:e=q.cwd(),debug:t,device:n,env:r=q.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=q.stdin.isTTY===!0,lan:u=!1,managed:d=!1,noCodesign:f=!1,noManaged:p=!1,noDevJobs:m=!1,platform:h=`web`,verbose:g=!1,webPort:_}={}){let v=Gt({env:r}),ee=r.PATH??r.Path??``,y=il(h)?h:void 0,b=ln(i||a),x=rl(_??r.COREFRAME_WEB_PORT),S,C,w,T,te,ne,re,ie,oe,se,ce,le,ue,E=!1,fe,D=r;if(d&&p)throw Error(`Cannot use --managed and --no-managed together.`);if(t===`managed-dev-overlay`&&d)throw Error(`Cannot use --managed with --debug managed-dev-overlay.`);if(i&&y===void 0)throw Error(`The --flutter-debug option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(a&&y===void 0)throw Error(`The --flutter-mcp option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(f&&h!==`macos`)throw Error(`The --no-codesign option is only supported for macOS Flutter development.`);if(o===`full`&&y===void 0)throw Error(`The --flutter-output option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(h===`webext`){if(d||p||t!==void 0||g)throw Error(`Managed development, debug features, and verbose native output are only supported for the main web or native development platforms.`);Ic(e)}if(c&&h!==`web`)throw Error(`Local HTTPS is only supported for the web development platform.`);if(n!==void 0&&h!==`ios`&&h!==`android`)throw Error(`A device name or ID is only supported for iOS or Android development.`);let pe=await v.measure(`routing`,()=>Ec({cwd:e,env:r,platform:h}));pe&&await v.measure(`portless`,()=>Dc({cwd:e,env:r,lan:u}));let O=y===void 0?h===`web`?x??await li.getAvailablePort():h===`webext`?x:void 0:x??await li.getAvailablePort(),k,he=new Promise(e=>{k=e}),A=()=>{E||(E=!0,k(),C?.kill(`SIGTERM`),ne?.kill(`SIGTERM`),re?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ie?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),oe?.close().catch(()=>void 0),S?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),_e().catch(()=>void 0))},_e=()=>T?(te??=T[Symbol.asyncDispose](),te):Promise.resolve(),M=e=>{fe??=e,A()},ve=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>M(e);return q.on(e,t),{handler:t,signal:e}}),N=async e=>{let t=ot(e);C=t;try{await t.expectSuccess()}catch(e){if(!E)throw e}finally{C===t&&(C=void 0)}};try{ce=y?en({path:j.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await Fs({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&un({device:_,mode:b,platform:i});let x=y?ce?.logger({scope:`dev.flutter`,properties:{platform:y,..._?{deviceId:_.id}:void 0}}):void 0;se=i&&_&&O!==void 0?await Ls({device:_,env:r,host:s,interactive:l,platform:i,port:O}):void 0;let C=se?.viteHost??(y?i?!0:`127.0.0.1`:s),te=O===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${O}`,fe=y===void 0?te:se?.serverUrl??Rs(y,void 0,O),k={},_e=!1,M;[k,_e]=await Promise.all([v.measure(`config`,()=>G({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await Jt(e))]),await v.measure(`i18n`,()=>Mr({cwd:e,projectConfig:k})),M=h!==`webext`&&k.dashboard?.enabled!==!1&&gi(e)?await li.getAvailablePort():void 0;let ve=await v.measure(`https`,async()=>c&&!pe?Xt({cwd:e}):void 0),ye=yc(r,h);D={...ye,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Zt]:K()}:void 0,...y?{COREFRAME_PLATFORM:y,[$t]:j.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...ve?{[Kt]:ve.cert,[qt]:ve.key}:void 0,...M?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${M}`}:void 0},te!==void 0&&fe!==void 0&&(le=await Ac({appOrigin:fe,cwd:e,device:_,flutterMcp:a,flutterMode:y===void 0?void 0:b,id:K(),localOrigin:te,platform:h}));let P=async()=>{if(!M)return;let t=_i({cwd:e,env:D,port:M});oe=t;try{await t.listen(),await t.wait()}finally{await t.close(),oe===t&&(oe=void 0)}},be=async()=>{let t=at({label:`web`}),n=at({color:`red`,label:`web`});t.pipe(q.stdout,{end:!1}),n.pipe(q.stderr,{end:!1}),re=F(pe?Hc:Uc,pe?Oc({host:C,lan:u,port:O}):nl({host:C,port:O,strictPort:h===`web`||y!==void 0}),{cwd:e,env:{...D,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[D.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:Bc+j.delimiter+ee},stdin:`inherit`});let r=Promise.allSettled([Qc(re.stdout,t),Qc(re.stderr,n)]);try{await re;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([it(t),it(n)]),re=void 0}},I=async()=>{let t=at({label:`webext`}),n=at({color:`red`,label:`webext`});t.pipe(q.stdout,{end:!1}),n.pipe(q.stderr,{end:!1}),ie=F(Vc,Lc({host:s,port:O}),{cwd:e,env:D,stdin:`inherit`});let r=Promise.allSettled([Qc(ie.stdout,t),Qc(ie.stderr,n)]);try{await ie;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([it(t),it(n)]),ie=void 0}},xe=async t=>{let n,r,i=!1,s,c=vc(D[$t],()=>{if(E||!n||!r||s||b!==`debug`&&i)return;let e=n,t=r;s=(async()=>{if(b===`debug`){await t.restart({debounce:!0,fullRestart:!0,reason:`manual`});return}i=!0;try{await t.stop()}catch(t){let n=t instanceof Error?t.message:String(t);x?.write(`warn`,`Flutter stop failed; terminating it: ${n}`,{properties:{stream:`control`}}),q.stderr.write(`Flutter stop failed; terminating it: ${n}\n`),await e.nodeChildProcess.then(e=>e.kill(`SIGTERM`))}})().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Flutter restart failed: ${t}`,{properties:{stream:`control`}}),q.stderr.write(`Flutter restart failed: ${t}\n`)}).finally(()=>{s=void 0})});try{for(;!E;){i=!1;let s=!1,c=h===`android`&&o===`filtered`&&!g?await ge():void 0,u=F(`flutter`,dn({device:_??{id:h},flutterDriver:a,mode:b,serverUrl:fe,verbose:g}),{cwd:j.join(e,`src-flutter`),env:cn(ye,{noCodesign:f}),stdio:[`pipe`,`pipe`,`pipe`]}),d=new uc({onEvent:async e=>{Jc(e.params.message)&&(s=!0),await le?.recordFlutterEvent(e)},verbose:g,write:async e=>{let t=await u.nodeChildProcess;if(!t.stdin)throw Error(`Flutter machine input is unavailable.`);t.stdin.write(e)===!1&&await Ut(t.stdin,`drain`)}}),p=e=>qc(dc(e,d),()=>s=!0);S=u,n=u,r=d;try{let e=!1;try{let e=c?c.capture(Zc(p(u),x,`output`)):Promise.all([Xc(p(u.stdout),q.stdout,x,`stdout`),Kc(u.stderr,q.stderr,x,`stderr`)]);await Promise.all([u,e])}catch{e=!0}if(i&&!E)continue;if(E)return;let n=l?await B.confirm({initialValue:!0,message:s?`${Wc} Restart Flutter?`:e?`Flutter failed. Retry?`:`Flutter exited unexpectedly. Restart Flutter?`}):!1;if(B.isCancel(n)||!n){if(!e&&!s){B.log.warn(`Flutter exited unexpectedly.`);return}B.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??he);return}}finally{S===u&&(S=void 0),n===u&&(n=void 0),r===d&&(r=void 0),d.close(),le?.recordFlutterExit().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Failed to record Flutter exit: ${t}`,{properties:{stream:`control`}})})}}}finally{(await c)()}},L=async()=>{if(h===`web`){await be();return}let t=be().then(()=>{if(!E)throw Error(`The Vite development server stopped while Flutter was still running.`)});await me({cwd:e});try{await Promise.race([t,xe(t)])}finally{A(),await Promise.allSettled([t,S]),S=void 0}},Se=async()=>{let t=ot({name:`panda`,command:Vc,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:D});ne=t;try{if(await t.expectSuccess(),!E)throw Error(`The Panda CSS watcher stopped while development was still running.`)}catch(e){if(!E)throw e}finally{ne===t&&(ne=void 0)}},Ce=async()=>{if(h===`webext`){await I();return}let e=Se(),t=L(),n=M?P():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),E&&await t}finally{A(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(_e&&(D={...D,[Qt]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(ue=await v.measure(`supervisor`,()=>Wt({cwd:e,env:r})))),E)return;if(h===`webext`){v.report(),await Ce();return}if(k.database?.dialect===`sqlite`){if(await v.measure(`database`,async()=>{let t=await de({config:k,cwd:e,env:r,tursoOutput:q.stdout,useSupervisorLease:!0});T=t,D={...D,...t.env}}),await v.measure(`schema`,()=>N({name:`db`,command:Vc,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E)return;ae({cwd:e,env:D,dialect:`sqlite`})}if(tl(k)){let t=at({label:`postgres`});t.pipe(q.stdout,{end:!1});try{let n=await v.measure(`database`,()=>el({config:k,cwd:e,env:D,failIfRunning:!0,interactive:l,isStopping:()=>E,postgresOutput:t,useSupervisorLease:!0}));if(!n)return;w=n,D={...D,...n.env};try{E||await v.measure(`schema`,()=>N({name:`db`,command:Vc,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E||(ae({cwd:e,env:D,dialect:`postgres`}),v.report(),await Ce())}finally{await n[Symbol.asyncDispose](),w===n&&(w=void 0)}}finally{t.end()}return}v.report(),await Ce()}finally{A(),await se?.close(),se=void 0;let e;try{await w?.[Symbol.asyncDispose]()}catch(t){e=t}finally{try{await _e()}finally{try{await le?.close()}finally{ue?.close(),ce?.close();for(let{handler:e,signal:t}of ve)q.off(t,e)}}fe&&(q.exitCode??=fe===`SIGINT`?130:143)}$c(e)}}async function Kc(e,t,n,r){for await(let i of Yc(e,n,r))t.write(`${i}\n`)||await Ut(t,`drain`)}async function*qc(e,t){for await(let n of e)Jc(n.message)&&t(),yield n}function Jc(e){return typeof e==`string`&&e.trim()===Wc}async function*Yc(e,t,n){for await(let r of e){let e=pe(r);e.message&&t?.write(e.level,e.message,{properties:{stream:n}}),yield r}}async function Xc(e,t,n,r){for await(let i of Zc(e,n,r))t.write(`${i}\n`)||await Ut(t,`drain`)}async function*Zc(e,t,n){for await(let r of e)r.message&&t?.write(r.level,r.message,{properties:{stream:n}}),yield r.message}async function Qc(e,t){for await(let n of e)t.write(`${n}\n`)||await Ut(t,`drain`)}function $c(e){if(e)throw e}async function el({interactive:e,isStopping:t,...n}){try{return await E(n)}catch(r){if(!(r instanceof h)||!e)throw r;let i=await B.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(B.isCancel(i)||!i){B.cancel(`Keeping the existing PostgreSQL process.`);return}return await fe(r),t()?void 0:E(n)}}function tl(e){return(e.database?.dialect??`postgres`)===`postgres`}function nl({host:e,port:t,strictPort:n=!1}){return[`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)],...n?[`--strictPort`]:[]]}function rl(e){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw Error(`COREFRAME_WEB_PORT must be a valid TCP port.`);return t}function il(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function al(e={}){let t=e.cwd??q.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await We(j.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await $e(n,t);if(!e.default||typeof e.default!=`object`)throw Error(`scripts/preview.ts must default-export preview hooks.`);for(let t of[`beforeBuild`,`afterBuild`])if(e.default[t]!==void 0&&typeof e.default[t]!=`function`)throw Error(`scripts/preview.ts ${t} must be a function.`);r=e.default}return rn({...e,cwd:t},r)}const ol=`worker-configuration.d.ts`;async function sl({check:e=!1,cwd:t=process.cwd()}={}){let n=await G({cwd:t}),r=await bt({coreframeConfig:n,cwd:t}),i=P(t,ol),a=P(t,`.coreframe-worker-types-${K()}.d.ts`);try{try{await F(`pnpm`,[`exec`,`wrangler`,`types`,a,`--config`,r.path,`--strict-vars=false`,`--include-runtime=false`],{cwd:t,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw cl(e),e}let o=ll(await H(a,`utf8`)),s=nt(r.config),c=et(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${ul(c)}\n`;if(e){if(await H(i,`utf8`).catch(()=>``)!==l)throw Error(`${ol} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await H(i,`utf8`).catch(()=>``);return u!==l&&await W(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await U(a,{force:!0})}}function cl(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
|
|
20
20
|
`)?t:`${t}\n`)}function ll(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
|
|
21
21
|
`)}function ul(e){return[`// Coreframe application string inventory declaration-merges with Wrangler's generated Env.`,`interface Env {`,...e.map(e=>` /** ${e.description.replaceAll(`*/`,`*\\/`)} */\n ${JSON.stringify(e.name)}?: string`),`}`].join(`
|
|
22
|
-
`)}const dl=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),fl=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],pl=[`dashboard`,`node_modules/@coreframe/dashboard/dist/package/app`,`node_modules/@coreframe/dashboard/package.json`,`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`],ml=[`coreframe.config.ts`,`node_modules/@coreframe/config/dist`,`node_modules/@coreframe/config/package.json`,`node_modules/@coreframe/deploy/dist`,`node_modules/@coreframe/deploy/package.json`,`node_modules/wrangler/package.json`,`package.json`,`pnpm-lock.yaml`,`src/api`,`wrangler.jsonc`],hl=`.coreframe/typegen.json`,gl=[`web`,`dashboard`,`worker`];async function _l({checkWorker:e=!1,cwd:t=J.cwd(),runners:n={}}={}){let r=await xl(t)??{generators:{},schemaVersion:1},i=[];return i.push(await yl({cwd:t,inputPaths:fl,name:`web`,outputPath:`.react-router`,run:()=>(n.web??bl)(t),state:r})),i.push(await yl({cwd:t,inputPaths:pl,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??ri)(t),state:r})),i.push(await yl({cwd:t,inputPaths:ml,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??sl)({check:e,cwd:t}),state:r})),i}function vl(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function yl({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await Cl(e,t),s=await wl(e,r),c=a.generators[n];if(s&&c?.inputFingerprint===o&&c.outputFingerprint===s)return{changed:!1,name:n,ran:!1};await i();let l=await wl(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await Sl(e,a),{changed:s!==l,name:n,ran:!0}}async function bl(e){let t=J.platform===`win32`?`react-router.cmd`:`react-router`,n=J.env;await I(t,[`typegen`],{cwd:e,env:{...n,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function xl(e){try{let t=JSON.parse(await U(M.resolve(e,hl),`utf8`));if(!Ol(t)||t.schemaVersion!==1)return;let n={};if(!Ol(t.generators))return;for(let e of gl){let r=t.generators[e];Ol(r)&&typeof r.inputFingerprint==`string`&&typeof r.outputFingerprint==`string`&&(n[e]={inputFingerprint:r.inputFingerprint,outputFingerprint:r.outputFingerprint})}return{generators:n,schemaVersion:1}}catch{return}}async function Sl(e,t){let n=M.resolve(e,hl);await H(M.dirname(n),{recursive:!0}),await G(n,`${JSON.stringify(t)}\n`,{mode:384})}async function Cl(e,t){let n=nt(`sha256`);for(let r of[...t].sort()){let t=M.resolve(e,r),i=await El(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Tl(t)){let i=M.join(t,r),a=M.relative(e,i).split(M.sep).join(`/`);n.update(`${a}\0`),n.update(await U(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await U(t)))}return n.digest(`hex`)}async function wl(e,t){if(await El(M.resolve(e,t)))return Cl(e,[t])}async function Tl(e){let t=[];async function n(e,r){let i=await Je(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(dl.has(a.name))continue;await n(M.join(e,a.name),M.join(r,a.name))}else a.isFile()&&t.push(M.join(r,a.name))}return await n(e,``),t.sort()}async function El(e){try{return await Xe(e)}catch(e){if(Dl(e))return;throw e}}function Dl(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Ol(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const kl=M.resolve(`node_modules`,`.bin`);J.env.PATH=kl+M.delimiter+J.env.PATH;const Al=J.platform===`win32`?`tsc.cmd`:`tsc`,jl=[{name:`scripts`,path:`scripts/tsconfig.json`},{name:`shared`,path:`src/shared/tsconfig.json`},{name:`api`,path:`src/api/tsconfig.json`},{name:`worker`,path:`src/api/worker/tsconfig.json`},{name:`web`,path:`src/web/tsconfig.json`},{name:`dashboard`,path:`dashboard/tsconfig.json`}];async function Ml(){await _l({checkWorker:!0});let e=[];for(let t of jl)try{await Ue(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>at({name:e.name,command:Al,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(J.exitCode=n[0].exitCode)}const Nl=r(s(zc),{displayName:`feature`,from:async e=>e}),Pl=r(s(on),{displayName:`filtered|full`,from:async e=>e}),Fl=[`Cookies and sessions are origin-scoped.`,`Exact-host passkeys may require re-registration unless a stable eligible parent RP ID was configured in advance.`,`External OAuth callbacks such as Google may need updating.`,`Database data and private backend resources are unchanged.`],Il=n({name:`deploy`,args:{environment:u({type:s(pt),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:i({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:i({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:i({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>$o([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),Ll=m({name:`staging`,cmds:{reassign:n({name:`reassign`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await kt();if(e){console.log(JSON.stringify({...t,notices:Fl}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Fl.join(` `)}`)}}),url:n({name:`url`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ht();console.log(e?JSON.stringify({url:t}):t)}})}}),Rl=m({name:`secrets`,cmds:{"rotate-access-token":n({name:`rotate-access-token`,args:{environment:u({type:s(pt),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:i({long:`yes`,short:`y`,description:`Confirm immediate signing-secret replacement and invalidation of outstanding access JWTs.`,defaultValue:()=>!1})},handler:async({environment:e,yes:t})=>{if(!t)throw Error(`Access-token signing-secret rotation requires --yes because it immediately invalidates outstanding access JWTs.`);await Pt({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:n({name:`status`,args:{environment:u({type:l(s(pt)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await gt({environment:e});console.log(t?JSON.stringify(n):Wl(n))}}),set:n({name:`set`,args:{environment:u({type:s(pt),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:u({type:l(p),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:i({long:`bulk`,description:`Queue known secrets from pasted or piped dotenv-formatted contents.`,defaultValue:()=>!1})},handler:async({environment:e,name:t,bulk:n})=>{if(n&&t)throw Error(`Use either a secret name or --bulk, not both.`);if(t){await Ct({environment:e,name:t,value:await Gl(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await Tt(),i=n?await ql(r):await Kl(r,e);await wt({environment:e,values:i});let a=Object.keys(i).sort();console.log(a.length>0?`Queued ${a.join(`, `)} for ${e}. Run coreframe deploy ${e} to apply.`:`No ${e} Worker secret updates were queued.`)}}),discard:n({name:`discard`,args:{environment:u({type:s(pt),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:u({type:p,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await mt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),zl=n({name:`typecheck`,args:{},handler:Ml}),Bl=m({name:`worker`,cmds:{typegen:n({name:`typegen`,args:{check:i({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await sl({check:e});console.log(e?`${Yl(t.path)} is current.`:`${Yl(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),Vl=n({name:`dev`,args:{debug:c({long:`debug`,type:l(Nl),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:i({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:i({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:c({long:`flutter-output`,type:Pl,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:i({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:c({long:`host`,type:l(p),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:i({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:i({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:i({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:i({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:i({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:u({type:l(s(Rc)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:u({type:l(p),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:c({long:`port`,type:l(o),description:`Port for the web development server.`}),verbose:i({long:`verbose`,description:`Show the full native development output.`,defaultValue:()=>!1})},handler:({debug:e,device:t,flutterDebug:n,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f,port:p,simulator:m,verbose:h})=>{let g=Hl({device:t,flutterDebug:n,platform:f,simulator:m});return Gc({debug:e,device:g.device,flutterDebug:g.flutterDebug,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f??`web`,verbose:h,webPort:p})}});function Hl({device:e,flutterDebug:t,platform:n,simulator:r}){if(!r)return{device:e,flutterDebug:t};if(n!==`ios`)throw Error(`The --simulator flag is only supported for the iOS development target.`);if(e!==void 0)throw Error(`The --simulator flag cannot be combined with an explicit device.`);return{device:`apple_ios_simulator`,flutterDebug:!0}}const Ul=n({name:`preview`,args:{host:c({long:`host`,type:l(p),description:`Host address for the preview server.`}),port:c({long:`port`,type:l(o),description:`Port for the preview server.`})},handler:({host:e,port:t})=>al({host:e,port:t})});function Wl(e){if(e.entries.length===0)return`No Worker environment values are declared in coreframe.config.ts.`;let t=e.entries.map(e=>[e.name,e.kind,e.local===`override`?`override`:`built-in default`,e.deployed.staging.replaceAll(`_`,` `),e.deployed.production.replaceAll(`_`,` `)]),n=[`Name`,`Kind`,`Local`,`Staging`,`Production`],r=n.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),i=(e,t=` `)=>e.map((e,n)=>e.padEnd(r[n],t)).join(` | `).trimEnd();return[i(n),i(r.map(e=>``.padEnd(e,`-`)),`-`),...t.map(e=>i(e))].join(`
|
|
23
|
-
`)}async function Gl(e){if(!
|
|
22
|
+
`)}const dl=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),fl=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],pl=[`dashboard`,`node_modules/@coreframe/dashboard/dist/package/app`,`node_modules/@coreframe/dashboard/package.json`,`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`],ml=[`coreframe.config.ts`,`node_modules/@coreframe/config/dist`,`node_modules/@coreframe/config/package.json`,`node_modules/@coreframe/deploy/dist`,`node_modules/@coreframe/deploy/package.json`,`node_modules/wrangler/package.json`,`package.json`,`pnpm-lock.yaml`,`src/api`,`wrangler.jsonc`],hl=`.coreframe/typegen.json`,gl=[`web`,`dashboard`,`worker`];async function _l({checkWorker:e=!1,cwd:t=q.cwd(),runners:n={}}={}){let r=await xl(t)??{generators:{},schemaVersion:1},i=[];return i.push(await yl({cwd:t,inputPaths:fl,name:`web`,outputPath:`.react-router`,run:()=>(n.web??bl)(t),state:r})),i.push(await yl({cwd:t,inputPaths:pl,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??ii)(t),state:r})),i.push(await yl({cwd:t,inputPaths:ml,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??sl)({check:e,cwd:t}),state:r})),i}function vl(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function yl({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await Cl(e,t),s=await wl(e,r),c=a.generators[n];if(s&&c?.inputFingerprint===o&&c.outputFingerprint===s)return{changed:!1,name:n,ran:!1};await i();let l=await wl(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await Sl(e,a),{changed:s!==l,name:n,ran:!0}}async function bl(e){let t=q.platform===`win32`?`react-router.cmd`:`react-router`,n=q.env;await F(t,[`typegen`],{cwd:e,env:{...n,PATH:j.resolve(e,`node_modules/.bin`)+j.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function xl(e){try{let t=JSON.parse(await H(j.resolve(e,hl),`utf8`));if(!Ol(t)||t.schemaVersion!==1)return;let n={};if(!Ol(t.generators))return;for(let e of gl){let r=t.generators[e];Ol(r)&&typeof r.inputFingerprint==`string`&&typeof r.outputFingerprint==`string`&&(n[e]={inputFingerprint:r.inputFingerprint,outputFingerprint:r.outputFingerprint})}return{generators:n,schemaVersion:1}}catch{return}}async function Sl(e,t){let n=j.resolve(e,hl);await V(j.dirname(n),{recursive:!0}),await W(n,`${JSON.stringify(t)}\n`,{mode:384})}async function Cl(e,t){let n=rt(`sha256`);for(let r of[...t].sort()){let t=j.resolve(e,r),i=await El(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Tl(t)){let i=j.join(t,r),a=j.relative(e,i).split(j.sep).join(`/`);n.update(`${a}\0`),n.update(await H(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await H(t)))}return n.digest(`hex`)}async function wl(e,t){if(await El(j.resolve(e,t)))return Cl(e,[t])}async function Tl(e){let t=[];async function n(e,r){let i=await Ye(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(dl.has(a.name))continue;await n(j.join(e,a.name),j.join(r,a.name))}else a.isFile()&&t.push(j.join(r,a.name))}return await n(e,``),t.sort()}async function El(e){try{return await Ze(e)}catch(e){if(Dl(e))return;throw e}}function Dl(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Ol(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const kl=j.resolve(`node_modules`,`.bin`);q.env.PATH=kl+j.delimiter+q.env.PATH;const Al=q.platform===`win32`?`tsc.cmd`:`tsc`,jl=[{name:`scripts`,path:`scripts/tsconfig.json`},{name:`shared`,path:`src/shared/tsconfig.json`},{name:`api`,path:`src/api/tsconfig.json`},{name:`worker`,path:`src/api/worker/tsconfig.json`},{name:`web`,path:`src/web/tsconfig.json`},{name:`dashboard`,path:`dashboard/tsconfig.json`}];async function Ml(){await _l({checkWorker:!0});let e=[];for(let t of jl)try{await We(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>ot({name:e.name,command:Al,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(q.exitCode=n[0].exitCode)}const Nl=r(s(zc),{displayName:`feature`,from:async e=>e}),Pl=r(s(sn),{displayName:`filtered|full`,from:async e=>e}),Fl=[`Cookies and sessions are origin-scoped.`,`Exact-host passkeys may require re-registration unless a stable eligible parent RP ID was configured in advance.`,`External OAuth callbacks such as Google may need updating.`,`Database data and private backend resources are unchanged.`],Il=n({name:`deploy`,args:{environment:u({type:s(mt),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:i({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:i({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:i({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>$o([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),Ll=m({name:`staging`,cmds:{reassign:n({name:`reassign`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await At();if(e){console.log(JSON.stringify({...t,notices:Fl}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Fl.join(` `)}`)}}),url:n({name:`url`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await gt();console.log(e?JSON.stringify({url:t}):t)}})}}),Rl=m({name:`secrets`,cmds:{"rotate-access-token":n({name:`rotate-access-token`,args:{environment:u({type:s(mt),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:i({long:`yes`,short:`y`,description:`Confirm immediate signing-secret replacement and invalidation of outstanding access JWTs.`,defaultValue:()=>!1})},handler:async({environment:e,yes:t})=>{if(!t)throw Error(`Access-token signing-secret rotation requires --yes because it immediately invalidates outstanding access JWTs.`);await Ft({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:n({name:`status`,args:{environment:u({type:l(s(mt)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await _t({environment:e});console.log(t?JSON.stringify(n):Wl(n))}}),set:n({name:`set`,args:{environment:u({type:s(mt),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:u({type:l(p),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:i({long:`bulk`,description:`Queue known secrets from pasted or piped dotenv-formatted contents.`,defaultValue:()=>!1})},handler:async({environment:e,name:t,bulk:n})=>{if(n&&t)throw Error(`Use either a secret name or --bulk, not both.`);if(t){await wt({environment:e,name:t,value:await Gl(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await Et(),i=n?await ql(r):await Kl(r,e);await Tt({environment:e,values:i});let a=Object.keys(i).sort();console.log(a.length>0?`Queued ${a.join(`, `)} for ${e}. Run coreframe deploy ${e} to apply.`:`No ${e} Worker secret updates were queued.`)}}),discard:n({name:`discard`,args:{environment:u({type:s(mt),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:u({type:p,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await ht({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),zl=n({name:`typecheck`,args:{},handler:Ml}),Bl=m({name:`worker`,cmds:{typegen:n({name:`typegen`,args:{check:i({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await sl({check:e});console.log(e?`${Yl(t.path)} is current.`:`${Yl(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),Vl=n({name:`dev`,args:{debug:c({long:`debug`,type:l(Nl),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:i({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:i({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:c({long:`flutter-output`,type:Pl,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:i({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:c({long:`host`,type:l(p),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:i({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:i({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:i({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:i({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:i({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:u({type:l(s(Rc)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:u({type:l(p),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:c({long:`port`,type:l(o),description:`Port for the web development server.`}),verbose:i({long:`verbose`,description:`Show the full native development output.`,defaultValue:()=>!1})},handler:({debug:e,device:t,flutterDebug:n,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f,port:p,simulator:m,verbose:h})=>{let g=Hl({device:t,flutterDebug:n,platform:f,simulator:m});return Gc({debug:e,device:g.device,flutterDebug:g.flutterDebug,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f??`web`,verbose:h,webPort:p})}});function Hl({device:e,flutterDebug:t,platform:n,simulator:r}){if(!r)return{device:e,flutterDebug:t};if(n!==`ios`)throw Error(`The --simulator flag is only supported for the iOS development target.`);if(e!==void 0)throw Error(`The --simulator flag cannot be combined with an explicit device.`);return{device:`apple_ios_simulator`,flutterDebug:!0}}const Ul=n({name:`preview`,args:{host:c({long:`host`,type:l(p),description:`Host address for the preview server.`}),port:c({long:`port`,type:l(o),description:`Port for the preview server.`})},handler:({host:e,port:t})=>al({host:e,port:t})});function Wl(e){if(e.entries.length===0)return`No Worker environment values are declared in coreframe.config.ts.`;let t=e.entries.map(e=>[e.name,e.kind,e.local===`override`?`override`:`built-in default`,e.deployed.staging.replaceAll(`_`,` `),e.deployed.production.replaceAll(`_`,` `)]),n=[`Name`,`Kind`,`Local`,`Staging`,`Production`],r=n.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),i=(e,t=` `)=>e.map((e,n)=>e.padEnd(r[n],t)).join(` | `).trimEnd();return[i(n),i(r.map(e=>``.padEnd(e,`-`)),`-`),...t.map(e=>i(e))].join(`
|
|
23
|
+
`)}async function Gl(e){if(!q.stdin.isTTY){let e=``;for await(let t of q.stdin)e+=t.toString();return e.replace(/\r?\n$/,``)}let t=await B.password({message:`Enter the new value for ${e}`});if(B.isCancel(t))throw B.cancel(`Secret update cancelled.`),Error(`Secret update cancelled.`);return t}async function Kl(e,t){if(!q.stdin.isTTY)throw Error(`Interactive secret setup requires a terminal. Provide a secret name or use --bulk with piped dotenv contents.`);if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let n={};for(let r of e){let e=r.requiredIn.includes(t),i=await B.password({message:`${r.name}: ${r.description}${e?` (required)`:` (optional; leave blank to skip)`}`,validate:n=>e&&!n?.trim()?`${r.name} is required in ${t}.`:void 0});if(B.isCancel(i))throw B.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);i.trim()&&(n[r.name]=i)}return n}async function ql(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=q.stdin.isTTY?await B.multiline({message:`Paste dotenv-formatted Worker secrets. Press Enter twice to submit.`,validate:e=>e?.trim()?void 0:`Paste at least one dotenv entry.`}):await Jl();if(B.isCancel(t))throw B.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=xt(t,e);return n.length>0&&B.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function Jl(){let e=``;for await(let t of q.stdin)e+=t.toString();return e}function Yl(e){return e.split(/[\\/]/).at(-1)??e}const Xl=n({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await _l();for(let t of e)console.log(vl(t))}});function Zl(e,{formatMessage:t,temporaryDirectory:n=je(),write:r=e=>console.error(e)}={}){let i=ru(e),a=ou($l(e,t),i);try{let t=N(we(N(n,`coreframe-error-`)),`error.log`);return z(t,`${ou(eu(e),i)}\n`,{mode:384}),r(`Error: ${a}\nFull diagnostic: ${t}`),t}catch{r(`Error: ${a}\nThe full diagnostic could not be written to the temporary directory.`);return}}function Ql(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,Zl(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function $l(e,t){try{return t?.(e)||(e instanceof Error?e.message:String(e)).split(/\r?\n/,1)[0]||`Unknown error`}catch{return`Unknown error`}}function eu(e){try{let t=tu(e);if(!(e instanceof Error)||!nu(t))return Vt(t,{customInspect:!1,depth:10});let n=typeof t.stack==`string`?t.stack:`${e.name}: ${e.message}`;return delete t.name,delete t.message,delete t.stack,`${n}${Reflect.ownKeys(t).length?`\n${Vt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function tu(e,t=new WeakMap){if((typeof e!=`object`||!e)&&typeof e!=`function`)return e;let n=e,r=t.get(n);if(r)return r;if(typeof e==`function`)return`[Function${e.name?`: ${e.name}`:``}]`;let i=Array.isArray(e)?[]:{};t.set(n,i),e instanceof Error&&(i.name=e.name,i.message=e.message,i.stack=e.stack??`${e.name}: ${e.message}`);for(let r of Reflect.ownKeys(n)){if(typeof r!=`string`||r.toLowerCase()===`env`||Array.isArray(e)&&r===`length`||e instanceof Error&&(r===`name`||r===`message`||r===`stack`))continue;let a=Object.getOwnPropertyDescriptor(n,r);!a||!(`value`in a)||Object.defineProperty(i,r,{configurable:!0,enumerable:!0,value:tu(a.value,t),writable:!0})}return i}function nu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ru(e,t=new WeakSet){let n=new Set;function r(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let i=e;if(!t.has(i)){t.add(i);for(let e of Reflect.ownKeys(i)){if(typeof e!=`string`)continue;let t=Object.getOwnPropertyDescriptor(i,e);!t||!(`value`in t)||(e.toLowerCase()===`env`?iu(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function iu(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&au(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function au(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function ou(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const su=m({name:`coreframe`,cmds:{build:wn,conflicts:qn,dashboard:bi,assets:$r,flutter:ei,i18n:ti,jobs:Ri,deploy:Il,staging:Ll,secrets:Rl,typegen:Xl,typecheck:zl,worker:Bl,dev:Vl,preview:Ul,upgrade:Yo,recipes:Xo,db:Zo}});import.meta.main&&Ql(su,{formatMessage:process.argv[2]===`db`?w:void 0});export{su as coreframeCli};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreframe/scripts",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.49",
|
|
4
4
|
"description": "Coreframe project workflow CLI and automation scripts",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -29,16 +29,16 @@
|
|
|
29
29
|
"nano-spawn": "^2.1.0",
|
|
30
30
|
"procband": "^0.3.9",
|
|
31
31
|
"yaml": "^2.9.0",
|
|
32
|
-
"@coreframe/db": "^0.1.26",
|
|
33
32
|
"@coreframe/config": "^0.1.18",
|
|
33
|
+
"@coreframe/db": "^0.1.27",
|
|
34
|
+
"@coreframe/assets": "^0.1.21",
|
|
34
35
|
"@coreframe/deploy": "^0.1.19",
|
|
35
|
-
"@coreframe/dev
|
|
36
|
+
"@coreframe/dev": "^0.1.34",
|
|
37
|
+
"@coreframe/dev-contracts": "^0.1.12",
|
|
36
38
|
"@coreframe/flutter-tools": "^0.1.30",
|
|
37
|
-
"@coreframe/
|
|
39
|
+
"@coreframe/jobs": "^0.1.1",
|
|
38
40
|
"@coreframe/object-storage": "^0.1.4",
|
|
39
|
-
"@coreframe/
|
|
40
|
-
"@coreframe/preview": "^0.1.26",
|
|
41
|
-
"@coreframe/jobs": "^0.1.1"
|
|
41
|
+
"@coreframe/preview": "^0.1.27"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/node": "^26.1.0",
|