@coreframe/scripts 0.2.25 → 0.2.27

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