@coreframe/scripts 0.2.32 → 0.2.34-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/coreframe.d.ts +72 -12
- package/dist/coreframe.js +16 -15
- package/package.json +11 -10
package/dist/coreframe.d.ts
CHANGED
|
@@ -137,6 +137,27 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
137
137
|
revision: string | undefined;
|
|
138
138
|
};
|
|
139
139
|
};
|
|
140
|
+
} | {
|
|
141
|
+
command: "jobs";
|
|
142
|
+
args: {
|
|
143
|
+
command: "status";
|
|
144
|
+
args: {
|
|
145
|
+
ids: string[];
|
|
146
|
+
matches: string[];
|
|
147
|
+
json: boolean;
|
|
148
|
+
};
|
|
149
|
+
} | {
|
|
150
|
+
command: "reset";
|
|
151
|
+
args: {
|
|
152
|
+
ids: string[];
|
|
153
|
+
matches: string[];
|
|
154
|
+
all: boolean;
|
|
155
|
+
breakLeases: boolean;
|
|
156
|
+
dryRun: boolean;
|
|
157
|
+
json: boolean;
|
|
158
|
+
yes: boolean;
|
|
159
|
+
};
|
|
160
|
+
};
|
|
140
161
|
} | {
|
|
141
162
|
command: "deploy";
|
|
142
163
|
args: {
|
|
@@ -261,6 +282,9 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
261
282
|
} | {
|
|
262
283
|
command: "db";
|
|
263
284
|
args: {
|
|
285
|
+
command: "reset";
|
|
286
|
+
args: {};
|
|
287
|
+
} | {
|
|
264
288
|
command: "ensure";
|
|
265
289
|
args: {};
|
|
266
290
|
} | {
|
|
@@ -289,9 +313,6 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
289
313
|
} | {
|
|
290
314
|
command: "migrations-check";
|
|
291
315
|
args: {};
|
|
292
|
-
} | {
|
|
293
|
-
command: "reset";
|
|
294
|
-
args: {};
|
|
295
316
|
} | {
|
|
296
317
|
command: "seed";
|
|
297
318
|
args: {};
|
|
@@ -442,6 +463,27 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
442
463
|
revision: string | undefined;
|
|
443
464
|
};
|
|
444
465
|
};
|
|
466
|
+
} | {
|
|
467
|
+
command: "jobs";
|
|
468
|
+
args: {
|
|
469
|
+
command: "status";
|
|
470
|
+
args: {
|
|
471
|
+
ids: string[];
|
|
472
|
+
matches: string[];
|
|
473
|
+
json: boolean;
|
|
474
|
+
};
|
|
475
|
+
} | {
|
|
476
|
+
command: "reset";
|
|
477
|
+
args: {
|
|
478
|
+
ids: string[];
|
|
479
|
+
matches: string[];
|
|
480
|
+
all: boolean;
|
|
481
|
+
breakLeases: boolean;
|
|
482
|
+
dryRun: boolean;
|
|
483
|
+
json: boolean;
|
|
484
|
+
yes: boolean;
|
|
485
|
+
};
|
|
486
|
+
};
|
|
445
487
|
} | {
|
|
446
488
|
command: "deploy";
|
|
447
489
|
args: {
|
|
@@ -566,6 +608,9 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
566
608
|
} | {
|
|
567
609
|
command: "db";
|
|
568
610
|
args: {
|
|
611
|
+
command: "reset";
|
|
612
|
+
args: {};
|
|
613
|
+
} | {
|
|
569
614
|
command: "ensure";
|
|
570
615
|
args: {};
|
|
571
616
|
} | {
|
|
@@ -594,9 +639,6 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
594
639
|
} | {
|
|
595
640
|
command: "migrations-check";
|
|
596
641
|
args: {};
|
|
597
|
-
} | {
|
|
598
|
-
command: "reset";
|
|
599
|
-
args: {};
|
|
600
642
|
} | {
|
|
601
643
|
command: "seed";
|
|
602
644
|
args: {};
|
|
@@ -681,6 +723,15 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
681
723
|
command: "materialize";
|
|
682
724
|
value: Promise<void>;
|
|
683
725
|
};
|
|
726
|
+
} | {
|
|
727
|
+
command: "jobs";
|
|
728
|
+
value: {
|
|
729
|
+
command: "status";
|
|
730
|
+
value: Promise<void>;
|
|
731
|
+
} | {
|
|
732
|
+
command: "reset";
|
|
733
|
+
value: Promise<void>;
|
|
734
|
+
};
|
|
684
735
|
} | {
|
|
685
736
|
command: "deploy";
|
|
686
737
|
value: Promise<void>;
|
|
@@ -750,6 +801,9 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
750
801
|
} | {
|
|
751
802
|
command: "db";
|
|
752
803
|
value: {
|
|
804
|
+
command: "reset";
|
|
805
|
+
value: Promise<void>;
|
|
806
|
+
} | {
|
|
753
807
|
command: "ensure";
|
|
754
808
|
value: Promise<void>;
|
|
755
809
|
} | {
|
|
@@ -770,9 +824,6 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
770
824
|
} | {
|
|
771
825
|
command: "migrations-check";
|
|
772
826
|
value: Promise<void>;
|
|
773
|
-
} | {
|
|
774
|
-
command: "reset";
|
|
775
|
-
value: Promise<void>;
|
|
776
827
|
} | {
|
|
777
828
|
command: "seed";
|
|
778
829
|
value: Promise<void>;
|
|
@@ -856,6 +907,15 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
856
907
|
command: "materialize";
|
|
857
908
|
value: Promise<void>;
|
|
858
909
|
};
|
|
910
|
+
} | {
|
|
911
|
+
command: "jobs";
|
|
912
|
+
value: {
|
|
913
|
+
command: "status";
|
|
914
|
+
value: Promise<void>;
|
|
915
|
+
} | {
|
|
916
|
+
command: "reset";
|
|
917
|
+
value: Promise<void>;
|
|
918
|
+
};
|
|
859
919
|
} | {
|
|
860
920
|
command: "deploy";
|
|
861
921
|
value: Promise<void>;
|
|
@@ -925,6 +985,9 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
925
985
|
} | {
|
|
926
986
|
command: "db";
|
|
927
987
|
value: {
|
|
988
|
+
command: "reset";
|
|
989
|
+
value: Promise<void>;
|
|
990
|
+
} | {
|
|
928
991
|
command: "ensure";
|
|
929
992
|
value: Promise<void>;
|
|
930
993
|
} | {
|
|
@@ -945,9 +1008,6 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
945
1008
|
} | {
|
|
946
1009
|
command: "migrations-check";
|
|
947
1010
|
value: Promise<void>;
|
|
948
|
-
} | {
|
|
949
|
-
command: "reset";
|
|
950
|
-
value: Promise<void>;
|
|
951
1011
|
} | {
|
|
952
1012
|
command: "seed";
|
|
953
1013
|
value: Promise<void>;
|
package/dist/coreframe.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as e from"@alloc/cmd-ts";import{
|
|
3
|
-
`)}function
|
|
2
|
+
import*as e from"@alloc/cmd-ts";import{array as t,command as n,extendType as r,flag as i,multioption as a,number as o,oneOf as s,option as c,optional as l,positional as u,rest as d,restPositionals as f,string as p,subcommands as m}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as h,checkDeployMigrations as g,checkSchemaPush as _,collectDeployMigrationFiles as v,createLocalPostgresDb as ee,createProjectPostgresDatabaseAdapter as y,createProjectSqliteDatabaseAdapter as b,createProjectSqliteDrizzleDatabase as x,ensureLocalDb as S,filterPendingMigrations as C,formatDbErrorMessage as w,formatMigrationList as te,formatMigrationScanFailures as ne,migrateHeldMigrations as re,migrateLocalDb as ie,readAppliedMigrationNames as ae,resetLocalDb as oe,runDrizzleKitCommand as T,scanDeployMigrationFiles as se,seedLocalDb as ce,setupLocalDb as le,startProjectPostgres as E,startProjectTurso as ue,stopProjectPostgres as D}from"@coreframe/db";import{checkFlutterClient as O,classifyFlutterDevOutputLine as de,ensureFlutterDevAssetDirectories as fe,flutterPlatforms as k,generateFlutterNativeBridge as A,prepareFlutterClient as pe,prepareFlutterDevOutput as me,productionApiOrigin as j,runFlutterAcceptance as he}from"@coreframe/flutter-tools";import M,{dirname as N,isAbsolute as ge,join as P,posix as _e,resolve as F,sep as ve}from"node:path";import I from"nano-spawn";import*as L from"@clack/prompts";import{addAsset as ye,backupAssets as be,buildAssets as xe,checkAssets as Se,printAssetResult as R,publishAssets as Ce}from"@coreframe/assets";import{assertAssetCredentialProfile as we,configureAssetCredentials as Te,createB2PrivateObjectStore as Ee}from"@coreframe/object-storage";import{access as De,chmod as Oe,copyFile as ke,cp as Ae,mkdir as z,mkdtemp as je,readFile as B,readdir as Me,rename as Ne,rm as V,stat as Pe,writeFile as H}from"node:fs/promises";import{homedir as Fe,networkInterfaces as Ie,tmpdir as Le}from"node:os";import{importProjectDependency as Re,importProjectModule as ze,normalizeWorkerEnvironment as Be,readProjectConfig as U,wranglerEnvironmentNames as Ve}from"@coreframe/config";import{createHash as He,randomUUID as W}from"node:crypto";import G from"node:process";import{chmodSync as Ue,existsSync as K,lstatSync as We,mkdirSync as Ge,mkdtempSync as Ke,readFileSync as q,readlinkSync as qe,rmSync as Je,symlinkSync as Ye,watch as Xe,writeFileSync as Ze}from"node:fs";import{finished as Qe}from"node:stream/promises";import{createPrefixStream as $e,supervise as et}from"procband";import{createConnection as tt,createServer as nt}from"node:net";import{inspectDevelopmentJobStates as rt}from"@coreframe/jobs";import{spawnSync as J}from"node:child_process";import{parse as it,stringify as at}from"yaml";import{accessTokenSigningSecretName as ot,clearAppliedPendingWorkerSecrets as st,deployEnvironments as ct,discardPendingWorkerSecret as lt,discoverStagingUrl as ut,inspectWorkerEnvironment as dt,materializeBuiltClientDeployConfig as ft,materializePrimaryWorkerConfig as pt,materializePrimaryWorkerTypeConfig as mt,parseDeclaredWorkerSecretEnv as ht,prepareAccessTokenSigningSecret as gt,queueWorkerSecret as _t,queueWorkerSecrets as vt,readDeclaredWorkerSecrets as yt,readPackageJson as bt,readPendingWorkerSecretSnapshot as xt,reassignStagingHostname as St,releaseName as Ct,resolveDeployConfig as wt,resolveReleaseVersion as Tt,rotateAccessTokenSigningSecret as Et,runAfterWorkerDeploy as Dt,runPostDeployChecks as Ot,validateWorkerEnvironmentForDeploy as kt,verifyAccessTokenSigningSecret as At,writePackageVersion as jt}from"@coreframe/deploy";import{inspect as Mt,parseEnv as Nt}from"node:util";import{once as Pt}from"node:events";import{connectDevSupervisor as Ft,createDevStartupTiming as It,devHttpsCertEnv as Lt,devHttpsKeyEnv as Rt,isManagedDevCheckout as zt,isPrimaryCheckout as Bt,prepareDevHttps as Vt}from"@coreframe/dev";import{devJobsEnv as Ht}from"@coreframe/dev-contracts/dev-jobs";import{managedDevEnv as Ut,managedDevFlutterRestartFileEnv as Wt}from"@coreframe/dev-contracts/managed-dev";import{openScopedLogs as Gt}from"leylines";import{setTimeout as Kt}from"node:timers/promises";import{determineAgent as qt}from"@vercel/detect-agent";import{runPreview as Jt}from"@coreframe/preview";const Yt=`FLUTTER_XCODE_COREFRAME_BUNDLE_IDENTIFIER_SUFFIX`,Xt=`COREFRAME_FLUTTER_DEVELOPMENT`,Zt=[`filtered`,`full`];function Qt(e,{noCodesign:t=!1}={}){return{...e,[Yt]:`.dev`,[Xt]:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function $t(e=!1){return e?`debug`:`profile`}function en({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 tn({device:e,flutterDriver:t,mode:n,serverUrl:r,verbose:i}){return[`run`,`--machine`,`--${n}`,`-d`,e.id,`--dart-define=COREFRAME_DEV_SERVER_URL=${r}`,...t?[`--dart-define=ENABLE_FLUTTER_DRIVER=true`]:[],...i?[`--verbose`]:[]]}const nn=[`web`,...k];function rn(e=`web`,{apiOrigin:t,cwd:n=process.cwd(),profile:r=!1,simulator:i=!1}={}){if(dn(e,{profile:r,simulator:i}),e===`web`)return[pn(`pnpm`,[`build`],n,{COREFRAME_PLATFORM:`web`})];let a=j(t);return[{kind:`prepare`,platform:e},pn(`flutter`,an(e,a,{profile:r,simulator:i}),F(n,`src-flutter`),{COREFRAME_API_ORIGIN:a})]}function an(e,t,{noCodesign:n=e===`macos`,profile:r=!1,simulator:i=!1}={}){dn(e,{profile:r,simulator:i});let a=j(t);return[`build`,e===`android`?`apk`:e,r?`--profile`:`--release`,...i?[`--simulator`]:[],...n?[`--no-codesign`]:[],`--dart-define=COREFRAME_API_ORIGIN=${a}`]}function on(e,{profile:t=!1}={}){let n=t?`profile`:`release`,r=F(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 sn(e,{profile:t=!1,simulator:n=!1}={}){let r=t?`profile`:`release`,i=F(e,`src-flutter/build/ios/${n?`iphonesimulator`:`iphoneos`}/Runner.app`),a=JSON.stringify(i);return n?[`iOS Simulator ${r} build succeeded.`,``,`Install it on a booted iOS Simulator:`,` 1. Verify available simulators:`,` xcrun simctl list devices`,` 2. Install the app:`,` xcrun simctl install booted ${a}`,``,"If multiple simulators are available, replace `booted` with the simulator UDID."].join(`
|
|
4
4
|
`):[`iOS ${r} build succeeded.`,``,`Install it on a connected iOS device:`,` 1. Enable Developer Mode, connect the device, and trust this Mac if prompted.`,` 2. Verify the device is visible:`,` xcrun devicectl list devices`,` 3. Install the signed app:`,` xcrun devicectl device install app --device <device-id> ${a}`,``,`If multiple devices are connected, use the device UDID shown by devicectl.`].join(`
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
7
|
-
`)}async function rn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=O,runCommand:s=on}={}){an(r,{profile:i,simulator:a});let c={...n};delete c[Ut],delete c[Wt],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:k(e??n.COREFRAME_API_ORIGIN);for(let e of Zt(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($t(t,{profile:i})):r===`ios`?console.log(en(t,{profile:i,simulator:a})):r===`windows`?console.log(tn(t)):r===`linux`&&console.log(nn(t))}function an(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 on(e,t,{cwd:n,env:r}){await L(e,t,{cwd:n,env:r,stdio:`inherit`})}function sn(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const cn=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return k(e)}}),ln=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(Xt)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:o({long:`api-origin`,type:s(cn),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})=>rn({apiOrigin:e,platform:t,profile:n,simulator:r})}),un=/^[a-f0-9]{64}$/,dn=/^[a-f0-9]{40}$/,fn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function pn(e){if(!un.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function mn(e){if(!dn.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function hn(e,t){if(!fn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function gn(e){return`projects/${hn(e,`Project ID`)}/i18n/v1`}function _n(e,t){return pn(t),`${gn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function vn(e,t){return mn(t),`${gn(e)}/commits/${t}.json`}function yn(e,t){return bn(t),`${gn(e)}/releases/${encodeURIComponent(t)}.json`}function bn(e){if(!e.startsWith(`v`)||e.length<2||e.length>128||/\s/.test(e)||e.includes(`..`))throw Error(`Release tag "${e}" must be a valid v-prefixed tag.`);return e}function Y(e,t){if(!t||t.startsWith(`/`)||t.includes(`\0`))throw Error(`Unsafe i18n artifact path "${t}".`);let n=F(e),r=F(n,t);if(r!==n&&!r.startsWith(`${n}${I}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function X(e,t,n){return`${e.directory}/${t}/${n}.json`}function xn(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function Sn(e){await L(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function Cn({config:e,cwd:t,strict:n,temporaryDirectory:r}){let i=[];try{for(let n of e.locales)for(let a of e.catalogs){let o=Y(t,X(e,n,a)),s=await On(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=N(r,`${n}-${a}.json`);await z(j(l),{recursive:!0}),await we(o,l),i.push({path:o,backup:l}),await kn(o,c)}await L(`pnpm`,[`exec`,`lingui`,`compile`,...n?[`--strict`]:[]],{cwd:t,stdio:`inherit`})}finally{try{for(let{path:e,backup:t}of i)await we(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await V(Y(t,xn(e,n,r)),{force:!0})}}}async function wn({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 On(Y(t,X(e,r,i)));for(let[e,t]of Object.entries(a)){if(t.obsolete||t.translation?.trim())continue;let a=t.message;if(typeof a!=`string`||!a)throw Error(`Missing source message metadata for ${r}:${e}.`);n.push({catalog:i,comments:t.comments?.filter(e=>typeof e==`string`)??[],context:t.context,id:e,locale:r,message:a,origins:t.origin?.map(([e,t])=>t?`${e}:${t}`:e)??[],placeholders:Object.keys(t.placeholders??{}).sort()})}}return n.sort((e,t)=>Pn(e).localeCompare(Pn(t)))}async function Tn({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 An(await jn({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function En({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[Pn(e),e])),a=new Map;for(let e of r.translations){let t=Pn(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 Ne(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(Pn(e));Mn({compileMessage:s,id:e.id,locale:e.locale,source:e.message,translation:t})}for(let n of e.locales)if(n!==e.sourceLocale)for(let r of e.catalogs){let i=Y(t,X(e,n,r)),o=await On(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(Pn({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 kn(i,o)}}async function Dn({config:e,cwd:t}){let n=await wn({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Ne(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await On(Y(t,X(e,n,i)));for(let[e,t]of Object.entries(a))if(!t.obsolete){if(typeof t.message!=`string`||typeof t.translation!=`string`)throw Error(`Incomplete source metadata for active translation ${n}:${e}.`);Mn({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function On(e){let t=JSON.parse(await B(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 kn(e,t){await z(j(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await H(n,`${JSON.stringify(t,null,2)}\n`),await Oe(n,e)}function An(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 jn({args:e,command:t,cwd:n,env:r,input:i}){return L(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 Mn({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=Nn(a),c=Nn(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 Nn(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 Pn(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function Fn(e){return Le(`sha256`).update(e).digest(`hex`)}async function In(e){return Fn(await B(e))}function Ln(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function Rn({bucket:e,digest:t,projectId:n,source:r,store:i}){if(pn(t),await In(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=_n(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${W()}.verify`;try{if(await i.download(e,a,o),await In(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await V(o,{force:!0})}}async function zn({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=Ln(n),o=N(i,`reference-${W()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await B(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await V(o,{force:!0})}await H(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await V(o,{force:!0})}let s=N(i,`reference-${W()}.verify.json`);try{if(await r.download(e,t,s),!(await B(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await V(s,{force:!0})}}async function Bn({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=Ln(t),o=Fn(a),s=N(i,`manifest-${o}.json`);await H(s,a,{flag:`wx`});try{await Rn({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await V(s,{force:!0})}return o}async function Vn({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=N(r,`reference-${W()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await B(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return mn(r.revision),pn(r.snapshot),r}finally{await V(i,{force:!0})}}async function Hn({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await Vn({bucket:e,key:vn(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 Un({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await zn({bucket:e,key:vn(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await zn({bucket:e,key:yn(t,i),reference:n,store:r,temporaryDirectory:a})}async function Wn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){pn(n);let o=N(F(t),`v1`,`sha256`,n.slice(0,2),n);if(await Kn(o,n)===!1){await z(j(o),{recursive:!0});let t=`${o}.${process.pid}.${W()}.tmp`;try{if(await i.download(e,_n(r,n),t),await In(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await V(o,{force:!0}),await Oe(t,o)}finally{await V(t,{force:!0})}}await z(j(a),{recursive:!0});let s=`${a}.${process.pid}.${W()}.tmp`;try{if(await we(o,s),await In(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await V(a,{force:!0}),await Oe(s,a)}finally{await V(s,{force:!0})}}async function Gn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=N(a,`manifest-${n}.json`);await Wn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await B(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}.`);mn(s.revision),s.baseline!==void 0&&pn(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}.`);pn(e.digest)}return s}async function Kn(e,t){try{return(await ke(e)).isFile()&&await In(e)===t}catch{return!1}}async function qn({cwd:e=process.cwd(),env:t=process.env}={}){if((await U({cwd:e})).i18n){if(t.COREFRAME_I18N_RELEASE_REVISION){await Xn({cwd:e,env:t,revision:t.COREFRAME_I18N_RELEASE_REVISION});return}await Sn(e)}}async function Jn({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await U({cwd:e});if(!n.i18n)return;let r=Zn(n.i18n),i=Y(e,r.directory);try{if(!(await ke(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await Sn(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await ke(Y(e,X(r,t,n)))).isFile())throw Error(`I18n catalog path is not a file: ${t}/${n}.json.`)}catch(t){if(t.code!==`ENOENT`)throw t;await Sn(e);return}}async function Yn({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){bn(r);let i=await Qn({cwd:e,env:t,store:n});await or(e);let a=await ar(e);await sr(e,r,a);let o=await Ee(N(Me(),`coreframe-i18n-prepare-`));try{let n=await Hn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,revision:a,store:i.store,temporaryDirectory:o});if(n){let e=await Gn({bucket:i.assets.sourceBucket,cacheRoot:i.cacheRoot,digest:n.snapshot,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return ir(i,e,a),await er(i,e),await Un({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:n,store:i.store,tag:r,temporaryDirectory:o}),{reused:!0,snapshot:n.snapshot}}return await rr(i,o,async()=>{let n=await $n(i,a,o);n||await nr(i),await Sn(e);let s=await wn({config:i.config,cwd:e}),c=await Tn({config:i.config,cwd:e,env:t,messages:s});await En({config:i.config,cwd:e,missing:s,response:c}),await Dn({config:i.config,cwd:e}),await Cn({config:i.config,cwd:e,strict:!0,temporaryDirectory:o});let l=await tr(i),u={...n?{baseline:n}:{},catalogs:i.config.catalogs,files:l,generator:s.length>0?i.config.generator?.id??`unconfigured`:`none`,linguiVersion:await cr(e),locales:i.config.locales,projectId:i.assets.projectId,revision:a,sourceLocale:i.config.sourceLocale,version:1},d=await Bn({bucket:i.assets.sourceBucket,manifest:u,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return await Un({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 V(o,{force:!0,recursive:!0})}}async function Xn({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await U({cwd:e});if(!i.i18n)return;let a=await Qn({cwd:e,env:t,store:r,projectConfig:i}),o=mn(n??await ar(e)),s=await Ee(N(Me(),`coreframe-i18n-materialize-`));try{let e=await Hn({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 Gn({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return ir(a,t,o),await er(a,t),{revision:o,snapshot:e.snapshot}}finally{await V(s,{force:!0,recursive:!0})}}function Zn(e){let t=hn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>hn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>hn(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 Qn({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await U({cwd:e});if(!i.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);if(!i.assets)throw Error(`I18n snapshots require the existing private build bucket configured under assets.`);let a=i.assets;return{assets:a,cacheRoot:F(e,`.coreframe`,`i18n`,`cache`),config:Zn(i.i18n),cwd:F(e),env:t,store:r??xe({config:a,env:t})}}async function $n(e,t,n){let{stdout:r}=await L(`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 Hn({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:mn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Gn({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return ir(e,i,t),await er(e,i),r.snapshot}}async function er(e,t){for(let n of t.files)if(await Wn({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:Y(e.cwd,n.path)}),(await ke(Y(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function tr(e){let t=[];for(let n of e.config.locales)for(let r of e.config.catalogs){let i=X(e.config,n,r),a=Y(e.cwd,i),o=await In(a);await Rn({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await ke(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function nr(e){let{stdout:t}=await L(`git`,[`rev-parse`,`--show-prefix`],{cwd:e.cwd,stdin:`ignore`}),n=t.trim(),{stdout:r}=await L(`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 Ne(`@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 L(`git`,[`show`,`${i}:${s}`],{cwd:e.cwd,stdin:`ignore`});await kn(Y(e.cwd,X(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function rr(e,t,n){let r=[];for(let n of e.config.locales)for(let i of e.config.catalogs){let a=X(e.config,n,i),o=Y(e.cwd,a);try{await Se(o)}catch{continue}let s=N(t,`previous-catalogs`,a);await z(j(s),{recursive:!0}),await Oe(o,s),r.push({backup:s,path:o})}try{let e=await n();return await V(N(t,`previous-catalogs`),{force:!0,recursive:!0}),e}catch(t){for(let t of e.config.locales)for(let n of e.config.catalogs)await V(Y(e.cwd,X(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await z(j(t),{recursive:!0}),await Oe(e,t);throw t}}function ir(e,t,n){if(t.revision!==n||t.projectId!==e.assets.projectId||t.sourceLocale!==e.config.sourceLocale||JSON.stringify(t.locales)!==JSON.stringify(e.config.locales)||JSON.stringify(t.catalogs)!==JSON.stringify(e.config.catalogs))throw Error(`I18n snapshot does not match commit or project configuration.`);let r=e.config.locales.flatMap(t=>e.config.catalogs.map(n=>X(e.config,t,n))),i=t.files.map(e=>e.path);if(new Set(i).size!==i.length||JSON.stringify(i.sort())!==JSON.stringify(r.sort()))throw Error(`I18n snapshot has an incomplete or unexpected artifact set.`)}async function ar(e){let{stdout:t}=await L(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return mn(t.trim())}async function or(e){let{stdout:t}=await L(`git`,[`status`,`--porcelain`],{cwd:e,stdin:`ignore`});if(t.trim())throw Error(`Tagged i18n preparation requires a clean Git tree.`)}async function sr(e,t,n){let{stdout:r}=await L(`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 cr(e){let{stdout:t}=await L(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const lr=[`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(` `),ur=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}}),dr=n(u,{displayName:`profile`,async from(e){return ye(e)}}),fr=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}}),pr=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return k(e)}}),mr=d({name:`assets`,cmds:{configure:t({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${lr}`,args:{profile:c({type:dr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{R.note(lr,`Required B2 key access`);let t=await R.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(R.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await R.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(R.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(fr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:o({long:`widths`,type:s(ur),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})=>_e(await pe({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 me({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(fr),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})=>_e(await he({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(fr),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 ge({fix:e,pack:n});_e(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:t({name:`publish`,args:{pack:o({long:`pack`,type:s(fr),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});_e(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:t({name:`status`,args:{pack:o({long:`pack`,type:s(fr),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 ge({pack:t});_e(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),hr=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:pr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>fe({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})=>D({check:e})}),prepare:t({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:c({type:a(ue),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:pr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>O({apiOrigin:e,platform:t})}),check:t({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:c({type:a(ue),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:pr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>se({apiOrigin:e,platform:t})})}}),gr=d({name:`i18n`,cmds:{build:t({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await qn()}}),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 Xn({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 Yn({tag:e});console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),_r=G.platform===`win32`?`react-router.cmd`:`react-router`,vr=G.platform===`win32`?`panda.cmd`:`panda`;async function yr(e=G.cwd()){await Sr(e),await xr(e,[`typegen`])}async function br(e=G.cwd(),t=G.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=A.resolve(e,`.coreframe/dashboard-build`),i=A.join(r,`client`),a=A.resolve(e,`dist/client/__dashboard`);if(await V(r,{force:!0,recursive:!0}),(await U({cwd:e})).deploy?.mode===`client`){await V(a,{force:!0,recursive:!0});return}await Cr(e,vr,[`build`],t),await xr(e,[`build`,...n?[`--mode`,n]:[]],t),await V(a,{force:!0,recursive:!0}),await z(A.dirname(a),{recursive:!0}),await Te(i,a,{recursive:!0})}async function xr(e,t,n=G.env){await Cr(e,_r,t,n)}async function Sr(e){await V(A.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function Cr(e,t,n,r=G.env){await L(t,n,{cwd:A.resolve(e,`dashboard`),env:{...r,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const Z={access:Se,chmod:Ce,mkdir:z,mkdtemp:Ee,readFile:B,readFileSync:q,rm:V,writeFile:H},wr={getAvailablePort:Er},Tr={homedir:Ae,kill:G.kill,networkInterfaces:je,tmpdir:Me};async function Er(){let e=Ze();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 Dr({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 Or(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=Ze(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 Or(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await kr(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 kr({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=Xe({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 Ar=G.platform===`win32`?`react-router.cmd`:`react-router`;function jr(e){return K(A.resolve(e,`dashboard/dashboard.config.ts`))}function Mr({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 G.on(e,t),{handler:t,signal:e}}),u=async(e,t)=>{try{await e,o||a?.fail(Error(`The dashboard development server stopped unexpectedly.`))}catch(e){o||a?.fail(e)}finally{await t.outputTasks,t.stdout.end(),t.stderr.end(),await Promise.allSettled([qe(t.stdout),qe(t.stderr)]),i===e&&(i=void 0)}};a=Dr({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await wr.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=Je({label:`dashboard`}),s=Je({color:`red`,label:`dashboard`});a.pipe(G.stdout,{end:!1}),s.pipe(G.stderr,{end:!1});let l=L(Ar,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:A.resolve(e,`dashboard`),env:{...t,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([Pr(l.stdout,a),Pr(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)G.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function Nr({cwd:e=G.cwd(),env:t=G.env,port:n}){let r=Mr({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function Pr(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const Fr=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})=>Nr({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})=>br(void 0,void 0,e)}),typegen:t({name:`typegen`,args:{},handler:()=>yr()})}}),Ir=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Lr(e,t){let n=zr(e,t);if(!Br(n)||!Vr(n,[`description`,`requires`,`routes`,`verifier`])||!Ur(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Ur))||n.verifier!==void 0&&!Ur(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=>Rr(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Br(e)||!Hr(e,[`path`,`router`,`when`])||!Ur(e.path)||!Ur(e.router)||!Ur(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 Rr(e){if(!Ir.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function zr(e,t){try{return Qe(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Br(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vr(e,t){return Object.keys(e).every(e=>t.includes(e))}function Hr(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Ur(e){return typeof e==`string`&&e.length>0}const Wr=`https://github.com/coreframe-js/coreframe.git`;function Gr(e,t){return J(`git`,e,{cwd:t,encoding:`utf8`})}function Kr(e,t){let n=Gr(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 qr(e,t){let n=Gr([`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 Jr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);Kr([`rev-parse`,`--show-toplevel`],e);let r=qr(n,e);if(r===null)Kr([`remote`,`add`,n,Wr],e),console.log(`Added ${n} remote: ${Wr}`);else if(r===Wr)console.log(`${n} remote already points at ${Wr}`);else throw Error(`${n} remote points at ${r}, not ${Wr}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);t&&(Kr([`fetch`,n,`--tags`,`--prune`],e),console.log(`Fetched ${n}.`))}const Yr=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;function Q(e){return Yr.test(e)?`v${e}`:e}function Xr(e){return`${Q(e)}:template`}function Zr(e,t){return`${Xr(e)}/${t}`}function Qr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=ni(e),a=oi(i,[`rev-parse`,`--show-toplevel`]),o=Q(r??ri(i));return Jr({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,repositoryRoot:a}}function $r(e,t,n){return ei(e,t,n).toString(`utf8`)}function ei(e,t,n){let r=`${t}:${n}`,i=J(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${si([`show`,r],i)}`);return i.stdout}function ti(e,t,n){let r=J(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(si([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function ni(e){let t=F(e);for(;;){let e=N(t,`package.json`),n=ai(e);if(n!==void 0&&ii(n,e).engines?.coreframe)return t;let r=j(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function ri(e){let t=N(e,`package.json`),n=ai(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=ii(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function ii(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ai(e){try{return q(e,`utf8`)}catch(e){if(ci(e)&&e.code===`ENOENT`)return;throw e}}function oi(e,t){let n=J(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(si(t,n));return n.stdout.trim()}function si(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 ci(e){return e instanceof Error&&`code`in e}const li=[{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:vi},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:yi},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:bi},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>_i(e,[`configureShellQueryFocus`,`initializeShellClient`,`authSessionHint`,`authClient.signOut()`,`clearSession`])},{path:`src/web/entry.client.tsx`,requirement:`load the package-owned Flutter development tools only for non-browser development`,test:e=>_i(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],ui=`src-flutter/lib/application.dart`,di=`src/api/worker/auth-origin.ts`;function fi(e){let t=[];for(let n of li){let r=N(e,n.path);if(!K(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=q(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}let n=pi(e,t),r=mi(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${ui} loopbackPort (${n}) must match ${di} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function pi(e,t){let n=hi(e,ui,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=gi(r??a);return o===void 0&&t.push(`${ui} must configure loopbackPort as a fixed integer port.`),o}function mi(e,t){let n=hi(e,di,t);if(n===void 0)return;let r=gi(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(`${di} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function hi(e,t,n){let r=N(e,t);if(!K(r)){n.push(`${t} is missing; it must define the Flutter loopback origin contract.`);return}return q(r,`utf8`)}function gi(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function _i(e,t){return t.every(t=>e.includes(t))}function vi(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 yi(e){try{let t=Qe(e);if(!xi(t)||!xi(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return xi(n)&&n.sdk===`flutter`}catch{return!1}}function bi(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 xi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Si({name:e,...t}){let n=Qr(t),r=`recipes/${e}/recipe.yaml`,i=Ti(Lr($r(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,
|
|
9
|
-
`)}
|
|
10
|
-
`)
|
|
5
|
+
`)}function cn(e){return[`Windows release build succeeded.`,``,`The unpackaged application bundle is at ${JSON.stringify(F(e,`src-flutter/build/windows/x64/runner/Release`))}.`,`Create and sign an installer with the Windows packaging workflow for distribution.`].join(`
|
|
6
|
+
`)}function ln(e){return[`Linux release build succeeded.`,``,`The application bundle is at ${JSON.stringify(F(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 un({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=pe,runCommand:s=fn}={}){dn(r,{profile:i,simulator:a});let c={...n};delete c[Yt],delete c[Xt],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:j(e??n.COREFRAME_API_ORIGIN);for(let e of rn(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(on(t,{profile:i})):r===`ios`?console.log(sn(t,{profile:i,simulator:a})):r===`windows`?console.log(cn(t)):r===`linux`&&console.log(ln(t))}function dn(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 fn(e,t,{cwd:n,env:r}){await I(e,t,{cwd:n,env:r,stdio:`inherit`})}function pn(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const mn=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return j(e)}}),hn=n({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:u({type:l(s(nn)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:c({long:`api-origin`,type:l(mn),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:i({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>un({apiOrigin:e,platform:t,profile:n,simulator:r})}),gn=/^[a-f0-9]{64}$/,_n=/^[a-f0-9]{40}$/,vn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function yn(e){if(!gn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function bn(e){if(!_n.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function xn(e,t){if(!vn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function Sn(e){return`projects/${xn(e,`Project ID`)}/i18n/v1`}function Cn(e,t){return yn(t),`${Sn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function wn(e,t){return bn(t),`${Sn(e)}/commits/${t}.json`}function Tn(e,t){return En(t),`${Sn(e)}/releases/${encodeURIComponent(t)}.json`}function En(e){if(!e.startsWith(`v`)||e.length<2||e.length>128||/\s/.test(e)||e.includes(`..`))throw Error(`Release tag "${e}" must be a valid v-prefixed tag.`);return e}function Y(e,t){if(!t||t.startsWith(`/`)||t.includes(`\0`))throw Error(`Unsafe i18n artifact path "${t}".`);let n=F(e),r=F(n,t);if(r!==n&&!r.startsWith(`${n}${ve}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function X(e,t,n){return`${e.directory}/${t}/${n}.json`}function Dn(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function On(e){await I(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function kn({config:e,cwd:t,strict:n,temporaryDirectory:r}){let i=[];try{for(let n of e.locales)for(let a of e.catalogs){let o=Y(t,X(e,n,a)),s=await Pn(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=P(r,`${n}-${a}.json`);await z(N(l),{recursive:!0}),await ke(o,l),i.push({path:o,backup:l}),await Fn(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 ke(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await V(Y(t,Dn(e,n,r)),{force:!0})}}}async function An({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 Pn(Y(t,X(e,r,i)));for(let[e,t]of Object.entries(a)){if(t.obsolete||t.translation?.trim())continue;let a=t.message;if(typeof a!=`string`||!a)throw Error(`Missing source message metadata for ${r}:${e}.`);n.push({catalog:i,comments:t.comments?.filter(e=>typeof e==`string`)??[],context:t.context,id:e,locale:r,message:a,origins:t.origin?.map(([e,t])=>t?`${e}:${t}`:e)??[],placeholders:Object.keys(t.placeholders??{}).sort()})}}return n.sort((e,t)=>Bn(e).localeCompare(Bn(t)))}async function jn({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 In(await Ln({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function Mn({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[Bn(e),e])),a=new Map;for(let e of r.translations){let t=Bn(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 Re(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(Bn(e));Rn({compileMessage:s,id:e.id,locale:e.locale,source:e.message,translation:t})}for(let n of e.locales)if(n!==e.sourceLocale)for(let r of e.catalogs){let i=Y(t,X(e,n,r)),o=await Pn(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(Bn({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 Fn(i,o)}}async function Nn({config:e,cwd:t}){let n=await An({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Re(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await Pn(Y(t,X(e,n,i)));for(let[e,t]of Object.entries(a))if(!t.obsolete){if(typeof t.message!=`string`||typeof t.translation!=`string`)throw Error(`Incomplete source metadata for active translation ${n}:${e}.`);Rn({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function Pn(e){let t=JSON.parse(await B(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 Fn(e,t){await z(N(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await H(n,`${JSON.stringify(t,null,2)}\n`),await Ne(n,e)}function In(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 Ln({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 Rn({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=zn(a),c=zn(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 zn(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 Bn(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function Vn(e){return He(`sha256`).update(e).digest(`hex`)}async function Hn(e){return Vn(await B(e))}function Un(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function Wn({bucket:e,digest:t,projectId:n,source:r,store:i}){if(yn(t),await Hn(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=Cn(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${W()}.verify`;try{if(await i.download(e,a,o),await Hn(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await V(o,{force:!0})}}async function Gn({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=Un(n),o=P(i,`reference-${W()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await B(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await V(o,{force:!0})}await H(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await V(o,{force:!0})}let s=P(i,`reference-${W()}.verify.json`);try{if(await r.download(e,t,s),!(await B(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await V(s,{force:!0})}}async function Kn({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=Un(t),o=Vn(a),s=P(i,`manifest-${o}.json`);await H(s,a,{flag:`wx`});try{await Wn({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await V(s,{force:!0})}return o}async function qn({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=P(r,`reference-${W()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await B(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return bn(r.revision),yn(r.snapshot),r}finally{await V(i,{force:!0})}}async function Jn({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await qn({bucket:e,key:wn(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 Yn({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await Gn({bucket:e,key:wn(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await Gn({bucket:e,key:Tn(t,i),reference:n,store:r,temporaryDirectory:a})}async function Xn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){yn(n);let o=P(F(t),`v1`,`sha256`,n.slice(0,2),n);if(await Qn(o,n)===!1){await z(N(o),{recursive:!0});let t=`${o}.${process.pid}.${W()}.tmp`;try{if(await i.download(e,Cn(r,n),t),await Hn(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await V(o,{force:!0}),await Ne(t,o)}finally{await V(t,{force:!0})}}await z(N(a),{recursive:!0});let s=`${a}.${process.pid}.${W()}.tmp`;try{if(await ke(o,s),await Hn(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await V(a,{force:!0}),await Ne(s,a)}finally{await V(s,{force:!0})}}async function Zn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=P(a,`manifest-${n}.json`);await Xn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await B(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}.`);bn(s.revision),s.baseline!==void 0&&yn(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}.`);yn(e.digest)}return s}async function Qn(e,t){try{return(await Pe(e)).isFile()&&await Hn(e)===t}catch{return!1}}async function $n({cwd:e=process.cwd(),env:t=process.env}={}){if((await U({cwd:e})).i18n){if(t.COREFRAME_I18N_RELEASE_REVISION){await nr({cwd:e,env:t,revision:t.COREFRAME_I18N_RELEASE_REVISION});return}await On(e)}}async function er({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await U({cwd:e});if(!n.i18n)return;let r=rr(n.i18n),i=Y(e,r.directory);try{if(!(await Pe(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await On(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Pe(Y(e,X(r,t,n)))).isFile())throw Error(`I18n catalog path is not a file: ${t}/${n}.json.`)}catch(t){if(t.code!==`ENOENT`)throw t;await On(e);return}}async function tr({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){En(r);let i=await ir({cwd:e,env:t,store:n});await fr(e);let a=await dr(e);await pr(e,r,a);let o=await je(P(Le(),`coreframe-i18n-prepare-`));try{let n=await Jn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,revision:a,store:i.store,temporaryDirectory:o});if(n){let e=await Zn({bucket:i.assets.sourceBucket,cacheRoot:i.cacheRoot,digest:n.snapshot,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return ur(i,e,a),await or(i,e),await Yn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:n,store:i.store,tag:r,temporaryDirectory:o}),{reused:!0,snapshot:n.snapshot}}return await lr(i,o,async()=>{let n=await ar(i,a,o);n||await cr(i),await On(e);let s=await An({config:i.config,cwd:e}),c=await jn({config:i.config,cwd:e,env:t,messages:s});await Mn({config:i.config,cwd:e,missing:s,response:c}),await Nn({config:i.config,cwd:e}),await kn({config:i.config,cwd:e,strict:!0,temporaryDirectory:o});let l=await sr(i),u={...n?{baseline:n}:{},catalogs:i.config.catalogs,files:l,generator:s.length>0?i.config.generator?.id??`unconfigured`:`none`,linguiVersion:await mr(e),locales:i.config.locales,projectId:i.assets.projectId,revision:a,sourceLocale:i.config.sourceLocale,version:1},d=await Kn({bucket:i.assets.sourceBucket,manifest:u,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return await Yn({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 V(o,{force:!0,recursive:!0})}}async function nr({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await U({cwd:e});if(!i.i18n)return;let a=await ir({cwd:e,env:t,store:r,projectConfig:i}),o=bn(n??await dr(e)),s=await je(P(Le(),`coreframe-i18n-materialize-`));try{let e=await Jn({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 Zn({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return ur(a,t,o),await or(a,t),{revision:o,snapshot:e.snapshot}}finally{await V(s,{force:!0,recursive:!0})}}function rr(e){let t=xn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>xn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>xn(e,`Catalog`)))];if(n.length===0||!n.includes(t))throw Error(`I18n locales must include the source locale.`);if(r.length===0)throw Error(`I18n configuration requires at least one catalog.`);if(e.generator&&(!e.generator.command.trim()||!e.generator.id.trim()))throw Error(`I18n generator command and ID must be non-empty.`);return{catalogs:r,directory:e.directory??`locales`,generator:e.generator,locales:n,sourceLocale:t}}async function ir({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await U({cwd:e});if(!i.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);if(!i.assets)throw Error(`I18n snapshots require the existing private build bucket configured under assets.`);let a=i.assets;return{assets:a,cacheRoot:F(e,`.coreframe`,`i18n`,`cache`),config:rr(i.i18n),cwd:F(e),env:t,store:r??Ee({config:a,env:t})}}async function ar(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 Jn({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:bn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Zn({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return ur(e,i,t),await or(e,i),r.snapshot}}async function or(e,t){for(let n of t.files)if(await Xn({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:Y(e.cwd,n.path)}),(await Pe(Y(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function sr(e){let t=[];for(let n of e.config.locales)for(let r of e.config.catalogs){let i=X(e.config,n,r),a=Y(e.cwd,i),o=await Hn(a);await Wn({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Pe(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function cr(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 Re(`@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 Fn(Y(e.cwd,X(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function lr(e,t,n){let r=[];for(let n of e.config.locales)for(let i of e.config.catalogs){let a=X(e.config,n,i),o=Y(e.cwd,a);try{await De(o)}catch{continue}let s=P(t,`previous-catalogs`,a);await z(N(s),{recursive:!0}),await Ne(o,s),r.push({backup:s,path:o})}try{let e=await n();return await V(P(t,`previous-catalogs`),{force:!0,recursive:!0}),e}catch(t){for(let t of e.config.locales)for(let n of e.config.catalogs)await V(Y(e.cwd,X(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await z(N(t),{recursive:!0}),await Ne(e,t);throw t}}function ur(e,t,n){if(t.revision!==n||t.projectId!==e.assets.projectId||t.sourceLocale!==e.config.sourceLocale||JSON.stringify(t.locales)!==JSON.stringify(e.config.locales)||JSON.stringify(t.catalogs)!==JSON.stringify(e.config.catalogs))throw Error(`I18n snapshot does not match commit or project configuration.`);let r=e.config.locales.flatMap(t=>e.config.catalogs.map(n=>X(e.config,t,n))),i=t.files.map(e=>e.path);if(new Set(i).size!==i.length||JSON.stringify(i.sort())!==JSON.stringify(r.sort()))throw Error(`I18n snapshot has an incomplete or unexpected artifact set.`)}async function dr(e){let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return bn(t.trim())}async function fr(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 pr(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 mr(e){let{stdout:t}=await I(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const hr=[`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(` `),gr=r(p,{displayName:`widths`,description:`Comma-separated responsive variant widths.`,async from(e){let t=e.split(`,`).map(e=>Number(e));if(t.length===0||t.some(e=>!Number.isInteger(e)||e<=0)||t.some((e,n)=>n>0&&e<=t[n-1]))throw Error(`Widths must be positive, unique, strictly ascending integers.`);return t}}),_r=r(p,{displayName:`profile`,async from(e){return we(e)}}),vr=r(p,{displayName:`pack`,description:`Asset pack name, such as training-videos.`,async from(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e))throw Error(`Asset pack names must use lowercase hyphen-separated segments.`);return e}}),yr=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return j(e)}}),br=m({name:`assets`,cmds:{configure:n({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${hr}`,args:{profile:u({type:_r,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{L.note(hr,`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 Te({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:n({name:`add`,args:{file:u({type:p,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:c({long:`id`,type:p,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:c({long:`alt`,type:l(p),description:`Required alt text for raster image and SVG assets.`}),pack:c({long:`pack`,type:l(vr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:c({long:`widths`,type:l(gr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>R(await ye({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:n({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:c({long:`branch`,type:p,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await be({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:n({name:`build`,args:{id:c({long:`id`,type:l(p),description:`Build only one logical asset ID.`}),pack:c({long:`pack`,type:l(vr),description:`Build only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>R(await xe({id:e,pack:n}),t,{kind:`build`})}),check:n({name:`check`,args:{fix:i({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:c({long:`pack`,type:l(vr),description:`Check only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await Se({fix:e,pack:n});R(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:n({name:`publish`,args:{pack:c({long:`pack`,type:l(vr),description:`Publish only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Ce({pack:t});R(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:n({name:`status`,args:{pack:c({long:`pack`,type:l(vr),description:`Report status for only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Se({pack:t});R(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),xr=m({name:`flutter`,cmds:{acceptance:n({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:yr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>he({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:n({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:i({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>A({check:e})}),prepare:n({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:u({type:s(k),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:yr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>pe({apiOrigin:e,platform:t})}),check:n({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:u({type:s(k),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:yr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>O({apiOrigin:e,platform:t})})}}),Sr=m({name:`i18n`,cmds:{build:n({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await $n()}}),materialize:n({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:c({long:`revision`,type:l(p),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await nr({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:n({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot.`,args:{tag:c({long:`tag`,type:p,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await tr({tag:e});console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),Cr=G.platform===`win32`?`react-router.cmd`:`react-router`,wr=G.platform===`win32`?`panda.cmd`:`panda`;async function Tr(e=G.cwd()){await Or(e),await Dr(e,[`typegen`])}async function Er(e=G.cwd(),t=G.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=M.resolve(e,`.coreframe/dashboard-build`),i=M.join(r,`client`),a=M.resolve(e,`dist/client/__dashboard`);if(await V(r,{force:!0,recursive:!0}),(await U({cwd:e})).deploy?.mode===`client`){await V(a,{force:!0,recursive:!0});return}await kr(e,wr,[`build`],t),await Dr(e,[`build`,...n?[`--mode`,n]:[]],t),await V(a,{force:!0,recursive:!0}),await z(M.dirname(a),{recursive:!0}),await Ae(i,a,{recursive:!0})}async function Dr(e,t,n=G.env){await kr(e,Cr,t,n)}async function Or(e){await V(M.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function kr(e,t,n,r=G.env){await I(t,n,{cwd:M.resolve(e,`dashboard`),env:{...r,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const Z={access:De,chmod:Oe,mkdir:z,mkdtemp:je,readFile:B,readFileSync:q,rm:V,writeFile:H},Ar={getAvailablePort:Mr},jr={homedir:Fe,kill:G.kill,networkInterfaces:Ie,tmpdir:Le};async function Mr(){let e=nt();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 Nr({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 Pr(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=nt(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 Pr(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await Fr(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 Fr({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=tt({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 Ir=G.platform===`win32`?`react-router.cmd`:`react-router`;function Lr(e){return K(M.resolve(e,`dashboard/dashboard.config.ts`))}function Rr({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 G.on(e,t),{handler:t,signal:e}}),u=async(e,t)=>{try{await e,o||a?.fail(Error(`The dashboard development server stopped unexpectedly.`))}catch(e){o||a?.fail(e)}finally{await t.outputTasks,t.stdout.end(),t.stderr.end(),await Promise.allSettled([Qe(t.stdout),Qe(t.stderr)]),i===e&&(i=void 0)}};a=Nr({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await Ar.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=$e({label:`dashboard`}),s=$e({color:`red`,label:`dashboard`});a.pipe(G.stdout,{end:!1}),s.pipe(G.stderr,{end:!1});let l=I(Ir,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:M.resolve(e,`dashboard`),env:{...t,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([Br(l.stdout,a),Br(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)G.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function zr({cwd:e=G.cwd(),env:t=G.env,port:n}){let r=Rr({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function Br(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const Vr=m({name:`dashboard`,cmds:{dev:n({name:`dev`,args:{port:c({long:`port`,type:o,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>zr({port:e})}),build:n({name:`build`,args:{mode:c({long:`mode`,type:l(p),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>Er(void 0,void 0,e)}),typegen:n({name:`typegen`,args:{},handler:()=>Tr()})}});function Hr(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}async function Ur({all:e,cwd:t=process.cwd(),ids:n=[],matches:r=[],now:i=new Date}={}){let a=await Yr(t),o=await Xr(a.config,t,async e=>a.module.developmentJobs.createStateAdmin(e).list()),s=rt({jobs:a.module.developmentJobs.jobs,now:i,records:o??[]}),c=qr(s,{all:e,ids:n,matches:r},{defaultAll:!0});return{database:{dialect:a.dialect,state:o?`existing`:`missing`},jobs:s.filter(e=>c.has(e.id)),version:1}}async function Wr({all:e,breakLeases:t=!1,cwd:n=process.cwd(),dryRun:r=!1,ids:i=[],json:a=!1,matches:o=[],now:s=new Date,yes:c=!1}){let l=await Ur({all:!0,cwd:n,now:s}),u=qr(l.jobs,{all:e,ids:i,matches:o},{defaultAll:!1}),d=l.jobs.filter(e=>u.has(e.id)),f=d.filter(e=>e.lease===`active`);if(r)return{database:l.database,dryRun:!0,jobs:d.map(e=>({id:e.id,status:e.lease===`active`&&!t?`blocked-active-lease`:e.persisted?`would-reset`:`no-state`})),version:1};if(f.length>0&&!t)throw Error(`Cannot reset active development job ${ei(f.map(e=>e.id))}. Wait for the lease to expire or pass --break-leases.`);if((t||e||o.length>0||d.length>1)&&!c){if(a||!process.stdin.isTTY)throw Error(`This reset requires --yes when prompts are unavailable.`);let e=await L.confirm({message:`Reset local development state for ${d.length} job${d.length===1?``:`s`}?`});if(L.isCancel(e)||!e)throw Error(`Development job state reset was cancelled.`)}if(l.database.state===`missing`)return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:`no-state`})),version:1};let p=await Yr(n),m=await Xr(p.config,n,async e=>p.module.developmentJobs.createStateAdmin(e).reset({breakLeases:t,jobIds:[...u],now:s}));if(!m)throw Error(`The local database disappeared before development job state was reset.`);if(m.activeLeaseIds.length>0&&!t)throw Error(`Cannot reset active development job ${ei(m.activeLeaseIds)}. Wait for the lease to expire or pass --break-leases.`);let h=new Set(m.resetIds);return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:h.has(e.id)?`reset`:`no-state`})),version:1}}function Gr(e){let t=$r(e.database);return e.jobs.length===0?`${t}No local development jobs are configured.`:`${t}${ti([`Job`,`Status`,`Last success`,`Next eligible`,`Lease`],e.jobs.map(e=>[e.id,e.lease===`active`?`running`:e.registration===`orphaned`?`orphaned`:e.eligibility,Qr(e.lastSucceededAt),Qr(e.nextEligibleAt),e.lease===`none`?`-`:`${e.lease} until ${Qr(e.leaseUntil)}`]))}`}function Kr(e){let t=$r(e.database);return e.jobs.length===0?`${t}No local development job state matched.`:`${t}${ti([`Job`,`Result`],e.jobs.map(e=>[e.id,e.status.replaceAll(`-`,` `)]))}`}function qr(e,{all:t=!1,ids:n=[],matches:r=[]},{defaultAll:i}){if(t&&(n.length>0||r.length>0))throw Error(`Use --all or explicit job selectors, not both.`);if(!t&&n.length===0&&r.length===0){if(i)return new Set(e.map(e=>e.id));throw Error(`Select one or more jobs by ID or --match, or pass --all.`)}let a=new Set(e.map(e=>e.id)),o=n.filter(e=>!a.has(e));if(o.length>0)throw Error(`Unknown development job ${ei(o)}.`);let s=new Set(t?a:n);for(let t of r){let n=Jr(t),r=e.filter(e=>n.test(e.id));if(r.length===0)throw Error(`Development job pattern ${JSON.stringify(t)} matched no jobs.`);for(let e of r)s.add(e.id)}return s}function Jr(e){if(!e)throw Error(`Development job patterns must not be empty.`);let t=[...e].map(e=>e===`*`?`.*`:e===`?`?`.`:e.replace(/[\\^$.[\]{}()+|]/gu,`\\$&`)).join(``);return RegExp(`^${t}$`,`u`)}async function Yr(e){let t=await U({cwd:e}),n=t.jobs?.entry;if(!n)throw Error(`coreframe.config.ts must configure jobs.entry before managing development job state.`);let r=await ze(n,e);if(!r.developmentJobs||!Array.isArray(r.developmentJobs.jobs)||typeof r.developmentJobs.createStateAdmin!=`function`)throw Error(`${n} must export developmentJobs with jobs and createStateAdmin properties.`);return{config:t,dialect:t.database?.dialect??`postgres`,module:r}}async function Xr(e,t,n){try{var r=Hr();let a=e.database?.dialect??`postgres`,o=a===`sqlite`?M.resolve(t,`.coreframe/turso.db`):M.resolve(t,`.coreframe/postgres/PG_VERSION`);try{await Pe(o)}catch(e){if(ni(e)&&e.code===`ENOENT`)return;throw e}if(a===`sqlite`)try{var i=Hr();let r=await x({cwd:t,env:i.a(await ue({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Zr(n,r)}finally{r.$client.close()}}catch(e){i.e=e}finally{await i.d()}let s=await ee({cwd:t,env:r.a(await E({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Zr(n,s)}finally{await s.$client.end()}}catch(e){r.e=e}finally{await r.d()}}async function Zr(e,t){try{return await e(t)}catch(e){throw ri(e)?Error(`The local development job state table is missing. Run coreframe db migrate-local, then retry.`,{cause:e}):e}}function Qr(e){return e?.toISOString()??`-`}function $r(e){return e.state===`missing`?`Local ${e.dialect} database is missing; no database was created.\n\n`:``}function ei(e){return e.map(e=>JSON.stringify(e)).join(`, `)}function ti(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),r=e=>e.map((e,t)=>e.padEnd(n[t])).join(` `).trimEnd();return[r(e),r(n.map(e=>`-`.repeat(e))),...t.map(r)].join(`
|
|
8
|
+
`)}function ni(e){return e instanceof Error&&`code`in e}function ri(e){let t=e;for(;t instanceof Error;){let e=t.message.toLowerCase();if(e.includes(`coreframe_dev_job_state`)&&(e.includes(`does not exist`)||e.includes(`no such table`)))return!0;t=t.cause}return!1}const ii={ids:f({type:p,displayName:`job`,description:`Exact local development job IDs.`}),matches:a({type:t(p),long:`match`,description:`Select job IDs with an anchored * and ? glob. Repeat to add patterns.`,defaultValue:()=>[]})},ai=m({name:`jobs`,cmds:{status:n({name:`status`,description:`Inspect local development job cooldown and lease state.`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1}),...ii},handler:async({ids:e,json:t,matches:n})=>{let r=await Ur({ids:e,matches:n});console.log(t?JSON.stringify(r):Gr(r))}}),reset:n({name:`reset`,description:`Make local development jobs eligible for their next startup check.`,args:{all:i({long:`all`,description:`Select every configured and orphaned development job.`,defaultValue:()=>!1}),breakLeases:i({long:`break-leases`,description:`Invalidate active job leases. The original invocation may keep running.`,defaultValue:()=>!1}),dryRun:i({long:`dry-run`,description:`Show the reset without changing local state.`,defaultValue:()=>!1}),json:i({long:`json`,description:`Print machine-readable JSON without prompting.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Confirm a multi-job, pattern, all-job, or lease-breaking reset.`,defaultValue:()=>!1}),...ii},handler:async({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o})=>{let s=await Wr({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o});console.log(i?JSON.stringify(s):Kr(s))}})}}),oi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function si(e,t){let n=li(e,t);if(!ui(n)||!di(n,[`description`,`requires`,`routes`,`verifier`])||!pi(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(pi))||n.verifier!==void 0&&!pi(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=>ci(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!ui(e)||!fi(e,[`path`,`router`,`when`])||!pi(e.path)||!pi(e.router)||!pi(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 ci(e){if(!oi.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function li(e,t){try{return it(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ui(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function di(e,t){return Object.keys(e).every(e=>t.includes(e))}function fi(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function pi(e){return typeof e==`string`&&e.length>0}const mi=`https://github.com/coreframe-js/coreframe.git`;function hi(e,t){return J(`git`,e,{cwd:t,encoding:`utf8`})}function gi(e,t){let n=hi(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 _i(e,t){let n=hi([`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 vi({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);gi([`rev-parse`,`--show-toplevel`],e);let r=_i(n,e);if(r===null)gi([`remote`,`add`,n,mi],e),console.log(`Added ${n} remote: ${mi}`);else if(r===mi)console.log(`${n} remote already points at ${mi}`);else throw Error(`${n} remote points at ${r}, not ${mi}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);t&&(gi([`fetch`,n,`--tags`,`--prune`],e),console.log(`Fetched ${n}.`))}const yi=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;function Q(e){return yi.test(e)?`v${e}`:e}function bi(e){return`${Q(e)}:template`}function xi(e,t){return`${bi(e)}/${t}`}function Si({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=Ei(e),a=Ai(i,[`rev-parse`,`--show-toplevel`]),o=Q(r??Di(i));return vi({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,repositoryRoot:a}}function Ci(e,t,n){return wi(e,t,n).toString(`utf8`)}function wi(e,t,n){let r=`${t}:${n}`,i=J(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${ji([`show`,r],i)}`);return i.stdout}function Ti(e,t,n){let r=J(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(ji([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function Ei(e){let t=F(e);for(;;){let e=P(t,`package.json`),n=ki(e);if(n!==void 0&&Oi(n,e).engines?.coreframe)return t;let r=N(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function Di(e){let t=P(e,`package.json`),n=ki(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=Oi(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function Oi(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ki(e){try{return q(e,`utf8`)}catch(e){if(Mi(e)&&e.code===`ENOENT`)return;throw e}}function Ai(e,t){let n=J(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(ji(t,n));return n.stdout.trim()}function ji(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 Mi(e){return e instanceof Error&&`code`in e}const Ni=[{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:Hi},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:Ui},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:Wi},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>Vi(e,[`configureShellQueryFocus`,`initializeShellClient`,`authSessionHint`,`authClient.signOut()`,`clearSession`])},{path:`src/web/entry.client.tsx`,requirement:`load the package-owned Flutter development tools only for non-browser development`,test:e=>Vi(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],Pi=`src-flutter/lib/application.dart`,Fi=`src/api/worker/auth-origin.ts`;function Ii(e){let t=[];for(let n of Ni){let r=P(e,n.path);if(!K(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=q(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}let n=Li(e,t),r=Ri(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${Pi} loopbackPort (${n}) must match ${Fi} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function Li(e,t){let n=zi(e,Pi,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=Bi(r??a);return o===void 0&&t.push(`${Pi} must configure loopbackPort as a fixed integer port.`),o}function Ri(e,t){let n=zi(e,Fi,t);if(n===void 0)return;let r=Bi(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(`${Fi} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function zi(e,t,n){let r=P(e,t);if(!K(r)){n.push(`${t} is missing; it must define the Flutter loopback origin contract.`);return}return q(r,`utf8`)}function Bi(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function Vi(e,t){return t.every(t=>e.includes(t))}function Hi(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 Ui(e){try{let t=it(e);if(!Gi(t)||!Gi(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return Gi(n)&&n.sdk===`flutter`}catch{return!1}}function Wi(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 Gi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ki({name:e,...t}){let n=Si(t),r=`recipes/${e}/recipe.yaml`,i=Yi(si(Ci(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(`
|
|
9
|
+
`)}`);return{name:e,ref:n.ref}}function qi(e){console.log(`Verified Coreframe recipe ${e.name} from ${e.ref}.`)}function Ji(e,t){for(let n of e){let e=`recipes/${n}/recipe.yaml`,r=Yi(si(Ci(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(`
|
|
10
|
+
`)}\nApply and verify ${n} before continuing.`)}}function Yi(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return Ii(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function Xi({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){ci(n);let a=Si({cwd:e,fetch:t,remote:r,target:i}),{projectRoot:o,ref:s,repositoryRoot:c}=a,l=`recipes/${n}`,u=`${l}/recipe.yaml`,d=si(Ci(c,s,u),u);Ji(d.requires,a);let f=Ci(c,s,`${l}/RECIPE.md`),p=Ti(c,s,`${l}/files`),m=Ti(c,s,`${l}/patches`),h=Ti(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(ra(t,`Recipe file ${e}`),t.startsWith(`.agents/`))throw Error(`Recipe file ${e} must be stored in the recipe's .agents directory.`);g.set(t,wi(c,s,e)),_.set(t,e)}for(let e of h){let t=e.slice(`${l}/`.length);if(ea(t,`Recipe asset ${e}`),g.has(t))throw Error(`Recipe declares ${t} as both a file and an agent asset.`);g.set(t,wi(c,s,e)),_.set(t,e)}for(let e of m){let t=ia(e,l);if(g.has(t))throw Error(`Recipe declares ${t} as both a file and a patch.`);let n=wi(c,s,e);aa(n.toString(`utf8`),t,e),na(o,t),oa(o,n,!1)?(v.push({contents:n,destinationPath:t}),b.push(t)):oa(o,n,!0)?x.push(t):y.push({destination:t,source:e})}let C=new Map;for(let[e,t]of g){let r=la(na(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(ea(e.router,`Recipe route router`),ta(e.path,`Recipe route path`),g.has(e.router))throw Error(`Recipe cannot replace its destination router ${e.router}.`);if(!g.has(e.path)&&!K(na(o,e.path)))throw Error(`Recipe route target ${e.path} does not exist.`);let t=w.get(e.router)??Qi(ua(na(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=ua(na(o,e),e),r=at(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=na(o,e);Ge(N(n),{recursive:!0}),Ze(n,t)}return v.length>0&&sa(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 Zi(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 Qi(e,t){let n=$i(e,t);if(!da(n)||!fa(n,[`routes`,`rules`])||!Array.isArray(n.rules)||!n.rules.every(pa)||!Array.isArray(n.routes))throw Error(`${t} must contain only string rules and a routes array.`);let r=n.routes.map((e,n)=>{if(!da(e)||!fa(e,[`path`,`when`])||!pa(e.path)||!pa(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 $i(e,t){try{return it(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ea(e,t){if(!e.startsWith(`.agents/`))throw Error(`${t} must be a normalized project-relative path beneath .agents/.`);ra(e,t)}function ta(e,t){if(ra(e,t),!/(?:^|\/)\.agents\/rules\/.+\.md$/u.test(e))throw Error(`${t} must point to a Markdown rule beneath an .agents/rules directory.`)}function na(e,t){ra(t,`Recipe destination`);let n=P(e,t),r=e;for(let e of t.split(`/`))if(r=P(r,e),K(r)&&We(r).isSymbolicLink())throw Error(`Recipe destination ${t} crosses symbolic link ${r}.`);return n}function ra(e,t){if(e.length===0||ge(e)||e===`..`||e.startsWith(`../`)||e.includes(`\\`)||_e.normalize(e)!==e)throw Error(`${t} must be a normalized project-relative path.`)}function ia(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 ra(r,`Recipe patch ${e}`),r}function aa(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 oa(e,t,n){let r=[`apply`,`--check`,`--whitespace=nowarn`];return n&&r.push(`--reverse`),r.push(`-`),J(`git`,r,{cwd:e,input:t}).status===0}function sa(e,t){let n=J(`git`,[`apply`,`--whitespace=nowarn`,`-`],{cwd:e,input:Buffer.concat(t.flatMap(e=>[e,Buffer.from(e.at(-1)===10?``:`
|
|
11
|
+
`)])),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 ca(e){return la(e)?.toString(`utf8`)}function la(e){try{return q(e)}catch(e){if(ma(e)&&e.code===`ENOENT`)return;throw e}}function ua(e,t){let n=ca(e);if(n===void 0)throw Error(`Required file ${t} does not exist.`);return n}function da(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fa(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function pa(e){return typeof e==`string`&&e.length>0}function ma(e){return e instanceof Error&&`code`in e}function ha(e={}){let{ref:t,repositoryRoot:n}=Si(e),r=Ti(n,t,`recipes`).filter(e=>/^recipes\/[^/]+\/recipe\.yaml$/u.test(e)).map(e=>{let r=e.split(`/`)[1];return ci(r),{description:si(Ci(n,t,e),e).description,name:r}});return r.sort((e,t)=>e.name.localeCompare(t.name)),{recipes:r,ref:t}}function ga(e){console.log(`Coreframe recipes at ${e.ref}:`);for(let t of e.recipes)console.log(`${t.name} — ${t.description}`)}const _a=`.agents/skills/coreframe-upgrade/SKILL.md`;function va(e,t={}){return J(`git`,e,t)}function ya(e){return e.stderr.toString(`utf8`).trim()||e.stdout.toString(`utf8`).trim()}function ba(e,t){let n=xi(e,t),r=va([`show`,n],{encoding:`utf8`});if(r.status!==0){let e=ya(r);throw Error(`Could not read ${n}.${e?` ${e}`:``}`)}return r.stdout.toString()}function xa(){let e=va([`rev-parse`,`--show-toplevel`],{encoding:`utf8`});if(e.status!==0){let t=ya(e);throw Error(`Could not find git repository root.${t?` ${t}`:``}`)}return e.stdout.toString().trim()}function Sa(e,t){let n=Ke(P(Le(),`coreframe-upgrade-skill-`)),r=P(n,`SKILL.md`);try{Ze(r,t);let n=ya(va([`--no-pager`,`diff`,`--no-index`,`--color=never`,`--`,e,r]));n&&console.log(n)}finally{Je(n,{force:!0,recursive:!0})}}function Ca({apply:e,target:t}){let n=P(xa(),_a),r=Q(t);if(!K(n))throw Error(`Local ${_a} does not exist.`);let i=q(n,`utf8`),a=ba(t,_a);return i===a?(console.log(`Coreframe upgrade skill matches ${r}:template/${_a}.`),0):e?(Ze(n,a),console.error(`Updated ${_a} from ${r}:template. Reread it before continuing the upgrade.`),20):(console.error(`Coreframe upgrade skill differs from ${r}:template/${_a}.`),console.error(`Run again with --apply to update it, then reread ${_a} before continuing.`),Sa(n,a),20)}const wa=[{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`}],Ta=[{matches:e=>e===`src-tauri`||e.startsWith(`src-tauri/`),reason:`legacy Tauri shell removed by breaking host migration`}],Ea=new Set([`100644`,`100755`,`120000`]);function Da(e,t={}){return J(`git`,e,t)}function Oa(e){let t=Da(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 ka(e){let t=Da(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 Oa([`rev-parse`,`--show-toplevel`]).trim()}function ja(e){let t=P(e,`package.json`);if(!K(t))throw Error(`Missing --base <git-ref>, and package.json does not exist.`);let n=JSON.parse(q(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 Ma(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=Ma(ka([`diff`,`--name-status`,`-z`,`--no-renames`,bi(e),bi(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 Pa(e,t){let n=ka([`ls-tree`,`-z`,`-r`,bi(e),`--`,t]);if(n.length===0)return null;let r=Ma(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 Fa(e){return ka([`cat-file`,`blob`,e.object])}function Ia(e,t){let n=F(e,t),r=e.endsWith(ve)?e:`${e}${ve}`;if(n!==e&&!n.startsWith(r))throw Error(`Refusing to access path outside repository: ${t}`);return n}function La(e){try{return We(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}function Ra(e){return(e.mode&73)!=0}function za(e){return e===null||e.type===`blob`&&Ea.has(e.mode)}function Ba(e){return wa.find(t=>t.matches(e))?.reason}function Va(e){return Ta.find(t=>t.matches(e))?.reason}function Ha(e,t,n){let r=Ia(e,t);if(n===null)return{matches:!La(r)};if(!za(n))return{matches:!1,reason:`unsupported template entry mode ${n.mode} ${n.type}`};let i;try{i=We(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=Fa(n);return n.mode===`120000`?i.isSymbolicLink()?{matches:Buffer.from(qe(r),`utf8`).equals(a)}:{matches:!1,reason:`worktree path is not a symlink`}:i.isFile()?(n.mode===`100755`?Ra(i):!Ra(i))?{matches:q(r).equals(a)}:{matches:!1,reason:`worktree executable bit differs from template`}:{matches:!1,reason:`worktree path is not a regular file`}}function Ua(e){La(e)&&Je(e,{force:!0,recursive:!1})}function Wa(e,t,n){let r=Ia(e,t);if(n===null){Ua(r);return}if(Ge(N(r),{recursive:!0}),n.mode===`120000`){Ua(r),Ye(Fa(n).toString(`utf8`),r);return}let i=La(r)?We(r):null;i&&!i.isFile()&&Ua(r),Ze(r,Fa(n)),Ue(r,n.mode===`100755`?493:420)}function Ga(e,t){return e===null&&t!==null?`add`:e!==null&&t===null?`delete`:`update`}function Ka(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 qa(e){let t=Aa(),n=Q(e.base??ja(t)),r=Q(e.target),i=Na(n,r),a=[],o=[],s=[],c=[];for(let e of i){let i=Ba(e.path);if(i){o.push({action:`ignored`,path:e.path,reason:i});continue}let l=Pa(n,e.path),u=Pa(r,e.path),d=Ga(l,u),f=u===null?Va(e.path):void 0;if(f){a.push({action:d,path:e.path,reason:f,targetEntry:u});continue}if(!za(l)||!za(u)){s.push({action:d,path:e.path,reason:`unsupported template entry type`});continue}if(Ha(t,e.path,u).matches){c.push({action:`unchanged`,path:e.path});continue}let p=Ha(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)Wa(t,e.path,e.targetEntry??null);console.log(`Coreframe template fast-forward: ${n} -> ${r}`),console.log(``),Ka(e.apply?`Applied clean template updates`:`Would apply clean template updates`,a),Ka(`Ignored downstream-owned paths`,o),Ka(`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 Ja=[`dependencies`,`devDependencies`];function Ya(e){let t=J(`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 Xa(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}: ${e instanceof Error?e.message:e}`)}}function Za(e,t){let n=`${Q(e)}:${t}`;return Xa(Ya([`show`,n]),n)}function Qa(e){return e.startsWith(`@coreframe/`)}function $a(e){return e.startsWith(`file:`)||e.startsWith(`link:`)||e.startsWith(`workspace:`)}function eo(e){return e.startsWith(`file:`)||e.startsWith(`link:`)}function to(e,t){let n=e.indexOf(`:`),r=e.slice(n+1),i=_e.normalize(_e.join(`template`,r,`package.json`));if(r.length===0||_e.isAbsolute(r)||i===`..`||i.startsWith(`../`))throw Error(`Invalid local template dependency for ${t}: ${e}`);return i}function no(e){let t=Za(e,`template/package.json`),n=[],r=new Set;for(let i of Ja)for(let[a,o]of Object.entries(t[i]??{})){if(!Qa(a)||!eo(o))continue;if(r.has(a))throw Error(`Target template declares ${a} more than once.`);let t=to(o,a),s=Za(e,t);if(s.name!==a||typeof s.version!=`string`)throw Error(`${Q(e)}:${t} must declare ${a} with a version.`);n.push({group:i,name:a,spec:`^${s.version}`}),r.add(a)}return n}function ro(e,t){for(let n of Ja){let r=e[n]?.[t];if(r)return{group:n,spec:r}}}function io(e,t,n){let r=t.match(/\n([\t ]+)"/u)?.[1]??` `,i=t.endsWith(`
|
|
11
12
|
`)?`
|
|
12
|
-
`:``;
|
|
13
|
-
`),`Pending Worker secret updates`),c?.accessTokenSigningSecret.provisioned&&R.log.info(`Provisioning Coreframe-managed access-token signing material.`),await to(n);let _=o.mode===`full`?await Ka(a,n,t):!1;try{m&&await Tt(Va,r,d),R.log.step(`Running pre-deploy build`),await L(`pnpm`,[`build`],{env:so(p),stdio:`inherit`}),R.log.step(`Running release build and uploading PostHog source maps`),h=!0,await L(`pnpm`,[`build`],{env:p,stdio:`inherit`}),_&&(R.log.step(`Running deploy-safe database migrations`),await L(`pnpm`,[`db`,`migrate`],{env:p,stdio:`inherit`})),R.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?{[et]:c.accessTokenSigningSecret.value}:{},...c?.pendingWorkerSecrets.values},t=Object.keys(e).length>0?await io(e):void 0,i=o.mode===`full`?await st({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:f}}}):await ot(process.cwd());try{await L(`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 tt(c.pendingWorkerSecrets),await wt({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&&(R.log.step(`Running required after-Worker deploy hook`),await xt(o,l)),n.skipPostDeployChecks||(R.log.step(`Running post-deploy checks`),await St(o,l)),R.outro(`Deployed ${f} to ${n.environment}`)}catch(e){throw!h&&m&&await H(Va,i),e}}function Ua(e){return{environment:Wa(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function Wa(e){if(e&&nt.includes(e))return e;throw Error(`Deploy environment must be one of: ${nt.join(`, `)}.`)}async function Ga(e,t){let n=await ht({environment:e}),r=n.values.DASHBOARD_PASSWORD??await ro(t,e);return Ct(await at({environment:e}),e,{availableNames:[...Object.keys(n.values),...r?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await ut({environment:e}),dashboardPassword:r,pendingWorkerSecrets:n}}async function Ka(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 qa(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 Ya(t,a)}async function qa(e){try{return await Ja(e)}finally{await e.close?.()}}async function Ja(e){return ee(await h(),await w(e))}async function Ya(e,t){if(t.length===0)return R.log.info(`No pending deploy migrations.`),!1;if(R.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 R.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(R.isCancel(n))throw R.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function Xa(){let{stdout:e}=await L(`git`,[`status`,`--porcelain`],{stdin:`ignore`});if(e.trim().length>0)throw Error(`Deploy requires a clean git tree.`);let{stdout:t}=await L(`git`,[`rev-parse`,`HEAD`],{stdin:`ignore`});return t.trim()}function Za(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function Qa(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function $a(e,t,n=it){return e.url?eo(e.url,t):t===`staging`&&e.stagingHostname?eo(await n(),t):eo(void 0,t)}function eo(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 to(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await R.confirm({initialValue:!1,message:`Deploy to production?`});if(R.isCancel(t)||!t)throw R.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}function no(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 ro(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Dt(await B(`.env`,`utf8`))}catch(e){throw ao(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 io(e){let t=await Ee(N(Me(),`coreframe-deploy-secrets-`)),n=N(t,`secrets.json`);return await H(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>V(t,{force:!0,recursive:!0})}}function ao(e){return e instanceof Error&&`code`in e}function oo(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 so(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function co(){let e=await uo();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function lo(e){let t=await uo(),n=fo();await Z.mkdir(A.dirname(n),{recursive:!0}),await Z.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function uo(){try{let e=await Z.readFile(fo(),`utf8`),t=JSON.parse(e);return po(t)?t:{}}catch{return{}}}function fo(){return A.join(Tr.homedir(),`.coreframe`,`preferences.json`)}function po(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function mo({env:e=G.env,interactive:t=G.stdin.isTTY===!0,platform:n,target:r}){let i=await xo(n,e).catch(()=>[]),a=r?zo(i,r):void 0;if(a)return a;if(!r&&i.length>0)return bo(i,n,t);let o=r?zo(await Co(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return wo(o,n,e,t);let s=await So(n,e),c=r?zo(s,r):void 0;if(c)return c;if(!r&&s.length>0)return bo(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 ho(e){let{device:t,host:n,interactive:r=G.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=Vo();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await vo();if(a&&i.includes(a))return a;if(i.length===1)return await yo(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await R.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(R.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await yo(o),o}async function go({device:e,env:t=G.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await Mo(e.id,a,t)}catch{R.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:_o(i,await ho({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function _o(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 vo(){return(await co()).mobileDevHost}async function yo(e){try{await lo({mobileDevHost:e})}catch(e){R.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function bo(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 R.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(R.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function xo(e,t){return e===`android`?Eo(t):Oo(t)}async function So(e,t){return e===`android`?Do(t):ko(t)}async function Co(e){let{stdout:t}=await L(`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 wo(e,t,n,r){let i=await To(t,n).catch(()=>[]),{stdout:a}=await L(`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 To(t,n).catch(()=>[]),o=zo(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return bo(s,t,r);if(a.length===1)return a[0];await Bt(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 To(e,t){return e===`ios`?ko(t,`booted`):(await Eo(t)).filter(e=>!e.physical)}async function Eo(e){let t=await jo(e,`platform-tools`,G.platform===`win32`?`adb.exe`:`adb`),{stdout:n}=await L(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 Po(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await Io(t,e,n,r):await Lo(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(Ho)}async function Do(e){let{stdout:t}=await L(await jo(e,`emulator`,G.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 Oo(e){let t=await Z.mkdtemp(A.join(Tr.tmpdir(),`coreframe-ios-devices-`)),n=A.join(t,`devices.json`);try{return await Z.writeFile(n,``),await L(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await Z.readFile(n,`utf8`)).result?.devices??[]).filter(Ao).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(Ho)}finally{await Z.rm(t,{force:!0,recursive:!0})}}async function ko(e,t=`available`){let{stdout:n}=await L(`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(Ho)}function Ao(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 jo(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:No(e);for(let e of i){let r=A.join(e,t,n);try{return await Z.access(r),r}catch{}}return n}async function Mo(e,t,n){let r=await jo(n,`platform-tools`,G.platform===`win32`?`adb.exe`:`adb`),{stdout:i}=await L(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 L(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 No(e){return G.platform===`darwin`?[A.join(Tr.homedir(),`Library`,`Android`,`sdk`)]:G.platform===`win32`&&e.LOCALAPPDATA?[A.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[A.join(Tr.homedir(),`Android`,`Sdk`)]}async function Po(e,t,n,r){return(await Fo(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function Fo(e,t,n){return(await L(e,n,{env:t,timeout:3e3})).stdout}async function Io(e,t,n,r){return Fo(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function Lo(e,t,n,r){return Fo(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>Ro(e)||r).catch(()=>r)}function Ro(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function zo(e,t){let n=e.map(e=>({device:e,score:Math.max(Bo(t,e.name),Bo(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function Bo(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 Vo(){return[...new Set(Object.values(Tr.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function Ho(e,t){return e.label.localeCompare(t.label)}var Uo=class{#e;#t=new Map;#n=new Set;#r;#i;#a;#o;#s=0;constructor({onEvent:e,verbose:t=!1,write:n}){this.#e=e,this.#r=t,this.#i=n}async handleLine(e){let t;try{t=JSON.parse(e)}catch{return $(e,`debug`)}if(!Array.isArray(t))return $(e,`debug`);let n=[];for(let e of t){if(!Jo(e)){n.push(...$(JSON.stringify(e),`debug`));continue}if(e.id!==void 0&&(`result`in e||`error`in e)){this.#c(e);continue}if(typeof e.event!=`string`)continue;let t={event:e.event,params:Jo(e.params)?e.params:{}};this.#l(t),await this.#e?.(t),n.push(...Go(t,this.#r))}return n}async restart({debounce:e=!1,fullRestart:t,reason:n}){let r=await this.#d();if(!r.supportsRestart)throw Error(`The running Flutter application does not support hot restart or reload.`);let i=await this.#u(`app.restart`,{appId:r.id,debounce:e,fullRestart:t,reason:n});if(!Jo(i)||typeof i.code!=`number`)throw Error(`Flutter returned an invalid restart response.`);let a={code:i.code,message:typeof i.message==`string`?i.message:``};if(a.code!==0)throw Error(a.message||`Flutter restart failed with code ${a.code}.`);return a}async stop(){let e=await this.#d();if(await this.#u(`app.stop`,{appId:e.id})!==!0)throw Error(`Flutter did not stop the running application.`)}close(e=Error(`The Flutter machine connection closed.`)){if(this.#o)return;let t=Xo(e);this.#o=t;for(let e of this.#t.values())e.reject(t);this.#t.clear(),this.#f(t)}#c(e){let t=String(e.id),n=this.#t.get(t);n&&(this.#t.delete(t),`error`in e?n.reject(Error(Yo(e.error))):n.resolve(e.result))}#l({event:e,params:t}){let n=typeof t.appId==`string`?t.appId:void 0;if(e===`app.start`&&n){this.#a={id:n,started:!1,supportsRestart:t.supportsRestart===!0};return}if(e===`app.started`&&n&&this.#a?.id===n){let e={...this.#a,started:!0};this.#a=e;for(let t of this.#n)t.resolve(e);this.#n.clear();return}e===`app.stop`&&n&&this.#a?.id===n&&(this.#a=void 0,this.#f(Error(`The Flutter application stopped before it was ready.`)))}async#u(e,t){if(this.#o)throw this.#o;let n=String(++this.#s),r,i,a=new Promise((e,t)=>{r=t,i=e});this.#t.set(n,{reject:r,resolve:i});try{await this.#i(`${JSON.stringify([{id:n,method:e,params:t}])}\n`)}catch(e){this.#t.delete(n),r(Xo(e))}return a}#d(){return this.#o?Promise.reject(this.#o):this.#a?.started?Promise.resolve(this.#a):new Promise((e,t)=>{this.#n.add({reject:t,resolve:e})})}#f(e){for(let t of this.#n)t.reject(e);this.#n.clear()}};async function*Wo(e,t){try{for await(let n of e)yield*await t.handleLine(n)}catch(e){throw t.close(e),e}finally{t.close()}}function Go({event:e,params:t},n){if(e===`daemon.log`||e===`app.log`)return $(qo(t.log),t.error===!0?`error`:`debug`);if(e===`daemon.logMessage`){let e=Ko(t.level);return!n&&e===`debug`?[]:[...$(qo(t.message),e),...n?$(qo(t.stackTrace),e):[]]}return e===`daemon.showMessage`?$(qo(t.message),Ko(t.level)):e===`app.warning`?$(qo(t.warning),`warn`):e===`app.progress`&&t.finished!==!0?$(qo(t.message),`debug`):e===`app.stop`&&t.error!==void 0?$(Yo(t.error),`error`):[]}function $(e,t){return e===void 0?[]:e.split(/\r?\n/u).map(e=>({level:t,message:e}))}function Ko(e){return e===`error`?`error`:e===`warning`||e===`warn`?`warn`:`debug`}function qo(e){return typeof e==`string`&&e.length>0?e:void 0}function Jo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yo(e){if(typeof e==`string`)return e;if(Jo(e)&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Xo(e){return e instanceof Error?e:Error(Yo(e))}async function Zo(e,t){if(!e)return()=>void 0;Be(A.dirname(e),{recursive:!0}),Ke(e,``,{flag:`a`});let n;try{n=q(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=Ge(e,{persistent:!1},()=>{if(i)return;let a=++r;B(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function Qo(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const $o=G.platform===`win32`?`portless.cmd`:`portless`,es=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),ts=/^Proxy is already running on port (\d+)\.$/,ns=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function rs(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(es,``).trim().match(ts);if(a?.[1]!==void 0&&i!==void 0&&ns.test(i.replace(es,``).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 is(e){let t=rs(e);t&&G.stdout.write(t.endsWith(`
|
|
14
|
-
`)?t:`${t}\n`)}async function as({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await Vt()).isAgent?!1:Pt(e)}async function os({cwd:e,env:t,lan:n=!1}){let r=A.join(`node_modules`,`.bin`,$o),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await L(A.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});is(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&is(e.stdout),e}}function ss({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 cs=A.join(`.coreframe`,`dev`,`session.json`);async function ls({appOrigin:e,cwd:t,device:n,flutterMcp:r,flutterMode:i,id:a,localOrigin:o,now:s=new Date,pid:c=process.pid,platform:l}){let u=A.resolve(t,cs),d=A.dirname(u),f={version:2,id:a,pid:c,projectRoot:A.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:A.resolve(t,`.leylines`,`logs.sqlite`),scopes:{browser:`browser`,...i===void 0?void 0:{flutter:`dev.flutter`},vite:`dev.vite`}},...i===void 0?void 0:{flutter:{mode:i,mcp:r,state:`starting`,...n===void 0?void 0:{device:n}}}},p=Promise.resolve(),m=()=>{let e=`${JSON.stringify(f,void 0,2)}\n`;return p=p.then(async()=>{await z(d,{recursive:!0});let t=A.join(d,`.session-${a}.json`);await H(t,e,{mode:384}),await Ce(t,384),await Oe(t,u)}),p};return await m(),{path:u,async recordFlutterEvent({event:e,params:t}){let n=f.flutter;if(!n)return;let r=fs(t.appId),i;if(e===`daemon.connected`){let e=ps(t.pid),r=fs(t.version);i={...us(n),state:`starting`,...e===void 0?void 0:{daemonPid:e},...r===void 0?void 0:{protocolVersion:r}}}else if(e===`app.start`&&r)i={...us(n),appId:r,state:`starting`,supportsRestart:t.supportsRestart===!0};else if(e===`app.started`&&r===n.appId)i={...n,state:`running`};else if(e===`app.debugPort`&&r===n.appId){let e=fs(t.wsUri);e&&(i={...n,vmServiceWsUri:e})}else if(e===`app.devTools`&&r===n.appId){let e=fs(t.uri);e&&(i={...n,devToolsUri:e})}else if(e===`app.dtd`&&r===n.appId){let e=fs(t.uri);e&&(i={...n,dtdUri:e})}else e===`app.stop`&&r===n.appId&&(i=ds(n));i&&(f={...f,flutter:i},await m())},async recordFlutterExit(){!f.flutter||f.flutter.state===`stopped`||(f={...f,flutter:ds(f.flutter)},await m())},async close(){await p;try{JSON.parse(await B(u,`utf8`)).id===a&&await V(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}function us(e){return{mode:e.mode,mcp:e.mcp,...e.device===void 0?void 0:{device:e.device},...e.daemonPid===void 0?void 0:{daemonPid:e.daemonPid},...e.protocolVersion===void 0?void 0:{protocolVersion:e.protocolVersion}}}function ds(e){return{...us(e),state:`stopped`,...e.appId===void 0?void 0:{appId:e.appId},...e.supportsRestart===void 0?void 0:{supportsRestart:e.supportsRestart}}}function fs(e){return typeof e==`string`?e:void 0}function ps(e){return typeof e==`number`?e:void 0}const ms=`extension:dev`;function hs(e){if(!K(N(e,`src-webext/wxt.config.ts`)))throw Error("No WXT configuration found at src-webext/wxt.config.ts. Apply the wxt recipe or add that convention before running `coreframe dev webext`.");let t=N(e,`package.json`),n;try{n=JSON.parse(q(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.${ms} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function gs({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`,ms,...n.length>0?[`--`,...n]:[]]}const _s=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],vs=[`managed-dev-overlay`],ys=A.resolve(`node_modules`,`.bin`),bs=G.platform===`win32`?`pnpm.cmd`:`pnpm`,xs=G.platform===`win32`?`portless.cmd`:`portless`,Ss=G.platform===`win32`?`react-router.cmd`:`react-router`,Cs=`Lost connection to device.`;async function ws({cwd:e=G.cwd(),debug:t,device:n,env:r=G.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=G.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=At({env:r}),ee=r.PATH??r.Path??``,y=Ls(h)?h:void 0,b=qt(i||a),x=Is(_??r.COREFRAME_WEB_PORT),S,C,w,te,T,ne,E,re,ie,oe,se,ce,ue,D=!1,O,k=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.`);hs(e)}if(c&&h!==`web`)throw Error(`Local HTTPS is only supported for the web development platform.`);if(n!==void 0&&h!==`ios`&&h!==`android`)throw Error(`A device name or ID is only supported for iOS or Android development.`);let fe=await v.measure(`routing`,()=>as({cwd:e,env:r,platform:h}));fe&&await v.measure(`portless`,()=>os({cwd:e,env:r,lan:u}));let j=y===void 0?h===`web`?x??await wr.getAvailablePort():h===`webext`?x:void 0:x??await wr.getAvailablePort(),M,N=new Promise(e=>{M=e}),P=()=>{D||(D=!0,M(),C?.kill(`SIGTERM`),ne?.kill(`SIGTERM`),E?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),re?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ie?.close().catch(()=>void 0),S?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),F().catch(()=>void 0))},F=()=>te?(T??=te[Symbol.asyncDispose](),T):Promise.resolve(),I=e=>{O??=e,P()},pe=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>I(e);return G.on(e,t),{handler:t,signal:e}}),me=async e=>{let t=Ye(e);C=t;try{await t.expectSuccess()}catch(e){if(!D)throw e}finally{C===t&&(C=void 0)}};try{se=y?zt({path:A.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await mo({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&Jt({device:_,mode:b,platform:i});let x=y?se?.logger({scope:`dev.flutter`,properties:{platform:y,..._?{deviceId:_.id}:void 0}}):void 0;oe=i&&_&&j!==void 0?await go({device:_,env:r,host:s,interactive:l,platform:i,port:j}):void 0;let C=oe?.viteHost??(y?i?!0:`127.0.0.1`:s),T=j===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${j}`,O=y===void 0?T:oe?.serverUrl??_o(y,void 0,j),M={},F=!1,I;[M,F]=await Promise.all([v.measure(`config`,()=>U({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await Nt(e))]),await v.measure(`i18n`,()=>Jn({cwd:e,projectConfig:M})),I=h!==`webext`&&jr(e)?await wr.getAvailablePort():void 0;let pe=await v.measure(`https`,async()=>c&&!fe?Ft({cwd:e}):void 0),he=Qo(r,h);k={...he,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[It]:W()}:void 0,...y?{COREFRAME_PLATFORM:y,[Rt]:A.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...pe?{[jt]:pe.cert,[Mt]:pe.key}:void 0,...I?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${I}`}:void 0},T!==void 0&&O!==void 0&&(ce=await ls({appOrigin:O,cwd:e,device:_,flutterMcp:a,flutterMode:y===void 0?void 0:b,id:W(),localOrigin:T,platform:h}));let ge=async()=>{if(!I)return;let t=Mr({cwd:e,env:k,port:I});ie=t;try{await t.listen(),await t.wait()}finally{await t.close(),ie===t&&(ie=void 0)}},_e=async()=>{let t=Je({label:`web`}),n=Je({color:`red`,label:`web`});t.pipe(G.stdout,{end:!1}),n.pipe(G.stderr,{end:!1}),E=L(fe?xs:Ss,fe?ss({host:C,lan:u,port:j}):Fs({host:C,port:j,strictPort:h===`web`||y!==void 0}),{cwd:e,env:{...k,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[k.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:ys+A.delimiter+ee},stdin:`inherit`});let r=Promise.allSettled([js(E.stdout,t),js(E.stderr,n)]);try{await E;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!D)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([qe(t),qe(n)]),E=void 0}},ve=async()=>{let t=Je({label:`webext`}),n=Je({color:`red`,label:`webext`});t.pipe(G.stdout,{end:!1}),n.pipe(G.stderr,{end:!1}),re=L(bs,gs({host:s,port:j}),{cwd:e,env:k,stdin:`inherit`});let r=Promise.allSettled([js(re.stdout,t),js(re.stderr,n)]);try{await re;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!D)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([qe(t),qe(n)]),re=void 0}},ye=async t=>{let n,r,i=!1,s,c=Zo(k[Rt],()=>{if(D||!n||!r||s||b!==`debug`&&i)return;let e=n,t=r;s=(async()=>{if(b===`debug`){await t.restart({debounce:!0,fullRestart:!0,reason:`manual`});return}i=!0;try{await t.stop()}catch(t){let n=t instanceof Error?t.message:String(t);x?.write(`warn`,`Flutter stop failed; terminating it: ${n}`,{properties:{stream:`control`}}),G.stderr.write(`Flutter stop failed; terminating it: ${n}\n`),await e.nodeChildProcess.then(e=>e.kill(`SIGTERM`))}})().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Flutter restart failed: ${t}`,{properties:{stream:`control`}}),G.stderr.write(`Flutter restart failed: ${t}\n`)}).finally(()=>{s=void 0})});try{for(;!D;){i=!1;let s=!1,c=h===`android`&&o===`filtered`&&!g?await de():void 0,u=L(`flutter`,Yt({device:_??{id:h},flutterDriver:a,mode:b,serverUrl:O,verbose:g}),{cwd:A.join(e,`src-flutter`),env:Kt(he,{noCodesign:f}),stdio:[`pipe`,`pipe`,`pipe`]}),d=new Uo({onEvent:async e=>{Ds(e.params.message)&&(s=!0),await ce?.recordFlutterEvent(e)},verbose:g,write:async e=>{let t=await u.nodeChildProcess;if(!t.stdin)throw Error(`Flutter machine input is unavailable.`);t.stdin.write(e)===!1&&await Ot(t.stdin,`drain`)}}),p=e=>Es(Wo(e,d),()=>s=!0);S=u,n=u,r=d;try{let e=!1;try{let e=c?c.capture(As(p(u),x,`output`)):Promise.all([ks(p(u.stdout),G.stdout,x,`stdout`),Ts(u.stderr,G.stderr,x,`stderr`)]);await Promise.all([u,e])}catch{e=!0}if(i&&!D)continue;if(D)return;let n=l?await R.confirm({initialValue:!0,message:s?`${Cs} Restart Flutter?`:e?`Flutter failed. Retry?`:`Flutter exited unexpectedly. Restart Flutter?`}):!1;if(R.isCancel(n)||!n){if(!e&&!s){R.log.warn(`Flutter exited unexpectedly.`);return}R.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??N);return}}finally{S===u&&(S=void 0),n===u&&(n=void 0),r===d&&(r=void 0),d.close(),ce?.recordFlutterExit().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Failed to record Flutter exit: ${t}`,{properties:{stream:`control`}})})}}}finally{(await c)()}},be=async()=>{if(h===`web`){await _e();return}let t=_e().then(()=>{if(!D)throw Error(`The Vite development server stopped while Flutter was still running.`)});await le({cwd:e});try{await Promise.race([t,ye(t)])}finally{P(),await Promise.allSettled([t,S]),S=void 0}},xe=async()=>{let t=Ye({name:`panda`,command:bs,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:k});ne=t;try{if(await t.expectSuccess(),!D)throw Error(`The Panda CSS watcher stopped while development was still running.`)}catch(e){if(!D)throw e}finally{ne===t&&(ne=void 0)}},Se=async()=>{if(h===`webext`){await ve();return}let e=xe(),t=be(),n=I?ge():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),D&&await t}finally{P(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(F&&(k={...k,[Lt]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(ue=await v.measure(`supervisor`,()=>kt({cwd:e,env:r})))),D)return;if(h===`webext`){v.report(),await Se();return}if(M.database?.dialect===`sqlite`&&(await v.measure(`database`,async()=>{let t=await ae({config:M,cwd:e,env:r,tursoOutput:G.stdout,useSupervisorLease:!0});te=t,k={...k,...t.env}}),await v.measure(`schema`,()=>me({name:`db`,command:bs,args:[`db`,`ensure`],cwd:e,env:k,prefix:!1})),D))return;if(Ps(M)){let t=Je({label:`postgres`});t.pipe(G.stdout,{end:!1});try{let n=await v.measure(`database`,()=>Ns({config:M,cwd:e,env:k,failIfRunning:!0,interactive:l,isStopping:()=>D,postgresOutput:t,useSupervisorLease:!0}));if(!n)return;w=n,k={...k,...n.env};try{D||await v.measure(`schema`,()=>me({name:`db`,command:bs,args:[`db`,`ensure`],cwd:e,env:k,prefix:!1})),D||(v.report(),await Se())}finally{await n[Symbol.asyncDispose](),w===n&&(w=void 0)}}finally{t.end()}return}v.report(),await Se()}finally{P(),await oe?.close(),oe=void 0;let e;try{await w?.[Symbol.asyncDispose]()}catch(t){e=t}finally{try{await F()}finally{try{await ce?.close()}finally{ue?.close(),se?.close();for(let{handler:e,signal:t}of pe)G.off(t,e)}}O&&(G.exitCode??=O===`SIGINT`?130:143)}Ms(e)}}async function Ts(e,t,n,r){for await(let i of Os(e,n,r))t.write(`${i}\n`)||await Ot(t,`drain`)}async function*Es(e,t){for await(let n of e)Ds(n.message)&&t(),yield n}function Ds(e){return typeof e==`string`&&e.trim()===Cs}async function*Os(e,t,n){for await(let r of e){let e=ce(r);e.message&&t?.write(e.level,e.message,{properties:{stream:n}}),yield r}}async function ks(e,t,n,r){for await(let i of As(e,n,r))t.write(`${i}\n`)||await Ot(t,`drain`)}async function*As(e,t,n){for await(let r of e)r.message&&t?.write(r.level,r.message,{properties:{stream:n}}),yield r.message}async function js(e,t){for await(let n of e)t.write(`${n}\n`)||await Ot(t,`drain`)}function Ms(e){if(e)throw e}async function Ns({interactive:e,isStopping:t,...n}){try{return await ie(n)}catch(r){if(!(r instanceof f)||!e)throw r;let i=await R.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(R.isCancel(i)||!i){R.cancel(`Keeping the existing PostgreSQL process.`);return}return await oe(r),t()?void 0:ie(n)}}function Ps(e){return(e.database?.dialect??`postgres`)===`postgres`}function Fs({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 Is(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 Ls(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function Rs(e={}){let t=e.cwd??G.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await Se(A.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Pe(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 Ht({...e,cwd:t},r)}const zs=`worker-configuration.d.ts`;async function Bs({check:e=!1,cwd:t=process.cwd()}={}){let n=await U({cwd:t}),r=await ct({coreframeConfig:n,cwd:t}),i=F(t,zs),a=F(t,`.coreframe-worker-types-${W()}.d.ts`);try{try{await L(`pnpm`,[`exec`,`wrangler`,`types`,a,`--config`,r.path,`--strict-vars=false`,`--include-runtime=false`],{cwd:t,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw Vs(e),e}let o=Hs(await B(a,`utf8`)),s=Ie(r.config),c=Fe(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${Us(c)}\n`;if(e){if(await B(i,`utf8`).catch(()=>``)!==l)throw Error(`${zs} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await B(i,`utf8`).catch(()=>``);return u!==l&&await H(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await V(a,{force:!0})}}function Vs(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
|
|
16
|
-
`)}function
|
|
17
|
-
`)}const Ws=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),Gs=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],Ks=[`dashboard`,`node_modules/@coreframe/dashboard/dist/package/app`,`node_modules/@coreframe/dashboard/package.json`,`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`],qs=[`coreframe.config.ts`,`node_modules/@coreframe/config/dist`,`node_modules/@coreframe/config/package.json`,`node_modules/@coreframe/deploy/dist`,`node_modules/@coreframe/deploy/package.json`,`node_modules/wrangler/package.json`,`package.json`,`pnpm-lock.yaml`,`src/api`,`wrangler.jsonc`],Js=`.coreframe/typegen.json`,Ys=[`web`,`dashboard`,`worker`];async function Xs({checkWorker:e=!1,cwd:t=G.cwd(),runners:n={}}={}){let r=await ec(t)??{generators:{},schemaVersion:1},i=[];return i.push(await Qs({cwd:t,inputPaths:Gs,name:`web`,outputPath:`.react-router`,run:()=>(n.web??$s)(t),state:r})),i.push(await Qs({cwd:t,inputPaths:Ks,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??yr)(t),state:r})),i.push(await Qs({cwd:t,inputPaths:qs,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??Bs)({check:e,cwd:t}),state:r})),i}function Zs(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function Qs({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await nc(e,t),s=await rc(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 rc(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await tc(e,a),{changed:s!==l,name:n,ran:!0}}async function $s(e){let t=G.platform===`win32`?`react-router.cmd`:`react-router`,n=G.env;await L(t,[`typegen`],{cwd:e,env:{...n,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function ec(e){try{let t=JSON.parse(await B(A.resolve(e,Js),`utf8`));if(!sc(t)||t.schemaVersion!==1)return;let n={};if(!sc(t.generators))return;for(let e of Ys){let r=t.generators[e];sc(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 tc(e,t){let n=A.resolve(e,Js);await z(A.dirname(n),{recursive:!0}),await H(n,`${JSON.stringify(t)}\n`,{mode:384})}async function nc(e,t){let n=Le(`sha256`);for(let r of[...t].sort()){let t=A.resolve(e,r),i=await ac(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await ic(t)){let i=A.join(t,r),a=A.relative(e,i).split(A.sep).join(`/`);n.update(`${a}\0`),n.update(await B(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await B(t)))}return n.digest(`hex`)}async function rc(e,t){if(await ac(A.resolve(e,t)))return nc(e,[t])}async function ic(e){let t=[];async function n(e,r){let i=await De(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(Ws.has(a.name))continue;await n(A.join(e,a.name),A.join(r,a.name))}else a.isFile()&&t.push(A.join(r,a.name))}return await n(e,``),t.sort()}async function ac(e){try{return await ke(e)}catch(e){if(oc(e))return;throw e}}function oc(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function sc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const cc=A.resolve(`node_modules`,`.bin`);G.env.PATH=cc+A.delimiter+G.env.PATH;const lc=G.platform===`win32`?`tsc.cmd`:`tsc`,uc=[{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 dc(){await Xs({checkWorker:!0});let e=[];for(let t of uc)try{await Se(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>Ye({name:e.name,command:lc,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(G.exitCode=n[0].exitCode)}const fc=n(a(vs),{displayName:`feature`,from:async e=>e}),pc=n(a(Gt),{displayName:`filtered|full`,from:async e=>e}),mc=[`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.`],hc=t({name:`deploy`,args:{environment:c({type:a(nt),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})=>Ha([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),gc=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 gt();if(e){console.log(JSON.stringify({...t,notices:mc}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${mc.join(` `)}`)}}),url:t({name:`url`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await it();console.log(e?JSON.stringify({url:t}):t)}})}}),_c=d({name:`secrets`,cmds:{"rotate-access-token":t({name:`rotate-access-token`,args:{environment:c({type:a(nt),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 bt({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(nt)),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 at({environment:e});console.log(t?JSON.stringify(n):Cc(n))}}),set:t({name:`set`,args:{environment:c({type:a(nt),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 dt({environment:e,name:t,value:await wc(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await pt(),i=n?await Ec(r):await Tc(r,e);await ft({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(nt),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 rt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),vc=t({name:`typecheck`,args:{},handler:dc}),yc=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 Bs({check:e});console.log(e?`${Oc(t.path)} is current.`:`${Oc(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),bc=t({name:`dev`,args:{debug:o({long:`debug`,type:s(fc),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:pc,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(_s)),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=xc({device:t,flutterDebug:n,platform:f,simulator:m});return ws({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 xc({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 Sc=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})=>Rs({host:e,port:t})});function Cc(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
|
|
13
|
+
`:``;Ze(e,`${JSON.stringify(n,null,r)}${i}`)}function ao(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t)console.log(` ${e}`);console.log(``)}}function oo(e){let t=F(Ya([`rev-parse`,`--show-toplevel`]).trim(),`package.json`),n=q(t,`utf8`),r=Xa(n,t),i=Q(e.target),a=no(i),o=new Set(a.map(({name:e})=>e)),s=[],c=[],l=[],u=0;for(let e of a){let t=ro(r,e.name);if(!t){c.push(`missing: ${e.name} ${e.spec} (${e.group})`);continue}if($a(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=Ja.flatMap(e=>Object.entries(r[e]??{}).filter(([e])=>Qa(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;io(t,n,r)}console.log(`Coreframe package sync: ${i}`),console.log(``),ao(e.apply?`Updated Coreframe packages`:`Would update Coreframe packages`,s.map(({currentSpec:e,name:t,spec:n})=>`update: ${t} ${e} -> ${n}`)),ao(`Missing target Coreframe packages`,c),ao(`Locally linked Coreframe packages`,l),ao(`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 so={...p,displayName:`recipe`,description:`Coreframe recipe name, such as yam-db.`,async from(e){return ci(e)}},co=m({name:`upgrade`,cmds:{"ensure-template-remote":n({name:`ensure-template-remote`,args:{remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Remote name to ensure.`}),noFetch:i({long:`no-fetch`,description:`Do not fetch the remote after ensuring it exists.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t})=>vi({fetch:!e,remote:t})}),"check-skill-current":n({name:`check-skill-current`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),apply:i({long:`apply`,description:`Replace the local upgrade skill with the target version when it differs.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>{process.exitCode=Ca({apply:e,target:t})}}),"fast-forward-template-files":n({name:`fast-forward-template-files`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),base:c({long:`base`,type:l(p),description:`Previous Coreframe template git ref. Defaults to package.json engines.coreframe.`}),apply:i({long:`apply`,description:`Write clean fast-forwards to the worktree.`,defaultValue:()=>!1})},handler:({apply:e,base:t,target:n})=>qa({apply:e,base:t,target:n})}),"sync-coreframe-packages":n({name:`sync-coreframe-packages`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),apply:i({long:`apply`,description:`Update existing published Coreframe dependency specifications.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>oo({apply:e,target:t})})}}),lo=m({name:`recipes`,cmds:{apply:n({name:`apply`,args:{recipe:u({type:so,displayName:`recipe`,description:`Recipe to prepare and apply.`}),target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Zi(Xi({fetch:!e,name:t,remote:n,target:r}))}),list:n({name:`list`,args:{target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,target:n})=>ga(ha({fetch:!e,remote:t,target:n}))}),verify:n({name:`verify`,args:{recipe:u({type:so,displayName:`recipe`,description:`Recipe adoption to verify.`}),target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>qi(Ki({fetch:!e,name:t,remote:n,target:r}))})}}),uo=m({name:`db`,cmds:{ensure:n({name:`ensure`,args:{},handler:S}),generate:n({name:`generate`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit generate.`})},handler:({args:e})=>T(`generate`,e)}),migrate:n({name:`migrate`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit migrate.`})},handler:({args:e})=>T(`migrate`,e)}),"migrate-held":n({name:`migrate-held`,args:{local:i({long:`local`,description:`Run held migrations against the Coreframe-managed local PostgreSQL database.`,defaultValue:()=>!1})},handler:({local:e})=>re({target:e?`local`:`deployment`})}),"migrate-local":n({name:`migrate-local`,args:{},handler:ie}),"migrations-check":n({name:`migrations-check`,args:{},handler:g}),reset:n({name:`reset`,args:{},handler:oe}),seed:n({name:`seed`,args:{},handler:()=>ce()}),"schema-check":n({name:`schema-check`,args:{seed:i({long:`seed`,description:`Run the configured project seed against the throwaway database.`,defaultValue:()=>!1})},handler:({seed:e})=>_({seed:e})}),setup:n({name:`setup`,args:{},handler:()=>le()}),studio:n({name:`studio`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit studio.`})},handler:({args:e})=>T(`studio`,e)})}}),fo=`package.json`;async function po(e=process.argv.slice(2),t=process.env){let n=mo(e);So(n);let{packageJson:r,source:i}=await bt(fo),a=await U(),o=wt(a.deploy,n.environment,t);Co(n,o.mode),Do(t,[`POSTHOG_API_KEY`,`POSTHOG_PROJECT_ID`]);let s=await wo(o,n.environment,()=>ut({env:t})),c=o.mode===`full`?await go(n.environment,t):void 0,l=await xo();await nr({env:t,revision:l});let u=l.slice(0,12),d=Tt(n.environment,r.version,u),f=Ct(r.name,d),p={...jo(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(`
|
|
14
|
+
`),`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 _o(a,n,t):!1;try{m&&await jt(fo,r,d),L.log.step(`Running pre-deploy build`),await I(`pnpm`,[`build`],{env:Mo(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?{[ot]:c.accessTokenSigningSecret.value}:{},...c?.pendingWorkerSecrets.values},t=Object.keys(e).length>0?await ko(e):void 0,i=o.mode===`full`?await pt({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:f}}}):await ft(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 st(c.pendingWorkerSecrets),await At({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 Dt(o,l)),n.skipPostDeployChecks||(L.log.step(`Running post-deploy checks`),await Ot(o,l)),L.outro(`Deployed ${f} to ${n.environment}`)}catch(e){throw!h&&m&&await H(fo,i),e}}function mo(e){return{environment:ho(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function ho(e){if(e&&ct.includes(e))return e;throw Error(`Deploy environment must be one of: ${ct.join(`, `)}.`)}async function go(e,t){let n=await xt({environment:e}),r=n.values.DASHBOARD_PASSWORD??await Oo(t,e);return kt(await dt({environment:e}),e,{availableNames:[...Object.keys(n.values),...r?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await gt({environment:e}),dashboardPassword:r,pendingWorkerSecrets:n}}async function _o(e,t,n){let r=e.database?.dialect??`postgres`,i;switch(r){case`postgres`:i=await y({env:n});break;case`sqlite`:i=await b({env:n});break;default:throw Error(`Unsupported database dialect "${r}".`)}let a=await vo(i),o=await se(a);if(o.length>0)throw Error(`Pending deploy migrations contain unsafe SQL. Move unsafe statements to held migrations.\n${ne(o)}`);return bo(t,a)}async function vo(e){try{return await yo(e)}finally{await e.close?.()}}async function yo(e){return C(await v(),await ae(e))}async function bo(e,t){if(t.length===0)return L.log.info(`No pending deploy migrations.`),!1;if(L.note(te(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 xo(){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 So(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function Co(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function wo(e,t,n=ut){return e.url?To(e.url,t):t===`staging`&&e.stagingHostname?To(await n(),t):To(void 0,t)}function To(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 Do(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 Oo(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Nt(await B(`.env`,`utf8`))}catch(e){throw Ao(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 ko(e){let t=await je(P(Le(),`coreframe-deploy-secrets-`)),n=P(t,`secrets.json`);return await H(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>V(t,{force:!0,recursive:!0})}}function Ao(e){return e instanceof Error&&`code`in e}function jo(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 Mo(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function No(){let e=await Fo();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function Po(e){let t=await Fo(),n=Io();await Z.mkdir(M.dirname(n),{recursive:!0}),await Z.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function Fo(){try{let e=await Z.readFile(Io(),`utf8`),t=JSON.parse(e);return Lo(t)?t:{}}catch{return{}}}function Io(){return M.join(jr.homedir(),`.coreframe`,`preferences.json`)}function Lo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Ro({env:e=G.env,interactive:t=G.stdin.isTTY===!0,platform:n,target:r}){let i=await Go(n,e).catch(()=>[]),a=r?ls(i,r):void 0;if(a)return a;if(!r&&i.length>0)return Wo(i,n,t);let o=r?ls(await qo(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return Jo(o,n,e,t);let s=await Ko(n,e),c=r?ls(s,r):void 0;if(c)return c;if(!r&&s.length>0)return Wo(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 zo(e){let{device:t,host:n,interactive:r=G.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=ds();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await Ho();if(a&&i.includes(a))return a;if(i.length===1)return await Uo(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 Uo(o),o}async function Bo({device:e,env:t=G.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await ns(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:Vo(i,await zo({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function Vo(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 Ho(){return(await No()).mobileDevHost}async function Uo(e){try{await Po({mobileDevHost:e})}catch(e){L.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function Wo(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 Go(e,t){return e===`android`?Xo(t):Qo(t)}async function Ko(e,t){return e===`android`?Zo(t):$o(t)}async function qo(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 Jo(e,t,n,r){let i=await Yo(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 Yo(t,n).catch(()=>[]),o=ls(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return Wo(s,t,r);if(a.length===1)return a[0];await Kt(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 Yo(e,t){return e===`ios`?$o(t,`booted`):(await Xo(t)).filter(e=>!e.physical)}async function Xo(e){let t=await ts(e,`platform-tools`,G.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 is(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await os(t,e,n,r):await ss(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(fs)}async function Zo(e){let{stdout:t}=await I(await ts(e,`emulator`,G.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 Qo(e){let t=await Z.mkdtemp(M.join(jr.tmpdir(),`coreframe-ios-devices-`)),n=M.join(t,`devices.json`);try{return await Z.writeFile(n,``),await I(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await Z.readFile(n,`utf8`)).result?.devices??[]).filter(es).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(fs)}finally{await Z.rm(t,{force:!0,recursive:!0})}}async function $o(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(fs)}function es(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 ts(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:rs(e);for(let e of i){let r=M.join(e,t,n);try{return await Z.access(r),r}catch{}}return n}async function ns(e,t,n){let r=await ts(n,`platform-tools`,G.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 rs(e){return G.platform===`darwin`?[M.join(jr.homedir(),`Library`,`Android`,`sdk`)]:G.platform===`win32`&&e.LOCALAPPDATA?[M.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[M.join(jr.homedir(),`Android`,`Sdk`)]}async function is(e,t,n,r){return(await as(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function as(e,t,n){return(await I(e,n,{env:t,timeout:3e3})).stdout}async function os(e,t,n,r){return as(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function ss(e,t,n,r){return as(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>cs(e)||r).catch(()=>r)}function cs(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function ls(e,t){let n=e.map(e=>({device:e,score:Math.max(us(t,e.name),us(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function us(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 ds(){return[...new Set(Object.values(jr.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function fs(e,t){return e.label.localeCompare(t.label)}var ps=class{#e;#t=new Map;#n=new Set;#r;#i;#a;#o;#s=0;constructor({onEvent:e,verbose:t=!1,write:n}){this.#e=e,this.#r=t,this.#i=n}async handleLine(e){let t;try{t=JSON.parse(e)}catch{return $(e,`debug`)}if(!Array.isArray(t))return $(e,`debug`);let n=[];for(let e of t){if(!vs(e)){n.push(...$(JSON.stringify(e),`debug`));continue}if(e.id!==void 0&&(`result`in e||`error`in e)){this.#c(e);continue}if(typeof e.event!=`string`)continue;let t={event:e.event,params:vs(e.params)?e.params:{}};this.#l(t),await this.#e?.(t),n.push(...hs(t,this.#r))}return n}async restart({debounce:e=!1,fullRestart:t,reason:n}){let r=await this.#d();if(!r.supportsRestart)throw Error(`The running Flutter application does not support hot restart or reload.`);let i=await this.#u(`app.restart`,{appId:r.id,debounce:e,fullRestart:t,reason:n});if(!vs(i)||typeof i.code!=`number`)throw Error(`Flutter returned an invalid restart response.`);let a={code:i.code,message:typeof i.message==`string`?i.message:``};if(a.code!==0)throw Error(a.message||`Flutter restart failed with code ${a.code}.`);return a}async stop(){let e=await this.#d();if(await this.#u(`app.stop`,{appId:e.id})!==!0)throw Error(`Flutter did not stop the running application.`)}close(e=Error(`The Flutter machine connection closed.`)){if(this.#o)return;let t=bs(e);this.#o=t;for(let e of this.#t.values())e.reject(t);this.#t.clear(),this.#f(t)}#c(e){let t=String(e.id),n=this.#t.get(t);n&&(this.#t.delete(t),`error`in e?n.reject(Error(ys(e.error))):n.resolve(e.result))}#l({event:e,params:t}){let n=typeof t.appId==`string`?t.appId:void 0;if(e===`app.start`&&n){this.#a={id:n,started:!1,supportsRestart:t.supportsRestart===!0};return}if(e===`app.started`&&n&&this.#a?.id===n){let e={...this.#a,started:!0};this.#a=e;for(let t of this.#n)t.resolve(e);this.#n.clear();return}e===`app.stop`&&n&&this.#a?.id===n&&(this.#a=void 0,this.#f(Error(`The Flutter application stopped before it was ready.`)))}async#u(e,t){if(this.#o)throw this.#o;let n=String(++this.#s),r,i,a=new Promise((e,t)=>{r=t,i=e});this.#t.set(n,{reject:r,resolve:i});try{await this.#i(`${JSON.stringify([{id:n,method:e,params:t}])}\n`)}catch(e){this.#t.delete(n),r(bs(e))}return a}#d(){return this.#o?Promise.reject(this.#o):this.#a?.started?Promise.resolve(this.#a):new Promise((e,t)=>{this.#n.add({reject:t,resolve:e})})}#f(e){for(let t of this.#n)t.reject(e);this.#n.clear()}};async function*ms(e,t){try{for await(let n of e)yield*await t.handleLine(n)}catch(e){throw t.close(e),e}finally{t.close()}}function hs({event:e,params:t},n){if(e===`daemon.log`||e===`app.log`)return $(_s(t.log),t.error===!0?`error`:`debug`);if(e===`daemon.logMessage`){let e=gs(t.level);return!n&&e===`debug`?[]:[...$(_s(t.message),e),...n?$(_s(t.stackTrace),e):[]]}return e===`daemon.showMessage`?$(_s(t.message),gs(t.level)):e===`app.warning`?$(_s(t.warning),`warn`):e===`app.progress`&&t.finished!==!0?$(_s(t.message),`debug`):e===`app.stop`&&t.error!==void 0?$(ys(t.error),`error`):[]}function $(e,t){return e===void 0?[]:e.split(/\r?\n/u).map(e=>({level:t,message:e}))}function gs(e){return e===`error`?`error`:e===`warning`||e===`warn`?`warn`:`debug`}function _s(e){return typeof e==`string`&&e.length>0?e:void 0}function vs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ys(e){if(typeof e==`string`)return e;if(vs(e)&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function bs(e){return e instanceof Error?e:Error(ys(e))}async function xs(e,t){if(!e)return()=>void 0;Ge(M.dirname(e),{recursive:!0}),Ze(e,``,{flag:`a`});let n;try{n=q(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=Xe(e,{persistent:!1},()=>{if(i)return;let a=++r;B(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function Ss(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const Cs=G.platform===`win32`?`portless.cmd`:`portless`,ws=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),Ts=/^Proxy is already running on port (\d+)\.$/,Es=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function Ds(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(ws,``).trim().match(Ts);if(a?.[1]!==void 0&&i!==void 0&&Es.test(i.replace(ws,``).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 Os(e){let t=Ds(e);t&&G.stdout.write(t.endsWith(`
|
|
15
|
+
`)?t:`${t}\n`)}async function ks({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await qt()).isAgent?!1:Bt(e)}async function As({cwd:e,env:t,lan:n=!1}){let r=M.join(`node_modules`,`.bin`,Cs),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await I(M.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});Os(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Os(e.stdout),e}}function js({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 Ms=M.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=M.resolve(t,Ms),d=M.dirname(u),f={version:2,id:a,pid:c,projectRoot:M.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:M.resolve(t,`.leylines`,`logs.sqlite`),scopes:{browser:`browser`,...i===void 0?void 0:{flutter:`dev.flutter`},vite:`dev.vite`}},...i===void 0?void 0:{flutter:{mode:i,mcp:r,state:`starting`,...n===void 0?void 0:{device:n}}}},p=Promise.resolve(),m=()=>{let e=`${JSON.stringify(f,void 0,2)}\n`;return p=p.then(async()=>{await z(d,{recursive:!0});let t=M.join(d,`.session-${a}.json`);await H(t,e,{mode:384}),await Oe(t,384),await Ne(t,u)}),p};return await m(),{path:u,async recordFlutterEvent({event:e,params:t}){let n=f.flutter;if(!n)return;let r=Is(t.appId),i;if(e===`daemon.connected`){let e=Ls(t.pid),r=Is(t.version);i={...Ps(n),state:`starting`,...e===void 0?void 0:{daemonPid:e},...r===void 0?void 0:{protocolVersion:r}}}else if(e===`app.start`&&r)i={...Ps(n),appId:r,state:`starting`,supportsRestart:t.supportsRestart===!0};else if(e===`app.started`&&r===n.appId)i={...n,state:`running`};else if(e===`app.debugPort`&&r===n.appId){let e=Is(t.wsUri);e&&(i={...n,vmServiceWsUri:e})}else if(e===`app.devTools`&&r===n.appId){let e=Is(t.uri);e&&(i={...n,devToolsUri:e})}else if(e===`app.dtd`&&r===n.appId){let e=Is(t.uri);e&&(i={...n,dtdUri:e})}else e===`app.stop`&&r===n.appId&&(i=Fs(n));i&&(f={...f,flutter:i},await m())},async recordFlutterExit(){!f.flutter||f.flutter.state===`stopped`||(f={...f,flutter:Fs(f.flutter)},await m())},async close(){await p;try{JSON.parse(await B(u,`utf8`)).id===a&&await V(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}function Ps(e){return{mode:e.mode,mcp:e.mcp,...e.device===void 0?void 0:{device:e.device},...e.daemonPid===void 0?void 0:{daemonPid:e.daemonPid},...e.protocolVersion===void 0?void 0:{protocolVersion:e.protocolVersion}}}function Fs(e){return{...Ps(e),state:`stopped`,...e.appId===void 0?void 0:{appId:e.appId},...e.supportsRestart===void 0?void 0:{supportsRestart:e.supportsRestart}}}function Is(e){return typeof e==`string`?e:void 0}function Ls(e){return typeof e==`number`?e:void 0}const Rs=`extension:dev`;function zs(e){if(!K(P(e,`src-webext/wxt.config.ts`)))throw Error("No WXT configuration found at src-webext/wxt.config.ts. Apply the wxt recipe or add that convention before running `coreframe dev webext`.");let t=P(e,`package.json`),n;try{n=JSON.parse(q(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 Bs({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 Vs=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],Hs=[`managed-dev-overlay`],Us=M.resolve(`node_modules`,`.bin`),Ws=G.platform===`win32`?`pnpm.cmd`:`pnpm`,Gs=G.platform===`win32`?`portless.cmd`:`portless`,Ks=G.platform===`win32`?`react-router.cmd`:`react-router`,qs=`Lost connection to device.`;async function Js({cwd:e=G.cwd(),debug:t,device:n,env:r=G.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=G.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=It({env:r}),ee=r.PATH??r.Path??``,y=sc(h)?h:void 0,b=$t(i||a),x=oc(_??r.COREFRAME_WEB_PORT),S,C,w,te,ne,re,ie,ae,oe,T,se,ce,le,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.`);zs(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 de=await v.measure(`routing`,()=>ks({cwd:e,env:r,platform:h}));de&&await v.measure(`portless`,()=>As({cwd:e,env:r,lan:u}));let k=y===void 0?h===`web`?x??await Ar.getAvailablePort():h===`webext`?x:void 0:x??await Ar.getAvailablePort(),A,pe=new Promise(e=>{A=e}),j=()=>{E||(E=!0,A(),C?.kill(`SIGTERM`),re?.kill(`SIGTERM`),ie?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ae?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),oe?.close().catch(()=>void 0),S?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),he().catch(()=>void 0))},he=()=>te?(ne??=te[Symbol.asyncDispose](),ne):Promise.resolve(),N=e=>{D??=e,j()},ge=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>N(e);return G.on(e,t),{handler:t,signal:e}}),P=async e=>{let t=et(e);C=t;try{await t.expectSuccess()}catch(e){if(!E)throw e}finally{C===t&&(C=void 0)}};try{se=y?Gt({path:M.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await Ro({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&en({device:_,mode:b,platform:i});let x=y?se?.logger({scope:`dev.flutter`,properties:{platform:y,..._?{deviceId:_.id}:void 0}}):void 0;T=i&&_&&k!==void 0?await Bo({device:_,env:r,host:s,interactive:l,platform:i,port:k}):void 0;let C=T?.viteHost??(y?i?!0:`127.0.0.1`:s),ne=k===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${k}`,D=y===void 0?ne:T?.serverUrl??Vo(y,void 0,k),A={},he=!1,N;[A,he]=await Promise.all([v.measure(`config`,()=>U({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await zt(e))]),await v.measure(`i18n`,()=>er({cwd:e,projectConfig:A})),N=h!==`webext`&&Lr(e)?await Ar.getAvailablePort():void 0;let ge=await v.measure(`https`,async()=>c&&!de?Vt({cwd:e}):void 0),_e=Ss(r,h);O={..._e,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Ht]:W()}:void 0,...y?{COREFRAME_PLATFORM:y,[Wt]:M.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...ge?{[Lt]:ge.cert,[Rt]:ge.key}:void 0,...N?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${N}`}:void 0},ne!==void 0&&D!==void 0&&(ce=await Ns({appOrigin:D,cwd:e,device:_,flutterMcp:a,flutterMode:y===void 0?void 0:b,id:W(),localOrigin:ne,platform:h}));let F=async()=>{if(!N)return;let t=Rr({cwd:e,env:O,port:N});oe=t;try{await t.listen(),await t.wait()}finally{await t.close(),oe===t&&(oe=void 0)}},ve=async()=>{let t=$e({label:`web`}),n=$e({color:`red`,label:`web`});t.pipe(G.stdout,{end:!1}),n.pipe(G.stderr,{end:!1}),ie=I(de?Gs:Ks,de?js({host:C,lan:u,port:k}):ac({host:C,port:k,strictPort:h===`web`||y!==void 0}),{cwd:e,env:{...O,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[O.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:Us+M.delimiter+ee},stdin:`inherit`});let r=Promise.allSettled([tc(ie.stdout,t),tc(ie.stderr,n)]);try{await ie;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([Qe(t),Qe(n)]),ie=void 0}},ye=async()=>{let t=$e({label:`webext`}),n=$e({color:`red`,label:`webext`});t.pipe(G.stdout,{end:!1}),n.pipe(G.stderr,{end:!1}),ae=I(Ws,Bs({host:s,port:k}),{cwd:e,env:O,stdin:`inherit`});let r=Promise.allSettled([tc(ae.stdout,t),tc(ae.stderr,n)]);try{await ae;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([Qe(t),Qe(n)]),ae=void 0}},be=async t=>{let n,r,i=!1,s,c=xs(O[Wt],()=>{if(E||!n||!r||s||b!==`debug`&&i)return;let e=n,t=r;s=(async()=>{if(b===`debug`){await t.restart({debounce:!0,fullRestart:!0,reason:`manual`});return}i=!0;try{await t.stop()}catch(t){let n=t instanceof Error?t.message:String(t);x?.write(`warn`,`Flutter stop failed; terminating it: ${n}`,{properties:{stream:`control`}}),G.stderr.write(`Flutter stop failed; terminating it: ${n}\n`),await e.nodeChildProcess.then(e=>e.kill(`SIGTERM`))}})().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Flutter restart failed: ${t}`,{properties:{stream:`control`}}),G.stderr.write(`Flutter restart failed: ${t}\n`)}).finally(()=>{s=void 0})});try{for(;!E;){i=!1;let s=!1,c=h===`android`&&o===`filtered`&&!g?await me():void 0,u=I(`flutter`,tn({device:_??{id:h},flutterDriver:a,mode:b,serverUrl:D,verbose:g}),{cwd:M.join(e,`src-flutter`),env:Qt(_e,{noCodesign:f}),stdio:[`pipe`,`pipe`,`pipe`]}),d=new ps({onEvent:async e=>{Zs(e.params.message)&&(s=!0),await ce?.recordFlutterEvent(e)},verbose:g,write:async e=>{let t=await u.nodeChildProcess;if(!t.stdin)throw Error(`Flutter machine input is unavailable.`);t.stdin.write(e)===!1&&await Pt(t.stdin,`drain`)}}),p=e=>Xs(ms(e,d),()=>s=!0);S=u,n=u,r=d;try{let e=!1;try{let e=c?c.capture(ec(p(u),x,`output`)):Promise.all([$s(p(u.stdout),G.stdout,x,`stdout`),Ys(u.stderr,G.stderr,x,`stderr`)]);await Promise.all([u,e])}catch{e=!0}if(i&&!E)continue;if(E)return;let n=l?await L.confirm({initialValue:!0,message:s?`${qs} Restart Flutter?`:e?`Flutter failed. Retry?`:`Flutter exited unexpectedly. Restart Flutter?`}):!1;if(L.isCancel(n)||!n){if(!e&&!s){L.log.warn(`Flutter exited unexpectedly.`);return}L.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??pe);return}}finally{S===u&&(S=void 0),n===u&&(n=void 0),r===d&&(r=void 0),d.close(),ce?.recordFlutterExit().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Failed to record Flutter exit: ${t}`,{properties:{stream:`control`}})})}}}finally{(await c)()}},xe=async()=>{if(h===`web`){await ve();return}let t=ve().then(()=>{if(!E)throw Error(`The Vite development server stopped while Flutter was still running.`)});await fe({cwd:e});try{await Promise.race([t,be(t)])}finally{j(),await Promise.allSettled([t,S]),S=void 0}},Se=async()=>{let t=et({name:`panda`,command:Ws,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:O});re=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{re===t&&(re=void 0)}},R=async()=>{if(h===`webext`){await ye();return}let e=Se(),t=xe(),n=N?F():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),E&&await t}finally{j(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(he&&(O={...O,[Ut]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(le=await v.measure(`supervisor`,()=>Ft({cwd:e,env:r})))),E)return;if(h===`webext`){v.report(),await R();return}if(A.database?.dialect===`sqlite`&&(await v.measure(`database`,async()=>{let t=await ue({config:A,cwd:e,env:r,tursoOutput:G.stdout,useSupervisorLease:!0});te=t,O={...O,...t.env}}),await v.measure(`schema`,()=>P({name:`db`,command:Ws,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),E))return;if(ic(A)){let t=$e({label:`postgres`});t.pipe(G.stdout,{end:!1});try{let n=await v.measure(`database`,()=>rc({config:A,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`,()=>P({name:`db`,command:Ws,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),E||(v.report(),await R())}finally{await n[Symbol.asyncDispose](),w===n&&(w=void 0)}}finally{t.end()}return}v.report(),await R()}finally{j(),await T?.close(),T=void 0;let e;try{await w?.[Symbol.asyncDispose]()}catch(t){e=t}finally{try{await he()}finally{try{await ce?.close()}finally{le?.close(),se?.close();for(let{handler:e,signal:t}of ge)G.off(t,e)}}D&&(G.exitCode??=D===`SIGINT`?130:143)}nc(e)}}async function Ys(e,t,n,r){for await(let i of Qs(e,n,r))t.write(`${i}\n`)||await Pt(t,`drain`)}async function*Xs(e,t){for await(let n of e)Zs(n.message)&&t(),yield n}function Zs(e){return typeof e==`string`&&e.trim()===qs}async function*Qs(e,t,n){for await(let r of e){let e=de(r);e.message&&t?.write(e.level,e.message,{properties:{stream:n}}),yield r}}async function $s(e,t,n,r){for await(let i of ec(e,n,r))t.write(`${i}\n`)||await Pt(t,`drain`)}async function*ec(e,t,n){for await(let r of e)r.message&&t?.write(r.level,r.message,{properties:{stream:n}}),yield r.message}async function tc(e,t){for await(let n of e)t.write(`${n}\n`)||await Pt(t,`drain`)}function nc(e){if(e)throw e}async function rc({interactive:e,isStopping:t,...n}){try{return await E(n)}catch(r){if(!(r instanceof h)||!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 D(r),t()?void 0:E(n)}}function ic(e){return(e.database?.dialect??`postgres`)===`postgres`}function ac({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 oc(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 sc(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function cc(e={}){let t=e.cwd??G.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await De(M.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await ze(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 Jt({...e,cwd:t},r)}const lc=`worker-configuration.d.ts`;async function uc({check:e=!1,cwd:t=process.cwd()}={}){let n=await U({cwd:t}),r=await mt({coreframeConfig:n,cwd:t}),i=F(t,lc),a=F(t,`.coreframe-worker-types-${W()}.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 dc(e),e}let o=fc(await B(a,`utf8`)),s=Ve(r.config),c=Be(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${pc(c)}\n`;if(e){if(await B(i,`utf8`).catch(()=>``)!==l)throw Error(`${lc} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await B(i,`utf8`).catch(()=>``);return u!==l&&await H(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await V(a,{force:!0})}}function dc(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
|
|
16
|
+
`)?t:`${t}\n`)}function fc(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
|
|
17
|
+
`)}function pc(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(`
|
|
18
|
+
`)}const mc=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),hc=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],gc=[`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`],_c=[`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`],vc=`.coreframe/typegen.json`,yc=[`web`,`dashboard`,`worker`];async function bc({checkWorker:e=!1,cwd:t=G.cwd(),runners:n={}}={}){let r=await wc(t)??{generators:{},schemaVersion:1},i=[];return i.push(await Sc({cwd:t,inputPaths:hc,name:`web`,outputPath:`.react-router`,run:()=>(n.web??Cc)(t),state:r})),i.push(await Sc({cwd:t,inputPaths:gc,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??Tr)(t),state:r})),i.push(await Sc({cwd:t,inputPaths:_c,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??uc)({check:e,cwd:t}),state:r})),i}function xc(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function Sc({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await Ec(e,t),s=await Dc(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 Dc(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await Tc(e,a),{changed:s!==l,name:n,ran:!0}}async function Cc(e){let t=G.platform===`win32`?`react-router.cmd`:`react-router`,n=G.env;await I(t,[`typegen`],{cwd:e,env:{...n,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function wc(e){try{let t=JSON.parse(await B(M.resolve(e,vc),`utf8`));if(!jc(t)||t.schemaVersion!==1)return;let n={};if(!jc(t.generators))return;for(let e of yc){let r=t.generators[e];jc(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 Tc(e,t){let n=M.resolve(e,vc);await z(M.dirname(n),{recursive:!0}),await H(n,`${JSON.stringify(t)}\n`,{mode:384})}async function Ec(e,t){let n=He(`sha256`);for(let r of[...t].sort()){let t=M.resolve(e,r),i=await kc(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Oc(t)){let i=M.join(t,r),a=M.relative(e,i).split(M.sep).join(`/`);n.update(`${a}\0`),n.update(await B(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await B(t)))}return n.digest(`hex`)}async function Dc(e,t){if(await kc(M.resolve(e,t)))return Ec(e,[t])}async function Oc(e){let t=[];async function n(e,r){let i=await Me(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(mc.has(a.name))continue;await n(M.join(e,a.name),M.join(r,a.name))}else a.isFile()&&t.push(M.join(r,a.name))}return await n(e,``),t.sort()}async function kc(e){try{return await Pe(e)}catch(e){if(Ac(e))return;throw e}}function Ac(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function jc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Mc=M.resolve(`node_modules`,`.bin`);G.env.PATH=Mc+M.delimiter+G.env.PATH;const Nc=G.platform===`win32`?`tsc.cmd`:`tsc`,Pc=[{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 Fc(){await bc({checkWorker:!0});let e=[];for(let t of Pc)try{await De(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>et({name:e.name,command:Nc,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(G.exitCode=n[0].exitCode)}const Ic=r(s(Hs),{displayName:`feature`,from:async e=>e}),Lc=r(s(Zt),{displayName:`filtered|full`,from:async e=>e}),Rc=[`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.`],zc=n({name:`deploy`,args:{environment:u({type:s(ct),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:i({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:i({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:i({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>po([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),Bc=m({name:`staging`,cmds:{reassign:n({name:`reassign`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await St();if(e){console.log(JSON.stringify({...t,notices:Rc}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Rc.join(` `)}`)}}),url:n({name:`url`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ut();console.log(e?JSON.stringify({url:t}):t)}})}}),Vc=m({name:`secrets`,cmds:{"rotate-access-token":n({name:`rotate-access-token`,args:{environment:u({type:s(ct),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:i({long:`yes`,short:`y`,description:`Confirm immediate signing-secret replacement and invalidation of outstanding access JWTs.`,defaultValue:()=>!1})},handler:async({environment:e,yes:t})=>{if(!t)throw Error(`Access-token signing-secret rotation requires --yes because it immediately invalidates outstanding access JWTs.`);await Et({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:n({name:`status`,args:{environment:u({type:l(s(ct)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await dt({environment:e});console.log(t?JSON.stringify(n):qc(n))}}),set:n({name:`set`,args:{environment:u({type:s(ct),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:u({type:l(p),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:i({long:`bulk`,description:`Queue known secrets from pasted or piped dotenv-formatted contents.`,defaultValue:()=>!1})},handler:async({environment:e,name:t,bulk:n})=>{if(n&&t)throw Error(`Use either a secret name or --bulk, not both.`);if(t){await _t({environment:e,name:t,value:await Jc(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await yt(),i=n?await Xc(r):await Yc(r,e);await vt({environment:e,values:i});let a=Object.keys(i).sort();console.log(a.length>0?`Queued ${a.join(`, `)} for ${e}. Run coreframe deploy ${e} to apply.`:`No ${e} Worker secret updates were queued.`)}}),discard:n({name:`discard`,args:{environment:u({type:s(ct),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:u({type:p,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await lt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),Hc=n({name:`typecheck`,args:{},handler:Fc}),Uc=m({name:`worker`,cmds:{typegen:n({name:`typegen`,args:{check:i({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await uc({check:e});console.log(e?`${Qc(t.path)} is current.`:`${Qc(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),Wc=n({name:`dev`,args:{debug:c({long:`debug`,type:l(Ic),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:i({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:i({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:c({long:`flutter-output`,type:Lc,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:i({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:c({long:`host`,type:l(p),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:i({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:i({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:i({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:i({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:i({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:u({type:l(s(Vs)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:u({type:l(p),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:c({long:`port`,type:l(o),description:`Port for the web development server.`}),verbose:i({long:`verbose`,description:`Show the full native development output.`,defaultValue:()=>!1})},handler:({debug:e,device:t,flutterDebug:n,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f,port:p,simulator:m,verbose:h})=>{let g=Gc({device:t,flutterDebug:n,platform:f,simulator:m});return Js({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 Gc({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 Kc=n({name:`preview`,args:{host:c({long:`host`,type:l(p),description:`Host address for the preview server.`}),port:c({long:`port`,type:l(o),description:`Port for the preview server.`})},handler:({host:e,port:t})=>cc({host:e,port:t})});function qc(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(`
|
|
19
|
+
`)}async function Jc(e){if(!G.stdin.isTTY){let e=``;for await(let t of G.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 Yc(e,t){if(!G.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 Xc(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=G.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 Zc();if(L.isCancel(t))throw L.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=ht(t,e);return n.length>0&&L.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function Zc(){let e=``;for await(let t of G.stdin)e+=t.toString();return e}function Qc(e){return e.split(/[\\/]/).at(-1)??e}const $c=n({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await bc();for(let t of e)console.log(xc(t))}});function el(e,{formatMessage:t,temporaryDirectory:n=Le(),write:r=e=>console.error(e)}={}){let i=ol(e),a=ll(nl(e,t),i);try{let t=P(Ke(P(n,`coreframe-error-`)),`error.log`);return Ze(t,`${ll(rl(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 tl(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,el(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function nl(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 rl(e){try{let t=il(e);if(!(e instanceof Error)||!al(t))return Mt(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${Mt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function il(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:il(a.value,t),writable:!0})}return i}function al(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ol(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`?sl(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function sl(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&cl(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function cl(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function ll(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const ul=m({name:`coreframe`,cmds:{build:hn,dashboard:Vr,assets:br,flutter:xr,i18n:Sr,jobs:ai,deploy:zc,staging:Bc,secrets:Vc,typegen:$c,typecheck:Hc,worker:Uc,dev:Wc,preview:Kc,upgrade:co,recipes:lo,db:uo}});import.meta.main&&tl(ul,{formatMessage:process.argv[2]===`db`?w:void 0});export{ul as coreframeCli};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreframe/scripts",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.34-next.0",
|
|
4
4
|
"description": "Coreframe project workflow CLI and automation scripts",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -29,15 +29,16 @@
|
|
|
29
29
|
"nano-spawn": "^2.1.0",
|
|
30
30
|
"procband": "^0.3.9",
|
|
31
31
|
"yaml": "^2.9.0",
|
|
32
|
-
"@coreframe/
|
|
33
|
-
"@coreframe/
|
|
34
|
-
"@coreframe/
|
|
35
|
-
"@coreframe/deploy": "^0.1.
|
|
36
|
-
"@coreframe/dev": "^0.1.
|
|
37
|
-
"@coreframe/
|
|
38
|
-
"@coreframe/
|
|
39
|
-
"@coreframe/object-storage": "^0.1.
|
|
40
|
-
"@coreframe/
|
|
32
|
+
"@coreframe/assets": "^0.1.18-next.0",
|
|
33
|
+
"@coreframe/db": "^0.1.20-next.0",
|
|
34
|
+
"@coreframe/dev": "^0.1.23-next.0",
|
|
35
|
+
"@coreframe/deploy": "^0.1.15-next.0",
|
|
36
|
+
"@coreframe/dev-contracts": "^0.1.10-next.0",
|
|
37
|
+
"@coreframe/flutter-tools": "^0.1.25-next.0",
|
|
38
|
+
"@coreframe/jobs": "^0.1.2-next.0",
|
|
39
|
+
"@coreframe/object-storage": "^0.1.5-next.0",
|
|
40
|
+
"@coreframe/config": "^0.1.15-next.0",
|
|
41
|
+
"@coreframe/preview": "^0.1.20-next.0"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
44
|
"@types/node": "^26.1.0",
|