@coreframe/scripts 0.2.26 → 0.2.28

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.
Files changed (2) hide show
  1. package/dist/coreframe.js +15 -15
  2. package/package.json +9 -9
package/dist/coreframe.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import*as e from"@alloc/cmd-ts";import{command as t,extendType as n,flag as r,number as i,oneOf as a,option as o,optional as s,positional as c,rest as l,string as u,subcommands as d}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as f,checkDeployMigrations as p,checkSchemaPush as m,collectDeployMigrationFiles as h,createProjectPostgresDatabaseAdapter as g,createProjectSqliteDatabaseAdapter as _,ensureLocalDb as v,filterPendingMigrations as ee,formatDbErrorMessage as y,formatMigrationList as b,formatMigrationScanFailures as x,migrateHeldMigrations as S,migrateLocalDb as C,readAppliedMigrationNames as w,resetLocalDb as te,runDrizzleKitCommand as T,scanDeployMigrationFiles as ne,seedLocalDb as re,setupLocalDb as ie,startProjectPostgres as ae,startProjectTurso as oe,stopProjectPostgres as se}from"@coreframe/db";import{checkFlutterClient as ce,classifyFlutterDevOutputLine as le,ensureFlutterDevAssetDirectories as ue,flutterPlatforms as E,generateFlutterNativeBridge as de,prepareFlutterClient as D,prepareFlutterDevOutput as fe,productionApiOrigin as O,runFlutterAcceptance as k}from"@coreframe/flutter-tools";import A,{dirname as j,isAbsolute as pe,join as M,posix as N,resolve as P,sep as F}from"node:path";import I from"nano-spawn";import*as L from"@clack/prompts";import{addAsset as me,backupAssets as he,buildAssets as ge,checkAssets as _e,printAssetResult as ve,publishAssets as ye}from"@coreframe/assets";import{assertAssetCredentialProfile as be,configureAssetCredentials as xe,createB2PrivateObjectStore as Se}from"@coreframe/object-storage";import{access as Ce,chmod as we,copyFile as Te,cp as Ee,mkdir as R,mkdtemp as De,readFile as z,readdir as Oe,rename as ke,rm as B,stat as Ae,writeFile as V}from"node:fs/promises";import{homedir as je,networkInterfaces as Me,tmpdir as Ne}from"node:os";import{importProjectDependency as Pe,importProjectModule as Fe,normalizeWorkerEnvironment as Ie,readProjectConfig as H,wranglerEnvironmentNames as Le}from"@coreframe/config";import{createHash as Re,randomUUID as U}from"node:crypto";import W from"node:process";import{chmodSync as ze,existsSync as G,lstatSync as Be,mkdirSync as Ve,mkdtempSync as He,readFileSync as K,readlinkSync as Ue,rmSync as We,symlinkSync as Ge,watch as Ke,writeFileSync as q}from"node:fs";import{finished as qe}from"node:stream/promises";import{createPrefixStream as J,supervise as Je}from"procband";import{createConnection as Ye,createServer as Xe}from"node:net";import{spawnSync as Y}from"node:child_process";import{parse as Ze,stringify as Qe}from"yaml";import{accessTokenSigningSecretName as $e,clearAppliedPendingWorkerSecrets as et,deployEnvironments as tt,discardPendingWorkerSecret as nt,discoverStagingUrl as rt,inspectWorkerEnvironment as it,materializeBuiltClientDeployConfig as at,materializePrimaryWorkerConfig as ot,materializePrimaryWorkerTypeConfig as st,parseDeclaredWorkerSecretEnv as ct,prepareAccessTokenSigningSecret as lt,queueWorkerSecret as ut,queueWorkerSecrets as dt,readDeclaredWorkerSecrets as ft,readPackageJson as pt,readPendingWorkerSecretSnapshot as mt,reassignStagingHostname as ht,releaseName as gt,resolveDeployConfig as _t,resolveReleaseVersion as vt,rotateAccessTokenSigningSecret as yt,runAfterWorkerDeploy as bt,runPostDeployChecks as xt,validateWorkerEnvironmentForDeploy as St,verifyAccessTokenSigningSecret as Ct,writePackageVersion as wt}from"@coreframe/deploy";import{inspect as Tt,parseEnv as Et}from"node:util";import{once as Dt}from"node:events";import{createDevStartupTiming as Ot,devHttpsCertEnv as kt,devHttpsKeyEnv as At,isManagedDevCheckout as jt,isPrimaryCheckout as Mt,prepareDevHttps as Nt}from"@coreframe/dev";import{devJobsEnv as Pt}from"@coreframe/dev-contracts/dev-jobs";import{managedDevEnv as Ft,managedDevFlutterRestartFileEnv as It}from"@coreframe/dev-contracts/managed-dev";import{openScopedLogs as Lt}from"leylines";import{setTimeout as Rt}from"node:timers/promises";import{determineAgent as zt}from"@vercel/detect-agent";import{runPreview as Bt}from"@coreframe/preview";const Vt=`FLUTTER_XCODE_COREFRAME_BUNDLE_IDENTIFIER_SUFFIX`,Ht=`COREFRAME_FLUTTER_DEVELOPMENT`,Ut=[`filtered`,`full`];function Wt(e,{noCodesign:t=!1}={}){return{...e,[Vt]:`.dev`,[Ht]:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function Gt(e=!1){return e?`debug`:`profile`}function Kt({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 qt({device:e,flutterDriver:t,mode:n,serverUrl:r,verbose:i}){return[`run`,`--${n}`,`-d`,e.id,`--dart-define=COREFRAME_DEV_SERVER_URL=${r}`,...t?[`--dart-define=ENABLE_FLUTTER_DRIVER=true`]:[],...i?[`--verbose`]:[]]}const Jt=[`web`,...E];function Yt(e=`web`,{apiOrigin:t,cwd:n=process.cwd(),profile:r=!1,simulator:i=!1}={}){if(nn(e,{profile:r,simulator:i}),e===`web`)return[an(`pnpm`,[`build`],n,{COREFRAME_PLATFORM:`web`})];let a=O(t);return[{kind:`prepare`,platform:e},an(`flutter`,Xt(e,a,{profile:r,simulator:i}),P(n,`src-flutter`),{COREFRAME_API_ORIGIN:a})]}function Xt(e,t,{noCodesign:n=e===`macos`,profile:r=!1,simulator:i=!1}={}){nn(e,{profile:r,simulator:i});let a=O(t);return[`build`,e===`android`?`apk`:e,r?`--profile`:`--release`,...i?[`--simulator`]:[],...n?[`--no-codesign`]:[],`--dart-define=COREFRAME_API_ORIGIN=${a}`]}function Zt(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 Qt(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(`
2
+ import*as e from"@alloc/cmd-ts";import{command as t,extendType as n,flag as r,number as i,oneOf as a,option as o,optional as s,positional as c,rest as l,string as u,subcommands as d}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as f,checkDeployMigrations as p,checkSchemaPush as m,collectDeployMigrationFiles as h,createProjectPostgresDatabaseAdapter as g,createProjectSqliteDatabaseAdapter as _,ensureLocalDb as v,filterPendingMigrations as ee,formatDbErrorMessage as y,formatMigrationList as b,formatMigrationScanFailures as x,migrateHeldMigrations as S,migrateLocalDb as C,readAppliedMigrationNames as w,resetLocalDb as te,runDrizzleKitCommand as T,scanDeployMigrationFiles as ne,seedLocalDb as re,setupLocalDb as ie,startProjectPostgres as ae,startProjectTurso as oe,stopProjectPostgres as se}from"@coreframe/db";import{checkFlutterClient as ce,classifyFlutterDevOutputLine as le,ensureFlutterDevAssetDirectories as ue,flutterPlatforms as de,generateFlutterNativeBridge as E,prepareFlutterClient as D,prepareFlutterDevOutput as fe,productionApiOrigin as O,runFlutterAcceptance as pe}from"@coreframe/flutter-tools";import k,{dirname as A,isAbsolute as j,join as M,posix as N,resolve as P,sep as F}from"node:path";import I from"nano-spawn";import*as L from"@clack/prompts";import{addAsset as me,backupAssets as he,buildAssets as ge,checkAssets as _e,printAssetResult as R,publishAssets as ve}from"@coreframe/assets";import{assertAssetCredentialProfile as ye,configureAssetCredentials as be,createB2PrivateObjectStore as xe}from"@coreframe/object-storage";import{access as z,chmod as Se,copyFile as Ce,cp as we,mkdir as B,mkdtemp as Te,readFile as V,readdir as Ee,rename as De,rm as H,stat as Oe,writeFile as U}from"node:fs/promises";import{homedir as ke,networkInterfaces as Ae,tmpdir as je}from"node:os";import{importProjectDependency as Me,importProjectModule as Ne,normalizeWorkerEnvironment as Pe,readProjectConfig as W,wranglerEnvironmentNames as Fe}from"@coreframe/config";import{createHash as Ie,randomUUID as G}from"node:crypto";import K from"node:process";import{chmodSync as Le,existsSync as q,lstatSync as Re,mkdirSync as ze,mkdtempSync as Be,readFileSync as J,readlinkSync as Ve,rmSync as He,symlinkSync as Ue,watch as We,writeFileSync as Ge}from"node:fs";import{finished as Ke}from"node:stream/promises";import{createPrefixStream as qe,supervise as Je}from"procband";import{createConnection as Ye,createServer as Xe}from"node:net";import{spawnSync as Y}from"node:child_process";import{parse as Ze,stringify as Qe}from"yaml";import{accessTokenSigningSecretName as $e,clearAppliedPendingWorkerSecrets as et,deployEnvironments as tt,discardPendingWorkerSecret as nt,discoverStagingUrl as rt,inspectWorkerEnvironment as it,materializeBuiltClientDeployConfig as at,materializePrimaryWorkerConfig as ot,materializePrimaryWorkerTypeConfig as st,parseDeclaredWorkerSecretEnv as ct,prepareAccessTokenSigningSecret as lt,queueWorkerSecret as ut,queueWorkerSecrets as dt,readDeclaredWorkerSecrets as ft,readPackageJson as pt,readPendingWorkerSecretSnapshot as mt,reassignStagingHostname as ht,releaseName as gt,resolveDeployConfig as _t,resolveReleaseVersion as vt,rotateAccessTokenSigningSecret as yt,runAfterWorkerDeploy as bt,runPostDeployChecks as xt,validateWorkerEnvironmentForDeploy as St,verifyAccessTokenSigningSecret as Ct,writePackageVersion as wt}from"@coreframe/deploy";import{inspect as Tt,parseEnv as Et}from"node:util";import{once as Dt}from"node:events";import{connectDevSupervisor as Ot,createDevStartupTiming as kt,devHttpsCertEnv as At,devHttpsKeyEnv as jt,isManagedDevCheckout as Mt,isPrimaryCheckout as Nt,prepareDevHttps as Pt}from"@coreframe/dev";import{devJobsEnv as Ft}from"@coreframe/dev-contracts/dev-jobs";import{managedDevEnv as It,managedDevFlutterRestartFileEnv as Lt}from"@coreframe/dev-contracts/managed-dev";import{openScopedLogs as Rt}from"leylines";import{setTimeout as zt}from"node:timers/promises";import{determineAgent as Bt}from"@vercel/detect-agent";import{runPreview as Vt}from"@coreframe/preview";const Ht=`FLUTTER_XCODE_COREFRAME_BUNDLE_IDENTIFIER_SUFFIX`,Ut=`COREFRAME_FLUTTER_DEVELOPMENT`,Wt=[`filtered`,`full`];function Gt(e,{noCodesign:t=!1}={}){return{...e,[Ht]:`.dev`,[Ut]:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function Kt(e=!1){return e?`debug`:`profile`}function qt({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 Jt({device:e,flutterDriver:t,mode:n,serverUrl:r,verbose:i}){return[`run`,`--${n}`,`-d`,e.id,`--dart-define=COREFRAME_DEV_SERVER_URL=${r}`,...t?[`--dart-define=ENABLE_FLUTTER_DRIVER=true`]:[],...i?[`--verbose`]:[]]}const Yt=[`web`,...de];function Xt(e=`web`,{apiOrigin:t,cwd:n=process.cwd(),profile:r=!1,simulator:i=!1}={}){if(rn(e,{profile:r,simulator:i}),e===`web`)return[on(`pnpm`,[`build`],n,{COREFRAME_PLATFORM:`web`})];let a=O(t);return[{kind:`prepare`,platform:e},on(`flutter`,Zt(e,a,{profile:r,simulator:i}),P(n,`src-flutter`),{COREFRAME_API_ORIGIN:a})]}function Zt(e,t,{noCodesign:n=e===`macos`,profile:r=!1,simulator:i=!1}={}){rn(e,{profile:r,simulator:i});let a=O(t);return[`build`,e===`android`?`apk`:e,r?`--profile`:`--release`,...i?[`--simulator`]:[],...n?[`--no-codesign`]:[],`--dart-define=COREFRAME_API_ORIGIN=${a}`]}function Qt(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 $t(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 $t(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 en(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 tn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=D,runCommand:s=rn}={}){nn(r,{profile:i,simulator:a});let c={...n};delete c[Vt],delete c[Ht],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:O(e??n.COREFRAME_API_ORIGIN);for(let e of Yt(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(Zt(t,{profile:i})):r===`ios`?console.log(Qt(t,{profile:i,simulator:a})):r===`windows`?console.log($t(t)):r===`linux`&&console.log(en(t))}function nn(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 rn(e,t,{cwd:n,env:r}){await I(e,t,{cwd:n,env:r,stdio:`inherit`})}function an(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const on=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return O(e)}}),sn=t({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:c({type:s(a(Jt)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:o({long:`api-origin`,type:s(on),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:r({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>tn({apiOrigin:e,platform:t,profile:n,simulator:r})}),cn=/^[a-f0-9]{64}$/,ln=/^[a-f0-9]{40}$/,un=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function dn(e){if(!cn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function fn(e){if(!ln.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function pn(e,t){if(!un.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function mn(e){return`projects/${pn(e,`Project ID`)}/i18n/v1`}function hn(e,t){return dn(t),`${mn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function gn(e,t){return fn(t),`${mn(e)}/commits/${t}.json`}function _n(e,t){return vn(t),`${mn(e)}/releases/${encodeURIComponent(t)}.json`}function vn(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=P(e),r=P(n,t);if(r!==n&&!r.startsWith(`${n}${F}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function Z(e,t,n){return`${e.directory}/${t}/${n}.json`}function yn(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function bn(e){await I(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function xn({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 En(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=M(r,`${n}-${a}.json`);await R(j(l),{recursive:!0}),await Te(o,l),i.push({path:o,backup:l}),await Dn(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 Te(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await B(X(t,yn(e,n,r)),{force:!0})}}}async function Sn({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 En(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)=>Mn(e).localeCompare(Mn(t)))}async function Cn({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 On(await kn({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function wn({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[Mn(e),e])),a=new Map;for(let e of r.translations){let t=Mn(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 Pe(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(Mn(e));An({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 En(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(Mn({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 Dn(i,o)}}async function Tn({config:e,cwd:t}){let n=await Sn({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Pe(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await En(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}.`);An({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function En(e){let t=JSON.parse(await z(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 Dn(e,t){await R(j(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await V(n,`${JSON.stringify(t,null,2)}\n`),await ke(n,e)}function On(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 kn({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 An({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=jn(a),c=jn(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 jn(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 Mn(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function Nn(e){return Re(`sha256`).update(e).digest(`hex`)}async function Pn(e){return Nn(await z(e))}function Fn(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function In({bucket:e,digest:t,projectId:n,source:r,store:i}){if(dn(t),await Pn(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=hn(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${U()}.verify`;try{if(await i.download(e,a,o),await Pn(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await B(o,{force:!0})}}async function Ln({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=Fn(n),o=M(i,`reference-${U()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await z(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await B(o,{force:!0})}await V(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await B(o,{force:!0})}let s=M(i,`reference-${U()}.verify.json`);try{if(await r.download(e,t,s),!(await z(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await B(s,{force:!0})}}async function Rn({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=Fn(t),o=Nn(a),s=M(i,`manifest-${o}.json`);await V(s,a,{flag:`wx`});try{await In({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await B(s,{force:!0})}return o}async function zn({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=M(r,`reference-${U()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await z(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return fn(r.revision),dn(r.snapshot),r}finally{await B(i,{force:!0})}}async function Bn({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await zn({bucket:e,key:gn(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 Vn({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await Ln({bucket:e,key:gn(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await Ln({bucket:e,key:_n(t,i),reference:n,store:r,temporaryDirectory:a})}async function Hn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){dn(n);let o=M(P(t),`v1`,`sha256`,n.slice(0,2),n);if(await Wn(o,n)===!1){await R(j(o),{recursive:!0});let t=`${o}.${process.pid}.${U()}.tmp`;try{if(await i.download(e,hn(r,n),t),await Pn(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await B(o,{force:!0}),await ke(t,o)}finally{await B(t,{force:!0})}}await R(j(a),{recursive:!0});let s=`${a}.${process.pid}.${U()}.tmp`;try{if(await Te(o,s),await Pn(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await B(a,{force:!0}),await ke(s,a)}finally{await B(s,{force:!0})}}async function Un({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=M(a,`manifest-${n}.json`);await Hn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await z(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}.`);fn(s.revision),s.baseline!==void 0&&dn(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}.`);dn(e.digest)}return s}async function Wn(e,t){try{return(await Ae(e)).isFile()&&await Pn(e)===t}catch{return!1}}async function Gn({cwd:e=process.cwd(),env:t=process.env}={}){if((await H({cwd:e})).i18n){if(t.COREFRAME_I18N_RELEASE_REVISION){await Jn({cwd:e,env:t,revision:t.COREFRAME_I18N_RELEASE_REVISION});return}await bn(e)}}async function Kn({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await H({cwd:e});if(!n.i18n)return;let r=Yn(n.i18n),i=X(e,r.directory);try{if(!(await Ae(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await bn(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Ae(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 bn(e);return}}async function qn({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){vn(r);let i=await Xn({cwd:e,env:t,store:n});await ir(e);let a=await rr(e);await ar(e,r,a);let o=await De(M(Ne(),`coreframe-i18n-prepare-`));try{let n=await Bn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,revision:a,store:i.store,temporaryDirectory:o});if(n){let e=await Un({bucket:i.assets.sourceBucket,cacheRoot:i.cacheRoot,digest:n.snapshot,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return nr(i,e,a),await Qn(i,e),await Vn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:n,store:i.store,tag:r,temporaryDirectory:o}),{reused:!0,snapshot:n.snapshot}}return await tr(i,o,async()=>{let n=await Zn(i,a,o);n||await er(i),await bn(e);let s=await Sn({config:i.config,cwd:e}),c=await Cn({config:i.config,cwd:e,env:t,messages:s});await wn({config:i.config,cwd:e,missing:s,response:c}),await Tn({config:i.config,cwd:e}),await xn({config:i.config,cwd:e,strict:!0,temporaryDirectory:o});let l=await $n(i),u={...n?{baseline:n}:{},catalogs:i.config.catalogs,files:l,generator:s.length>0?i.config.generator?.id??`unconfigured`:`none`,linguiVersion:await or(e),locales:i.config.locales,projectId:i.assets.projectId,revision:a,sourceLocale:i.config.sourceLocale,version:1},d=await Rn({bucket:i.assets.sourceBucket,manifest:u,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return await Vn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:{revision:a,snapshot:d,version:1},store:i.store,tag:r,temporaryDirectory:o}),{reused:!1,snapshot:d}})}finally{await B(o,{force:!0,recursive:!0})}}async function Jn({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await H({cwd:e});if(!i.i18n)return;let a=await Xn({cwd:e,env:t,store:r,projectConfig:i}),o=fn(n??await rr(e)),s=await De(M(Ne(),`coreframe-i18n-materialize-`));try{let e=await Bn({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 Un({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return nr(a,t,o),await Qn(a,t),{revision:o,snapshot:e.snapshot}}finally{await B(s,{force:!0,recursive:!0})}}function Yn(e){let t=pn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>pn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>pn(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 Xn({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await H({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:Yn(i.i18n),cwd:P(e),env:t,store:r??Se({config:a,env:t})}}async function Zn(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 Bn({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:fn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Un({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return nr(e,i,t),await Qn(e,i),r.snapshot}}async function Qn(e,t){for(let n of t.files)if(await Hn({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:X(e.cwd,n.path)}),(await Ae(X(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function $n(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 Pn(a);await In({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Ae(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function er(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 Pe(`@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 Dn(X(e.cwd,Z(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function tr(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 Ce(o)}catch{continue}let s=M(t,`previous-catalogs`,a);await R(j(s),{recursive:!0}),await ke(o,s),r.push({backup:s,path:o})}try{let e=await n();return await B(M(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 B(X(e.cwd,Z(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await R(j(t),{recursive:!0}),await ke(e,t);throw t}}function nr(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 rr(e){let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return fn(t.trim())}async function ir(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 ar(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 or(e){let{stdout:t}=await I(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const sr=[`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(` `),cr=n(u,{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}}),lr=n(u,{displayName:`profile`,async from(e){return be(e)}}),ur=n(u,{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}}),dr=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return O(e)}}),fr=d({name:`assets`,cmds:{configure:t({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${sr}`,args:{profile:c({type:lr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{L.note(sr,`Required B2 key access`);let t=await L.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(L.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await L.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(L.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await xe({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:t({name:`add`,args:{file:c({type:u,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:o({long:`id`,type:u,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:o({long:`alt`,type:s(u),description:`Required alt text for raster image and SVG assets.`}),pack:o({long:`pack`,type:s(ur),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:o({long:`widths`,type:s(cr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>ve(await me({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:t({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:o({long:`branch`,type:u,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await he({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:t({name:`build`,args:{id:o({long:`id`,type:s(u),description:`Build only one logical asset ID.`}),pack:o({long:`pack`,type:s(ur),description:`Build only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>ve(await ge({id:e,pack:n}),t,{kind:`build`})}),check:t({name:`check`,args:{fix:r({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:o({long:`pack`,type:s(ur),description:`Check only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await _e({fix:e,pack:n});ve(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:t({name:`publish`,args:{pack:o({long:`pack`,type:s(ur),description:`Publish only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await ye({pack:t});ve(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:t({name:`status`,args:{pack:o({long:`pack`,type:s(ur),description:`Report status for only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await _e({pack:t});ve(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),pr=d({name:`flutter`,cmds:{acceptance:t({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:dr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>k({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:t({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:r({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>de({check:e})}),prepare:t({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:c({type:a(E),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:dr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>D({apiOrigin:e,platform:t})}),check:t({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:c({type:a(E),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:dr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>ce({apiOrigin:e,platform:t})})}}),mr=d({name:`i18n`,cmds:{build:t({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await Gn()}}),materialize:t({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:o({long:`revision`,type:s(u),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Jn({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:t({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot.`,args:{tag:o({long:`tag`,type:u,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await qn({tag:e});console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),hr=W.platform===`win32`?`react-router.cmd`:`react-router`,gr=W.platform===`win32`?`panda.cmd`:`panda`;async function _r(e=W.cwd()){await br(e),await yr(e,[`typegen`])}async function vr(e=W.cwd(),t=W.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=A.resolve(e,`.coreframe/dashboard-build`),i=A.join(r,`client`),a=A.resolve(e,`dist/client/__dashboard`);if(await B(r,{force:!0,recursive:!0}),(await H({cwd:e})).deploy?.mode===`client`){await B(a,{force:!0,recursive:!0});return}await xr(e,gr,[`build`],t),await yr(e,[`build`,...n?[`--mode`,n]:[]],t),await B(a,{force:!0,recursive:!0}),await R(A.dirname(a),{recursive:!0}),await Ee(i,a,{recursive:!0})}async function yr(e,t,n=W.env){await xr(e,hr,t,n)}async function br(e){await B(A.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function xr(e,t,n,r=W.env){await I(t,n,{cwd:A.resolve(e,`dashboard`),env:{...r,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const Q={access:Ce,chmod:we,mkdir:R,mkdtemp:De,readFile:z,readFileSync:K,rm:B,writeFile:V},Sr={getAvailablePort:wr},Cr={homedir:je,kill:W.kill,networkInterfaces:Me,tmpdir:Ne};async function wr(){let e=Xe();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 Tr({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 Er(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=Xe(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 Er(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await Dr(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 Dr({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=Ye({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 Or=W.platform===`win32`?`react-router.cmd`:`react-router`;function kr(e){return G(A.resolve(e,`dashboard/dashboard.config.ts`))}function Ar({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 W.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([qe(t.stdout),qe(t.stderr)]),i===e&&(i=void 0)}};a=Tr({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await Sr.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=J({label:`dashboard`}),s=J({color:`red`,label:`dashboard`});a.pipe(W.stdout,{end:!1}),s.pipe(W.stderr,{end:!1});let l=I(Or,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:A.resolve(e,`dashboard`),env:{...t,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([Mr(l.stdout,a),Mr(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)W.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function jr({cwd:e=W.cwd(),env:t=W.env,port:n}){let r=Ar({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function Mr(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const Nr=d({name:`dashboard`,cmds:{dev:t({name:`dev`,args:{port:o({long:`port`,type:i,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>jr({port:e})}),build:t({name:`build`,args:{mode:o({long:`mode`,type:s(u),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>vr(void 0,void 0,e)}),typegen:t({name:`typegen`,args:{},handler:()=>_r()})}}),Pr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Fr(e,t){let n=Lr(e,t);if(!Rr(n)||!zr(n,[`description`,`requires`,`routes`,`verifier`])||!Vr(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Vr))||n.verifier!==void 0&&!Vr(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=>Ir(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Rr(e)||!Br(e,[`path`,`router`,`when`])||!Vr(e.path)||!Vr(e.router)||!Vr(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 Ir(e){if(!Pr.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function Lr(e,t){try{return Ze(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Rr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zr(e,t){return Object.keys(e).every(e=>t.includes(e))}function Br(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Vr(e){return typeof e==`string`&&e.length>0}const Hr=`https://github.com/coreframe-js/coreframe.git`;function Ur(e,t){return Y(`git`,e,{cwd:t,encoding:`utf8`})}function Wr(e,t){let n=Ur(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 Gr(e,t){let n=Ur([`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 Kr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);Wr([`rev-parse`,`--show-toplevel`],e);let r=Gr(n,e);if(r===null)Wr([`remote`,`add`,n,Hr],e),console.log(`Added ${n} remote: ${Hr}`);else if(r===Hr)console.log(`${n} remote already points at ${Hr}`);else throw Error(`${n} remote points at ${r}, not ${Hr}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);t&&(Wr([`fetch`,n,`--tags`,`--prune`],e),console.log(`Fetched ${n}.`))}const qr=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;function $(e){return qr.test(e)?`v${e}`:e}function Jr(e){return`${$(e)}:template`}function Yr(e,t){return`${Jr(e)}/${t}`}function Xr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=ei(e),a=ii(i,[`rev-parse`,`--show-toplevel`]),o=$(r??ti(i));return Kr({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,repositoryRoot:a}}function Zr(e,t,n){return Qr(e,t,n).toString(`utf8`)}function Qr(e,t,n){let r=`${t}:${n}`,i=Y(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${ai([`show`,r],i)}`);return i.stdout}function $r(e,t,n){let r=Y(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(ai([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function ei(e){let t=P(e);for(;;){let e=M(t,`package.json`),n=ri(e);if(n!==void 0&&ni(n,e).engines?.coreframe)return t;let r=j(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function ti(e){let t=M(e,`package.json`),n=ri(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=ni(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function ni(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ri(e){try{return K(e,`utf8`)}catch(e){if(oi(e)&&e.code===`ENOENT`)return;throw e}}function ii(e,t){let n=Y(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(ai(t,n));return n.stdout.trim()}function ai(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 oi(e){return e instanceof Error&&`code`in e}const si=[{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:gi},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:_i},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:vi},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>hi(e,[`configureShellQueryFocus`,`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=>hi(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],ci=`src-flutter/lib/application.dart`,li=`src/api/worker/auth-origin.ts`;function ui(e){let t=[];for(let n of si){let r=M(e,n.path);if(!G(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=K(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}let n=di(e,t),r=fi(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${ci} loopbackPort (${n}) must match ${li} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function di(e,t){let n=pi(e,ci,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=mi(r??a);return o===void 0&&t.push(`${ci} must configure loopbackPort as a fixed integer port.`),o}function fi(e,t){let n=pi(e,li,t);if(n===void 0)return;let r=mi(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(`${li} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function pi(e,t,n){let r=M(e,t);if(!G(r)){n.push(`${t} is missing; it must define the Flutter loopback origin contract.`);return}return K(r,`utf8`)}function mi(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function hi(e,t){return t.every(t=>e.includes(t))}function gi(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 _i(e){try{let t=Ze(e);if(!yi(t)||!yi(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return yi(n)&&n.sdk===`flutter`}catch{return!1}}function vi(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 yi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bi({name:e,...t}){let n=Xr(t),r=`recipes/${e}/recipe.yaml`,i=Ci(Fr(Zr(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(`
8
- `)}`);return{name:e,ref:n.ref}}function xi(e){console.log(`Verified Coreframe recipe ${e.name} from ${e.ref}.`)}function Si(e,t){for(let n of e){let e=`recipes/${n}/recipe.yaml`,r=Ci(Fr(Zr(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(`
9
- `)}\nApply and verify ${n} before continuing.`)}}function Ci(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return ui(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function wi({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){Ir(n);let a=Xr({cwd:e,fetch:t,remote:r,target:i}),{projectRoot:o,ref:s,repositoryRoot:c}=a,l=`recipes/${n}`,u=`${l}/recipe.yaml`,d=Fr(Zr(c,s,u),u);Si(d.requires,a);let f=Zr(c,s,`${l}/RECIPE.md`),p=$r(c,s,`${l}/files`),m=$r(c,s,`${l}/patches`),h=$r(c,s,`${l}/.agents`),g=new Map,_=new Map,v=[],ee=[],y=[],b=[],x=[],S=[];for(let e of p){let t=e.slice(`${l}/files/`.length);if(ji(t,`Recipe file ${e}`),t.startsWith(`.agents/`))throw Error(`Recipe file ${e} must be stored in the recipe's .agents directory.`);g.set(t,Qr(c,s,e)),_.set(t,e)}for(let e of h){let t=e.slice(`${l}/`.length);if(Oi(t,`Recipe asset ${e}`),g.has(t))throw Error(`Recipe declares ${t} as both a file and an agent asset.`);g.set(t,Qr(c,s,e)),_.set(t,e)}for(let e of m){let t=Mi(e,l);if(g.has(t))throw Error(`Recipe declares ${t} as both a file and a patch.`);let n=Qr(c,s,e);Ni(n.toString(`utf8`),t,e),Ai(o,t),Pi(o,n,!1)?(v.push({contents:n,destinationPath:t}),b.push(t)):Pi(o,n,!0)?x.push(t):y.push({destination:t,source:e})}let C=new Map;for(let[e,t]of g){let r=Li(Ai(o,e));if(r===void 0)C.set(e,t),ee.push(e);else if(r.equals(t))x.push(e);else if(e.startsWith(`.agents/`))throw Error(`Recipe ${n} cannot replace modified ${e}. Reconcile that agent asset manually.`);else y.push({destination:e,source:_.get(e)})}let w=new Map;for(let e of d.routes){if(Oi(e.router,`Recipe route router`),ki(e.path,`Recipe route path`),g.has(e.router))throw Error(`Recipe cannot replace its destination router ${e.router}.`);if(!g.has(e.path)&&!G(Ai(o,e.path)))throw Error(`Recipe route target ${e.path} does not exist.`);let t=w.get(e.router)??Ei(Ri(Ai(o,e.router),e.router),e.router);w.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 w){t.routes.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path));let n=Ri(Ai(o,e),e),r=Qe(t,{lineWidth:0});r===n?x.push(e):(C.set(e,r),S.push(e))}for(let{destinationPath:e}of v)if(C.has(e))throw Error(`Recipe cannot both write and patch ${e}.`);for(let[e,t]of C){let n=Ai(o,e);Ve(j(n),{recursive:!0}),q(n,t)}return v.length>0&&Fi(o,v.map(({contents:e})=>e)),{created:ee.sort(),instructions:f,mergeRequired:y.sort((e,t)=>e.destination.localeCompare(t.destination)),name:n,patched:b.sort(),ref:s,unchanged:[...new Set(x)].sort(),updated:S.sort()}}function Ti(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 Ei(e,t){let n=Di(e,t);if(!zi(n)||!Bi(n,[`routes`,`rules`])||!Array.isArray(n.rules)||!n.rules.every(Vi)||!Array.isArray(n.routes))throw Error(`${t} must contain only string rules and a routes array.`);let r=n.routes.map((e,n)=>{if(!zi(e)||!Bi(e,[`path`,`when`])||!Vi(e.path)||!Vi(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 Di(e,t){try{return Ze(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Oi(e,t){if(!e.startsWith(`.agents/`))throw Error(`${t} must be a normalized project-relative path beneath .agents/.`);ji(e,t)}function ki(e,t){if(ji(e,t),!/(?:^|\/)\.agents\/rules\/.+\.md$/u.test(e))throw Error(`${t} must point to a Markdown rule beneath an .agents/rules directory.`)}function Ai(e,t){ji(t,`Recipe destination`);let n=M(e,t),r=e;for(let e of t.split(`/`))if(r=M(r,e),G(r)&&Be(r).isSymbolicLink())throw Error(`Recipe destination ${t} crosses symbolic link ${r}.`);return n}function ji(e,t){if(e.length===0||pe(e)||e===`..`||e.startsWith(`../`)||e.includes(`\\`)||N.normalize(e)!==e)throw Error(`${t} must be a normalized project-relative path.`)}function Mi(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 ji(r,`Recipe patch ${e}`),r}function Ni(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 Pi(e,t,n){let r=[`apply`,`--check`,`--whitespace=nowarn`];return n&&r.push(`--reverse`),r.push(`-`),Y(`git`,r,{cwd:e,input:t}).status===0}function Fi(e,t){let n=Y(`git`,[`apply`,`--whitespace=nowarn`,`-`],{cwd:e,input:Buffer.concat(t.flatMap(e=>[e,Buffer.from(e.at(-1)===10?``:`
10
- `)])),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 Ii(e){return Li(e)?.toString(`utf8`)}function Li(e){try{return K(e)}catch(e){if(Hi(e)&&e.code===`ENOENT`)return;throw e}}function Ri(e,t){let n=Ii(e);if(n===void 0)throw Error(`Required file ${t} does not exist.`);return n}function zi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bi(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Vi(e){return typeof e==`string`&&e.length>0}function Hi(e){return e instanceof Error&&`code`in e}function Ui(e={}){let{ref:t,repositoryRoot:n}=Xr(e),r=$r(n,t,`recipes`).filter(e=>/^recipes\/[^/]+\/recipe\.yaml$/u.test(e)).map(e=>{let r=e.split(`/`)[1];return Ir(r),{description:Fr(Zr(n,t,e),e).description,name:r}});return r.sort((e,t)=>e.name.localeCompare(t.name)),{recipes:r,ref:t}}function Wi(e){console.log(`Coreframe recipes at ${e.ref}:`);for(let t of e.recipes)console.log(`${t.name} — ${t.description}`)}const Gi=`.agents/skills/coreframe-upgrade/SKILL.md`;function Ki(e,t={}){return Y(`git`,e,t)}function qi(e){return e.stderr.toString(`utf8`).trim()||e.stdout.toString(`utf8`).trim()}function Ji(e,t){let n=Yr(e,t),r=Ki([`show`,n],{encoding:`utf8`});if(r.status!==0){let e=qi(r);throw Error(`Could not read ${n}.${e?` ${e}`:``}`)}return r.stdout.toString()}function Yi(){let e=Ki([`rev-parse`,`--show-toplevel`],{encoding:`utf8`});if(e.status!==0){let t=qi(e);throw Error(`Could not find git repository root.${t?` ${t}`:``}`)}return e.stdout.toString().trim()}function Xi(e,t){let n=He(M(Ne(),`coreframe-upgrade-skill-`)),r=M(n,`SKILL.md`);try{q(r,t);let n=qi(Ki([`--no-pager`,`diff`,`--no-index`,`--color=never`,`--`,e,r]));n&&console.log(n)}finally{We(n,{force:!0,recursive:!0})}}function Zi({apply:e,target:t}){let n=M(Yi(),Gi),r=$(t);if(!G(n))throw Error(`Local ${Gi} does not exist.`);let i=K(n,`utf8`),a=Ji(t,Gi);return i===a?(console.log(`Coreframe upgrade skill matches ${r}:template/${Gi}.`),0):e?(q(n,a),console.error(`Updated ${Gi} from ${r}:template. Reread it before continuing the upgrade.`),20):(console.error(`Coreframe upgrade skill differs from ${r}:template/${Gi}.`),console.error(`Run again with --apply to update it, then reread ${Gi} before continuing.`),Xi(n,a),20)}const Qi=[{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`}],$i=[{matches:e=>e===`src-tauri`||e.startsWith(`src-tauri/`),reason:`legacy Tauri shell removed by breaking host migration`}],ea=new Set([`100644`,`100755`,`120000`]);function ta(e,t={}){return Y(`git`,e,t)}function na(e){let t=ta(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 ra(e){let t=ta(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 ia(){return na([`rev-parse`,`--show-toplevel`]).trim()}function aa(e){let t=M(e,`package.json`);if(!G(t))throw Error(`Missing --base <git-ref>, and package.json does not exist.`);let n=JSON.parse(K(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 oa(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 sa(e,t){let n=oa(ra([`diff`,`--name-status`,`-z`,`--no-renames`,Jr(e),Jr(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 ca(e,t){let n=ra([`ls-tree`,`-z`,`-r`,Jr(e),`--`,t]);if(n.length===0)return null;let r=oa(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 la(e){return ra([`cat-file`,`blob`,e.object])}function ua(e,t){let n=P(e,t),r=e.endsWith(F)?e:`${e}${F}`;if(n!==e&&!n.startsWith(r))throw Error(`Refusing to access path outside repository: ${t}`);return n}function da(e){try{return Be(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}function fa(e){return(e.mode&73)!=0}function pa(e){return e===null||e.type===`blob`&&ea.has(e.mode)}function ma(e){return Qi.find(t=>t.matches(e))?.reason}function ha(e){return $i.find(t=>t.matches(e))?.reason}function ga(e,t,n){let r=ua(e,t);if(n===null)return{matches:!da(r)};if(!pa(n))return{matches:!1,reason:`unsupported template entry mode ${n.mode} ${n.type}`};let i;try{i=Be(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=la(n);return n.mode===`120000`?i.isSymbolicLink()?{matches:Buffer.from(Ue(r),`utf8`).equals(a)}:{matches:!1,reason:`worktree path is not a symlink`}:i.isFile()?(n.mode===`100755`?fa(i):!fa(i))?{matches:K(r).equals(a)}:{matches:!1,reason:`worktree executable bit differs from template`}:{matches:!1,reason:`worktree path is not a regular file`}}function _a(e){da(e)&&We(e,{force:!0,recursive:!1})}function va(e,t,n){let r=ua(e,t);if(n===null){_a(r);return}if(Ve(j(r),{recursive:!0}),n.mode===`120000`){_a(r),Ge(la(n).toString(`utf8`),r);return}let i=da(r)?Be(r):null;i&&!i.isFile()&&_a(r),q(r,la(n)),ze(r,n.mode===`100755`?493:420)}function ya(e,t){return e===null&&t!==null?`add`:e!==null&&t===null?`delete`:`update`}function ba(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 xa(e){let t=ia(),n=$(e.base??aa(t)),r=$(e.target),i=sa(n,r),a=[],o=[],s=[],c=[];for(let e of i){let i=ma(e.path);if(i){o.push({action:`ignored`,path:e.path,reason:i});continue}let l=ca(n,e.path),u=ca(r,e.path),d=ya(l,u),f=u===null?ha(e.path):void 0;if(f){a.push({action:d,path:e.path,reason:f,targetEntry:u});continue}if(!pa(l)||!pa(u)){s.push({action:d,path:e.path,reason:`unsupported template entry type`});continue}if(ga(t,e.path,u).matches){c.push({action:`unchanged`,path:e.path});continue}let p=ga(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)va(t,e.path,e.targetEntry??null);console.log(`Coreframe template fast-forward: ${n} -> ${r}`),console.log(``),ba(e.apply?`Applied clean template updates`:`Would apply clean template updates`,a),ba(`Ignored downstream-owned paths`,o),ba(`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).`))}const Sa=[`dependencies`,`devDependencies`];function Ca(e){let t=Y(`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 wa(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}: ${e instanceof Error?e.message:e}`)}}function Ta(e,t){let n=`${$(e)}:${t}`;return wa(Ca([`show`,n]),n)}function Ea(e){return e.startsWith(`@coreframe/`)}function Da(e){return e.startsWith(`file:`)||e.startsWith(`link:`)||e.startsWith(`workspace:`)}function Oa(e){return e.startsWith(`file:`)||e.startsWith(`link:`)}function ka(e,t){let n=e.indexOf(`:`),r=e.slice(n+1),i=N.normalize(N.join(`template`,r,`package.json`));if(r.length===0||N.isAbsolute(r)||i===`..`||i.startsWith(`../`))throw Error(`Invalid local template dependency for ${t}: ${e}`);return i}function Aa(e){let t=Ta(e,`template/package.json`),n=[],r=new Set;for(let i of Sa)for(let[a,o]of Object.entries(t[i]??{})){if(!Ea(a)||!Oa(o))continue;if(r.has(a))throw Error(`Target template declares ${a} more than once.`);let t=ka(o,a),s=Ta(e,t);if(s.name!==a||typeof s.version!=`string`)throw Error(`${$(e)}:${t} must declare ${a} with a version.`);n.push({group:i,name:a,spec:`^${s.version}`}),r.add(a)}return n}function ja(e,t){for(let n of Sa){let r=e[n]?.[t];if(r)return{group:n,spec:r}}}function Ma(e,t,n){let r=t.match(/\n([\t ]+)"/u)?.[1]??` `,i=t.endsWith(`
5
+ `)}function en(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 tn(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 nn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=D,runCommand:s=an}={}){rn(r,{profile:i,simulator:a});let c={...n};delete c[Ht],delete c[Ut],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:O(e??n.COREFRAME_API_ORIGIN);for(let e of Xt(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(Qt(t,{profile:i})):r===`ios`?console.log($t(t,{profile:i,simulator:a})):r===`windows`?console.log(en(t)):r===`linux`&&console.log(tn(t))}function rn(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 an(e,t,{cwd:n,env:r}){await I(e,t,{cwd:n,env:r,stdio:`inherit`})}function on(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const sn=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return O(e)}}),cn=t({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:c({type:s(a(Yt)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:o({long:`api-origin`,type:s(sn),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:r({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>nn({apiOrigin:e,platform:t,profile:n,simulator:r})}),ln=/^[a-f0-9]{64}$/,un=/^[a-f0-9]{40}$/,dn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function fn(e){if(!ln.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function pn(e){if(!un.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function mn(e,t){if(!dn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function hn(e){return`projects/${mn(e,`Project ID`)}/i18n/v1`}function gn(e,t){return fn(t),`${hn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function _n(e,t){return pn(t),`${hn(e)}/commits/${t}.json`}function vn(e,t){return yn(t),`${hn(e)}/releases/${encodeURIComponent(t)}.json`}function yn(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=P(e),r=P(n,t);if(r!==n&&!r.startsWith(`${n}${F}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function Z(e,t,n){return`${e.directory}/${t}/${n}.json`}function bn(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function xn(e){await I(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function Sn({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 Dn(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=M(r,`${n}-${a}.json`);await B(A(l),{recursive:!0}),await Ce(o,l),i.push({path:o,backup:l}),await On(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 Ce(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await H(X(t,bn(e,n,r)),{force:!0})}}}async function Cn({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 Dn(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)=>Nn(e).localeCompare(Nn(t)))}async function wn({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 kn(await An({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function Tn({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[Nn(e),e])),a=new Map;for(let e of r.translations){let t=Nn(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 Me(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(Nn(e));jn({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 Dn(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(Nn({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 On(i,o)}}async function En({config:e,cwd:t}){let n=await Cn({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Me(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await Dn(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}.`);jn({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function Dn(e){let t=JSON.parse(await V(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 On(e,t){await B(A(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await U(n,`${JSON.stringify(t,null,2)}\n`),await De(n,e)}function kn(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 An({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 jn({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=Mn(a),c=Mn(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 Mn(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 Nn(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function Pn(e){return Ie(`sha256`).update(e).digest(`hex`)}async function Fn(e){return Pn(await V(e))}function In(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function Ln({bucket:e,digest:t,projectId:n,source:r,store:i}){if(fn(t),await Fn(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=gn(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${G()}.verify`;try{if(await i.download(e,a,o),await Fn(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await H(o,{force:!0})}}async function Rn({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=In(n),o=M(i,`reference-${G()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await V(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await H(o,{force:!0})}await U(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await H(o,{force:!0})}let s=M(i,`reference-${G()}.verify.json`);try{if(await r.download(e,t,s),!(await V(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await H(s,{force:!0})}}async function zn({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=In(t),o=Pn(a),s=M(i,`manifest-${o}.json`);await U(s,a,{flag:`wx`});try{await Ln({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await H(s,{force:!0})}return o}async function Bn({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=M(r,`reference-${G()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await V(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return pn(r.revision),fn(r.snapshot),r}finally{await H(i,{force:!0})}}async function Vn({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await Bn({bucket:e,key:_n(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 Hn({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await Rn({bucket:e,key:_n(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await Rn({bucket:e,key:vn(t,i),reference:n,store:r,temporaryDirectory:a})}async function Un({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){fn(n);let o=M(P(t),`v1`,`sha256`,n.slice(0,2),n);if(await Gn(o,n)===!1){await B(A(o),{recursive:!0});let t=`${o}.${process.pid}.${G()}.tmp`;try{if(await i.download(e,gn(r,n),t),await Fn(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await H(o,{force:!0}),await De(t,o)}finally{await H(t,{force:!0})}}await B(A(a),{recursive:!0});let s=`${a}.${process.pid}.${G()}.tmp`;try{if(await Ce(o,s),await Fn(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await H(a,{force:!0}),await De(s,a)}finally{await H(s,{force:!0})}}async function Wn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=M(a,`manifest-${n}.json`);await Un({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await V(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}.`);pn(s.revision),s.baseline!==void 0&&fn(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}.`);fn(e.digest)}return s}async function Gn(e,t){try{return(await Oe(e)).isFile()&&await Fn(e)===t}catch{return!1}}async function Kn({cwd:e=process.cwd(),env:t=process.env}={}){if((await W({cwd:e})).i18n){if(t.COREFRAME_I18N_RELEASE_REVISION){await Yn({cwd:e,env:t,revision:t.COREFRAME_I18N_RELEASE_REVISION});return}await xn(e)}}async function qn({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await W({cwd:e});if(!n.i18n)return;let r=Xn(n.i18n),i=X(e,r.directory);try{if(!(await Oe(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await xn(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Oe(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 xn(e);return}}async function Jn({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){yn(r);let i=await Zn({cwd:e,env:t,store:n});await ar(e);let a=await ir(e);await or(e,r,a);let o=await Te(M(je(),`coreframe-i18n-prepare-`));try{let n=await Vn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,revision:a,store:i.store,temporaryDirectory:o});if(n){let e=await Wn({bucket:i.assets.sourceBucket,cacheRoot:i.cacheRoot,digest:n.snapshot,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return rr(i,e,a),await $n(i,e),await Hn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:n,store:i.store,tag:r,temporaryDirectory:o}),{reused:!0,snapshot:n.snapshot}}return await nr(i,o,async()=>{let n=await Qn(i,a,o);n||await tr(i),await xn(e);let s=await Cn({config:i.config,cwd:e}),c=await wn({config:i.config,cwd:e,env:t,messages:s});await Tn({config:i.config,cwd:e,missing:s,response:c}),await En({config:i.config,cwd:e}),await Sn({config:i.config,cwd:e,strict:!0,temporaryDirectory:o});let l=await er(i),u={...n?{baseline:n}:{},catalogs:i.config.catalogs,files:l,generator:s.length>0?i.config.generator?.id??`unconfigured`:`none`,linguiVersion:await sr(e),locales:i.config.locales,projectId:i.assets.projectId,revision:a,sourceLocale:i.config.sourceLocale,version:1},d=await zn({bucket:i.assets.sourceBucket,manifest:u,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return await Hn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:{revision:a,snapshot:d,version:1},store:i.store,tag:r,temporaryDirectory:o}),{reused:!1,snapshot:d}})}finally{await H(o,{force:!0,recursive:!0})}}async function Yn({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await W({cwd:e});if(!i.i18n)return;let a=await Zn({cwd:e,env:t,store:r,projectConfig:i}),o=pn(n??await ir(e)),s=await Te(M(je(),`coreframe-i18n-materialize-`));try{let e=await Vn({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 Wn({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return rr(a,t,o),await $n(a,t),{revision:o,snapshot:e.snapshot}}finally{await H(s,{force:!0,recursive:!0})}}function Xn(e){let t=mn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>mn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>mn(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 Zn({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await W({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:Xn(i.i18n),cwd:P(e),env:t,store:r??xe({config:a,env:t})}}async function Qn(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 Vn({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:pn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Wn({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return rr(e,i,t),await $n(e,i),r.snapshot}}async function $n(e,t){for(let n of t.files)if(await Un({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:X(e.cwd,n.path)}),(await Oe(X(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function er(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 Fn(a);await Ln({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Oe(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function tr(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 Me(`@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 On(X(e.cwd,Z(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function nr(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 z(o)}catch{continue}let s=M(t,`previous-catalogs`,a);await B(A(s),{recursive:!0}),await De(o,s),r.push({backup:s,path:o})}try{let e=await n();return await H(M(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 H(X(e.cwd,Z(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await B(A(t),{recursive:!0}),await De(e,t);throw t}}function rr(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 ir(e){let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return pn(t.trim())}async function ar(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 or(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 sr(e){let{stdout:t}=await I(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const cr=[`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(` `),lr=n(u,{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}}),ur=n(u,{displayName:`profile`,async from(e){return ye(e)}}),dr=n(u,{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}}),fr=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return O(e)}}),pr=d({name:`assets`,cmds:{configure:t({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${cr}`,args:{profile:c({type:ur,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{L.note(cr,`Required B2 key access`);let t=await L.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(L.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await L.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(L.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await be({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:t({name:`add`,args:{file:c({type:u,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:o({long:`id`,type:u,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:o({long:`alt`,type:s(u),description:`Required alt text for raster image and SVG assets.`}),pack:o({long:`pack`,type:s(dr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:o({long:`widths`,type:s(lr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>R(await me({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:t({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:o({long:`branch`,type:u,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await he({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:t({name:`build`,args:{id:o({long:`id`,type:s(u),description:`Build only one logical asset ID.`}),pack:o({long:`pack`,type:s(dr),description:`Build only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>R(await ge({id:e,pack:n}),t,{kind:`build`})}),check:t({name:`check`,args:{fix:r({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:o({long:`pack`,type:s(dr),description:`Check only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await _e({fix:e,pack:n});R(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:t({name:`publish`,args:{pack:o({long:`pack`,type:s(dr),description:`Publish only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await ve({pack:t});R(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:t({name:`status`,args:{pack:o({long:`pack`,type:s(dr),description:`Report status for only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await _e({pack:t});R(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),mr=d({name:`flutter`,cmds:{acceptance:t({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:fr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>pe({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:t({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:r({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>E({check:e})}),prepare:t({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:c({type:a(de),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:fr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>D({apiOrigin:e,platform:t})}),check:t({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:c({type:a(de),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:fr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>ce({apiOrigin:e,platform:t})})}}),hr=d({name:`i18n`,cmds:{build:t({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await Kn()}}),materialize:t({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:o({long:`revision`,type:s(u),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Yn({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:t({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot.`,args:{tag:o({long:`tag`,type:u,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await Jn({tag:e});console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),gr=K.platform===`win32`?`react-router.cmd`:`react-router`,_r=K.platform===`win32`?`panda.cmd`:`panda`;async function vr(e=K.cwd()){await xr(e),await br(e,[`typegen`])}async function yr(e=K.cwd(),t=K.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=k.resolve(e,`.coreframe/dashboard-build`),i=k.join(r,`client`),a=k.resolve(e,`dist/client/__dashboard`);if(await H(r,{force:!0,recursive:!0}),(await W({cwd:e})).deploy?.mode===`client`){await H(a,{force:!0,recursive:!0});return}await Sr(e,_r,[`build`],t),await br(e,[`build`,...n?[`--mode`,n]:[]],t),await H(a,{force:!0,recursive:!0}),await B(k.dirname(a),{recursive:!0}),await we(i,a,{recursive:!0})}async function br(e,t,n=K.env){await Sr(e,gr,t,n)}async function xr(e){await H(k.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function Sr(e,t,n,r=K.env){await I(t,n,{cwd:k.resolve(e,`dashboard`),env:{...r,PATH:k.resolve(e,`node_modules/.bin`)+k.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const Q={access:z,chmod:Se,mkdir:B,mkdtemp:Te,readFile:V,readFileSync:J,rm:H,writeFile:U},Cr={getAvailablePort:Tr},wr={homedir:ke,kill:K.kill,networkInterfaces:Ae,tmpdir:je};async function Tr(){let e=Xe();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 Er({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 Dr(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=Xe(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 Dr(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await Or(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 Or({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=Ye({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 kr=K.platform===`win32`?`react-router.cmd`:`react-router`;function Ar(e){return q(k.resolve(e,`dashboard/dashboard.config.ts`))}function jr({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 K.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([Ke(t.stdout),Ke(t.stderr)]),i===e&&(i=void 0)}};a=Er({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await Cr.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=qe({label:`dashboard`}),s=qe({color:`red`,label:`dashboard`});a.pipe(K.stdout,{end:!1}),s.pipe(K.stderr,{end:!1});let l=I(kr,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:k.resolve(e,`dashboard`),env:{...t,PATH:k.resolve(e,`node_modules/.bin`)+k.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([Nr(l.stdout,a),Nr(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)K.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function Mr({cwd:e=K.cwd(),env:t=K.env,port:n}){let r=jr({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function Nr(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const Pr=d({name:`dashboard`,cmds:{dev:t({name:`dev`,args:{port:o({long:`port`,type:i,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>Mr({port:e})}),build:t({name:`build`,args:{mode:o({long:`mode`,type:s(u),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>yr(void 0,void 0,e)}),typegen:t({name:`typegen`,args:{},handler:()=>vr()})}}),Fr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Ir(e,t){let n=Rr(e,t);if(!zr(n)||!Br(n,[`description`,`requires`,`routes`,`verifier`])||!Hr(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Hr))||n.verifier!==void 0&&!Hr(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=>Lr(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!zr(e)||!Vr(e,[`path`,`router`,`when`])||!Hr(e.path)||!Hr(e.router)||!Hr(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 Lr(e){if(!Fr.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function Rr(e,t){try{return Ze(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function zr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Br(e,t){return Object.keys(e).every(e=>t.includes(e))}function Vr(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Hr(e){return typeof e==`string`&&e.length>0}const Ur=`https://github.com/coreframe-js/coreframe.git`;function Wr(e,t){return Y(`git`,e,{cwd:t,encoding:`utf8`})}function Gr(e,t){let n=Wr(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 Kr(e,t){let n=Wr([`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 qr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);Gr([`rev-parse`,`--show-toplevel`],e);let r=Kr(n,e);if(r===null)Gr([`remote`,`add`,n,Ur],e),console.log(`Added ${n} remote: ${Ur}`);else if(r===Ur)console.log(`${n} remote already points at ${Ur}`);else throw Error(`${n} remote points at ${r}, not ${Ur}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);t&&(Gr([`fetch`,n,`--tags`,`--prune`],e),console.log(`Fetched ${n}.`))}const Jr=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;function $(e){return Jr.test(e)?`v${e}`:e}function Yr(e){return`${$(e)}:template`}function Xr(e,t){return`${Yr(e)}/${t}`}function Zr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=ti(e),a=ai(i,[`rev-parse`,`--show-toplevel`]),o=$(r??ni(i));return qr({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,repositoryRoot:a}}function Qr(e,t,n){return $r(e,t,n).toString(`utf8`)}function $r(e,t,n){let r=`${t}:${n}`,i=Y(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${oi([`show`,r],i)}`);return i.stdout}function ei(e,t,n){let r=Y(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(oi([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function ti(e){let t=P(e);for(;;){let e=M(t,`package.json`),n=ii(e);if(n!==void 0&&ri(n,e).engines?.coreframe)return t;let r=A(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function ni(e){let t=M(e,`package.json`),n=ii(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=ri(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function ri(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ii(e){try{return J(e,`utf8`)}catch(e){if(si(e)&&e.code===`ENOENT`)return;throw e}}function ai(e,t){let n=Y(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(oi(t,n));return n.stdout.trim()}function oi(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 si(e){return e instanceof Error&&`code`in e}const ci=[{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:_i},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:vi},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:yi},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>gi(e,[`configureShellQueryFocus`,`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=>gi(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],li=`src-flutter/lib/application.dart`,ui=`src/api/worker/auth-origin.ts`;function di(e){let t=[];for(let n of ci){let r=M(e,n.path);if(!q(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=J(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}let n=fi(e,t),r=pi(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${li} loopbackPort (${n}) must match ${ui} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function fi(e,t){let n=mi(e,li,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=hi(r??a);return o===void 0&&t.push(`${li} must configure loopbackPort as a fixed integer port.`),o}function pi(e,t){let n=mi(e,ui,t);if(n===void 0)return;let r=hi(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(`${ui} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function mi(e,t,n){let r=M(e,t);if(!q(r)){n.push(`${t} is missing; it must define the Flutter loopback origin contract.`);return}return J(r,`utf8`)}function hi(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function gi(e,t){return t.every(t=>e.includes(t))}function _i(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 vi(e){try{let t=Ze(e);if(!bi(t)||!bi(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return bi(n)&&n.sdk===`flutter`}catch{return!1}}function yi(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 bi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xi({name:e,...t}){let n=Zr(t),r=`recipes/${e}/recipe.yaml`,i=wi(Ir(Qr(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(`
8
+ `)}`);return{name:e,ref:n.ref}}function Si(e){console.log(`Verified Coreframe recipe ${e.name} from ${e.ref}.`)}function Ci(e,t){for(let n of e){let e=`recipes/${n}/recipe.yaml`,r=wi(Ir(Qr(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(`
9
+ `)}\nApply and verify ${n} before continuing.`)}}function wi(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return di(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function Ti({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){Lr(n);let a=Zr({cwd:e,fetch:t,remote:r,target:i}),{projectRoot:o,ref:s,repositoryRoot:c}=a,l=`recipes/${n}`,u=`${l}/recipe.yaml`,d=Ir(Qr(c,s,u),u);Ci(d.requires,a);let f=Qr(c,s,`${l}/RECIPE.md`),p=ei(c,s,`${l}/files`),m=ei(c,s,`${l}/patches`),h=ei(c,s,`${l}/.agents`),g=new Map,_=new Map,v=[],ee=[],y=[],b=[],x=[],S=[];for(let e of p){let t=e.slice(`${l}/files/`.length);if(Mi(t,`Recipe file ${e}`),t.startsWith(`.agents/`))throw Error(`Recipe file ${e} must be stored in the recipe's .agents directory.`);g.set(t,$r(c,s,e)),_.set(t,e)}for(let e of h){let t=e.slice(`${l}/`.length);if(ki(t,`Recipe asset ${e}`),g.has(t))throw Error(`Recipe declares ${t} as both a file and an agent asset.`);g.set(t,$r(c,s,e)),_.set(t,e)}for(let e of m){let t=Ni(e,l);if(g.has(t))throw Error(`Recipe declares ${t} as both a file and a patch.`);let n=$r(c,s,e);Pi(n.toString(`utf8`),t,e),ji(o,t),Fi(o,n,!1)?(v.push({contents:n,destinationPath:t}),b.push(t)):Fi(o,n,!0)?x.push(t):y.push({destination:t,source:e})}let C=new Map;for(let[e,t]of g){let r=Ri(ji(o,e));if(r===void 0)C.set(e,t),ee.push(e);else if(r.equals(t))x.push(e);else if(e.startsWith(`.agents/`))throw Error(`Recipe ${n} cannot replace modified ${e}. Reconcile that agent asset manually.`);else y.push({destination:e,source:_.get(e)})}let w=new Map;for(let e of d.routes){if(ki(e.router,`Recipe route router`),Ai(e.path,`Recipe route path`),g.has(e.router))throw Error(`Recipe cannot replace its destination router ${e.router}.`);if(!g.has(e.path)&&!q(ji(o,e.path)))throw Error(`Recipe route target ${e.path} does not exist.`);let t=w.get(e.router)??Di(zi(ji(o,e.router),e.router),e.router);w.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 w){t.routes.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path));let n=zi(ji(o,e),e),r=Qe(t,{lineWidth:0});r===n?x.push(e):(C.set(e,r),S.push(e))}for(let{destinationPath:e}of v)if(C.has(e))throw Error(`Recipe cannot both write and patch ${e}.`);for(let[e,t]of C){let n=ji(o,e);ze(A(n),{recursive:!0}),Ge(n,t)}return v.length>0&&Ii(o,v.map(({contents:e})=>e)),{created:ee.sort(),instructions:f,mergeRequired:y.sort((e,t)=>e.destination.localeCompare(t.destination)),name:n,patched:b.sort(),ref:s,unchanged:[...new Set(x)].sort(),updated:S.sort()}}function Ei(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 Di(e,t){let n=Oi(e,t);if(!Bi(n)||!Vi(n,[`routes`,`rules`])||!Array.isArray(n.rules)||!n.rules.every(Hi)||!Array.isArray(n.routes))throw Error(`${t} must contain only string rules and a routes array.`);let r=n.routes.map((e,n)=>{if(!Bi(e)||!Vi(e,[`path`,`when`])||!Hi(e.path)||!Hi(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 Oi(e,t){try{return Ze(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ki(e,t){if(!e.startsWith(`.agents/`))throw Error(`${t} must be a normalized project-relative path beneath .agents/.`);Mi(e,t)}function Ai(e,t){if(Mi(e,t),!/(?:^|\/)\.agents\/rules\/.+\.md$/u.test(e))throw Error(`${t} must point to a Markdown rule beneath an .agents/rules directory.`)}function ji(e,t){Mi(t,`Recipe destination`);let n=M(e,t),r=e;for(let e of t.split(`/`))if(r=M(r,e),q(r)&&Re(r).isSymbolicLink())throw Error(`Recipe destination ${t} crosses symbolic link ${r}.`);return n}function Mi(e,t){if(e.length===0||j(e)||e===`..`||e.startsWith(`../`)||e.includes(`\\`)||N.normalize(e)!==e)throw Error(`${t} must be a normalized project-relative path.`)}function Ni(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 Mi(r,`Recipe patch ${e}`),r}function Pi(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 Fi(e,t,n){let r=[`apply`,`--check`,`--whitespace=nowarn`];return n&&r.push(`--reverse`),r.push(`-`),Y(`git`,r,{cwd:e,input:t}).status===0}function Ii(e,t){let n=Y(`git`,[`apply`,`--whitespace=nowarn`,`-`],{cwd:e,input:Buffer.concat(t.flatMap(e=>[e,Buffer.from(e.at(-1)===10?``:`
10
+ `)])),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 Li(e){return Ri(e)?.toString(`utf8`)}function Ri(e){try{return J(e)}catch(e){if(Ui(e)&&e.code===`ENOENT`)return;throw e}}function zi(e,t){let n=Li(e);if(n===void 0)throw Error(`Required file ${t} does not exist.`);return n}function Bi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vi(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Hi(e){return typeof e==`string`&&e.length>0}function Ui(e){return e instanceof Error&&`code`in e}function Wi(e={}){let{ref:t,repositoryRoot:n}=Zr(e),r=ei(n,t,`recipes`).filter(e=>/^recipes\/[^/]+\/recipe\.yaml$/u.test(e)).map(e=>{let r=e.split(`/`)[1];return Lr(r),{description:Ir(Qr(n,t,e),e).description,name:r}});return r.sort((e,t)=>e.name.localeCompare(t.name)),{recipes:r,ref:t}}function Gi(e){console.log(`Coreframe recipes at ${e.ref}:`);for(let t of e.recipes)console.log(`${t.name} — ${t.description}`)}const Ki=`.agents/skills/coreframe-upgrade/SKILL.md`;function qi(e,t={}){return Y(`git`,e,t)}function Ji(e){return e.stderr.toString(`utf8`).trim()||e.stdout.toString(`utf8`).trim()}function Yi(e,t){let n=Xr(e,t),r=qi([`show`,n],{encoding:`utf8`});if(r.status!==0){let e=Ji(r);throw Error(`Could not read ${n}.${e?` ${e}`:``}`)}return r.stdout.toString()}function Xi(){let e=qi([`rev-parse`,`--show-toplevel`],{encoding:`utf8`});if(e.status!==0){let t=Ji(e);throw Error(`Could not find git repository root.${t?` ${t}`:``}`)}return e.stdout.toString().trim()}function Zi(e,t){let n=Be(M(je(),`coreframe-upgrade-skill-`)),r=M(n,`SKILL.md`);try{Ge(r,t);let n=Ji(qi([`--no-pager`,`diff`,`--no-index`,`--color=never`,`--`,e,r]));n&&console.log(n)}finally{He(n,{force:!0,recursive:!0})}}function Qi({apply:e,target:t}){let n=M(Xi(),Ki),r=$(t);if(!q(n))throw Error(`Local ${Ki} does not exist.`);let i=J(n,`utf8`),a=Yi(t,Ki);return i===a?(console.log(`Coreframe upgrade skill matches ${r}:template/${Ki}.`),0):e?(Ge(n,a),console.error(`Updated ${Ki} from ${r}:template. Reread it before continuing the upgrade.`),20):(console.error(`Coreframe upgrade skill differs from ${r}:template/${Ki}.`),console.error(`Run again with --apply to update it, then reread ${Ki} before continuing.`),Zi(n,a),20)}const $i=[{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`}],ea=[{matches:e=>e===`src-tauri`||e.startsWith(`src-tauri/`),reason:`legacy Tauri shell removed by breaking host migration`}],ta=new Set([`100644`,`100755`,`120000`]);function na(e,t={}){return Y(`git`,e,t)}function ra(e){let t=na(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 ia(e){let t=na(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 aa(){return ra([`rev-parse`,`--show-toplevel`]).trim()}function oa(e){let t=M(e,`package.json`);if(!q(t))throw Error(`Missing --base <git-ref>, and package.json does not exist.`);let n=JSON.parse(J(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 sa(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 ca(e,t){let n=sa(ia([`diff`,`--name-status`,`-z`,`--no-renames`,Yr(e),Yr(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 la(e,t){let n=ia([`ls-tree`,`-z`,`-r`,Yr(e),`--`,t]);if(n.length===0)return null;let r=sa(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 ua(e){return ia([`cat-file`,`blob`,e.object])}function da(e,t){let n=P(e,t),r=e.endsWith(F)?e:`${e}${F}`;if(n!==e&&!n.startsWith(r))throw Error(`Refusing to access path outside repository: ${t}`);return n}function fa(e){try{return Re(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}function pa(e){return(e.mode&73)!=0}function ma(e){return e===null||e.type===`blob`&&ta.has(e.mode)}function ha(e){return $i.find(t=>t.matches(e))?.reason}function ga(e){return ea.find(t=>t.matches(e))?.reason}function _a(e,t,n){let r=da(e,t);if(n===null)return{matches:!fa(r)};if(!ma(n))return{matches:!1,reason:`unsupported template entry mode ${n.mode} ${n.type}`};let i;try{i=Re(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=ua(n);return n.mode===`120000`?i.isSymbolicLink()?{matches:Buffer.from(Ve(r),`utf8`).equals(a)}:{matches:!1,reason:`worktree path is not a symlink`}:i.isFile()?(n.mode===`100755`?pa(i):!pa(i))?{matches:J(r).equals(a)}:{matches:!1,reason:`worktree executable bit differs from template`}:{matches:!1,reason:`worktree path is not a regular file`}}function va(e){fa(e)&&He(e,{force:!0,recursive:!1})}function ya(e,t,n){let r=da(e,t);if(n===null){va(r);return}if(ze(A(r),{recursive:!0}),n.mode===`120000`){va(r),Ue(ua(n).toString(`utf8`),r);return}let i=fa(r)?Re(r):null;i&&!i.isFile()&&va(r),Ge(r,ua(n)),Le(r,n.mode===`100755`?493:420)}function ba(e,t){return e===null&&t!==null?`add`:e!==null&&t===null?`delete`:`update`}function xa(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 Sa(e){let t=aa(),n=$(e.base??oa(t)),r=$(e.target),i=ca(n,r),a=[],o=[],s=[],c=[];for(let e of i){let i=ha(e.path);if(i){o.push({action:`ignored`,path:e.path,reason:i});continue}let l=la(n,e.path),u=la(r,e.path),d=ba(l,u),f=u===null?ga(e.path):void 0;if(f){a.push({action:d,path:e.path,reason:f,targetEntry:u});continue}if(!ma(l)||!ma(u)){s.push({action:d,path:e.path,reason:`unsupported template entry type`});continue}if(_a(t,e.path,u).matches){c.push({action:`unchanged`,path:e.path});continue}let p=_a(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)ya(t,e.path,e.targetEntry??null);console.log(`Coreframe template fast-forward: ${n} -> ${r}`),console.log(``),xa(e.apply?`Applied clean template updates`:`Would apply clean template updates`,a),xa(`Ignored downstream-owned paths`,o),xa(`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).`))}const Ca=[`dependencies`,`devDependencies`];function wa(e){let t=Y(`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 Ta(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}: ${e instanceof Error?e.message:e}`)}}function Ea(e,t){let n=`${$(e)}:${t}`;return Ta(wa([`show`,n]),n)}function Da(e){return e.startsWith(`@coreframe/`)}function Oa(e){return e.startsWith(`file:`)||e.startsWith(`link:`)||e.startsWith(`workspace:`)}function ka(e){return e.startsWith(`file:`)||e.startsWith(`link:`)}function Aa(e,t){let n=e.indexOf(`:`),r=e.slice(n+1),i=N.normalize(N.join(`template`,r,`package.json`));if(r.length===0||N.isAbsolute(r)||i===`..`||i.startsWith(`../`))throw Error(`Invalid local template dependency for ${t}: ${e}`);return i}function ja(e){let t=Ea(e,`template/package.json`),n=[],r=new Set;for(let i of Ca)for(let[a,o]of Object.entries(t[i]??{})){if(!Da(a)||!ka(o))continue;if(r.has(a))throw Error(`Target template declares ${a} more than once.`);let t=Aa(o,a),s=Ea(e,t);if(s.name!==a||typeof s.version!=`string`)throw Error(`${$(e)}:${t} must declare ${a} with a version.`);n.push({group:i,name:a,spec:`^${s.version}`}),r.add(a)}return n}function Ma(e,t){for(let n of Ca){let r=e[n]?.[t];if(r)return{group:n,spec:r}}}function Na(e,t,n){let r=t.match(/\n([\t ]+)"/u)?.[1]??` `,i=t.endsWith(`
11
11
  `)?`
12
- `:``;q(e,`${JSON.stringify(n,null,r)}${i}`)}function Na(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t)console.log(` ${e}`);console.log(``)}}function Pa(e){let t=P(Ca([`rev-parse`,`--show-toplevel`]).trim(),`package.json`),n=K(t,`utf8`),r=wa(n,t),i=$(e.target),a=Aa(i),o=new Set(a.map(({name:e})=>e)),s=[],c=[],l=[],u=0;for(let e of a){let t=ja(r,e.name);if(!t){c.push(`missing: ${e.name} ${e.spec} (${e.group})`);continue}if(Da(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=Sa.flatMap(e=>Object.entries(r[e]??{}).filter(([e])=>Ea(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;Ma(t,n,r)}console.log(`Coreframe package sync: ${i}`),console.log(``),Na(e.apply?`Updated Coreframe packages`:`Would update Coreframe packages`,s.map(({currentSpec:e,name:t,spec:n})=>`update: ${t} ${e} -> ${n}`)),Na(`Missing target Coreframe packages`,c),Na(`Locally linked Coreframe packages`,l),Na(`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 Fa={...u,displayName:`recipe`,description:`Coreframe recipe name, such as yam-db.`,async from(e){return Ir(e)}},Ia=d({name:`upgrade`,cmds:{"ensure-template-remote":t({name:`ensure-template-remote`,args:{remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Remote name to ensure.`}),noFetch:r({long:`no-fetch`,description:`Do not fetch the remote after ensuring it exists.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t})=>Kr({fetch:!e,remote:t})}),"check-skill-current":t({name:`check-skill-current`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),apply:r({long:`apply`,description:`Replace the local upgrade skill with the target version when it differs.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>{process.exitCode=Zi({apply:e,target:t})}}),"fast-forward-template-files":t({name:`fast-forward-template-files`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),base:o({long:`base`,type:s(u),description:`Previous Coreframe template git ref. Defaults to package.json engines.coreframe.`}),apply:r({long:`apply`,description:`Write clean fast-forwards to the worktree.`,defaultValue:()=>!1})},handler:({apply:e,base:t,target:n})=>xa({apply:e,base:t,target:n})}),"sync-coreframe-packages":t({name:`sync-coreframe-packages`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),apply:r({long:`apply`,description:`Update existing published Coreframe dependency specifications.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>Pa({apply:e,target:t})})}}),La=d({name:`recipes`,cmds:{apply:t({name:`apply`,args:{recipe:c({type:Fa,displayName:`recipe`,description:`Recipe to prepare and apply.`}),target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Ti(wi({fetch:!e,name:t,remote:n,target:r}))}),list:t({name:`list`,args:{target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,target:n})=>Wi(Ui({fetch:!e,remote:t,target:n}))}),verify:t({name:`verify`,args:{recipe:c({type:Fa,displayName:`recipe`,description:`Recipe adoption to verify.`}),target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>xi(bi({fetch:!e,name:t,remote:n,target:r}))})}}),Ra=d({name:`db`,cmds:{ensure:t({name:`ensure`,args:{},handler:v}),generate:t({name:`generate`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit generate.`})},handler:({args:e})=>T(`generate`,e)}),migrate:t({name:`migrate`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit migrate.`})},handler:({args:e})=>T(`migrate`,e)}),"migrate-held":t({name:`migrate-held`,args:{local:r({long:`local`,description:`Run held migrations against the Coreframe-managed local PostgreSQL database.`,defaultValue:()=>!1})},handler:({local:e})=>S({target:e?`local`:`deployment`})}),"migrate-local":t({name:`migrate-local`,args:{},handler:C}),"migrations-check":t({name:`migrations-check`,args:{},handler:p}),reset:t({name:`reset`,args:{},handler:te}),seed:t({name:`seed`,args:{},handler:()=>re()}),"schema-check":t({name:`schema-check`,args:{seed:r({long:`seed`,description:`Run the configured project seed against the throwaway database.`,defaultValue:()=>!1})},handler:({seed:e})=>m({seed:e})}),setup:t({name:`setup`,args:{},handler:()=>ie()}),studio:t({name:`studio`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit studio.`})},handler:({args:e})=>T(`studio`,e)})}}),za=`package.json`;async function Ba(e=process.argv.slice(2),t=process.env){let n=Va(e);Ya(n);let{packageJson:r,source:i}=await pt(za),a=await H(),o=_t(a.deploy,n.environment,t);Xa(n,o.mode),eo(t,[`POSTHOG_API_KEY`,`POSTHOG_PROJECT_ID`]);let s=await Za(o,n.environment,()=>rt({env:t})),c=o.mode===`full`?await Ua(n.environment,t):void 0,l=await Ja();await Jn({env:t,revision:l});let u=l.slice(0,12),d=vt(n.environment,r.version,u),f=gt(r.name,d),p={...io(t,n.environment,f,r.name,d),COREFRAME_I18N_RELEASE_REVISION:l},m=n.environment===`production`,h=!1;L.intro(`Deploy ${f} to ${n.environment}`);let g=Object.keys(c?.pendingWorkerSecrets.values??{}).sort();g.length>0&&L.note(g.join(`
13
- `),`Pending Worker secret updates`),c?.accessTokenSigningSecret.provisioned&&L.log.info(`Provisioning Coreframe-managed access-token signing material.`),await $a(n);let _=o.mode===`full`?await Wa(a,n,t):!1;try{m&&await wt(za,r,d),L.log.step(`Running pre-deploy build`),await I(`pnpm`,[`build`],{env:ao(p),stdio:`inherit`}),L.log.step(`Running release build and uploading PostHog source maps`),h=!0,await I(`pnpm`,[`build`],{env:p,stdio:`inherit`}),_&&(L.log.step(`Running deploy-safe database migrations`),await I(`pnpm`,[`db`,`migrate`],{env:p,stdio:`inherit`})),L.log.step(o.mode===`full`?`Deploying Worker and static assets to Cloudflare`:`Deploying static assets to Cloudflare`);let e={...c?.dashboardPassword?{DASHBOARD_PASSWORD:c.dashboardPassword}:{},...c?.accessTokenSigningSecret.value?{[$e]:c.accessTokenSigningSecret.value}:{},...c?.pendingWorkerSecrets.values},t=Object.keys(e).length>0?await no(e):void 0,i=o.mode===`full`?await ot({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:f}}}):await at(process.cwd());try{await I(`pnpm`,[`exec`,`wrangler`,`deploy`,`--config`,i.path,...o.mode===`full`?[`--env`,n.environment]:[],`--strict`,`--keep-vars`,`--tag`,f,`--message`,`Deploy ${f}`,...t?[`--secrets-file`,t.path]:[]],{env:p,stdio:`inherit`}),c&&(await et(c.pendingWorkerSecrets),await Ct({environment:n.environment}))}finally{await i.dispose(),await t?.dispose()}let l={environment:n.environment,releaseName:f,url:s,version:d};o.mode===`full`&&o.afterWorkerDeploy&&(L.log.step(`Running required after-Worker deploy hook`),await bt(o,l)),n.skipPostDeployChecks||(L.log.step(`Running post-deploy checks`),await xt(o,l)),L.outro(`Deployed ${f} to ${n.environment}`)}catch(e){throw!h&&m&&await V(za,i),e}}function Va(e){return{environment:Ha(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function Ha(e){if(e&&tt.includes(e))return e;throw Error(`Deploy environment must be one of: ${tt.join(`, `)}.`)}async function Ua(e,t){let n=await mt({environment:e}),r=n.values.DASHBOARD_PASSWORD??await to(t,e);return St(await it({environment:e}),e,{availableNames:[...Object.keys(n.values),...r?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await lt({environment:e}),dashboardPassword:r,pendingWorkerSecrets:n}}async function Wa(e,t,n){let r=e.database?.dialect??`postgres`,i;switch(r){case`postgres`:i=await g({env:n});break;case`sqlite`:i=await _({env:n});break;default:throw Error(`Unsupported database dialect "${r}".`)}let a=await Ga(i),o=await ne(a);if(o.length>0)throw Error(`Pending deploy migrations contain unsafe SQL. Move unsafe statements to held migrations.\n${x(o)}`);return qa(t,a)}async function Ga(e){try{return await Ka(e)}finally{await e.close?.()}}async function Ka(e){return ee(await h(),await w(e))}async function qa(e,t){if(t.length===0)return L.log.info(`No pending deploy migrations.`),!1;if(L.note(b(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 L.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(L.isCancel(n))throw L.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function Ja(){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 Ya(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function Xa(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function Za(e,t,n=rt){return e.url?Qa(e.url,t):t===`staging`&&e.stagingHostname?Qa(await n(),t):Qa(void 0,t)}function Qa(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 $a(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await L.confirm({initialValue:!1,message:`Deploy to production?`});if(L.isCancel(t)||!t)throw L.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}function eo(e,t){let n=t.filter(t=>!e[t]);if(n.length>0)throw Error(`Missing required deploy environment variables: ${n.join(`, `)}`);return Object.fromEntries(t.map(t=>[t,e[t]]))}async function to(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Et(await z(`.env`,`utf8`))}catch(e){throw ro(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 no(e){let t=await De(M(Ne(),`coreframe-deploy-secrets-`)),n=M(t,`secrets.json`);return await V(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>B(t,{force:!0,recursive:!0})}}function ro(e){return e instanceof Error&&`code`in e}function io(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 ao(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function oo(){let e=await co();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function so(e){let t=await co(),n=lo();await Q.mkdir(A.dirname(n),{recursive:!0}),await Q.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function co(){try{let e=await Q.readFile(lo(),`utf8`),t=JSON.parse(e);return uo(t)?t:{}}catch{return{}}}function lo(){return A.join(Cr.homedir(),`.coreframe`,`preferences.json`)}function uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function fo({env:e=W.env,interactive:t=W.stdin.isTTY===!0,platform:n,target:r}){let i=await yo(n,e).catch(()=>[]),a=r?Lo(i,r):void 0;if(a)return a;if(!r&&i.length>0)return vo(i,n,t);let o=r?Lo(await xo(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return So(o,n,e,t);let s=await bo(n,e),c=r?Lo(s,r):void 0;if(c)return c;if(!r&&s.length>0)return vo(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 po(e){let{device:t,host:n,interactive:r=W.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=zo();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await go();if(a&&i.includes(a))return a;if(i.length===1)return await _o(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await L.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(L.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await _o(o),o}async function mo({device:e,env:t=W.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await Ao(e.id,a,t)}catch{L.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:ho(i,await po({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function ho(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 go(){return(await oo()).mobileDevHost}async function _o(e){try{await so({mobileDevHost:e})}catch(e){L.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function vo(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 L.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(L.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function yo(e,t){return e===`android`?wo(t):Eo(t)}async function bo(e,t){return e===`android`?To(t):Do(t)}async function xo(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 So(e,t,n,r){let i=await Co(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 Co(t,n).catch(()=>[]),o=Lo(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return vo(s,t,r);if(a.length===1)return a[0];await Rt(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 Co(e,t){return e===`ios`?Do(t,`booted`):(await wo(t)).filter(e=>!e.physical)}async function wo(e){let t=await ko(e,`platform-tools`,W.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 Mo(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await Po(t,e,n,r):await Fo(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(Bo)}async function To(e){let{stdout:t}=await I(await ko(e,`emulator`,W.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 Eo(e){let t=await Q.mkdtemp(A.join(Cr.tmpdir(),`coreframe-ios-devices-`)),n=A.join(t,`devices.json`);try{return await Q.writeFile(n,``),await I(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await Q.readFile(n,`utf8`)).result?.devices??[]).filter(Oo).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(Bo)}finally{await Q.rm(t,{force:!0,recursive:!0})}}async function Do(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(Bo)}function Oo(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 ko(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:jo(e);for(let e of i){let r=A.join(e,t,n);try{return await Q.access(r),r}catch{}}return n}async function Ao(e,t,n){let r=await ko(n,`platform-tools`,W.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 jo(e){return W.platform===`darwin`?[A.join(Cr.homedir(),`Library`,`Android`,`sdk`)]:W.platform===`win32`&&e.LOCALAPPDATA?[A.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[A.join(Cr.homedir(),`Android`,`Sdk`)]}async function Mo(e,t,n,r){return(await No(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function No(e,t,n){return(await I(e,n,{env:t,timeout:3e3})).stdout}async function Po(e,t,n,r){return No(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function Fo(e,t,n,r){return No(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>Io(e)||r).catch(()=>r)}function Io(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function Lo(e,t){let n=e.map(e=>({device:e,score:Math.max(Ro(t,e.name),Ro(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function Ro(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 zo(){return[...new Set(Object.values(Cr.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function Bo(e,t){return e.label.localeCompare(t.label)}async function Vo(e,t){if(!e)return()=>void 0;Ve(A.dirname(e),{recursive:!0}),q(e,``,{flag:`a`});let n;try{n=K(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=Ke(e,{persistent:!1},()=>{if(i)return;let a=++r;z(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function Ho(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const Uo=W.platform===`win32`?`portless.cmd`:`portless`,Wo=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),Go=/^Proxy is already running on port (\d+)\.$/,Ko=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function qo(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(Wo,``).trim().match(Go);if(a?.[1]!==void 0&&i!==void 0&&Ko.test(i.replace(Wo,``).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 Jo(e){let t=qo(e);t&&W.stdout.write(t.endsWith(`
14
- `)?t:`${t}\n`)}async function Yo({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await zt()).isAgent?!1:Mt(e)}async function Xo({cwd:e,env:t,lan:n=!1}){let r=A.join(`node_modules`,`.bin`,Uo),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await I(A.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});Jo(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Jo(e.stdout),e}}function Zo({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 Qo=/A Dart VM Service on .+ is available at: (https?:\/\/\S+)/u,$o=/The Flutter DevTools debugger and profiler on .+ is available at: (https?:\/\/\S+)/u,es=A.join(`.coreframe`,`dev`,`session.json`);async function ts({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=A.resolve(t,es),d=A.dirname(u),f={version:1,id:a,pid:c,projectRoot:A.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:A.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,...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 R(d,{recursive:!0});let t=A.join(d,`.session-${a}.json`);await V(t,e),await ke(t,u)}),p};return await m(),{path:u,async recordFlutterOutput(e){let t=e.match(Qo)?.[1],n=e.match($o)?.[1];f.flutter===void 0||t===void 0&&n===void 0||(f={...f,flutter:{...f.flutter,...t===void 0?void 0:{vmServiceUri:t},...n===void 0?void 0:{devToolsUri:n}}},await m())},async close(){await p;try{JSON.parse(await z(u,`utf8`)).id===a&&await B(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}const ns=`extension:dev`;function rs(e){if(!G(M(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=M(e,`package.json`),n;try{n=JSON.parse(K(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.${ns} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function is({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`,ns,...n.length>0?[`--`,...n]:[]]}const as=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],os=[`managed-dev-overlay`],ss=A.resolve(`node_modules`,`.bin`),cs=W.platform===`win32`?`pnpm.cmd`:`pnpm`,ls=W.platform===`win32`?`portless.cmd`:`portless`,us=W.platform===`win32`?`react-router.cmd`:`react-router`;async function ds({cwd:e=W.cwd(),debug:t,device:n,env:r=W.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=W.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=Ot({env:r}),ee=r.PATH??r.Path??``,y=bs(h)?h:void 0,b=Gt(i||a),x=ys(_??r.COREFRAME_WEB_PORT),S,C,w,te,T,ne,re,ie,ae,se,ce,le,E=!1,de,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.`);rs(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 O=await v.measure(`routing`,()=>Yo({cwd:e,env:r,platform:h}));O&&await v.measure(`portless`,()=>Xo({cwd:e,env:r,lan:u}));let k=y===void 0?h===`web`?x??await Sr.getAvailablePort():h===`webext`?x:void 0:x??await Sr.getAvailablePort(),j,pe=new Promise(e=>{j=e}),M=()=>{E||(E=!0,j(),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),ae?.close().catch(()=>void 0),S?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),N().catch(()=>void 0))},N=()=>te?(T??=te[Symbol.asyncDispose](),T):Promise.resolve(),P=e=>{de??=e,M()},F=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>P(e);return W.on(e,t),{handler:t,signal:e}}),me=async e=>{let t=Je(e);C=t;try{await t.expectSuccess()}catch(e){if(!E)throw e}finally{C===t&&(C=void 0)}};try{ce=y?Lt({path:A.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await fo({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&Kt({device:_,mode:b,platform:i});let x=y?ce?.logger({scope:`dev.flutter`,properties:{platform:y,..._?{deviceId:_.id}:void 0}}):void 0;se=i&&_&&k!==void 0?await mo({device:_,env:r,host:s,interactive:l,platform:i,port:k}):void 0;let C=se?.viteHost??(y?i?!0:`127.0.0.1`:s),T=k===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${k}`,de=y===void 0?T:se?.serverUrl??ho(y,void 0,k),j={},N=!1,P;[j,N]=await Promise.all([v.measure(`config`,()=>H({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await jt(e))]),await v.measure(`i18n`,()=>Kn({cwd:e,projectConfig:j})),P=h!==`webext`&&kr(e)?await Sr.getAvailablePort():void 0;let F=await v.measure(`https`,async()=>c&&!O?Nt({cwd:e}):void 0),he=Ho(r,h);D={...he,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Pt]:U()}:void 0,...y?{COREFRAME_PLATFORM:y,[It]:A.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...F?{[kt]:F.cert,[At]:F.key}:void 0,...P?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${P}`}:void 0},T!==void 0&&de!==void 0&&(le=await ts({appOrigin:de,cwd:e,device:_,flutterMcp:a,flutterMode:y===void 0?void 0:b,id:U(),localOrigin:T,platform:h}));let ge=async()=>{if(!P)return;let t=Ar({cwd:e,env:D,port:P});ae=t;try{await t.listen(),await t.wait()}finally{await t.close(),ae===t&&(ae=void 0)}},_e=async()=>{let t=J({label:`web`}),n=J({color:`red`,label:`web`});t.pipe(W.stdout,{end:!1}),n.pipe(W.stderr,{end:!1}),re=I(O?ls:us,O?Zo({host:C,lan:u,port:k}):vs({host:C,port:k,strictPort:h===`web`||y!==void 0}),{cwd:e,env:{...D,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[D.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:ss+A.delimiter+ee},stdin:`inherit`});let r=Promise.allSettled([ms(re.stdout,t),ms(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([qe(t),qe(n)]),re=void 0}},ve=async()=>{let t=J({label:`webext`}),n=J({color:`red`,label:`webext`});t.pipe(W.stdout,{end:!1}),n.pipe(W.stderr,{end:!1}),ie=I(cs,is({host:s,port:k}),{cwd:e,env:D,stdin:`inherit`});let r=Promise.allSettled([ms(ie.stdout,t),ms(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([qe(t),qe(n)]),ie=void 0}},ye=async t=>{let n,r=!1,i=Vo(D[It],()=>{if(!(E||!n)){if(b===`debug`){n.nodeChildProcess.then(e=>e.stdin?.write(`R`)).catch(()=>void 0);return}r||(r=!0,n.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0))}});try{for(;!E;){r=!1;let i=h===`android`&&o===`filtered`&&!g?await fe():void 0,s=I(`flutter`,qt({device:_??{id:h},flutterDriver:a,mode:b,serverUrl:de,verbose:g}),{cwd:A.join(e,`src-flutter`),env:Wt(he,{noCodesign:f}),stdio:[b===`debug`?`pipe`:`ignore`,`pipe`,`pipe`]});S=s,n=s;try{let e=i?i.capture(ps(s,x,`output`,le?.recordFlutterOutput)):Promise.all([fs(s.stdout,W.stdout,x,`stdout`,le?.recordFlutterOutput),fs(s.stderr,W.stderr,x,`stderr`,le?.recordFlutterOutput)]);if(await Promise.all([s,e]),!r||E)return}catch{if(r&&!E)continue;if(E)return;let e=l?await L.confirm({initialValue:!0,message:`Flutter failed. Retry?`}):!1;if(L.isCancel(e)||!e){L.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??pe);return}}finally{S===s&&(S=void 0),n===s&&(n=void 0)}}}finally{(await i)()}},be=async()=>{if(h===`web`){await _e();return}let t=_e().then(()=>{if(!E)throw Error(`The Vite development server stopped while Flutter was still running.`)});await ue({cwd:e});try{await Promise.race([t,ye(t)])}finally{M(),await Promise.allSettled([t,S]),S=void 0}},xe=async()=>{let t=Je({name:`panda`,command:cs,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)}},Se=async()=>{if(h===`webext`){await ve();return}let e=xe(),t=be(),n=P?ge():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),E&&await t}finally{M(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(N&&(D={...D,[Ft]:`1`}),E)return;if(h===`webext`){v.report(),await Se();return}if(j.database?.dialect===`sqlite`&&(await v.measure(`database`,async()=>{let t=await oe({config:j,cwd:e,env:r,tursoOutput:W.stdout,useSupervisorLease:!0});te=t,D={...D,...t.env}}),await v.measure(`schema`,()=>me({name:`db`,command:cs,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E))return;if(_s(j)){let t=J({label:`postgres`});t.pipe(W.stdout,{end:!1});try{let n=await v.measure(`database`,()=>gs({config:j,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`,()=>me({name:`db`,command:cs,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E||(v.report(),await Se())}finally{await n[Symbol.asyncDispose](),w===n&&(w=void 0)}}finally{t.end()}return}v.report(),await Se()}finally{M(),await se?.close(),se=void 0;let e;try{await w?.[Symbol.asyncDispose]()}catch(t){e=t}finally{await N();try{await le?.close()}finally{ce?.close();for(let{handler:e,signal:t}of F)W.off(t,e)}de&&(W.exitCode??=de===`SIGINT`?130:143)}hs(e)}}async function fs(e,t,n,r,i){for await(let a of ps(e,n,r,i))t.write(`${a}\n`)||await Dt(t,`drain`)}async function*ps(e,t,n,r){for await(let i of e){let e=le(i);e.message&&(t?.write(e.level,e.message,{properties:{stream:n}}),await r?.(e.message)),yield i}}async function ms(e,t){for await(let n of e)t.write(`${n}\n`)||await Dt(t,`drain`)}function hs(e){if(e)throw e}async function gs({interactive:e,isStopping:t,...n}){try{return await ae(n)}catch(r){if(!(r instanceof f)||!e)throw r;let i=await L.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(L.isCancel(i)||!i){L.cancel(`Keeping the existing PostgreSQL process.`);return}return await se(r),t()?void 0:ae(n)}}function _s(e){return(e.database?.dialect??`postgres`)===`postgres`}function vs({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 ys(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 bs(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function xs(e={}){let t=e.cwd??W.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await Ce(A.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Fe(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 Bt({...e,cwd:t},r)}const Ss=`worker-configuration.d.ts`;async function Cs({check:e=!1,cwd:t=process.cwd()}={}){let n=await H({cwd:t}),r=await st({coreframeConfig:n,cwd:t}),i=P(t,Ss),a=P(t,`.coreframe-worker-types-${U()}.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 ws(e),e}let o=Ts(await z(a,`utf8`)),s=Le(r.config),c=Ie(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${Es(c)}\n`;if(e){if(await z(i,`utf8`).catch(()=>``)!==l)throw Error(`${Ss} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await z(i,`utf8`).catch(()=>``);return u!==l&&await V(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await B(a,{force:!0})}}function ws(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
15
- `)?t:`${t}\n`)}function Ts(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
16
- `)}function Es(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(`
17
- `)}const Ds=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),Os=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],ks=[`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`],As=[`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`],js=`.coreframe/typegen.json`,Ms=[`web`,`dashboard`,`worker`];async function Ns({checkWorker:e=!1,cwd:t=W.cwd(),runners:n={}}={}){let r=await Ls(t)??{generators:{},schemaVersion:1},i=[];return i.push(await Fs({cwd:t,inputPaths:Os,name:`web`,outputPath:`.react-router`,run:()=>(n.web??Is)(t),state:r})),i.push(await Fs({cwd:t,inputPaths:ks,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??_r)(t),state:r})),i.push(await Fs({cwd:t,inputPaths:As,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??Cs)({check:e,cwd:t}),state:r})),i}function Ps(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function Fs({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await zs(e,t),s=await Bs(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 Bs(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await Rs(e,a),{changed:s!==l,name:n,ran:!0}}async function Is(e){let t=W.platform===`win32`?`react-router.cmd`:`react-router`,n=W.env;await I(t,[`typegen`],{cwd:e,env:{...n,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function Ls(e){try{let t=JSON.parse(await z(A.resolve(e,js),`utf8`));if(!Ws(t)||t.schemaVersion!==1)return;let n={};if(!Ws(t.generators))return;for(let e of Ms){let r=t.generators[e];Ws(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 Rs(e,t){let n=A.resolve(e,js);await R(A.dirname(n),{recursive:!0}),await V(n,`${JSON.stringify(t)}\n`,{mode:384})}async function zs(e,t){let n=Re(`sha256`);for(let r of[...t].sort()){let t=A.resolve(e,r),i=await Hs(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Vs(t)){let i=A.join(t,r),a=A.relative(e,i).split(A.sep).join(`/`);n.update(`${a}\0`),n.update(await z(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await z(t)))}return n.digest(`hex`)}async function Bs(e,t){if(await Hs(A.resolve(e,t)))return zs(e,[t])}async function Vs(e){let t=[];async function n(e,r){let i=await Oe(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(Ds.has(a.name))continue;await n(A.join(e,a.name),A.join(r,a.name))}else a.isFile()&&t.push(A.join(r,a.name))}return await n(e,``),t.sort()}async function Hs(e){try{return await Ae(e)}catch(e){if(Us(e))return;throw e}}function Us(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Ws(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gs=A.resolve(`node_modules`,`.bin`);W.env.PATH=Gs+A.delimiter+W.env.PATH;const Ks=W.platform===`win32`?`tsc.cmd`:`tsc`,qs=[{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 Js(){await Ns({checkWorker:!0});let e=[];for(let t of qs)try{await Ce(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>Je({name:e.name,command:Ks,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(W.exitCode=n[0].exitCode)}const Ys=n(a(os),{displayName:`feature`,from:async e=>e}),Xs=n(a(Ut),{displayName:`filtered|full`,from:async e=>e}),Zs=[`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.`],Qs=t({name:`deploy`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:r({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:r({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:r({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:r({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>Ba([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),$s=d({name:`staging`,cmds:{reassign:t({name:`reassign`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ht();if(e){console.log(JSON.stringify({...t,notices:Zs}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Zs.join(` `)}`)}}),url:t({name:`url`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await rt();console.log(e?JSON.stringify({url:t}):t)}})}}),ec=d({name:`secrets`,cmds:{"rotate-access-token":t({name:`rotate-access-token`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:r({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 yt({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:t({name:`status`,args:{environment:c({type:s(a(tt)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await it({environment:e});console.log(t?JSON.stringify(n):oc(n))}}),set:t({name:`set`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:c({type:s(u),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:r({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 ut({environment:e,name:t,value:await sc(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await ft(),i=n?await lc(r):await cc(r,e);await dt({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:t({name:`discard`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:c({type:u,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await nt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),tc=t({name:`typecheck`,args:{},handler:Js}),nc=d({name:`worker`,cmds:{typegen:t({name:`typegen`,args:{check:r({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await Cs({check:e});console.log(e?`${dc(t.path)} is current.`:`${dc(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),rc=t({name:`dev`,args:{debug:o({long:`debug`,type:s(Ys),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:r({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:r({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:o({long:`flutter-output`,type:Xs,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:r({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:o({long:`host`,type:s(u),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:r({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:r({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:r({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:r({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:r({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:c({type:s(a(as)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:c({type:s(u),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:o({long:`port`,type:s(i),description:`Port for the web development server.`}),verbose:r({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=ic({device:t,flutterDebug:n,platform:f,simulator:m});return ds({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 ic({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 ac=t({name:`preview`,args:{host:o({long:`host`,type:s(u),description:`Host address for the preview server.`}),port:o({long:`port`,type:s(i),description:`Port for the preview server.`})},handler:({host:e,port:t})=>xs({host:e,port:t})});function oc(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=>e.map((e,t)=>e.padEnd(r[t])).join(` `).trimEnd();return[i(n),i(r.map(e=>`-`.repeat(e))),...t].join(`
18
- `)}async function sc(e){if(!W.stdin.isTTY){let e=``;for await(let t of W.stdin)e+=t.toString();return e.replace(/\r?\n$/,``)}let t=await L.password({message:`Enter the new value for ${e}`});if(L.isCancel(t))throw L.cancel(`Secret update cancelled.`),Error(`Secret update cancelled.`);return t}async function cc(e,t){if(!W.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 L.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(L.isCancel(i))throw L.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);i.trim()&&(n[r.name]=i)}return n}async function lc(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=W.stdin.isTTY?await L.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 uc();if(L.isCancel(t))throw L.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=ct(t,e);return n.length>0&&L.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function uc(){let e=``;for await(let t of W.stdin)e+=t.toString();return e}function dc(e){return e.split(/[\\/]/).at(-1)??e}const fc=t({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await Ns();for(let t of e)console.log(Ps(t))}});function pc(e,{formatMessage:t,temporaryDirectory:n=Ne(),write:r=e=>console.error(e)}={}){let i=yc(e),a=Sc(hc(e,t),i);try{let t=M(He(M(n,`coreframe-error-`)),`error.log`);return q(t,`${Sc(gc(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 mc(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,pc(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function hc(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 gc(e){try{let t=_c(e);if(!(e instanceof Error)||!vc(t))return Tt(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${Tt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function _c(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:_c(a.value,t),writable:!0})}return i}function vc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yc(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`?bc(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function bc(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&xc(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function xc(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function Sc(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const Cc=d({name:`coreframe`,cmds:{build:sn,dashboard:Nr,assets:fr,flutter:pr,i18n:mr,deploy:Qs,staging:$s,secrets:ec,typegen:fc,typecheck:tc,worker:nc,dev:rc,preview:ac,upgrade:Ia,recipes:La,db:Ra}});import.meta.main&&mc(Cc,{formatMessage:process.argv[2]===`db`?y:void 0});export{Cc as coreframeCli};
12
+ `:``;Ge(e,`${JSON.stringify(n,null,r)}${i}`)}function Pa(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t)console.log(` ${e}`);console.log(``)}}function Fa(e){let t=P(wa([`rev-parse`,`--show-toplevel`]).trim(),`package.json`),n=J(t,`utf8`),r=Ta(n,t),i=$(e.target),a=ja(i),o=new Set(a.map(({name:e})=>e)),s=[],c=[],l=[],u=0;for(let e of a){let t=Ma(r,e.name);if(!t){c.push(`missing: ${e.name} ${e.spec} (${e.group})`);continue}if(Oa(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=Ca.flatMap(e=>Object.entries(r[e]??{}).filter(([e])=>Da(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;Na(t,n,r)}console.log(`Coreframe package sync: ${i}`),console.log(``),Pa(e.apply?`Updated Coreframe packages`:`Would update Coreframe packages`,s.map(({currentSpec:e,name:t,spec:n})=>`update: ${t} ${e} -> ${n}`)),Pa(`Missing target Coreframe packages`,c),Pa(`Locally linked Coreframe packages`,l),Pa(`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 Ia={...u,displayName:`recipe`,description:`Coreframe recipe name, such as yam-db.`,async from(e){return Lr(e)}},La=d({name:`upgrade`,cmds:{"ensure-template-remote":t({name:`ensure-template-remote`,args:{remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Remote name to ensure.`}),noFetch:r({long:`no-fetch`,description:`Do not fetch the remote after ensuring it exists.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t})=>qr({fetch:!e,remote:t})}),"check-skill-current":t({name:`check-skill-current`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),apply:r({long:`apply`,description:`Replace the local upgrade skill with the target version when it differs.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>{process.exitCode=Qi({apply:e,target:t})}}),"fast-forward-template-files":t({name:`fast-forward-template-files`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),base:o({long:`base`,type:s(u),description:`Previous Coreframe template git ref. Defaults to package.json engines.coreframe.`}),apply:r({long:`apply`,description:`Write clean fast-forwards to the worktree.`,defaultValue:()=>!1})},handler:({apply:e,base:t,target:n})=>Sa({apply:e,base:t,target:n})}),"sync-coreframe-packages":t({name:`sync-coreframe-packages`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),apply:r({long:`apply`,description:`Update existing published Coreframe dependency specifications.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>Fa({apply:e,target:t})})}}),Ra=d({name:`recipes`,cmds:{apply:t({name:`apply`,args:{recipe:c({type:Ia,displayName:`recipe`,description:`Recipe to prepare and apply.`}),target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Ei(Ti({fetch:!e,name:t,remote:n,target:r}))}),list:t({name:`list`,args:{target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,target:n})=>Gi(Wi({fetch:!e,remote:t,target:n}))}),verify:t({name:`verify`,args:{recipe:c({type:Ia,displayName:`recipe`,description:`Recipe adoption to verify.`}),target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Si(xi({fetch:!e,name:t,remote:n,target:r}))})}}),za=d({name:`db`,cmds:{ensure:t({name:`ensure`,args:{},handler:v}),generate:t({name:`generate`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit generate.`})},handler:({args:e})=>T(`generate`,e)}),migrate:t({name:`migrate`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit migrate.`})},handler:({args:e})=>T(`migrate`,e)}),"migrate-held":t({name:`migrate-held`,args:{local:r({long:`local`,description:`Run held migrations against the Coreframe-managed local PostgreSQL database.`,defaultValue:()=>!1})},handler:({local:e})=>S({target:e?`local`:`deployment`})}),"migrate-local":t({name:`migrate-local`,args:{},handler:C}),"migrations-check":t({name:`migrations-check`,args:{},handler:p}),reset:t({name:`reset`,args:{},handler:te}),seed:t({name:`seed`,args:{},handler:()=>re()}),"schema-check":t({name:`schema-check`,args:{seed:r({long:`seed`,description:`Run the configured project seed against the throwaway database.`,defaultValue:()=>!1})},handler:({seed:e})=>m({seed:e})}),setup:t({name:`setup`,args:{},handler:()=>ie()}),studio:t({name:`studio`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit studio.`})},handler:({args:e})=>T(`studio`,e)})}}),Ba=`package.json`;async function Va(e=process.argv.slice(2),t=process.env){let n=Ha(e);Xa(n);let{packageJson:r,source:i}=await pt(Ba),a=await W(),o=_t(a.deploy,n.environment,t);Za(n,o.mode),to(t,[`POSTHOG_API_KEY`,`POSTHOG_PROJECT_ID`]);let s=await Qa(o,n.environment,()=>rt({env:t})),c=o.mode===`full`?await Wa(n.environment,t):void 0,l=await Ya();await Yn({env:t,revision:l});let u=l.slice(0,12),d=vt(n.environment,r.version,u),f=gt(r.name,d),p={...ao(t,n.environment,f,r.name,d),COREFRAME_I18N_RELEASE_REVISION:l},m=n.environment===`production`,h=!1;L.intro(`Deploy ${f} to ${n.environment}`);let g=Object.keys(c?.pendingWorkerSecrets.values??{}).sort();g.length>0&&L.note(g.join(`
13
+ `),`Pending Worker secret updates`),c?.accessTokenSigningSecret.provisioned&&L.log.info(`Provisioning Coreframe-managed access-token signing material.`),await eo(n);let _=o.mode===`full`?await Ga(a,n,t):!1;try{m&&await wt(Ba,r,d),L.log.step(`Running pre-deploy build`),await I(`pnpm`,[`build`],{env:oo(p),stdio:`inherit`}),L.log.step(`Running release build and uploading PostHog source maps`),h=!0,await I(`pnpm`,[`build`],{env:p,stdio:`inherit`}),_&&(L.log.step(`Running deploy-safe database migrations`),await I(`pnpm`,[`db`,`migrate`],{env:p,stdio:`inherit`})),L.log.step(o.mode===`full`?`Deploying Worker and static assets to Cloudflare`:`Deploying static assets to Cloudflare`);let e={...c?.dashboardPassword?{DASHBOARD_PASSWORD:c.dashboardPassword}:{},...c?.accessTokenSigningSecret.value?{[$e]:c.accessTokenSigningSecret.value}:{},...c?.pendingWorkerSecrets.values},t=Object.keys(e).length>0?await ro(e):void 0,i=o.mode===`full`?await ot({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:f}}}):await at(process.cwd());try{await I(`pnpm`,[`exec`,`wrangler`,`deploy`,`--config`,i.path,...o.mode===`full`?[`--env`,n.environment]:[],`--strict`,`--keep-vars`,`--tag`,f,`--message`,`Deploy ${f}`,...t?[`--secrets-file`,t.path]:[]],{env:p,stdio:`inherit`}),c&&(await et(c.pendingWorkerSecrets),await Ct({environment:n.environment}))}finally{await i.dispose(),await t?.dispose()}let l={environment:n.environment,releaseName:f,url:s,version:d};o.mode===`full`&&o.afterWorkerDeploy&&(L.log.step(`Running required after-Worker deploy hook`),await bt(o,l)),n.skipPostDeployChecks||(L.log.step(`Running post-deploy checks`),await xt(o,l)),L.outro(`Deployed ${f} to ${n.environment}`)}catch(e){throw!h&&m&&await U(Ba,i),e}}function Ha(e){return{environment:Ua(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function Ua(e){if(e&&tt.includes(e))return e;throw Error(`Deploy environment must be one of: ${tt.join(`, `)}.`)}async function Wa(e,t){let n=await mt({environment:e}),r=n.values.DASHBOARD_PASSWORD??await no(t,e);return St(await it({environment:e}),e,{availableNames:[...Object.keys(n.values),...r?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await lt({environment:e}),dashboardPassword:r,pendingWorkerSecrets:n}}async function Ga(e,t,n){let r=e.database?.dialect??`postgres`,i;switch(r){case`postgres`:i=await g({env:n});break;case`sqlite`:i=await _({env:n});break;default:throw Error(`Unsupported database dialect "${r}".`)}let a=await Ka(i),o=await ne(a);if(o.length>0)throw Error(`Pending deploy migrations contain unsafe SQL. Move unsafe statements to held migrations.\n${x(o)}`);return Ja(t,a)}async function Ka(e){try{return await qa(e)}finally{await e.close?.()}}async function qa(e){return ee(await h(),await w(e))}async function Ja(e,t){if(t.length===0)return L.log.info(`No pending deploy migrations.`),!1;if(L.note(b(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 L.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(L.isCancel(n))throw L.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function Ya(){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 Xa(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function Za(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function Qa(e,t,n=rt){return e.url?$a(e.url,t):t===`staging`&&e.stagingHostname?$a(await n(),t):$a(void 0,t)}function $a(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 eo(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await L.confirm({initialValue:!1,message:`Deploy to production?`});if(L.isCancel(t)||!t)throw L.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}function to(e,t){let n=t.filter(t=>!e[t]);if(n.length>0)throw Error(`Missing required deploy environment variables: ${n.join(`, `)}`);return Object.fromEntries(t.map(t=>[t,e[t]]))}async function no(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Et(await V(`.env`,`utf8`))}catch(e){throw io(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 ro(e){let t=await Te(M(je(),`coreframe-deploy-secrets-`)),n=M(t,`secrets.json`);return await U(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>H(t,{force:!0,recursive:!0})}}function io(e){return e instanceof Error&&`code`in e}function ao(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 oo(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function so(){let e=await lo();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function co(e){let t=await lo(),n=uo();await Q.mkdir(k.dirname(n),{recursive:!0}),await Q.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function lo(){try{let e=await Q.readFile(uo(),`utf8`),t=JSON.parse(e);return fo(t)?t:{}}catch{return{}}}function uo(){return k.join(wr.homedir(),`.coreframe`,`preferences.json`)}function fo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function po({env:e=K.env,interactive:t=K.stdin.isTTY===!0,platform:n,target:r}){let i=await bo(n,e).catch(()=>[]),a=r?Ro(i,r):void 0;if(a)return a;if(!r&&i.length>0)return yo(i,n,t);let o=r?Ro(await So(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return Co(o,n,e,t);let s=await xo(n,e),c=r?Ro(s,r):void 0;if(c)return c;if(!r&&s.length>0)return yo(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 mo(e){let{device:t,host:n,interactive:r=K.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=Bo();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await _o();if(a&&i.includes(a))return a;if(i.length===1)return await vo(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await L.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(L.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await vo(o),o}async function ho({device:e,env:t=K.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await jo(e.id,a,t)}catch{L.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:go(i,await mo({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function go(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 _o(){return(await so()).mobileDevHost}async function vo(e){try{await co({mobileDevHost:e})}catch(e){L.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function yo(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 L.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(L.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function bo(e,t){return e===`android`?To(t):Do(t)}async function xo(e,t){return e===`android`?Eo(t):Oo(t)}async function So(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 Co(e,t,n,r){let i=await wo(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 wo(t,n).catch(()=>[]),o=Ro(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return yo(s,t,r);if(a.length===1)return a[0];await zt(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 wo(e,t){return e===`ios`?Oo(t,`booted`):(await To(t)).filter(e=>!e.physical)}async function To(e){let t=await Ao(e,`platform-tools`,K.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 No(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await Fo(t,e,n,r):await Io(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(Vo)}async function Eo(e){let{stdout:t}=await I(await Ao(e,`emulator`,K.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 Do(e){let t=await Q.mkdtemp(k.join(wr.tmpdir(),`coreframe-ios-devices-`)),n=k.join(t,`devices.json`);try{return await Q.writeFile(n,``),await I(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await Q.readFile(n,`utf8`)).result?.devices??[]).filter(ko).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(Vo)}finally{await Q.rm(t,{force:!0,recursive:!0})}}async function Oo(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(Vo)}function ko(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 Ao(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:Mo(e);for(let e of i){let r=k.join(e,t,n);try{return await Q.access(r),r}catch{}}return n}async function jo(e,t,n){let r=await Ao(n,`platform-tools`,K.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 Mo(e){return K.platform===`darwin`?[k.join(wr.homedir(),`Library`,`Android`,`sdk`)]:K.platform===`win32`&&e.LOCALAPPDATA?[k.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[k.join(wr.homedir(),`Android`,`Sdk`)]}async function No(e,t,n,r){return(await Po(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function Po(e,t,n){return(await I(e,n,{env:t,timeout:3e3})).stdout}async function Fo(e,t,n,r){return Po(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function Io(e,t,n,r){return Po(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>Lo(e)||r).catch(()=>r)}function Lo(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function Ro(e,t){let n=e.map(e=>({device:e,score:Math.max(zo(t,e.name),zo(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function zo(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 Bo(){return[...new Set(Object.values(wr.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function Vo(e,t){return e.label.localeCompare(t.label)}async function Ho(e,t){if(!e)return()=>void 0;ze(k.dirname(e),{recursive:!0}),Ge(e,``,{flag:`a`});let n;try{n=J(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=We(e,{persistent:!1},()=>{if(i)return;let a=++r;V(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function Uo(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const Wo=K.platform===`win32`?`portless.cmd`:`portless`,Go=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),Ko=/^Proxy is already running on port (\d+)\.$/,qo=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function Jo(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(Go,``).trim().match(Ko);if(a?.[1]!==void 0&&i!==void 0&&qo.test(i.replace(Go,``).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 Yo(e){let t=Jo(e);t&&K.stdout.write(t.endsWith(`
14
+ `)?t:`${t}\n`)}async function Xo({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await Bt()).isAgent?!1:Nt(e)}async function Zo({cwd:e,env:t,lan:n=!1}){let r=k.join(`node_modules`,`.bin`,Wo),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await I(k.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});Yo(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Yo(e.stdout),e}}function Qo({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 $o=/A Dart VM Service on .+ is available at: (https?:\/\/\S+)/u,es=/The Flutter DevTools debugger and profiler on .+ is available at: (https?:\/\/\S+)/u,ts=k.join(`.coreframe`,`dev`,`session.json`);async function ns({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=k.resolve(t,ts),d=k.dirname(u),f={version:1,id:a,pid:c,projectRoot:k.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:k.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,...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 B(d,{recursive:!0});let t=k.join(d,`.session-${a}.json`);await U(t,e),await De(t,u)}),p};return await m(),{path:u,async recordFlutterOutput(e){let t=e.match($o)?.[1],n=e.match(es)?.[1];f.flutter===void 0||t===void 0&&n===void 0||(f={...f,flutter:{...f.flutter,...t===void 0?void 0:{vmServiceUri:t},...n===void 0?void 0:{devToolsUri:n}}},await m())},async close(){await p;try{JSON.parse(await V(u,`utf8`)).id===a&&await H(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}const rs=`extension:dev`;function is(e){if(!q(M(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=M(e,`package.json`),n;try{n=JSON.parse(J(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.${rs} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function as({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`,rs,...n.length>0?[`--`,...n]:[]]}const os=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],ss=[`managed-dev-overlay`],cs=k.resolve(`node_modules`,`.bin`),ls=K.platform===`win32`?`pnpm.cmd`:`pnpm`,us=K.platform===`win32`?`portless.cmd`:`portless`,ds=K.platform===`win32`?`react-router.cmd`:`react-router`;async function fs({cwd:e=K.cwd(),debug:t,device:n,env:r=K.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=K.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=kt({env:r}),ee=r.PATH??r.Path??``,y=xs(h)?h:void 0,b=Kt(i||a),x=bs(_??r.COREFRAME_WEB_PORT),S,C,w,te,T,ne,re,ie,ae,se,ce,le,de,E=!1,D,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&&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.`);is(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`,()=>Xo({cwd:e,env:r,platform:h}));pe&&await v.measure(`portless`,()=>Zo({cwd:e,env:r,lan:u}));let A=y===void 0?h===`web`?x??await Cr.getAvailablePort():h===`webext`?x:void 0:x??await Cr.getAvailablePort(),j,M=new Promise(e=>{j=e}),N=()=>{E||(E=!0,j(),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),ae?.close().catch(()=>void 0),S?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),P().catch(()=>void 0))},P=()=>te?(T??=te[Symbol.asyncDispose](),T):Promise.resolve(),F=e=>{D??=e,N()},me=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>F(e);return K.on(e,t),{handler:t,signal:e}}),he=async e=>{let t=Je(e);C=t;try{await t.expectSuccess()}catch(e){if(!E)throw e}finally{C===t&&(C=void 0)}};try{ce=y?Rt({path:k.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await po({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&qt({device:_,mode:b,platform:i});let x=y?ce?.logger({scope:`dev.flutter`,properties:{platform:y,..._?{deviceId:_.id}:void 0}}):void 0;se=i&&_&&A!==void 0?await ho({device:_,env:r,host:s,interactive:l,platform:i,port:A}):void 0;let C=se?.viteHost??(y?i?!0:`127.0.0.1`:s),T=A===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${A}`,D=y===void 0?T:se?.serverUrl??go(y,void 0,A),j={},P=!1,F;[j,P]=await Promise.all([v.measure(`config`,()=>W({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await Mt(e))]),await v.measure(`i18n`,()=>qn({cwd:e,projectConfig:j})),F=h!==`webext`&&Ar(e)?await Cr.getAvailablePort():void 0;let me=await v.measure(`https`,async()=>c&&!pe?Pt({cwd:e}):void 0),ge=Uo(r,h);O={...ge,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Ft]:G()}:void 0,...y?{COREFRAME_PLATFORM:y,[Lt]:k.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...me?{[At]:me.cert,[jt]:me.key}:void 0,...F?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${F}`}:void 0},T!==void 0&&D!==void 0&&(le=await ns({appOrigin:D,cwd:e,device:_,flutterMcp:a,flutterMode:y===void 0?void 0:b,id:G(),localOrigin:T,platform:h}));let _e=async()=>{if(!F)return;let t=jr({cwd:e,env:O,port:F});ae=t;try{await t.listen(),await t.wait()}finally{await t.close(),ae===t&&(ae=void 0)}},R=async()=>{let t=qe({label:`web`}),n=qe({color:`red`,label:`web`});t.pipe(K.stdout,{end:!1}),n.pipe(K.stderr,{end:!1}),re=I(pe?us:ds,pe?Qo({host:C,lan:u,port:A}):ys({host:C,port:A,strictPort:h===`web`||y!==void 0}),{cwd:e,env:{...O,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[O.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:cs+k.delimiter+ee},stdin:`inherit`});let r=Promise.allSettled([hs(re.stdout,t),hs(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([Ke(t),Ke(n)]),re=void 0}},ve=async()=>{let t=qe({label:`webext`}),n=qe({color:`red`,label:`webext`});t.pipe(K.stdout,{end:!1}),n.pipe(K.stderr,{end:!1}),ie=I(ls,as({host:s,port:A}),{cwd:e,env:O,stdin:`inherit`});let r=Promise.allSettled([hs(ie.stdout,t),hs(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([Ke(t),Ke(n)]),ie=void 0}},ye=async t=>{let n,r=!1,i=Ho(O[Lt],()=>{if(!(E||!n)){if(b===`debug`){n.nodeChildProcess.then(e=>e.stdin?.write(`R`)).catch(()=>void 0);return}r||(r=!0,n.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0))}});try{for(;!E;){r=!1;let i=h===`android`&&o===`filtered`&&!g?await fe():void 0,s=I(`flutter`,Jt({device:_??{id:h},flutterDriver:a,mode:b,serverUrl:D,verbose:g}),{cwd:k.join(e,`src-flutter`),env:Gt(ge,{noCodesign:f}),stdio:[b===`debug`?`pipe`:`ignore`,`pipe`,`pipe`]});S=s,n=s;try{let e=i?i.capture(ms(s,x,`output`,le?.recordFlutterOutput)):Promise.all([ps(s.stdout,K.stdout,x,`stdout`,le?.recordFlutterOutput),ps(s.stderr,K.stderr,x,`stderr`,le?.recordFlutterOutput)]);if(await Promise.all([s,e]),!r||E)return}catch{if(r&&!E)continue;if(E)return;let e=l?await L.confirm({initialValue:!0,message:`Flutter failed. Retry?`}):!1;if(L.isCancel(e)||!e){L.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??M);return}}finally{S===s&&(S=void 0),n===s&&(n=void 0)}}}finally{(await i)()}},be=async()=>{if(h===`web`){await R();return}let t=R().then(()=>{if(!E)throw Error(`The Vite development server stopped while Flutter was still running.`)});await ue({cwd:e});try{await Promise.race([t,ye(t)])}finally{N(),await Promise.allSettled([t,S]),S=void 0}},xe=async()=>{let t=Je({name:`panda`,command:ls,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:O});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)}},z=async()=>{if(h===`webext`){await ve();return}let e=xe(),t=be(),n=F?_e():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),E&&await t}finally{N(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(P&&(O={...O,[It]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(de=await v.measure(`supervisor`,()=>Ot({cwd:e,env:r})))),E)return;if(h===`webext`){v.report(),await z();return}if(j.database?.dialect===`sqlite`&&(await v.measure(`database`,async()=>{let t=await oe({config:j,cwd:e,env:r,tursoOutput:K.stdout,useSupervisorLease:!0});te=t,O={...O,...t.env}}),await v.measure(`schema`,()=>he({name:`db`,command:ls,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),E))return;if(vs(j)){let t=qe({label:`postgres`});t.pipe(K.stdout,{end:!1});try{let n=await v.measure(`database`,()=>_s({config:j,cwd:e,env:O,failIfRunning:!0,interactive:l,isStopping:()=>E,postgresOutput:t,useSupervisorLease:!0}));if(!n)return;w=n,O={...O,...n.env};try{E||await v.measure(`schema`,()=>he({name:`db`,command:ls,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),E||(v.report(),await z())}finally{await n[Symbol.asyncDispose](),w===n&&(w=void 0)}}finally{t.end()}return}v.report(),await z()}finally{N(),await se?.close(),se=void 0;let e;try{await w?.[Symbol.asyncDispose]()}catch(t){e=t}finally{try{await P()}finally{try{await le?.close()}finally{de?.close(),ce?.close();for(let{handler:e,signal:t}of me)K.off(t,e)}}D&&(K.exitCode??=D===`SIGINT`?130:143)}gs(e)}}async function ps(e,t,n,r,i){for await(let a of ms(e,n,r,i))t.write(`${a}\n`)||await Dt(t,`drain`)}async function*ms(e,t,n,r){for await(let i of e){let e=le(i);e.message&&(t?.write(e.level,e.message,{properties:{stream:n}}),await r?.(e.message)),yield i}}async function hs(e,t){for await(let n of e)t.write(`${n}\n`)||await Dt(t,`drain`)}function gs(e){if(e)throw e}async function _s({interactive:e,isStopping:t,...n}){try{return await ae(n)}catch(r){if(!(r instanceof f)||!e)throw r;let i=await L.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(L.isCancel(i)||!i){L.cancel(`Keeping the existing PostgreSQL process.`);return}return await se(r),t()?void 0:ae(n)}}function vs(e){return(e.database?.dialect??`postgres`)===`postgres`}function ys({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 bs(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 xs(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function Ss(e={}){let t=e.cwd??K.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await z(k.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Ne(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 Vt({...e,cwd:t},r)}const Cs=`worker-configuration.d.ts`;async function ws({check:e=!1,cwd:t=process.cwd()}={}){let n=await W({cwd:t}),r=await st({coreframeConfig:n,cwd:t}),i=P(t,Cs),a=P(t,`.coreframe-worker-types-${G()}.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 Ts(e),e}let o=Es(await V(a,`utf8`)),s=Fe(r.config),c=Pe(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${Ds(c)}\n`;if(e){if(await V(i,`utf8`).catch(()=>``)!==l)throw Error(`${Cs} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await V(i,`utf8`).catch(()=>``);return u!==l&&await U(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await H(a,{force:!0})}}function Ts(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
15
+ `)?t:`${t}\n`)}function Es(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
16
+ `)}function Ds(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(`
17
+ `)}const Os=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),ks=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],As=[`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`],js=[`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`],Ms=`.coreframe/typegen.json`,Ns=[`web`,`dashboard`,`worker`];async function Ps({checkWorker:e=!1,cwd:t=K.cwd(),runners:n={}}={}){let r=await Rs(t)??{generators:{},schemaVersion:1},i=[];return i.push(await Is({cwd:t,inputPaths:ks,name:`web`,outputPath:`.react-router`,run:()=>(n.web??Ls)(t),state:r})),i.push(await Is({cwd:t,inputPaths:As,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??vr)(t),state:r})),i.push(await Is({cwd:t,inputPaths:js,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??ws)({check:e,cwd:t}),state:r})),i}function Fs(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function Is({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await Bs(e,t),s=await Vs(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 Vs(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await zs(e,a),{changed:s!==l,name:n,ran:!0}}async function Ls(e){let t=K.platform===`win32`?`react-router.cmd`:`react-router`,n=K.env;await I(t,[`typegen`],{cwd:e,env:{...n,PATH:k.resolve(e,`node_modules/.bin`)+k.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function Rs(e){try{let t=JSON.parse(await V(k.resolve(e,Ms),`utf8`));if(!Gs(t)||t.schemaVersion!==1)return;let n={};if(!Gs(t.generators))return;for(let e of Ns){let r=t.generators[e];Gs(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 zs(e,t){let n=k.resolve(e,Ms);await B(k.dirname(n),{recursive:!0}),await U(n,`${JSON.stringify(t)}\n`,{mode:384})}async function Bs(e,t){let n=Ie(`sha256`);for(let r of[...t].sort()){let t=k.resolve(e,r),i=await Us(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Hs(t)){let i=k.join(t,r),a=k.relative(e,i).split(k.sep).join(`/`);n.update(`${a}\0`),n.update(await V(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await V(t)))}return n.digest(`hex`)}async function Vs(e,t){if(await Us(k.resolve(e,t)))return Bs(e,[t])}async function Hs(e){let t=[];async function n(e,r){let i=await Ee(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(Os.has(a.name))continue;await n(k.join(e,a.name),k.join(r,a.name))}else a.isFile()&&t.push(k.join(r,a.name))}return await n(e,``),t.sort()}async function Us(e){try{return await Oe(e)}catch(e){if(Ws(e))return;throw e}}function Ws(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Gs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ks=k.resolve(`node_modules`,`.bin`);K.env.PATH=Ks+k.delimiter+K.env.PATH;const qs=K.platform===`win32`?`tsc.cmd`:`tsc`,Js=[{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 Ys(){await Ps({checkWorker:!0});let e=[];for(let t of Js)try{await z(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>Je({name:e.name,command:qs,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(K.exitCode=n[0].exitCode)}const Xs=n(a(ss),{displayName:`feature`,from:async e=>e}),Zs=n(a(Wt),{displayName:`filtered|full`,from:async e=>e}),Qs=[`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.`],$s=t({name:`deploy`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:r({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:r({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:r({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:r({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>Va([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),ec=d({name:`staging`,cmds:{reassign:t({name:`reassign`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ht();if(e){console.log(JSON.stringify({...t,notices:Qs}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Qs.join(` `)}`)}}),url:t({name:`url`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await rt();console.log(e?JSON.stringify({url:t}):t)}})}}),tc=d({name:`secrets`,cmds:{"rotate-access-token":t({name:`rotate-access-token`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:r({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 yt({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:t({name:`status`,args:{environment:c({type:s(a(tt)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await it({environment:e});console.log(t?JSON.stringify(n):sc(n))}}),set:t({name:`set`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:c({type:s(u),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:r({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 ut({environment:e,name:t,value:await cc(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await ft(),i=n?await uc(r):await lc(r,e);await dt({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:t({name:`discard`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:c({type:u,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await nt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),nc=t({name:`typecheck`,args:{},handler:Ys}),rc=d({name:`worker`,cmds:{typegen:t({name:`typegen`,args:{check:r({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await ws({check:e});console.log(e?`${fc(t.path)} is current.`:`${fc(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),ic=t({name:`dev`,args:{debug:o({long:`debug`,type:s(Xs),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:r({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:r({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:o({long:`flutter-output`,type:Zs,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:r({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:o({long:`host`,type:s(u),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:r({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:r({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:r({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:r({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:r({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:c({type:s(a(os)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:c({type:s(u),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:o({long:`port`,type:s(i),description:`Port for the web development server.`}),verbose:r({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=ac({device:t,flutterDebug:n,platform:f,simulator:m});return fs({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 ac({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 oc=t({name:`preview`,args:{host:o({long:`host`,type:s(u),description:`Host address for the preview server.`}),port:o({long:`port`,type:s(i),description:`Port for the preview server.`})},handler:({host:e,port:t})=>Ss({host:e,port:t})});function sc(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=>e.map((e,t)=>e.padEnd(r[t])).join(` `).trimEnd();return[i(n),i(r.map(e=>`-`.repeat(e))),...t].join(`
18
+ `)}async function cc(e){if(!K.stdin.isTTY){let e=``;for await(let t of K.stdin)e+=t.toString();return e.replace(/\r?\n$/,``)}let t=await L.password({message:`Enter the new value for ${e}`});if(L.isCancel(t))throw L.cancel(`Secret update cancelled.`),Error(`Secret update cancelled.`);return t}async function lc(e,t){if(!K.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 L.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(L.isCancel(i))throw L.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);i.trim()&&(n[r.name]=i)}return n}async function uc(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=K.stdin.isTTY?await L.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 dc();if(L.isCancel(t))throw L.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=ct(t,e);return n.length>0&&L.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function dc(){let e=``;for await(let t of K.stdin)e+=t.toString();return e}function fc(e){return e.split(/[\\/]/).at(-1)??e}const pc=t({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await Ps();for(let t of e)console.log(Fs(t))}});function mc(e,{formatMessage:t,temporaryDirectory:n=je(),write:r=e=>console.error(e)}={}){let i=bc(e),a=Cc(gc(e,t),i);try{let t=M(Be(M(n,`coreframe-error-`)),`error.log`);return Ge(t,`${Cc(_c(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 hc(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,mc(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function gc(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 _c(e){try{let t=vc(e);if(!(e instanceof Error)||!yc(t))return Tt(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${Tt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function vc(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:vc(a.value,t),writable:!0})}return i}function yc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bc(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`?xc(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function xc(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&Sc(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function Sc(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function Cc(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const wc=d({name:`coreframe`,cmds:{build:cn,dashboard:Pr,assets:pr,flutter:mr,i18n:hr,deploy:$s,staging:ec,secrets:tc,typegen:pc,typecheck:nc,worker:rc,dev:ic,preview:oc,upgrade:La,recipes:Ra,db:za}});import.meta.main&&hc(wc,{formatMessage:process.argv[2]===`db`?y:void 0});export{wc as coreframeCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreframe/scripts",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
4
4
  "description": "Coreframe project workflow CLI and automation scripts",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,15 +29,15 @@
29
29
  "nano-spawn": "^2.1.0",
30
30
  "procband": "^0.3.8",
31
31
  "yaml": "^2.9.0",
32
- "@coreframe/assets": "^0.1.13",
33
- "@coreframe/db": "^0.1.14",
34
- "@coreframe/deploy": "^0.1.10",
35
- "@coreframe/dev": "^0.1.17",
36
- "@coreframe/flutter-tools": "^0.1.19",
37
- "@coreframe/config": "^0.1.10",
32
+ "@coreframe/assets": "^0.1.14",
33
+ "@coreframe/config": "^0.1.11",
34
+ "@coreframe/db": "^0.1.15",
35
+ "@coreframe/deploy": "^0.1.11",
36
+ "@coreframe/dev": "^0.1.18",
37
+ "@coreframe/dev-contracts": "^0.1.8",
38
+ "@coreframe/flutter-tools": "^0.1.21",
38
39
  "@coreframe/object-storage": "^0.1.4",
39
- "@coreframe/preview": "^0.1.13",
40
- "@coreframe/dev-contracts": "^0.1.8"
40
+ "@coreframe/preview": "^0.1.14"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "^26.1.0",