@coreframe/scripts 0.2.25 → 0.2.26

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