@stacksjs/buddy 0.75.515 → 0.75.518

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/app-store-connect.js +2 -2
  2. package/dist/cli.js +4 -4
  3. package/dist/cloud-tenants.js +1 -1
  4. package/dist/commands/about.js +1 -1
  5. package/dist/commands/add.js +1 -1
  6. package/dist/commands/ai-access.js +2 -2
  7. package/dist/commands/ai-context.js +2 -2
  8. package/dist/commands/auth-prune-options.js +1 -1
  9. package/dist/commands/auth.js +1 -1
  10. package/dist/commands/build.js +1 -1
  11. package/dist/commands/cd.js +3 -3
  12. package/dist/commands/changelog.js +1 -1
  13. package/dist/commands/clean.js +1 -1
  14. package/dist/commands/cloud.js +7 -7
  15. package/dist/commands/comments.js +2 -2
  16. package/dist/commands/commerce-import.js +3 -3
  17. package/dist/commands/commit.js +1 -1
  18. package/dist/commands/completion.js +7 -7
  19. package/dist/commands/config-migrate.js +5 -5
  20. package/dist/commands/configure.js +2 -2
  21. package/dist/commands/create.js +1 -1
  22. package/dist/commands/db.js +1 -1
  23. package/dist/commands/deploy-fly.js +2 -2
  24. package/dist/commands/deploy-preview.js +1 -1
  25. package/dist/commands/deploy-ssh-target.js +1 -1
  26. package/dist/commands/deploy.js +588 -19
  27. package/dist/commands/desktop-apple.js +12 -12
  28. package/dist/commands/desktop-probe.js +1 -1
  29. package/dist/commands/dev.js +4 -4
  30. package/dist/commands/dns.js +2 -2
  31. package/dist/commands/docs/agent-counts.js +2 -2
  32. package/dist/commands/docs/buddy-commands.js +11 -11
  33. package/dist/commands/docs/capabilities.js +2 -2
  34. package/dist/commands/docs/desktop-matrix.js +2 -2
  35. package/dist/commands/docs/framework-repo.js +1 -1
  36. package/dist/commands/docs/generated-artifacts.js +3 -3
  37. package/dist/commands/docs/links.js +2 -2
  38. package/dist/commands/docs/native-skills.js +2 -2
  39. package/dist/commands/docs/snippets.js +7 -7
  40. package/dist/commands/doctor.js +3 -3
  41. package/dist/commands/domains.js +2 -2
  42. package/dist/commands/email.js +26 -26
  43. package/dist/commands/env.js +1 -1
  44. package/dist/commands/extension.js +3 -3
  45. package/dist/commands/features.js +3 -3
  46. package/dist/commands/feedback.js +3 -3
  47. package/dist/commands/fresh.js +1 -1
  48. package/dist/commands/gdpr.js +6 -6
  49. package/dist/commands/generate.js +5 -5
  50. package/dist/commands/http.js +1 -1
  51. package/dist/commands/install.js +1 -1
  52. package/dist/commands/integrations-probe.js +2 -2
  53. package/dist/commands/key.js +1 -1
  54. package/dist/commands/libs.js +1 -1
  55. package/dist/commands/link.js +2 -2
  56. package/dist/commands/lint.js +2 -2
  57. package/dist/commands/list.js +2 -2
  58. package/dist/commands/mail.js +13 -13
  59. package/dist/commands/maintenance.js +1 -1
  60. package/dist/commands/make.js +1 -1
  61. package/dist/commands/migrate-project.js +1 -1
  62. package/dist/commands/migrate.js +59 -59
  63. package/dist/commands/outdated.js +1 -1
  64. package/dist/commands/package.js +1 -1
  65. package/dist/commands/phone.js +13 -13
  66. package/dist/commands/ports.js +2 -2
  67. package/dist/commands/prepublish.js +1 -1
  68. package/dist/commands/preview-deploy.js +1 -1
  69. package/dist/commands/projects.js +1 -1
  70. package/dist/commands/publish.js +8 -8
  71. package/dist/commands/queue.js +1 -1
  72. package/dist/commands/release.js +7 -7
  73. package/dist/commands/route.js +1 -1
  74. package/dist/commands/saas.js +1 -1
  75. package/dist/commands/schedule.js +1 -1
  76. package/dist/commands/search.js +1 -1
  77. package/dist/commands/security.js +2 -2
  78. package/dist/commands/seed.js +1 -1
  79. package/dist/commands/serve.js +1 -1
  80. package/dist/commands/server-image.js +2 -2
  81. package/dist/commands/server-trust.js +2 -2
  82. package/dist/commands/server.js +10 -8
  83. package/dist/commands/setup-ai.js +2 -2
  84. package/dist/commands/setup.js +5 -5
  85. package/dist/commands/share.js +1 -1
  86. package/dist/commands/simulator.js +1 -1
  87. package/dist/commands/sms.js +25 -25
  88. package/dist/commands/socials.js +3 -3
  89. package/dist/commands/stacks.js +1 -1
  90. package/dist/commands/storage-backup.js +1 -1
  91. package/dist/commands/telemetry.js +1 -1
  92. package/dist/commands/test.js +1 -1
  93. package/dist/commands/tinker.js +1 -1
  94. package/dist/commands/types.js +1 -1
  95. package/dist/commands/upgrade.js +1 -1
  96. package/dist/commands/user.js +2 -2
  97. package/dist/config.js +1 -1
  98. package/dist/custom-cli.js +1 -1
  99. package/dist/database-backup.js +2 -2
  100. package/dist/database-preflight.js +1 -1
  101. package/dist/deploy-notify.js +3 -3
  102. package/dist/deployment-inputs.js +1 -1
  103. package/dist/deployment-revision.js +4 -4
  104. package/dist/dns-credentials.js +1 -1
  105. package/dist/email-reprocess.js +1 -1
  106. package/dist/feedback-links.js +1 -1
  107. package/dist/global-options.js +1 -1
  108. package/dist/lazy-commands.js +1 -1
  109. package/dist/mail-dns-health.js +1 -1
  110. package/dist/mail-users.js +1 -1
  111. package/dist/migrators/index.js +1 -1
  112. package/dist/migrators/laravel/index.js +1 -1
  113. package/dist/migrators/laravel/migrations.js +4 -4
  114. package/dist/migrators/laravel/models.js +4 -4
  115. package/dist/native-project.js +7 -7
  116. package/dist/native-site.js +2 -2
  117. package/dist/pantry-service-ports.js +2 -2
  118. package/dist/production-server.js +1 -1
  119. package/dist/project-setup.js +1 -1
  120. package/dist/publish-stx.js +1 -1
  121. package/dist/registry.js +1 -1
  122. package/dist/release-ios.js +1 -1
  123. package/dist/result.js +1 -1
  124. package/dist/scaffold-app.js +4 -4
  125. package/dist/scaffold-desktop.js +1 -1
  126. package/dist/scaffold-package-app.js +7 -7
  127. package/dist/scaffold-site.js +1 -1
  128. package/dist/storage-backup.js +1 -1
  129. package/dist/system-dependencies.js +1 -1
  130. package/dist/unbacked-data.js +1 -1
  131. package/dist/unvendor-rewrite.js +2 -2
  132. package/dist/version-info.js +1 -1
  133. package/dist/workflow-prune.js +3 -3
  134. package/package.json +55 -55
@@ -1,6 +1,6 @@
1
- import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{resultFailed}from"../result";const REQUIRED_TOOLS=["codesign","security","productbuild","pkgutil","xcrun"];function env(name){return process.env[name]?.trim()||""}function xml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}async function nativeAppleConfig(){const{loadMacosDesktop}=await import("@stacksjs/desktop-build");return loadMacosDesktop(projectPath(),packageMetadata().version)}function packageMetadata(){const packageJson=JSON.parse(readFileSync(projectPath("package.json"),"utf8"));return{name:packageJson.name||"Stacks",version:packageJson.version||"0.1.0"}}export function resolveAppleDesktopConfig(options={},native){const metadata=packageMetadata(),provisioningProfile=options.provisioningProfile||env("APPLE_PROVISIONING_PROFILE"),apiKeyPath=options.apiKeyPath||env("APP_STORE_CONNECT_API_KEY_PATH"),craftArm64=options.craftArm64||env("CRAFT_BIN_ARM64"),craftX64=options.craftX64||env("CRAFT_BIN_X64"),keychain=options.keychain||env("APPLE_KEYCHAIN");return{appName:options.appName||env("APPLE_APP_NAME")||native?.appName||env("APP_NAME")||metadata.name,bundleId:options.bundleId||env("APPLE_BUNDLE_ID")||native?.bundleId||"",teamId:options.teamId||env("APPLE_TEAM_ID")||native?.teamId||"",version:options.appVersion||env("APPLE_APP_VERSION")||native?.version||metadata.version,buildNumber:options.buildNumber||env("APPLE_BUILD_NUMBER")||(native?native.buildNumber:"")||env("GITHUB_RUN_NUMBER")||String(Math.floor(Date.now()/1000)),minimumMacos:options.minimumMacos||env("APPLE_MINIMUM_MACOS")||native?.minimumSystemVersion||"13.0",category:options.category||env("APPLE_APP_CATEGORY")||native?.category||"public.app-category.productivity",appSigningIdentity:options.appSigningIdentity||env("APPLE_APP_SIGNING_IDENTITY"),installerSigningIdentity:options.installerSigningIdentity||env("APPLE_INSTALLER_SIGNING_IDENTITY"),provisioningProfile:provisioningProfile?resolve(provisioningProfile):"",apiKeyId:options.apiKeyId||env("APP_STORE_CONNECT_API_KEY_ID"),apiIssuerId:options.apiIssuerId||env("APP_STORE_CONNECT_API_ISSUER_ID"),apiKeyPath:apiKeyPath?resolve(apiKeyPath):"",icon:options.icon||env("APPLE_APP_ICON")||(native?.icon?resolve(projectPath(),native.icon):void 0),universal:Boolean(options.universal)||env("APPLE_UNIVERSAL")==="true",craftArm64:craftArm64?resolve(craftArm64):void 0,craftX64:craftX64?resolve(craftX64):void 0,keychain:keychain?resolve(keychain):void 0}}export function withApiKeyFile(config){const pem=env("APP_STORE_CONNECT_API_KEY").replaceAll("\\n",`
2
- `);if(config.apiKeyPath||!pem||!config.apiKeyId)return config;if(!pem.includes("-----BEGIN PRIVATE KEY-----"))throw Error("APP_STORE_CONNECT_API_KEY must hold the PEM text of the .p8 key");const directory=mkdtempSync(join(tmpdir(),"apple-api-key-")),apiKeyPath=join(directory,`AuthKey_${config.apiKeyId}.p8`);writeFileSync(apiKeyPath,`${pem}
3
- `,{mode:384});process.on("exit",()=>rmSync(directory,{recursive:!0,force:!0}));return{...config,apiKeyPath}}export function validateAppleDesktopConfig(config,includeApi=!0){const errors=[];if(process.platform!=="darwin")errors.push("Mac App Store packaging must run on macOS");if(!config.appName)errors.push("APPLE_APP_NAME or --app-name is required");if(!/^[A-Za-z0-9][A-Za-z0-9.-]+$/.test(config.bundleId))errors.push("APPLE_BUNDLE_ID must be a reverse-DNS bundle identifier");if(!/^[A-Z0-9]{10}$/.test(config.teamId))errors.push("APPLE_TEAM_ID must be the 10-character Apple Developer team ID");if(!/^\d+(?:\.\d+){0,2}$/.test(config.version))errors.push("The marketing version must contain one to three numeric components");if(!/^[A-Za-z0-9.-]+$/.test(config.buildNumber))errors.push("The build number must contain only letters, numbers, periods, and hyphens");if(config.buildNumber==="next")errors.push("--build-number next is resolved by desktop:apple:publish; give desktop:apple:package a number");if(!config.appSigningIdentity)errors.push("APPLE_APP_SIGNING_IDENTITY is required");if(!config.installerSigningIdentity)errors.push("APPLE_INSTALLER_SIGNING_IDENTITY is required");if(!config.provisioningProfile||!existsSync(config.provisioningProfile))errors.push("APPLE_PROVISIONING_PROFILE must point to an existing .provisionprofile file");if(config.icon&&!existsSync(resolve(config.icon)))errors.push(`Apple app icon does not exist: ${config.icon}`);if(!/^\d+(?:\.\d+){0,2}$/.test(config.minimumMacos))errors.push("APPLE_MINIMUM_MACOS must be a macOS version such as 13.0");if(!isAppleCategory(config.category))errors.push("APPLE_APP_CATEGORY must be an Apple LSApplicationCategoryType such as public.app-category.productivity");if(includeApi){if(!config.apiKeyId)errors.push("APP_STORE_CONNECT_API_KEY_ID is required");if(!config.apiIssuerId)errors.push("APP_STORE_CONNECT_API_ISSUER_ID is required");if(!config.apiKeyPath||!existsSync(config.apiKeyPath))errors.push("APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file, or APP_STORE_CONNECT_API_KEY hold its text")}if(config.universal){for(const[variable,path]of[["CRAFT_BIN_ARM64",config.craftArm64],["CRAFT_BIN_X64",config.craftX64]])if(!path||!existsSync(path))errors.push(`${variable} must point to a native Craft runtime for a universal build`);else if(readFileSync(path).subarray(0,2).toString()==="#!")errors.push(`${variable} points at a script, not a native Craft runtime: ${path}`)}for(const tool of config.universal?[...REQUIRED_TOOLS,"lipo"]:REQUIRED_TOOLS)if(!Bun.which(tool))errors.push(`Required Apple command is unavailable: ${tool}`);return errors}function bundleFiles(appPath){const walk=(dir,prefix)=>readdirSync(dir,{withFileTypes:!0}).flatMap((entry)=>{const relative=prefix?`${prefix}/${entry.name}`:entry.name;return entry.isDirectory()?walk(join(dir,entry.name),relative):[relative]});return walk(appPath,"")}export function isAppleCategory(value){return/^public\.app-category\.[a-z][a-z0-9-]*$/.test(value)}export function storeRejectionFindings(paths,executable="stacks-desktop"){const findings=[],has=(path)=>paths.includes(path);for(const required of["Contents/Info.plist",`Contents/MacOS/${executable}`,"Contents/embedded.provisionprofile"])if(!has(required))findings.push(`missing required bundle file: ${required}`);for(const path of paths){const base=path.split("/").pop()??"";if(base===".DS_Store"||path.startsWith("__MACOSX/")||base.startsWith("._"))findings.push(`forbidden file in the bundle: ${path}`);if(/\.(?:dylib|so|framework|app|xpc)$/.test(path)){if(!(path.startsWith("Contents/Frameworks/")||path.startsWith("Contents/MacOS/")||path.startsWith("Contents/XPCServices/")||path.startsWith("Contents/PlugIns/")))findings.push(`nested code outside a signed location: ${path}`)}if(path.startsWith("Contents/Resources/")&&/\.(?:sh|command|dylib|so)$/.test(path))findings.push(`executable content under Resources: ${path}`)}return findings}export function renderInfoPlist(config,executable="stacks-desktop"){const iconEntry=config.icon?`
1
+ import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{resultFailed}from"../result";const REQUIRED_TOOLS=["codesign","security","productbuild","pkgutil","xcrun"];function env(name){return process.env[name]?.trim()||""}function xml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}async function nativeAppleConfig(){const{loadMacosDesktop}=await import("@stacksjs/desktop-build");return loadMacosDesktop(projectPath(),packageMetadata().version)}function packageMetadata(){const packageJson=JSON.parse(readFileSync(projectPath("package.json"),"utf8"));return{name:packageJson.name||"Stacks",version:packageJson.version||"0.1.0"}}export function resolveAppleDesktopConfig(options={},native){const metadata=packageMetadata();const provisioningProfile=options.provisioningProfile||env("APPLE_PROVISIONING_PROFILE");const apiKeyPath=options.apiKeyPath||env("APP_STORE_CONNECT_API_KEY_PATH");const craftArm64=options.craftArm64||env("CRAFT_BIN_ARM64");const craftX64=options.craftX64||env("CRAFT_BIN_X64");const keychain=options.keychain||env("APPLE_KEYCHAIN");return{appName:options.appName||env("APPLE_APP_NAME")||native?.appName||env("APP_NAME")||metadata.name,bundleId:options.bundleId||env("APPLE_BUNDLE_ID")||native?.bundleId||"",teamId:options.teamId||env("APPLE_TEAM_ID")||native?.teamId||"",version:options.appVersion||env("APPLE_APP_VERSION")||native?.version||metadata.version,buildNumber:options.buildNumber||env("APPLE_BUILD_NUMBER")||(native?native.buildNumber:"")||env("GITHUB_RUN_NUMBER")||String(Math.floor(Date.now()/1000)),minimumMacos:options.minimumMacos||env("APPLE_MINIMUM_MACOS")||native?.minimumSystemVersion||"13.0",category:options.category||env("APPLE_APP_CATEGORY")||native?.category||"public.app-category.productivity",appSigningIdentity:options.appSigningIdentity||env("APPLE_APP_SIGNING_IDENTITY"),installerSigningIdentity:options.installerSigningIdentity||env("APPLE_INSTALLER_SIGNING_IDENTITY"),provisioningProfile:provisioningProfile?resolve(provisioningProfile):"",apiKeyId:options.apiKeyId||env("APP_STORE_CONNECT_API_KEY_ID"),apiIssuerId:options.apiIssuerId||env("APP_STORE_CONNECT_API_ISSUER_ID"),apiKeyPath:apiKeyPath?resolve(apiKeyPath):"",icon:options.icon||env("APPLE_APP_ICON")||(native?.icon?resolve(projectPath(),native.icon):undefined),universal:Boolean(options.universal)||env("APPLE_UNIVERSAL")==="true",craftArm64:craftArm64?resolve(craftArm64):undefined,craftX64:craftX64?resolve(craftX64):undefined,keychain:keychain?resolve(keychain):undefined}}export function withApiKeyFile(config){const pem=env("APP_STORE_CONNECT_API_KEY").replaceAll("\\n",`
2
+ `);if(config.apiKeyPath||!pem||!config.apiKeyId)return config;if(!pem.includes("-----BEGIN PRIVATE KEY-----"))throw new Error("APP_STORE_CONNECT_API_KEY must hold the PEM text of the .p8 key");const directory=mkdtempSync(join(tmpdir(),"apple-api-key-"));const apiKeyPath=join(directory,`AuthKey_${config.apiKeyId}.p8`);writeFileSync(apiKeyPath,`${pem}
3
+ `,{mode:384});process.on("exit",()=>rmSync(directory,{recursive:true,force:true}));return{...config,apiKeyPath}}export function validateAppleDesktopConfig(config,includeApi=true){const errors=[];if(process.platform!=="darwin")errors.push("Mac App Store packaging must run on macOS");if(!config.appName)errors.push("APPLE_APP_NAME or --app-name is required");if(!/^[A-Za-z0-9][A-Za-z0-9.-]+$/.test(config.bundleId))errors.push("APPLE_BUNDLE_ID must be a reverse-DNS bundle identifier");if(!/^[A-Z0-9]{10}$/.test(config.teamId))errors.push("APPLE_TEAM_ID must be the 10-character Apple Developer team ID");if(!/^\d+(?:\.\d+){0,2}$/.test(config.version))errors.push("The marketing version must contain one to three numeric components");if(!/^[A-Za-z0-9.-]+$/.test(config.buildNumber))errors.push("The build number must contain only letters, numbers, periods, and hyphens");if(config.buildNumber==="next")errors.push("--build-number next is resolved by desktop:apple:publish; give desktop:apple:package a number");if(!config.appSigningIdentity)errors.push("APPLE_APP_SIGNING_IDENTITY is required");if(!config.installerSigningIdentity)errors.push("APPLE_INSTALLER_SIGNING_IDENTITY is required");if(!config.provisioningProfile||!existsSync(config.provisioningProfile))errors.push("APPLE_PROVISIONING_PROFILE must point to an existing .provisionprofile file");if(config.icon&&!existsSync(resolve(config.icon)))errors.push(`Apple app icon does not exist: ${config.icon}`);if(!/^\d+(?:\.\d+){0,2}$/.test(config.minimumMacos))errors.push("APPLE_MINIMUM_MACOS must be a macOS version such as 13.0");if(!isAppleCategory(config.category))errors.push("APPLE_APP_CATEGORY must be an Apple LSApplicationCategoryType such as public.app-category.productivity");if(includeApi){if(!config.apiKeyId)errors.push("APP_STORE_CONNECT_API_KEY_ID is required");if(!config.apiIssuerId)errors.push("APP_STORE_CONNECT_API_ISSUER_ID is required");if(!config.apiKeyPath||!existsSync(config.apiKeyPath))errors.push("APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file, or APP_STORE_CONNECT_API_KEY hold its text")}if(config.universal){for(const[variable,path]of[["CRAFT_BIN_ARM64",config.craftArm64],["CRAFT_BIN_X64",config.craftX64]]){if(!path||!existsSync(path))errors.push(`${variable} must point to a native Craft runtime for a universal build`);else if(readFileSync(path).subarray(0,2).toString()==="#!")errors.push(`${variable} points at a script, not a native Craft runtime: ${path}`)}}for(const tool of config.universal?[...REQUIRED_TOOLS,"lipo"]:REQUIRED_TOOLS){if(!Bun.which(tool))errors.push(`Required Apple command is unavailable: ${tool}`)}return errors}function bundleFiles(appPath){const walk=(dir,prefix)=>readdirSync(dir,{withFileTypes:true}).flatMap((entry)=>{const relative=prefix?`${prefix}/${entry.name}`:entry.name;return entry.isDirectory()?walk(join(dir,entry.name),relative):[relative]});return walk(appPath,"")}export function isAppleCategory(value){return/^public\.app-category\.[a-z][a-z0-9-]*$/.test(value)}export function storeRejectionFindings(paths,executable="stacks-desktop"){const findings=[];const has=(path)=>paths.includes(path);for(const required of["Contents/Info.plist",`Contents/MacOS/${executable}`,"Contents/embedded.provisionprofile"]){if(!has(required))findings.push(`missing required bundle file: ${required}`)}for(const path of paths){const base=path.split("/").pop()??"";if(base===".DS_Store"||path.startsWith("__MACOSX/")||base.startsWith("._"))findings.push(`forbidden file in the bundle: ${path}`);if(/\.(?:dylib|so|framework|app|xpc)$/.test(path)){const allowed=path.startsWith("Contents/Frameworks/")||path.startsWith("Contents/MacOS/")||path.startsWith("Contents/XPCServices/")||path.startsWith("Contents/PlugIns/");if(!allowed)findings.push(`nested code outside a signed location: ${path}`)}if(path.startsWith("Contents/Resources/")&&/\.(?:sh|command|dylib|so)$/.test(path))findings.push(`executable content under Resources: ${path}`)}return findings}export function renderInfoPlist(config,executable="stacks-desktop"){const iconEntry=config.icon?`
4
4
  <key>CFBundleIconFile</key>
5
5
  <string>AppIcon</string>`:"";return`<?xml version="1.0" encoding="UTF-8"?>
6
6
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -96,16 +96,16 @@ jobs:
96
96
  s3-prefix: \${{ vars.RELEASE_S3_PREFIX }}
97
97
  s3-public-url: \${{ vars.RELEASE_S3_PUBLIC_URL }}
98
98
  secrets: inherit
99
- `}function command(args,cwd=projectPath(),extraEnv={}){const result=Bun.spawnSync(args,{cwd,env:{...process.env,...extraEnv},stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(result.exitCode!==0)throw Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`)}export function signingPlan(input){const sign=(entitlements,target)=>["codesign","--force","--timestamp","--options","runtime","--entitlements",entitlements,...input.keychain?["--keychain",input.keychain]:[],"--sign",input.identity,target];return[sign(input.helperEntitlements,input.helperPath),sign(input.appEntitlements,input.appPath)]}export const captureCommand=(args)=>{const result=Bun.spawnSync(args,{cwd:projectPath(),stdin:"inherit",stdout:"pipe",stderr:"inherit"});if(result.exitCode!==0)throw Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`);return result.stdout.toString()},MACH_O_ARCHITECTURE={arm64:"arm64",x64:"x86_64"};export function parseLipoArchs(output){return output.trim().split(/\s+/).filter(Boolean).sort()}export function mergeUniversalBinary(input,run=captureCommand){for(const architecture of["arm64","x64"]){const expected=MACH_O_ARCHITECTURE[architecture],found=parseLipoArchs(run(["lipo","-archs",input[architecture]]));if(found.length!==1||found[0]!==expected)throw Error(`${input.name}: the ${architecture} input ${input[architecture]} contains ${found.join(" + ")||"no architectures"}, expected only ${expected}`)}run(["lipo","-create","-output",input.output,input.arm64,input.x64]);const merged=parseLipoArchs(run(["lipo","-archs",input.output])),expected=Object.values(MACH_O_ARCHITECTURE).sort();if(merged.join(" ")!==expected.join(" "))throw Error(`${input.name}: the universal binary ${input.output} contains ${merged.join(" + ")||"no architectures"}, expected ${expected.join(" + ")}`);return merged}export function buildUniversalPayload(input,run=captureCommand){const slice=(architecture)=>join(input.directory,architecture,"stacks-desktop");for(const architecture of["arm64","x64"]){mkdirSync(join(input.directory,architecture),{recursive:!0});run(input.launcherCompileArgs(architecture,slice(architecture)))}const launcher=join(input.directory,"stacks-desktop"),runtime=join(input.directory,"craft-runtime");mergeUniversalBinary({name:"stacks-desktop",arm64:slice("arm64"),x64:slice("x64"),output:launcher},run);const architectures=mergeUniversalBinary({name:"craft-runtime",arm64:input.craft.arm64,x64:input.craft.x64,output:runtime},run);return{launcher,runtime,architectures}}export function launcherSliceCompileArgs(base,architecture){return["bun",...base,`--target=bun-darwin-${architecture}`]}export function parseDistributionIdentities(output,teamId){const named=(kinds)=>new RegExp(`"((?:${kinds}): [^"]+ \\(${teamId}\\))"`).exec(output)?.[1];return{app:named("Apple Distribution|3rd Party Mac Developer Application"),installer:named("3rd Party Mac Developer Installer|Mac Installer Distribution")}}export function withKeychainIdentities(config,read=readIdentities){if(config.appSigningIdentity&&config.installerSigningIdentity||!config.teamId)return config;const found=parseDistributionIdentities(read(config.keychain),config.teamId);return{...config,appSigningIdentity:config.appSigningIdentity||found.app||"",installerSigningIdentity:config.installerSigningIdentity||found.installer||""}}function readIdentities(keychain){const result=Bun.spawnSync(["security","find-identity","-v",...keychain?[keychain]:[]],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0?result.stdout.toString():""}async function appStoreClient(config){if(!config.apiKeyId||!config.apiIssuerId||!config.apiKeyPath||!existsSync(config.apiKeyPath))throw Error("App Store Connect API key ID, issuer ID, and .p8 key (APP_STORE_CONNECT_API_KEY or APP_STORE_CONNECT_API_KEY_PATH) are required");const{AppStoreConnectClient}=await import("ts-pantry");return new AppStoreConnectClient({keyId:config.apiKeyId,issuerId:config.apiIssuerId,keyPath:config.apiKeyPath})}async function appStoreAppId(client,bundleId){const app=await client.findApp(bundleId);if(!app)throw Error(`App Store Connect has no app for ${bundleId}. Create it under Apps first.`);return app.id}async function withDownloadedProfile(config){if(config.provisioningProfile||!config.bundleId)return config;const client=await appStoreClient(config),bundle=await client.findBundleId(config.bundleId);if(!bundle)throw Error(`No Apple bundle id ${config.bundleId}. Run buddy desktop:apple:provision --apply first.`);const profile=(await client.listProfiles(bundle.id)).filter((item)=>item.attributes.profileState==="ACTIVE"&&item.attributes.profileContent).sort((a,b)=>String(b.attributes.expirationDate).localeCompare(String(a.attributes.expirationDate)))[0];if(!profile)throw Error(`No active Mac App Store profile for ${config.bundleId}. Run buddy desktop:apple:provision --apply first.`);const directory=storagePath("framework/desktop-dist/apple");mkdirSync(directory,{recursive:!0});const provisioningProfile=join(directory,`${config.bundleId}.provisionprofile`);writeFileSync(provisioningProfile,Buffer.from(String(profile.attributes.profileContent),"base64"),{mode:420});log.info(`Using the Mac App Store profile "${profile.attributes.name}" from App Store Connect`);return{...config,provisioningProfile}}async function withNextBuildNumber(config){if(config.buildNumber!=="next")return config;const client=await appStoreClient(config),{nextBuildNumber}=await import("ts-pantry"),buildNumber=await nextBuildNumber(client,await appStoreAppId(client,config.bundleId));log.info(`Building ${config.version} (${buildNumber})`);return{...config,buildNumber}}async function releaseConfig(options,native){const config=withKeychainIdentities(withApiKeyFile(resolveAppleDesktopConfig(options,native)));return await withNextBuildNumber(await withDownloadedProfile(config))}async function distributeToTestFlight(config,groups,whatsNew){const client=await appStoreClient(config),{distributeTestFlightBuild}=await import("ts-pantry");log.info(`Waiting for App Store Connect to process ${config.version} (${config.buildNumber})...`);const result=await distributeTestFlightBuild(client,{appId:await appStoreAppId(client,config.bundleId),version:config.version,buildNumber:config.buildNumber,groups,whatsNew});log.success(`${config.version} (${config.buildNumber}) is on TestFlight for ${result.groups.map((group)=>group.name).join(", ")}`)}function commitsSinceLastTag(){const run=(args)=>Bun.spawnSync(args,{cwd:projectPath(),stdout:"pipe",stderr:"pipe"}),tag=run(["git","describe","--tags","--abbrev=0"]),range=tag.exitCode===0?[`${tag.stdout.toString().trim()}..HEAD`]:[];return run(["git","log","--no-merges","--format=- %s","-20",...range]).stdout.toString().trim().slice(0,4000)}function signingIdentityExists(identity,keychain){if(!identity)return!1;const result=Bun.spawnSync(["security","find-identity","-v",...keychain?[keychain]:[]],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0&&result.stdout.toString().includes(identity)}function provisioningProfileMatches(config){if(!config.provisioningProfile||!existsSync(config.provisioningProfile))return!1;const result=Bun.spawnSync(["security","cms","-D","-i",config.provisioningProfile],{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)return!1;const profile=result.stdout.toString();return profile.includes(config.bundleId)&&profile.includes(config.teamId)}async function buildDesktop(){const{runAction}=await import("@stacksjs/actions"),{Action}=await import("@stacksjs/enums"),result=await runAction(Action.BuildDesktop);if(resultFailed(result))throw result.error}function sha256(path){return createHash("sha256").update(readFileSync(path)).digest("hex")}async function packageAppleDesktop(config,skipBuild=!1,native=null){const errors=validateAppleDesktopConfig(config,!1);if(config.keychain&&!existsSync(config.keychain))errors.push(`APPLE_KEYCHAIN does not exist: ${config.keychain}`);const where=config.keychain?` in ${config.keychain}`:"";if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed${where}: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed${where}: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(native&&config.universal)errors.push("--universal is not supported for a native macOS app yet: the AppKit host is built for this machine's architecture");if(errors.length)throw Error(errors.join(`
100
- `));if(native)return packageNativeApple(config,native);if(!skipBuild)await buildDesktop();const desktopDist=storagePath("framework/desktop-dist");let launcher=join(desktopDist,"stacks-desktop"),runtime=join(desktopDist,"craft-runtime");const manifest=join(desktopDist,"desktop.json");for(const path of[launcher,runtime,manifest])if(!existsSync(path))throw Error(`Desktop build artifact is missing: ${path}`);let architectures=[process.arch==="x64"?"x86_64":process.arch],craftSlices;if(config.universal){const universalDir=join(desktopDist,"universal");if(existsSync(universalDir))rmSync(universalDir,{recursive:!0});const{desktopLauncherCompileArgs,resolveDesktopLauncher}=await import("@stacksjs/desktop-build"),entry=resolveDesktopLauncher(projectPath()),minify=process.env.DESKTOP_MINIFY!=="false",payload=buildUniversalPayload({directory:universalDir,launcherCompileArgs:(architecture,outfile)=>launcherSliceCompileArgs(desktopLauncherCompileArgs({entry,outfile,minify}),architecture),craft:{arm64:config.craftArm64,x64:config.craftX64}});launcher=payload.launcher;runtime=payload.runtime;architectures=payload.architectures;craftSlices={arm64:config.craftArm64,x64:config.craftX64}}const appleDir=join(desktopDist,"apple"),appPath=join(appleDir,`${config.appName}.app`),contents=join(appPath,"Contents"),macosDir=join(contents,"MacOS"),resourcesDir=join(contents,"Resources");if(existsSync(appleDir))rmSync(appleDir,{recursive:!0});mkdirSync(macosDir,{recursive:!0});mkdirSync(resourcesDir,{recursive:!0});copyFileSync(launcher,join(macosDir,"stacks-desktop"));copyFileSync(runtime,join(macosDir,"craft-runtime"));if(config.universal){const parsed=JSON.parse(readFileSync(manifest,"utf8"));writeFileSync(join(resourcesDir,"desktop.json"),`${JSON.stringify({...parsed,architecture:"universal"},null,2)}
101
- `)}else copyFileSync(manifest,join(resourcesDir,"desktop.json"));copyFileSync(config.provisioningProfile,join(contents,"embedded.provisionprofile"));chmodSync(join(contents,"embedded.provisionprofile"),420);chmodSync(join(macosDir,"stacks-desktop"),493);chmodSync(join(macosDir,"craft-runtime"),493);if(config.icon)copyFileSync(resolve(config.icon),join(resourcesDir,"AppIcon.icns"));const infoPlist=join(contents,"Info.plist"),appEntitlements=join(appleDir,"app.entitlements"),helperEntitlements=join(appleDir,"helper.entitlements");writeFileSync(infoPlist,renderInfoPlist(config));writeFileSync(appEntitlements,renderAppEntitlements(config));writeFileSync(helperEntitlements,renderHelperEntitlements());command(["plutil","-lint",infoPlist,appEntitlements,helperEntitlements]);for(const args of signingPlan({identity:config.appSigningIdentity,appPath,helperPath:join(macosDir,"craft-runtime"),appEntitlements,helperEntitlements,keychain:config.keychain}))command(args);command(["codesign","--verify","--deep","--strict","--verbose=2",appPath]);command(["codesign","-d","--entitlements","-","--xml",appPath]);const findings=storeRejectionFindings(bundleFiles(appPath));if(findings.length>0)throw Error(`The app bundle would be rejected by App Review:
99
+ `}function command(args,cwd=projectPath(),extraEnv={}){const result=Bun.spawnSync(args,{cwd,env:{...process.env,...extraEnv},stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(result.exitCode!==0)throw new Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`)}export function signingPlan(input){const sign=(entitlements,target)=>["codesign","--force","--timestamp","--options","runtime","--entitlements",entitlements,...input.keychain?["--keychain",input.keychain]:[],"--sign",input.identity,target];return[sign(input.helperEntitlements,input.helperPath),sign(input.appEntitlements,input.appPath)]}export const captureCommand=(args)=>{const result=Bun.spawnSync(args,{cwd:projectPath(),stdin:"inherit",stdout:"pipe",stderr:"inherit"});if(result.exitCode!==0)throw new Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`);return result.stdout.toString()};export const MACH_O_ARCHITECTURE={arm64:"arm64",x64:"x86_64"};export function parseLipoArchs(output){return output.trim().split(/\s+/).filter(Boolean).sort()}export function mergeUniversalBinary(input,run=captureCommand){for(const architecture of["arm64","x64"]){const expected=MACH_O_ARCHITECTURE[architecture];const found=parseLipoArchs(run(["lipo","-archs",input[architecture]]));if(found.length!==1||found[0]!==expected){throw new Error(`${input.name}: the ${architecture} input ${input[architecture]} contains ${found.join(" + ")||"no architectures"}, expected only ${expected}`)}}run(["lipo","-create","-output",input.output,input.arm64,input.x64]);const merged=parseLipoArchs(run(["lipo","-archs",input.output]));const expected=Object.values(MACH_O_ARCHITECTURE).sort();if(merged.join(" ")!==expected.join(" "))throw new Error(`${input.name}: the universal binary ${input.output} contains ${merged.join(" + ")||"no architectures"}, expected ${expected.join(" + ")}`);return merged}export function buildUniversalPayload(input,run=captureCommand){const slice=(architecture)=>join(input.directory,architecture,"stacks-desktop");for(const architecture of["arm64","x64"]){mkdirSync(join(input.directory,architecture),{recursive:true});run(input.launcherCompileArgs(architecture,slice(architecture)))}const launcher=join(input.directory,"stacks-desktop");const runtime=join(input.directory,"craft-runtime");mergeUniversalBinary({name:"stacks-desktop",arm64:slice("arm64"),x64:slice("x64"),output:launcher},run);const architectures=mergeUniversalBinary({name:"craft-runtime",arm64:input.craft.arm64,x64:input.craft.x64,output:runtime},run);return{launcher,runtime,architectures}}export function launcherSliceCompileArgs(base,architecture){return["bun",...base,`--target=bun-darwin-${architecture}`]}export function parseDistributionIdentities(output,teamId){const named=(kinds)=>new RegExp(`"((?:${kinds}): [^"]+ \\(${teamId}\\))"`).exec(output)?.[1];return{app:named("Apple Distribution|3rd Party Mac Developer Application"),installer:named("3rd Party Mac Developer Installer|Mac Installer Distribution")}}export function withKeychainIdentities(config,read=readIdentities){if(config.appSigningIdentity&&config.installerSigningIdentity||!config.teamId)return config;const found=parseDistributionIdentities(read(config.keychain),config.teamId);return{...config,appSigningIdentity:config.appSigningIdentity||found.app||"",installerSigningIdentity:config.installerSigningIdentity||found.installer||""}}function readIdentities(keychain){const result=Bun.spawnSync(["security","find-identity","-v",...keychain?[keychain]:[]],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0?result.stdout.toString():""}async function appStoreClient(config){if(!config.apiKeyId||!config.apiIssuerId||!config.apiKeyPath||!existsSync(config.apiKeyPath))throw new Error("App Store Connect API key ID, issuer ID, and .p8 key (APP_STORE_CONNECT_API_KEY or APP_STORE_CONNECT_API_KEY_PATH) are required");const{AppStoreConnectClient}=await import("ts-pantry");return new AppStoreConnectClient({keyId:config.apiKeyId,issuerId:config.apiIssuerId,keyPath:config.apiKeyPath})}async function appStoreAppId(client,bundleId){const app=await client.findApp(bundleId);if(!app)throw new Error(`App Store Connect has no app for ${bundleId}. Create it under Apps first.`);return app.id}async function withDownloadedProfile(config){if(config.provisioningProfile||!config.bundleId)return config;const client=await appStoreClient(config);const bundle=await client.findBundleId(config.bundleId);if(!bundle)throw new Error(`No Apple bundle id ${config.bundleId}. Run buddy desktop:apple:provision --apply first.`);const profile=(await client.listProfiles(bundle.id)).filter((item)=>item.attributes.profileState==="ACTIVE"&&item.attributes.profileContent).sort((a,b)=>String(b.attributes.expirationDate).localeCompare(String(a.attributes.expirationDate)))[0];if(!profile)throw new Error(`No active Mac App Store profile for ${config.bundleId}. Run buddy desktop:apple:provision --apply first.`);const directory=storagePath("framework/desktop-dist/apple");mkdirSync(directory,{recursive:true});const provisioningProfile=join(directory,`${config.bundleId}.provisionprofile`);writeFileSync(provisioningProfile,Buffer.from(String(profile.attributes.profileContent),"base64"),{mode:420});log.info(`Using the Mac App Store profile "${profile.attributes.name}" from App Store Connect`);return{...config,provisioningProfile}}async function withNextBuildNumber(config){if(config.buildNumber!=="next")return config;const client=await appStoreClient(config);const{nextBuildNumber}=await import("ts-pantry");const buildNumber=await nextBuildNumber(client,await appStoreAppId(client,config.bundleId));log.info(`Building ${config.version} (${buildNumber})`);return{...config,buildNumber}}async function releaseConfig(options,native){const config=withKeychainIdentities(withApiKeyFile(resolveAppleDesktopConfig(options,native)));return await withNextBuildNumber(await withDownloadedProfile(config))}async function distributeToTestFlight(config,groups,whatsNew){const client=await appStoreClient(config);const{distributeTestFlightBuild}=await import("ts-pantry");log.info(`Waiting for App Store Connect to process ${config.version} (${config.buildNumber})...`);const result=await distributeTestFlightBuild(client,{appId:await appStoreAppId(client,config.bundleId),version:config.version,buildNumber:config.buildNumber,groups,whatsNew});log.success(`${config.version} (${config.buildNumber}) is on TestFlight for ${result.groups.map((group)=>group.name).join(", ")}`)}function commitsSinceLastTag(){const run=(args)=>Bun.spawnSync(args,{cwd:projectPath(),stdout:"pipe",stderr:"pipe"});const tag=run(["git","describe","--tags","--abbrev=0"]);const range=tag.exitCode===0?[`${tag.stdout.toString().trim()}..HEAD`]:[];return run(["git","log","--no-merges","--format=- %s","-20",...range]).stdout.toString().trim().slice(0,4000)}function signingIdentityExists(identity,keychain){if(!identity)return false;const result=Bun.spawnSync(["security","find-identity","-v",...keychain?[keychain]:[]],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0&&result.stdout.toString().includes(identity)}function provisioningProfileMatches(config){if(!config.provisioningProfile||!existsSync(config.provisioningProfile))return false;const result=Bun.spawnSync(["security","cms","-D","-i",config.provisioningProfile],{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)return false;const profile=result.stdout.toString();return profile.includes(config.bundleId)&&profile.includes(config.teamId)}async function buildDesktop(){const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktop);if(resultFailed(result))throw result.error}function sha256(path){return createHash("sha256").update(readFileSync(path)).digest("hex")}async function packageAppleDesktop(config,skipBuild=false,native=null){const errors=validateAppleDesktopConfig(config,false);if(config.keychain&&!existsSync(config.keychain))errors.push(`APPLE_KEYCHAIN does not exist: ${config.keychain}`);const where=config.keychain?` in ${config.keychain}`:"";if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed${where}: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed${where}: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(native&&config.universal)errors.push("--universal is not supported for a native macOS app yet: the AppKit host is built for this machine's architecture");if(errors.length)throw new Error(errors.join(`
100
+ `));if(native)return packageNativeApple(config,native);if(!skipBuild)await buildDesktop();const desktopDist=storagePath("framework/desktop-dist");let launcher=join(desktopDist,"stacks-desktop");let runtime=join(desktopDist,"craft-runtime");const manifest=join(desktopDist,"desktop.json");for(const path of[launcher,runtime,manifest]){if(!existsSync(path))throw new Error(`Desktop build artifact is missing: ${path}`)}let architectures=[process.arch==="x64"?"x86_64":process.arch];let craftSlices;if(config.universal){const universalDir=join(desktopDist,"universal");if(existsSync(universalDir))rmSync(universalDir,{recursive:true});const{desktopLauncherCompileArgs,resolveDesktopLauncher}=await import("@stacksjs/desktop-build");const entry=resolveDesktopLauncher(projectPath());const minify=process.env.DESKTOP_MINIFY!=="false";const payload=buildUniversalPayload({directory:universalDir,launcherCompileArgs:(architecture,outfile)=>launcherSliceCompileArgs(desktopLauncherCompileArgs({entry,outfile,minify}),architecture),craft:{arm64:config.craftArm64,x64:config.craftX64}});launcher=payload.launcher;runtime=payload.runtime;architectures=payload.architectures;craftSlices={arm64:config.craftArm64,x64:config.craftX64}}const appleDir=join(desktopDist,"apple");const appPath=join(appleDir,`${config.appName}.app`);const contents=join(appPath,"Contents");const macosDir=join(contents,"MacOS");const resourcesDir=join(contents,"Resources");if(existsSync(appleDir))rmSync(appleDir,{recursive:true});mkdirSync(macosDir,{recursive:true});mkdirSync(resourcesDir,{recursive:true});copyFileSync(launcher,join(macosDir,"stacks-desktop"));copyFileSync(runtime,join(macosDir,"craft-runtime"));if(config.universal){const parsed=JSON.parse(readFileSync(manifest,"utf8"));writeFileSync(join(resourcesDir,"desktop.json"),`${JSON.stringify({...parsed,architecture:"universal"},null,2)}
101
+ `)}else{copyFileSync(manifest,join(resourcesDir,"desktop.json"))}copyFileSync(config.provisioningProfile,join(contents,"embedded.provisionprofile"));chmodSync(join(contents,"embedded.provisionprofile"),420);chmodSync(join(macosDir,"stacks-desktop"),493);chmodSync(join(macosDir,"craft-runtime"),493);if(config.icon)copyFileSync(resolve(config.icon),join(resourcesDir,"AppIcon.icns"));const infoPlist=join(contents,"Info.plist");const appEntitlements=join(appleDir,"app.entitlements");const helperEntitlements=join(appleDir,"helper.entitlements");writeFileSync(infoPlist,renderInfoPlist(config));writeFileSync(appEntitlements,renderAppEntitlements(config));writeFileSync(helperEntitlements,renderHelperEntitlements());command(["plutil","-lint",infoPlist,appEntitlements,helperEntitlements]);for(const args of signingPlan({identity:config.appSigningIdentity,appPath,helperPath:join(macosDir,"craft-runtime"),appEntitlements,helperEntitlements,keychain:config.keychain}))command(args);command(["codesign","--verify","--deep","--strict","--verbose=2",appPath]);command(["codesign","-d","--entitlements","-","--xml",appPath]);const findings=storeRejectionFindings(bundleFiles(appPath));if(findings.length>0){throw new Error(`The app bundle would be rejected by App Review:
102
102
  ${findings.map((finding)=>` - ${finding}`).join(`
103
- `)}`);return finishPackage(config,appPath,appleDir,{architectures,craft:{sha256:sha256(join(macosDir,"craft-runtime")),...craftSlices&&{slices:{arm64:sha256(craftSlices.arm64),x64:sha256(craftSlices.x64)}}}})}async function packageNativeApple(config,native){const{prepareMacosAgent,prepareMacosNative}=await import("@stacksjs/actions"),{assembleMacosApp}=await import("@stacksjs/desktop-build"),store={...native,appName:config.appName,executable:config.appName,bundleId:config.bundleId,teamId:config.teamId,version:config.version,buildNumber:config.buildNumber,minimumSystemVersion:config.minimumMacos,category:config.category,...config.icon?{icon:config.icon}:{},sandbox:!0},prepared=await prepareMacosNative(store),agent=store.agent?await prepareMacosAgent(store,prepared,"app-store"):void 0,appleDir=join(storagePath("framework/desktop/macos"),"apple");if(existsSync(appleDir))rmSync(appleDir,{recursive:!0});mkdirSync(appleDir,{recursive:!0});const assembled=assembleMacosApp({config:store,root:projectPath(),host:prepared.host,nativeBundle:prepared.nativeBundle,output:appleDir,distribution:"app-store",provisioningProfile:config.provisioningProfile,signingIdentity:config.appSigningIdentity,keychain:config.keychain,agent});for(const note of assembled.notes)await log.warn(note);command(["codesign","-d","--entitlements","-","--xml",assembled.appPath]);const findings=storeRejectionFindings(bundleFiles(assembled.appPath),store.executable);if(findings.length>0)throw Error(`The app bundle would be rejected by App Review:
103
+ `)}`)}return finishPackage(config,appPath,appleDir,{architectures,craft:{sha256:sha256(join(macosDir,"craft-runtime")),...craftSlices&&{slices:{arm64:sha256(craftSlices.arm64),x64:sha256(craftSlices.x64)}}}})}async function packageNativeApple(config,native){const{prepareMacosAgent,prepareMacosNative}=await import("@stacksjs/actions");const{assembleMacosApp}=await import("@stacksjs/desktop-build");const store={...native,appName:config.appName,executable:config.appName,bundleId:config.bundleId,teamId:config.teamId,version:config.version,buildNumber:config.buildNumber,minimumSystemVersion:config.minimumMacos,category:config.category,...config.icon?{icon:config.icon}:{},sandbox:true};const prepared=await prepareMacosNative(store);const agent=store.agent?await prepareMacosAgent(store,prepared,"app-store"):undefined;const appleDir=join(storagePath("framework/desktop/macos"),"apple");if(existsSync(appleDir))rmSync(appleDir,{recursive:true});mkdirSync(appleDir,{recursive:true});const assembled=assembleMacosApp({config:store,root:projectPath(),host:prepared.host,nativeBundle:prepared.nativeBundle,output:appleDir,distribution:"app-store",provisioningProfile:config.provisioningProfile,signingIdentity:config.appSigningIdentity,keychain:config.keychain,agent});for(const note of assembled.notes)await log.warn(note);command(["codesign","-d","--entitlements","-","--xml",assembled.appPath]);const findings=storeRejectionFindings(bundleFiles(assembled.appPath),store.executable);if(findings.length>0)throw new Error(`The app bundle would be rejected by App Review:
104
104
  ${findings.map((finding)=>` - ${finding}`).join(`
105
105
  `)}`);return finishPackage(config,assembled.appPath,appleDir,{architectures:[process.arch==="x64"?"x86_64":process.arch],craft:{kind:"native-appkit",hostKey:prepared.hostKey,sha256:sha256(prepared.host)}})}function finishPackage(config,appPath,appleDir,provenance){const packagePath=join(appleDir,`${config.appName}-${config.version}-${config.buildNumber}.pkg`);command(["productbuild","--component",appPath,"/Applications",...config.keychain?["--keychain",config.keychain]:[],"--sign",config.installerSigningIdentity,packagePath]);command(["pkgutil","--check-signature",packagePath]);const packageHash=sha256(packagePath);writeFileSync(join(appleDir,"checksums.sha256"),`${packageHash} ${basename(packagePath)}
106
106
  `);writeFileSync(join(appleDir,"apple-provenance.json"),`${JSON.stringify({schemaVersion:"1.0.0",appName:config.appName,bundleId:config.bundleId,teamId:config.teamId,version:config.version,buildNumber:config.buildNumber,minimumMacos:config.minimumMacos,architectures:provenance.architectures,package:{name:basename(packagePath),sha256:packageHash},sourceRevision:Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:projectPath()}).stdout.toString().trim(),craft:provenance.craft},null,2)}
107
- `);return packagePath}function validateOrUpload(packagePath,config,validateOnly){const errors=validateAppleDesktopConfig(config,!0);if(errors.length)throw Error(errors.join(`
108
- `));const common=["--type","macos","--file",packagePath,"--apiKey",config.apiKeyId,"--apiIssuer",config.apiIssuerId],env={API_PRIVATE_KEYS_DIR:resolve(config.apiKeyPath,"..")};command(["xcrun","altool","--validate-app",...common],projectPath(),env);if(!validateOnly)command(["xcrun","altool","--upload-app",...common],projectPath(),env)}export function renderFailure(error){return`${error instanceof Error?error.message:String(error)}
109
- `}function fail(error){process.stderr.write(renderFailure(error));process.exit(1)}export function desktopApple(buddy){buddy.command("desktop:apple:csr","Generate local private keys and CSRs for Mac App Store distribution certificates").option("--common-name <name>","Certificate request common name").option("--output <path>","Directory for private keys and certificate requests").action(async(options)=>{try{const metadata=packageMetadata(),outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning")),{generateMacCertificateRequests}=await import("ts-pantry");generateMacCertificateRequests({outputDirectory,commonName:options.commonName||metadata.name});log.success(`Generated Apple certificate requests and private keys in ${outputDirectory}`)}catch(error){fail(error)}});buddy.command("desktop:apple:provision","Plan or reconcile Apple Bundle ID, capabilities, certificates, and profile").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--capabilities <types>","Comma-separated Apple capability types").option("--app-certificate-csr <path>","CSR for a missing Mac App Distribution certificate").option("--installer-certificate-csr <path>","CSR for a missing Mac Installer Distribution certificate").option("--profile-name <name>","Provisioning profile name").option("--output <path>","Directory for the plan and downloaded Apple assets").option("--plan","Report the idempotent Apple resource diff without mutating it").option("--apply","Apply the Apple resource diff without revoking existing certificates").action(async(options)=>{try{if(options.plan&&options.apply)throw Error("Choose either --plan or --apply");const config=withApiKeyFile(resolveAppleDesktopConfig(options,await nativeAppleConfig()));if(!config.bundleId)throw Error("APPLE_BUNDLE_ID or --bundle-id is required");if(!config.apiKeyId||!config.apiIssuerId||!config.apiKeyPath||!existsSync(config.apiKeyPath))throw Error("App Store Connect API key ID, issuer ID, and existing .p8 key path are required");const readCsr=(file)=>{if(!file)return;const resolved=resolve(file);if(!existsSync(resolved))throw Error(`Apple certificate CSR does not exist: ${resolved}`);return readFileSync(resolved,"utf8")},{exportAppleCertificateP12,provisionMacApp}=await import("ts-pantry"),result=await provisionMacApp({identifier:config.bundleId,name:config.appName,capabilities:options.capabilities?.split(",").map((value)=>value.trim()).filter(Boolean),appCertificateCsr:readCsr(options.appCertificateCsr),installerCertificateCsr:readCsr(options.installerCertificateCsr),profileName:options.profileName,keyId:config.apiKeyId,issuerId:config.apiIssuerId,keyPath:config.apiKeyPath,checkOnly:!options.apply}),outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning"));mkdirSync(outputDirectory,{recursive:!0});for(const certificate of result.certificates){if(!certificate.certificateContent)continue;const fileName=certificate.type==="MAC_APP_DISTRIBUTION"?"mac-app-distribution.cer":"mac-installer-distribution.cer";writeFileSync(join(outputDirectory,fileName),Buffer.from(certificate.certificateContent,"base64"),{mode:384})}if(result.profile.profileContent)writeFileSync(join(outputDirectory,"mac-app-store.provisionprofile"),Buffer.from(result.profile.profileContent,"base64"),{mode:384});const certificatePassword=env("APPLE_CERTIFICATE_PASSWORD"),certificateExports=[{type:"MAC_APP_DISTRIBUTION",csr:options.appCertificateCsr,certificate:"mac-app-distribution.cer",output:"mac-app-distribution.p12",name:`${config.appName} Mac App Distribution`},{type:"MAC_INSTALLER_DISTRIBUTION",csr:options.installerCertificateCsr,certificate:"mac-installer-distribution.cer",output:"mac-installer-distribution.p12",name:`${config.appName} Mac Installer Distribution`}];for(const certificateExport of certificateExports){if(!result.certificates.find((item)=>item.type===certificateExport.type)?.certificateContent||!certificateExport.csr||!certificatePassword)continue;exportAppleCertificateP12({certificatePath:join(outputDirectory,certificateExport.certificate),privateKeyPath:resolve(certificateExport.csr.replace(/\.csr$/i,".key")),outputPath:join(outputDirectory,certificateExport.output),password:certificatePassword,name:certificateExport.name})}const certificates=result.certificates.map((item)=>{const certificate={...item};delete certificate.certificateContent;return certificate}),profile={...result.profile};delete profile.profileContent;const report={...result,certificates,profile},reportPath=join(outputDirectory,"provisioning-plan.json");writeFileSync(reportPath,`${JSON.stringify(report,null,2)}
110
- `,{mode:384});log.success(`${options.apply?"Applied":"Planned"} Apple provisioning: ${reportPath}`);if(!result.appRecord.exists&&result.appRecord.manualAction)log.warn(result.appRecord.manualAction)}catch(error){fail(error)}});buddy.command("desktop:apple:doctor","Validate Mac App Store tooling, credentials, certificates, and project metadata").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--keychain <path>","Look for the signing identities in this keychain file only (or APPLE_KEYCHAIN)").action(async(options)=>{try{const config=withApiKeyFile(resolveAppleDesktopConfig(options,await nativeAppleConfig())),errors=validateAppleDesktopConfig(config,!0);if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(errors.length)throw Error(errors.join(`
111
- `));log.success(`Mac App Store prerequisites are ready for ${config.bundleId}`)}catch(error){fail(error)}});buddy.command("desktop:apple:init","Create a GitHub Actions caller for the reusable Stacks Mac App Store workflow").option("--force","Replace an existing workflow").action((options)=>{try{const workflowPath=projectPath(".github/workflows/apple-app-store.yml");if(existsSync(workflowPath)&&!options.force)throw Error(`${workflowPath} already exists. Use --force to replace it.`);mkdirSync(resolve(workflowPath,".."),{recursive:!0});writeFileSync(workflowPath,renderAppleWorkflowCaller());log.success(`Created ${workflowPath}`)}catch(error){fail(error)}});const addSharedOptions=(commandBuilder)=>commandBuilder.option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-version <version>","Marketing version").option("--build-number <number>",'Unique App Store build number, or "next" for one past the highest on App Store Connect (publish only)').option("--minimum-macos <version>","Minimum supported macOS version").option("--category <category>","LSApplicationCategoryType value").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--icon <path>","Optional .icns app icon").option("--skip-build","Package existing storage/framework/desktop-dist artifacts").option("--universal","Ship one arm64 + x86_64 binary, merged with lipo").option("--craft-arm64 <path>","Thin arm64 Craft runtime for --universal (or CRAFT_BIN_ARM64)").option("--craft-x64 <path>","Thin x86_64 Craft runtime for --universal (or CRAFT_BIN_X64)").option("--keychain <path>","Sign with identities from this keychain file only (or APPLE_KEYCHAIN)");addSharedOptions(buddy.command("desktop:apple:package","Build, sandbox, sign, and package a Mac App Store desktop app")).action(async(options)=>{try{const native=await nativeAppleConfig(),packagePath=await packageAppleDesktop(withKeychainIdentities(resolveAppleDesktopConfig(options,native)),Boolean(options.skipBuild),native);log.success(`Created signed Mac App Store package ${packagePath}`)}catch(error){fail(error)}});addSharedOptions(buddy.command("desktop:apple:publish","Build and validate or upload a signed Mac App Store package")).option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--validate-only","Validate with App Store Connect without uploading").option("--package-only","Create the signed package without contacting App Store Connect").option("--testflight <groups>","After the upload, wait for processing and give the build to these comma-separated TestFlight groups").option("--whats-new <text>",'TestFlight "What to Test" (default: the commit subjects since the last tag)').action(async(options)=>{try{const groups=options.testflight?.split(",").map((name)=>name.trim()).filter(Boolean)??[];if(groups.length&&(options.validateOnly||options.packageOnly))throw Error("--testflight needs an upload, so it cannot be combined with --validate-only or --package-only");const native=await nativeAppleConfig(),config=await releaseConfig(options,native),packagePath=await packageAppleDesktop(config,Boolean(options.skipBuild),native);if(!options.packageOnly)validateOrUpload(packagePath,config,Boolean(options.validateOnly));log.success(options.packageOnly?`Created signed Mac App Store package ${packagePath}`:options.validateOnly?`Validated ${packagePath} with App Store Connect`:`Uploaded ${packagePath} to App Store Connect`);if(groups.length)await distributeToTestFlight(config,groups,options.whatsNew??commitsSinceLastTag())}catch(error){fail(error)}})}
107
+ `);return packagePath}function validateOrUpload(packagePath,config,validateOnly){const errors=validateAppleDesktopConfig(config,true);if(errors.length)throw new Error(errors.join(`
108
+ `));const common=["--type","macos","--file",packagePath,"--apiKey",config.apiKeyId,"--apiIssuer",config.apiIssuerId];const keysDirectory=resolve(config.apiKeyPath,"..");const env={API_PRIVATE_KEYS_DIR:keysDirectory};command(["xcrun","altool","--validate-app",...common],projectPath(),env);if(!validateOnly)command(["xcrun","altool","--upload-app",...common],projectPath(),env)}export function renderFailure(error){return`${error instanceof Error?error.message:String(error)}
109
+ `}function fail(error){process.stderr.write(renderFailure(error));process.exit(1)}export function desktopApple(buddy){buddy.command("desktop:apple:csr","Generate local private keys and CSRs for Mac App Store distribution certificates").option("--common-name <name>","Certificate request common name").option("--output <path>","Directory for private keys and certificate requests").action(async(options)=>{try{const metadata=packageMetadata();const outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning"));const{generateMacCertificateRequests}=await import("ts-pantry");generateMacCertificateRequests({outputDirectory,commonName:options.commonName||metadata.name});log.success(`Generated Apple certificate requests and private keys in ${outputDirectory}`)}catch(error){fail(error)}});buddy.command("desktop:apple:provision","Plan or reconcile Apple Bundle ID, capabilities, certificates, and profile").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--capabilities <types>","Comma-separated Apple capability types").option("--app-certificate-csr <path>","CSR for a missing Mac App Distribution certificate").option("--installer-certificate-csr <path>","CSR for a missing Mac Installer Distribution certificate").option("--profile-name <name>","Provisioning profile name").option("--output <path>","Directory for the plan and downloaded Apple assets").option("--plan","Report the idempotent Apple resource diff without mutating it").option("--apply","Apply the Apple resource diff without revoking existing certificates").action(async(options)=>{try{if(options.plan&&options.apply)throw new Error("Choose either --plan or --apply");const config=withApiKeyFile(resolveAppleDesktopConfig(options,await nativeAppleConfig()));if(!config.bundleId)throw new Error("APPLE_BUNDLE_ID or --bundle-id is required");if(!config.apiKeyId||!config.apiIssuerId||!config.apiKeyPath||!existsSync(config.apiKeyPath))throw new Error("App Store Connect API key ID, issuer ID, and existing .p8 key path are required");const readCsr=(file)=>{if(!file)return;const resolved=resolve(file);if(!existsSync(resolved))throw new Error(`Apple certificate CSR does not exist: ${resolved}`);return readFileSync(resolved,"utf8")};const{exportAppleCertificateP12,provisionMacApp}=await import("ts-pantry");const result=await provisionMacApp({identifier:config.bundleId,name:config.appName,capabilities:options.capabilities?.split(",").map((value)=>value.trim()).filter(Boolean),appCertificateCsr:readCsr(options.appCertificateCsr),installerCertificateCsr:readCsr(options.installerCertificateCsr),profileName:options.profileName,keyId:config.apiKeyId,issuerId:config.apiIssuerId,keyPath:config.apiKeyPath,checkOnly:!options.apply});const outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning"));mkdirSync(outputDirectory,{recursive:true});for(const certificate of result.certificates){if(!certificate.certificateContent)continue;const fileName=certificate.type==="MAC_APP_DISTRIBUTION"?"mac-app-distribution.cer":"mac-installer-distribution.cer";writeFileSync(join(outputDirectory,fileName),Buffer.from(certificate.certificateContent,"base64"),{mode:384})}if(result.profile.profileContent){writeFileSync(join(outputDirectory,"mac-app-store.provisionprofile"),Buffer.from(result.profile.profileContent,"base64"),{mode:384})}const certificatePassword=env("APPLE_CERTIFICATE_PASSWORD");const certificateExports=[{type:"MAC_APP_DISTRIBUTION",csr:options.appCertificateCsr,certificate:"mac-app-distribution.cer",output:"mac-app-distribution.p12",name:`${config.appName} Mac App Distribution`},{type:"MAC_INSTALLER_DISTRIBUTION",csr:options.installerCertificateCsr,certificate:"mac-installer-distribution.cer",output:"mac-installer-distribution.p12",name:`${config.appName} Mac Installer Distribution`}];for(const certificateExport of certificateExports){const certificate=result.certificates.find((item)=>item.type===certificateExport.type);if(!certificate?.certificateContent||!certificateExport.csr||!certificatePassword)continue;exportAppleCertificateP12({certificatePath:join(outputDirectory,certificateExport.certificate),privateKeyPath:resolve(certificateExport.csr.replace(/\.csr$/i,".key")),outputPath:join(outputDirectory,certificateExport.output),password:certificatePassword,name:certificateExport.name})}const certificates=result.certificates.map((item)=>{const certificate={...item};delete certificate.certificateContent;return certificate});const profile={...result.profile};delete profile.profileContent;const report={...result,certificates,profile};const reportPath=join(outputDirectory,"provisioning-plan.json");writeFileSync(reportPath,`${JSON.stringify(report,null,2)}
110
+ `,{mode:384});log.success(`${options.apply?"Applied":"Planned"} Apple provisioning: ${reportPath}`);if(!result.appRecord.exists&&result.appRecord.manualAction)log.warn(result.appRecord.manualAction)}catch(error){fail(error)}});buddy.command("desktop:apple:doctor","Validate Mac App Store tooling, credentials, certificates, and project metadata").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--keychain <path>","Look for the signing identities in this keychain file only (or APPLE_KEYCHAIN)").action(async(options)=>{try{const config=withApiKeyFile(resolveAppleDesktopConfig(options,await nativeAppleConfig()));const errors=validateAppleDesktopConfig(config,true);if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(errors.length)throw new Error(errors.join(`
111
+ `));log.success(`Mac App Store prerequisites are ready for ${config.bundleId}`)}catch(error){fail(error)}});buddy.command("desktop:apple:init","Create a GitHub Actions caller for the reusable Stacks Mac App Store workflow").option("--force","Replace an existing workflow").action((options)=>{try{const workflowPath=projectPath(".github/workflows/apple-app-store.yml");if(existsSync(workflowPath)&&!options.force)throw new Error(`${workflowPath} already exists. Use --force to replace it.`);mkdirSync(resolve(workflowPath,".."),{recursive:true});writeFileSync(workflowPath,renderAppleWorkflowCaller());log.success(`Created ${workflowPath}`)}catch(error){fail(error)}});const addSharedOptions=(commandBuilder)=>commandBuilder.option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-version <version>","Marketing version").option("--build-number <number>",'Unique App Store build number, or "next" for one past the highest on App Store Connect (publish only)').option("--minimum-macos <version>","Minimum supported macOS version").option("--category <category>","LSApplicationCategoryType value").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--icon <path>","Optional .icns app icon").option("--skip-build","Package existing storage/framework/desktop-dist artifacts").option("--universal","Ship one arm64 + x86_64 binary, merged with lipo").option("--craft-arm64 <path>","Thin arm64 Craft runtime for --universal (or CRAFT_BIN_ARM64)").option("--craft-x64 <path>","Thin x86_64 Craft runtime for --universal (or CRAFT_BIN_X64)").option("--keychain <path>","Sign with identities from this keychain file only (or APPLE_KEYCHAIN)");addSharedOptions(buddy.command("desktop:apple:package","Build, sandbox, sign, and package a Mac App Store desktop app")).action(async(options)=>{try{const native=await nativeAppleConfig();const packagePath=await packageAppleDesktop(withKeychainIdentities(resolveAppleDesktopConfig(options,native)),Boolean(options.skipBuild),native);log.success(`Created signed Mac App Store package ${packagePath}`)}catch(error){fail(error)}});addSharedOptions(buddy.command("desktop:apple:publish","Build and validate or upload a signed Mac App Store package")).option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--validate-only","Validate with App Store Connect without uploading").option("--package-only","Create the signed package without contacting App Store Connect").option("--testflight <groups>","After the upload, wait for processing and give the build to these comma-separated TestFlight groups").option("--whats-new <text>",'TestFlight "What to Test" (default: the commit subjects since the last tag)').action(async(options)=>{try{const groups=options.testflight?.split(",").map((name)=>name.trim()).filter(Boolean)??[];if(groups.length&&(options.validateOnly||options.packageOnly))throw new Error("--testflight needs an upload, so it cannot be combined with --validate-only or --package-only");const native=await nativeAppleConfig();const config=await releaseConfig(options,native);const packagePath=await packageAppleDesktop(config,Boolean(options.skipBuild),native);if(!options.packageOnly)validateOrUpload(packagePath,config,Boolean(options.validateOnly));log.success(options.packageOnly?`Created signed Mac App Store package ${packagePath}`:options.validateOnly?`Validated ${packagePath} with App Store Connect`:`Uploaded ${packagePath} to App Store Connect`);if(groups.length)await distributeToTestFlight(config,groups,options.whatsNew??commitsSinceLastTag())}catch(error){fail(error)}})}
@@ -1,2 +1,2 @@
1
- import process from"node:process";import{runTool}from"./run-tool";export function desktopProbeFlags(options){const flags=[];if(options.browser===!0)flags.push("--browser");else if(typeof options.browser==="string"&&options.browser.length>0)flags.push(`--browser=${options.browser}`);if(options.open===!1)flags.push("--no-open");if(options.record)flags.push("--record");const valued=[["out","out"],["craftBin","craft-bin"],["interactionWindow","interaction-window"],["idle","idle"],["load","load"],["cpuLoad","cpu-load"],["instances","instances"],["timeout","timeout"]];for(const[key,flag]of valued){const value=options[key];if(value!==void 0&&value!==""&&typeof value!=="boolean")flags.push(`--${flag}=${value}`)}return flags}export function desktopProbe(buddy){buddy.command("desktop:probe","Measure WebGL2/WebGPU, frame pacing, input and audio latency, gamepad, fullscreen and pointer lock in a Craft window").option("--browser [name]","Run the same page in a browser instead (default browser, or a named one on macOS)").option("--no-open","With --browser, print the URL instead of opening it").option("--record","Write the record into the framework repository's probe results (framework checkout only)").option("--out <file>","Also write the record as JSON to this file").option("--craft-bin <path>","Craft binary to use (defaults to CRAFT_BIN, then craft on PATH)").option("--interaction-window <seconds>","How long to wait for real clicks and key presses; 0 skips them (default 20)").option("--idle <seconds>","Idle frame-pacing sample length (default 3)").option("--load <seconds>","Loaded frame-pacing sample length (default 6)").option("--cpu-load <ms>","Busy-wait added to each loaded frame (default 6)").option("--instances <count>","Instanced cubes drawn per loaded frame, 12 triangles each (default 40000)").option("--timeout <seconds>","Give up after this long").example("buddy desktop:probe --record").example("buddy desktop:probe --browser=Safari --record").action(async(options)=>{try{const{run}=await import("@stacksjs/desktop-build/probe/runner");await runTool(run,...desktopProbeFlags(options))}catch(error){process.stderr.write(`${error instanceof Error?error.message:String(error)}
1
+ import process from"node:process";import{runTool}from"./run-tool";export function desktopProbeFlags(options){const flags=[];if(options.browser===true)flags.push("--browser");else if(typeof options.browser==="string"&&options.browser.length>0)flags.push(`--browser=${options.browser}`);if(options.open===false)flags.push("--no-open");if(options.record)flags.push("--record");const valued=[["out","out"],["craftBin","craft-bin"],["interactionWindow","interaction-window"],["idle","idle"],["load","load"],["cpuLoad","cpu-load"],["instances","instances"],["timeout","timeout"]];for(const[key,flag]of valued){const value=options[key];if(value!==undefined&&value!==""&&typeof value!=="boolean")flags.push(`--${flag}=${value}`)}return flags}export function desktopProbe(buddy){buddy.command("desktop:probe","Measure WebGL2/WebGPU, frame pacing, input and audio latency, gamepad, fullscreen and pointer lock in a Craft window").option("--browser [name]","Run the same page in a browser instead (default browser, or a named one on macOS)").option("--no-open","With --browser, print the URL instead of opening it").option("--record","Write the record into the framework repository's probe results (framework checkout only)").option("--out <file>","Also write the record as JSON to this file").option("--craft-bin <path>","Craft binary to use (defaults to CRAFT_BIN, then craft on PATH)").option("--interaction-window <seconds>","How long to wait for real clicks and key presses; 0 skips them (default 20)").option("--idle <seconds>","Idle frame-pacing sample length (default 3)").option("--load <seconds>","Loaded frame-pacing sample length (default 6)").option("--cpu-load <ms>","Busy-wait added to each loaded frame (default 6)").option("--instances <count>","Instanced cubes drawn per loaded frame, 12 triangles each (default 40000)").option("--timeout <seconds>","Give up after this long").example("buddy desktop:probe --record").example("buddy desktop:probe --browser=Safari --record").action(async(options)=>{try{const{run}=await import("@stacksjs/desktop-build/probe/runner");await runTool(run,...desktopProbeFlags(options))}catch(error){process.stderr.write(`${error instanceof Error?error.message:String(error)}
2
2
  `);process.exit(1)}})}
@@ -1,6 +1,6 @@
1
- import{execSync}from"node:child_process";import{existsSync,readdirSync,readFileSync}from"node:fs";import readline from"node:readline";import process from"node:process";import{bold,cyan,dim,green,intro,log,onUnknownSubcommand,outro,prompts,runCommand,yellow}from"@stacksjs/cli";import{homedir}from"node:os";import{dirname,join,relative}from"node:path";import{fileURLToPath}from"node:url";import{Action}from"@stacksjs/enums";import{inspectDefaultsProvenance,libsPath,projectPath,stxPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{version}from"../../package.json";import{resultFailed}from"../result";const DEV_BOOT_STARTING_LINE_COUNT=3;function eraseDevBootStartingLines(progressLines=0){if(!process.stdout.isTTY)return;for(let i=0;i<DEV_BOOT_STARTING_LINE_COUNT+progressLines;i++){readline.moveCursor(process.stdout,0,-1);readline.clearLine(process.stdout,0)}}export const DEV_BOOT_PROGRESS_EVERY_SECONDS=10;const DEV_BOOT_VERBOSE_HINT_SECONDS=30;export function devBootProgressLine(elapsedSeconds,waitingOn,verbose=!1){if(!waitingOn.length||elapsedSeconds<DEV_BOOT_PROGRESS_EVERY_SECONDS)return null;const servers=waitingOn.map((server)=>`the ${server.name} on :${server.port}`).join(", "),line=`still starting, ${Math.floor(elapsedSeconds)}s so far, waiting for ${servers}`;return!verbose&&elapsedSeconds>=DEV_BOOT_VERBOSE_HINT_SECONDS?`${line} (\`./buddy dev --verbose\` shows its output)`:line}let developmentRpx;function resolveRpxEntryPath(){return[projectPath("node_modules/@stacksjs/rpx/dist/index.js"),join(homedir(),"Code/Tools/rpx/packages/rpx/dist/index.js"),projectPath("pantry/@stacksjs/rpx/dist/src/index.js")].find((entry)=>existsSync(entry))??null}async function importDevelopmentRpx(){if(developmentRpx)return developmentRpx;const entry=resolveRpxEntryPath();developmentRpx=entry?await import(entry):await import("@stacksjs/rpx");return developmentRpx}const activeRpxRegistryIds=[];let _actions;async function actions(){if(!_actions)_actions=await import("@stacksjs/actions");return _actions}async function checkFrameworkDefaults(){let skew;try{skew=inspectDefaultsProvenance(projectPath())}catch{return}if(skew.status==="not-applicable"||skew.status==="current")return;if(skew.status==="stale")throw Error(`Framework defaults version mismatch: storage/framework/defaults is from ${skew.vendored}, but @stacksjs/defaults ${skew.installed} is installed. Run \`buddy upgrade\` to synchronize them before starting development servers.`);try{const{measureDefaultsDrift}=await actions(),drift=measureDefaultsDrift(projectPath(),{shallow:!0});if(!drift||drift.length===0)return;log.warn(`storage/framework/defaults does not match the installed @stacksjs/defaults ${skew.installed}.`);log.warn("The app runs the vendored copy. Run `buddy upgrade` to sync it, or `buddy doctor` for the file counts.")}catch{}}export const interactiveDevChoices=[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"native",title:"Native App"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}];export async function dispatchInteractiveDevSelection(selection,runners){if(!Object.hasOwn(runners,selection))return!1;await runners[selection]();return!0}export function resolvePrettyDevDomain(appUrl,nativeMode=!1){if(!appUrl||nativeMode)return null;try{const hostname=new URL(/^https?:\/\//i.test(appUrl)?appUrl:`https://${appUrl}`).hostname.toLowerCase();if(hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1"||hostname==="0.0.0.0")return null;return hostname}catch{return null}}export function shouldUsePrettyDevUrls(input){return input.domain!==null&&!input.localhostOnly&&(input.proxyManagedExternally||input.systemAuthorized)}const APPLICATION_VIEW_CANDIDATES=["app/index","app","dashboard/index","dashboard","home/index","home","composer","workspace/index","workspace","feed","portal","admin","account/index","account","profile/index","profile"],SITE_LAYOUT_NAMES=new Set(["default","guest","marketing","site"]);export function normalizeDevelopmentEntryPath(path){const value=path?.trim();if(!value||value==="/")return"/";try{const parsed=new URL(value,"http://stacks.localhost");return`${parsed.pathname}${parsed.search}${parsed.hash}`}catch{return"/"}}function configuredApplicationPath(root){if(process.env.APP_PATH)return process.env.APP_PATH;try{return readFileSync(join(root,"config/app.ts"),"utf8").match(/^[ \t]*appPath\s*:\s*(['"`])([^'"`]+)\1/m)?.[2]}catch{return}}function configuredDevelopmentLaunch(root){const environmentValue=process.env.STACKS_DEV_LAUNCH?.trim().toLowerCase();if(environmentValue==="browser"||environmentValue==="native")return environmentValue;try{const value=readFileSync(join(root,"config/app.ts"),"utf8").match(/\bdevLaunch\s*:\s*(['"`])(browser|native)\1/)?.[2];return value==="browser"||value==="native"?value:void 0}catch{return}}export function resolveDevelopmentLaunch(input={}){if(input.browser||input.site)return"browser";if(input.native)return"native";const root=input.root??projectPath();return input.configuredLaunch??configuredDevelopmentLaunch(root)??"browser"}function viewSource(root,route){const base=join(root,"resources/views",route);for(const extension of["stx","vue","html"]){const path=`${base}.${extension}`;if(existsSync(path))try{return readFileSync(path,"utf8")}catch{return""}}return}function usesApplicationLayout(source){const layout=source.match(/@extends\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1]??source.match(/@layout\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1];if(!layout)return!1;return!SITE_LAYOUT_NAMES.has(layout.split("/").at(-1)??layout)}export function resolveDevelopmentEntryPath(input={}){if(input.site)return"/";const root=input.root??projectPath(),configuredPath=input.configuredPath??configuredApplicationPath(root);if(configuredPath)return normalizeDevelopmentEntryPath(configuredPath);const loginExists=viewSource(root,"login")!==void 0||viewSource(root,"auth/login")!==void 0,candidates=APPLICATION_VIEW_CANDIDATES.map((route)=>({route,source:viewSource(root,route)})).filter((candidate)=>candidate.source!==void 0),appCandidate=candidates.find((candidate)=>usesApplicationLayout(candidate.source))??(loginExists?candidates[0]:void 0);if(appCandidate)return normalizeDevelopmentEntryPath(`/${appCandidate.route.replace(/\/index$/,"")}`);return loginExists?"/login":"/"}export function developmentUrl(baseUrl,entryPath){const normalized=normalizeDevelopmentEntryPath(entryPath);if(normalized==="/")return baseUrl.replace(/\/$/,"");return new URL(normalized,`${baseUrl.replace(/\/$/,"")}/`).toString()}export function developmentBrowserCommand(url,platform=process.platform){if(platform==="darwin")return["open",url];if(platform==="win32")return["cmd","/c","start","",url];return["xdg-open",url]}function openDevelopmentBrowser(url){if(!process.stdout.isTTY||process.env.CI||process.env.STACKS_DEV_NO_OPEN==="1")return;try{Bun.spawn(developmentBrowserCommand(url),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref()}catch{}}async function canStartPrettyDevProxy(){if(await waitForHttpsProxy(443,150))return!0;try{const{authorizeSystemAccess}=await importDevelopmentRpx();return authorizeSystemAccess({interactive:!1})}catch{return!1}}export function dev(buddy){const descriptions={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",native:"Start the app in a native Craft window",dashboard:"Start the Dashboard development server",api:"Start the local API development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",browser:"Open the application in a browser instead of its configured native window",site:"Open the marketing site instead of the application",project:"Target a specific project",verbose:"Enable verbose output",detach:"Keep the dev servers running after this process or its shell exits (for `nohup ./buddy dev --detach &`)"};buddy.command("dev [server]",descriptions.dev).option("-f, --frontend",descriptions.frontend).option("-a, --api",descriptions.api).option("-c, --components",descriptions.components).option("-d, --dashboard",descriptions.dashboard).option("-k, --desktop",descriptions.desktop).option("-n, --native",descriptions.native).option("-o, --docs",descriptions.docs).option("-s, --system-tray",descriptions.systemTray).option("-i, --interactive",descriptions.interactive,{default:!1}).option("-l, --with-localhost",descriptions.withLocalhost,{default:!1}).option("--browser",descriptions.browser,{default:!1}).option("--site",descriptions.site,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).option("--detach",descriptions.detach,{default:!1}).action(async(server,options)=>{if(options.detach)process.env.STACKS_DEV_DETACH="1";const perf=Bun.nanoseconds();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await checkFrameworkDefaults();const target=server||(options.frontend?"frontend":void 0)||(options.api?"api":void 0)||(options.components?"components":void 0)||(options.dashboard?"dashboard":void 0)||(options.desktop?"desktop":void 0)||(options.native?"native":void 0)||(options.systemTray||options["system-tray"]?"system-tray":void 0)||(options.docs?"docs":void 0);if(target){const serverOptions={...options},a=await actions();switch(target){case"native":await startDevelopmentServer({...serverOptions,native:!0},perf);break;case"frontend":await a.runFrontendDevServer(serverOptions);break;case"api":await a.runApiDevServer(serverOptions);break;case"components":await a.runComponentsDevServer(serverOptions);break;case"dashboard":await a.runDashboardDevServer(serverOptions);break;case"desktop":await startDevelopmentServer({...serverOptions,native:!0},perf);break;case"system-tray":await a.runSystemTrayDevServer(serverOptions);break;case"docs":await a.runDocsDevServer(serverOptions);break;default:await log.error(`Unknown server: ${target}`);process.exit(ExitCode.InvalidArgument)}}else if(wantsInteractive(options)){const selectedValue=await prompts.select({message:descriptions.select,choices:interactiveDevChoices.map((choice)=>({value:choice.value,label:choice.title}))}),a=await actions();if(!await dispatchInteractiveDevSelection(selectedValue,{all:()=>startDevelopmentServer(options,perf),frontend:()=>a.runFrontendDevServer(options),api:()=>a.runApiDevServer(options),dashboard:()=>a.runDashboardDevServer(options),desktop:()=>startDevelopmentServer({...options,native:!0},perf),native:()=>startDevelopmentServer({...options,native:!0},perf),components:()=>a.runComponentsDevServer(options),docs:()=>a.runDocsDevServer(options)})){await log.error("Invalid option during interactive mode");process.exit(ExitCode.InvalidArgument)}}else await startDevelopmentServer(options,perf);outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("dev:components",descriptions.components).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:components"),result=await runCommand("bun run dev",{cwd:libsPath("components/stx")});if(options.verbose)log.info("buddy dev:components result",result);if(resultFailed(result)){await outro("While running the dev:components command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("dev:docs",descriptions.docs).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:docs"),result=await(await actions()).runAction(Action.DevDocs,options);if(resultFailed(result)){await outro("While running the dev:docs command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("dev:native",descriptions.native).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:native");await startDevelopmentServer({...options,native:!0},perf)});buddy.command("dev:desktop",descriptions.desktop).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:desktop"),{hasMacosDesktop}=await import("@stacksjs/desktop-build");if(await hasMacosDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions"),{Action}=await import("@stacksjs/enums"),result=await runAction(Action.BuildDesktopMacos,options);if(resultFailed(result)){await outro("While building the native macOS app, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Opened the native macOS app",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}await startDevelopmentServer({...options,native:!0},perf)});buddy.command("dev:api",descriptions.api).option("-p, --project [project]",descriptions.project,{default:!1}).option("--no-watch-types","Skip the model/config type-regeneration watcher").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();const a=await actions();if(options.watchTypes!==!1)a.watchTypes(options).catch((err)=>{log.warn("[dev:api] type watcher exited:",err)});await a.runApiDevServer(options)});buddy.command("dev:frontend",descriptions.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",descriptions.project,{default:!1}).option("--site",descriptions.site,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await(await actions()).runFrontendDevServer(options)});buddy.command("dev:dashboard",descriptions.dashboard).alias("dev:admin").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runDashboardDevServer(options)});buddy.command("dev:system-tray",descriptions.systemTray).alias("dev:tray").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runSystemTrayDevServer(options)});onUnknownSubcommand(buddy,"dev")}export async function startDevelopmentServer(_options,_startTime){const options=_options,startedAt=_startTime,appUrl=process.env.APP_URL??"stacks.localhost",nativeMode=resolveDevelopmentLaunch({browser:options.browser,native:options.native,site:options.site})==="native",entryPath=resolveDevelopmentEntryPath({site:options.site});process.env.STACKS_DEV_ENTRY_PATH=entryPath;const proxyManagedExternally=process.env.STACKS_PROXY_MANAGED==="1",preferredFrontendPort=Number(process.env.PORT)||3000,preferredApiPort=Number(process.env.PORT_API)||3008,preferredDocsPort=Number(process.env.PORT_DOCS)||3006,preferredDashboardPort=Number(process.env.PORT_ADMIN)||3002;if(process.env.STACKS_DEV_NO_KILL!=="1")await cleanupStaleDevProcesses([preferredFrontendPort,preferredApiPort,preferredDocsPort,preferredDashboardPort]);const portShifts=[],claimPort=async(label,preferred)=>{if(proxyManagedExternally)return preferred;const port=await findAvailablePort(preferred);if(port!==preferred)portShifts.push(`${label} :${preferred} \u2192 :${port}`);return port},frontendPort=await claimPort("Frontend",preferredFrontendPort),apiPort=await claimPort("API",preferredApiPort),docsPort=await claimPort("Docs",preferredDocsPort),dashboardPort=await claimPort("Dashboard",preferredDashboardPort);process.env.PORT=String(frontendPort);process.env.PORT_API=String(apiPort);process.env.PORT_DOCS=String(docsPort);process.env.PORT_ADMIN=String(dashboardPort);const includeDashboard=process.env.STACKS_DEV_DASHBOARD==="1",domain=resolvePrettyDevDomain(appUrl,nativeMode),appLooksCustom=domain!==null,localhostOnly=process.env.STACKS_DEV_LOCALHOST==="1",prettyUrlsRequested=appLooksCustom&&!localhostOnly,systemAuthorized=!prettyUrlsRequested||proxyManagedExternally?!0:await canStartPrettyDevProxy(),usePrettyUrls=shouldUsePrettyDevUrls({domain,localhostOnly,proxyManagedExternally,systemAuthorized}),prettySetupRequired=prettyUrlsRequested&&!usePrettyUrls,hasCustomDomain=usePrettyUrls&&!proxyManagedExternally,displayedDomain=usePrettyUrls?domain:null,dashboardDomain=displayedDomain?`dashboard.${displayedDomain}`:null,frontendBaseUrl=displayedDomain?`https://${displayedDomain}`:`http://localhost:${frontendPort}`,frontendUrl=developmentUrl(frontendBaseUrl,entryPath),apiUrl=displayedDomain?`https://${displayedDomain}/api`:`http://localhost:${apiPort}`,docsUrl=displayedDomain?`https://${displayedDomain}/docs`:`http://localhost:${docsPort}`,dashboardUrl=dashboardDomain?`https://${dashboardDomain}`:`http://localhost:${dashboardPort}`;process.env.STACKS_PROXY_MANAGED="1";process.env.STACKS_DEV_QUIET="1";console.log();if(prettySetupRequired){console.log(` ${yellow("\u26A0")} ${yellow("Pretty URL setup required")} ${dim("- using localhost for this session")}`);console.log(` ${dim(" ")}${dim("Run `./buddy setup:ssl` once, then restart `./buddy dev`.")}`);console.log()}if(portShifts.length>0){console.log(` ${yellow("\u26A0")} ${yellow("Ports in use by another process")} ${dim(`- ${portShifts.join(", ")}`)}`);console.log()}console.log(` ${bold(cyan("stacks"))} ${dim(`v${version}`)} ${dim("starting\u2026")}`);console.log();const rpxTlsPreflight=hasCustomDomain&&domain?prepareRpxTlsForDev({domain,includeDashboard,options}):Promise.resolve();if(localhostOnly&&domain&&!proxyManagedExternally)removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??!1).catch(()=>{});rpxTlsPreflight.catch(()=>{});let isExiting=!1,closeNativeApp;const SHUTDOWN_GRACE_MS=1500,cleanup=(signal)=>{if(isExiting)return;isExiting=!0;console.log();console.log(` ${bold(cyan("stacks"))} ${dim(`received ${signal} - shutting down the dev server`)}`);if(signal==="SIGHUP")console.log(` ${dim(" ")}${dim("The launching shell went away (a closed terminal, or a CI step that ended). nohup does not prevent this.")}`);closeNativeApp?.();const rpxTeardown=(async()=>{try{await unregisterRpxProxies(activeRpxRegistryIds);activeRpxRegistryIds.length=0;if(hasCustomDomain&&domain)await removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??!1)}catch{}})(),teardownDeadline=new Promise((resolve)=>setTimeout(resolve,SHUTDOWN_GRACE_MS));Promise.race([rpxTeardown,teardownDeadline]).finally(()=>{try{process.kill(-process.pid,"SIGTERM")}catch{try{process.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{process.kill(0,"SIGKILL")}catch{process.exit(1)}},SHUTDOWN_GRACE_MS).unref()})};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);process.on("SIGHUP",cleanup);const quietOpts={...options,quiet:!0},a=await actions(),ports=[{name:"API",port:apiPort}],readinessTimeoutMs=30000;let readyAnnounced=!1;const nativeUrl=developmentUrl(`http://localhost:${frontendPort}`,entryPath),nativeWindowReady=nativeMode?waitForPort(frontendPort,readinessTimeoutMs).then(async(ready)=>{if(!ready){log.warn(`Native window skipped because the frontend did not answer within ${readinessTimeoutMs/1000}s`);return}closeNativeApp=await launchNativeAppWindow(nativeUrl,options)}):Promise.resolve(),waitingOn=new Set(ports),bootStartedMs=Date.now();let progressLines=0,nextProgressAt=DEV_BOOT_PROGRESS_EVERY_SECONDS;const progress=setInterval(()=>{const elapsed=(Date.now()-bootStartedMs)/1000;if(elapsed<nextProgressAt)return;nextProgressAt+=DEV_BOOT_PROGRESS_EVERY_SECONDS;const line=devBootProgressLine(elapsed,[...waitingOn],options.verbose);if(!line)return;console.log(` ${dim(line)}`);progressLines++},1000);progress.unref?.();Promise.all(ports.map((p)=>waitForPort(p.port,Number.POSITIVE_INFINITY).then(()=>waitingOn.delete(p)))).then(async()=>{clearInterval(progress);if(readyAnnounced)return;readyAnnounced=!0;let proxyReachable=!1;if(hasCustomDomain&&domain){(async()=>{try{await rpxTlsPreflight;await registerRpxProxiesForDomain({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options})}catch{}})();proxyReachable=await waitForHttpsProxy(443,16000);if(!proxyReachable){console.log(` ${yellow("\u26A0")} ${yellow("HTTPS proxy not reachable on :443")} - serving ${cyan(`http://localhost:${frontendPort}`)} instead`);console.log(` ${dim(" ")}${dim("rpx needs a valid SUDO_PASSWORD in .env to bind :443; trust the local CA, then restart `./buddy dev`.")}`);if(options.verbose)console.log(` ${dim(" ")}${dim(`Trust CA: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}}eraseDevBootStartingLines(progressLines);printDevReadyBanner({options,nativeMode,hasCustomDomain:!!appLooksCustom&&!localhostOnly,proxyReachable:proxyManagedExternally?!0:proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain});if(!nativeMode){const browserUrl=hasCustomDomain&&(proxyManagedExternally||proxyReachable)?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);openDevelopmentBrowser(browserUrl)}if(startedAt){const elapsedMs=(Bun.nanoseconds()-startedAt)/1e6;console.log(` ${dim(`ready in ${(elapsedMs/1000).toFixed(1)}s`)}`);console.log();printDevEngineNotes();console.log()}if(process.env.STACKS_PRINT_ROUTES==="1")await printRegisteredRoutes(apiPort).catch(()=>{})}).catch(()=>{});await Promise.all([a.runFrontendDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Frontend: ${error}`)}),a.runApiDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`API: ${error}`)}),a.runDocsDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Docs: ${error}`)}),includeDashboard?a.runDashboardDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Dashboard: ${error}`)}):Promise.resolve(),nativeWindowReady.catch((error)=>{if(options.verbose)log.warn(`Native window: ${error}`)})])}function isComingSoonMode(){if(existsSync(projectPath("storage/framework/coming-soon")))return!0;try{const idx=projectPath("resources/views/index.stx");return existsSync(idx)&&/siteMode\s*=\s*['"]coming-soon['"]/.test(readFileSync(idx,"utf8"))}catch{return!1}}function blogIsConfigured(){try{const dir=projectPath("content/blog");return existsSync(dir)&&readdirSync(dir).some((f)=>f.endsWith(".md"))}catch{return!1}}function printDevReadyBanner(input){const{options,nativeMode,hasCustomDomain,proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain}=input,verbose=options.verbose??!1,useProxy=hasCustomDomain&&proxyReachable,feUrl=useProxy?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath),feBaseUrl=useProxy?frontendBaseUrl:`http://localhost:${frontendPort}`,apUrl=useProxy?apiUrl:`http://localhost:${apiPort}`,dcUrl=useProxy?docsUrl:`http://localhost:${docsPort}`,dbUrl=useProxy?dashboardUrl:`http://localhost:${dashboardPort}`,blogUrl=`${feBaseUrl}/blog`;console.log();const frontendLabel=entryPath==="/"?"Site":"App";console.log(` ${green("\u279C")} ${bold(frontendLabel.padEnd(8))}: ${cyan(feUrl)}`);if(entryPath!=="/")console.log(` ${dim("\u279C")} ${dim("Site")}: ${dim(feBaseUrl)}`);if(nativeMode)console.log(` ${green("\u279C")} ${bold("Native")}: ${cyan(`Craft \u2192 ${feUrl}`)}`);console.log(` ${green("\u279C")} ${bold("API")}: ${cyan(apUrl)}`);console.log(` ${green("\u279C")} ${bold("Docs")}: ${cyan(dcUrl)}`);if(blogIsConfigured())console.log(` ${green("\u279C")} ${bold("Blog")}: ${cyan(blogUrl)}`);if(includeDashboard)console.log(` ${green("\u279C")} ${bold("Dashboard")}: ${cyan(dbUrl)}`);if(useProxy){console.log(` ${dim("\u279C")} ${dim("Direct")}: ${dim(`${developmentUrl(`http://localhost:${frontendPort}`,entryPath)} (bypasses the proxy)`)}`);if(includeDashboard&&dashboardDomain)console.log(` ${dim("\u279C")} ${dim("Direct")}: ${dim(`http://localhost:${dashboardPort} (dashboard, bypasses the proxy)`)}`)}if(isComingSoonMode()){console.log();console.log(` ${yellow("\u25CF")} ${bold(yellow("Coming soon mode"))} ${dim("- visitors see the holding page; bypass with the coming-soon secret.")}`)}if(verbose&&domain){console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`localhost:${frontendPort} \u2192 ${domain}`)}`);console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/api \u2192 localhost:${apiPort}`)}`);console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/docs \u2192 localhost:${docsPort}`)}`);if(includeDashboard)console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} \u2192 ${dashboardDomain}`)}`)}console.log()}function printDevEngineNotes(){const routesFile=stxPath("routes.ts"),routesLabel=relative(projectPath(),routesFile);if(["config/css.ts","css.config.ts","config/crosswind.ts","crosswind.config.ts"].some((config)=>existsSync(join(projectPath(),config))))console.log(` ${green("[ts-css]")} ${dim("CSS engine loaded")}`);if(existsSync(routesFile))try{const routeCount=(readFileSync(routesFile,"utf8").match(/pattern:/g)??[]).length;if(routeCount>0)console.log(` ${green("[stx]")} ${dim(`Generated ${routeCount} routes \u2192 ${routesLabel}`)}`)}catch{console.log(` ${green("[stx]")} ${dim(`Routes manifest \u2192 ${routesLabel}`)}`)}}async function launchNativeAppWindow(url,options){let createApp;try{createApp=(await importCraftSdk()).createApp}catch(error){if(options.verbose)log.warn(`Native window unavailable: ${error}`);console.log(` ${dim("Native window unavailable. Install craft-native or set CRAFT_BIN to a Craft binary.")}
1
+ import{execSync}from"node:child_process";import{existsSync,readdirSync,readFileSync}from"node:fs";import readline from"node:readline";import process from"node:process";import{bold,cyan,dim,green,intro,log,onUnknownSubcommand,outro,prompts,runCommand,yellow}from"@stacksjs/cli";import{homedir}from"node:os";import{dirname,join,relative}from"node:path";import{fileURLToPath}from"node:url";import{Action}from"@stacksjs/enums";import{inspectDefaultsProvenance,libsPath,projectPath,stxPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{version}from"../../package.json";import{resultFailed}from"../result";const DEV_BOOT_STARTING_LINE_COUNT=3;function eraseDevBootStartingLines(progressLines=0){if(!process.stdout.isTTY)return;for(let i=0;i<DEV_BOOT_STARTING_LINE_COUNT+progressLines;i++){readline.moveCursor(process.stdout,0,-1);readline.clearLine(process.stdout,0)}}export const DEV_BOOT_PROGRESS_EVERY_SECONDS=10;const DEV_BOOT_VERBOSE_HINT_SECONDS=30;export function devBootProgressLine(elapsedSeconds,waitingOn,verbose=false){if(!waitingOn.length||elapsedSeconds<DEV_BOOT_PROGRESS_EVERY_SECONDS)return null;const servers=waitingOn.map((server)=>`the ${server.name} on :${server.port}`).join(", ");const line=`still starting, ${Math.floor(elapsedSeconds)}s so far, waiting for ${servers}`;return!verbose&&elapsedSeconds>=DEV_BOOT_VERBOSE_HINT_SECONDS?`${line} (\`./buddy dev --verbose\` shows its output)`:line}let developmentRpx;function resolveRpxEntryPath(){const candidates=[projectPath("node_modules/@stacksjs/rpx/dist/index.js"),join(homedir(),"Code/Tools/rpx/packages/rpx/dist/index.js"),projectPath("pantry/@stacksjs/rpx/dist/src/index.js")];return candidates.find((entry)=>existsSync(entry))??null}async function importDevelopmentRpx(){if(developmentRpx)return developmentRpx;const entry=resolveRpxEntryPath();developmentRpx=entry?await import(entry):await import("@stacksjs/rpx");return developmentRpx}const activeRpxRegistryIds=[];let _actions;async function actions(){if(!_actions)_actions=await import("@stacksjs/actions");return _actions}async function checkFrameworkDefaults(){let skew;try{skew=inspectDefaultsProvenance(projectPath())}catch{return}if(skew.status==="not-applicable"||skew.status==="current")return;if(skew.status==="stale"){throw new Error(`Framework defaults version mismatch: storage/framework/defaults is from ${skew.vendored}, but @stacksjs/defaults ${skew.installed} is installed. Run \`buddy upgrade\` to synchronize them before starting development servers.`)}try{const{measureDefaultsDrift}=await actions();const drift=measureDefaultsDrift(projectPath(),{shallow:true});if(!drift||drift.length===0)return;log.warn(`storage/framework/defaults does not match the installed @stacksjs/defaults ${skew.installed}.`);log.warn("The app runs the vendored copy. Run `buddy upgrade` to sync it, or `buddy doctor` for the file counts.")}catch{}}export const interactiveDevChoices=[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"native",title:"Native App"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}];export async function dispatchInteractiveDevSelection(selection,runners){if(!Object.hasOwn(runners,selection))return false;await runners[selection]();return true}export function resolvePrettyDevDomain(appUrl,nativeMode=false){if(!appUrl||nativeMode)return null;try{const url=new URL(/^https?:\/\//i.test(appUrl)?appUrl:`https://${appUrl}`);const hostname=url.hostname.toLowerCase();if(hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1"||hostname==="0.0.0.0")return null;return hostname}catch{return null}}export function shouldUsePrettyDevUrls(input){return input.domain!==null&&!input.localhostOnly&&(input.proxyManagedExternally||input.systemAuthorized)}const APPLICATION_VIEW_CANDIDATES=["app/index","app","dashboard/index","dashboard","home/index","home","composer","workspace/index","workspace","feed","portal","admin","account/index","account","profile/index","profile"];const SITE_LAYOUT_NAMES=new Set(["default","guest","marketing","site"]);export function normalizeDevelopmentEntryPath(path){const value=path?.trim();if(!value||value==="/")return"/";try{const parsed=new URL(value,"http://stacks.localhost");return`${parsed.pathname}${parsed.search}${parsed.hash}`}catch{return"/"}}function configuredApplicationPath(root){if(process.env.APP_PATH)return process.env.APP_PATH;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");return source.match(/^[ \t]*appPath\s*:\s*(['"`])([^'"`]+)\1/m)?.[2]}catch{return}}function configuredDevelopmentLaunch(root){const environmentValue=process.env.STACKS_DEV_LAUNCH?.trim().toLowerCase();if(environmentValue==="browser"||environmentValue==="native")return environmentValue;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");const value=source.match(/\bdevLaunch\s*:\s*(['"`])(browser|native)\1/)?.[2];return value==="browser"||value==="native"?value:undefined}catch{return}}export function resolveDevelopmentLaunch(input={}){if(input.browser||input.site)return"browser";if(input.native)return"native";const root=input.root??projectPath();return input.configuredLaunch??configuredDevelopmentLaunch(root)??"browser"}function viewSource(root,route){const base=join(root,"resources/views",route);for(const extension of["stx","vue","html"]){const path=`${base}.${extension}`;if(existsSync(path)){try{return readFileSync(path,"utf8")}catch{return""}}}return}function usesApplicationLayout(source){const layout=source.match(/@extends\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1]??source.match(/@layout\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1];if(!layout)return false;return!SITE_LAYOUT_NAMES.has(layout.split("/").at(-1)??layout)}export function resolveDevelopmentEntryPath(input={}){if(input.site)return"/";const root=input.root??projectPath();const configuredPath=input.configuredPath??configuredApplicationPath(root);if(configuredPath)return normalizeDevelopmentEntryPath(configuredPath);const loginExists=viewSource(root,"login")!==undefined||viewSource(root,"auth/login")!==undefined;const candidates=APPLICATION_VIEW_CANDIDATES.map((route)=>({route,source:viewSource(root,route)})).filter((candidate)=>candidate.source!==undefined);const appCandidate=candidates.find((candidate)=>usesApplicationLayout(candidate.source))??(loginExists?candidates[0]:undefined);if(appCandidate)return normalizeDevelopmentEntryPath(`/${appCandidate.route.replace(/\/index$/,"")}`);return loginExists?"/login":"/"}export function developmentUrl(baseUrl,entryPath){const normalized=normalizeDevelopmentEntryPath(entryPath);if(normalized==="/")return baseUrl.replace(/\/$/,"");return new URL(normalized,`${baseUrl.replace(/\/$/,"")}/`).toString()}export function developmentBrowserCommand(url,platform=process.platform){if(platform==="darwin")return["open",url];if(platform==="win32")return["cmd","/c","start","",url];return["xdg-open",url]}function openDevelopmentBrowser(url){if(!process.stdout.isTTY||process.env.CI||process.env.STACKS_DEV_NO_OPEN==="1")return;try{const subprocess=Bun.spawn(developmentBrowserCommand(url),{stdin:"ignore",stdout:"ignore",stderr:"ignore"});subprocess.unref()}catch{}}async function canStartPrettyDevProxy(){if(await waitForHttpsProxy(443,150))return true;try{const{authorizeSystemAccess}=await importDevelopmentRpx();return authorizeSystemAccess({interactive:false})}catch{return false}}export function dev(buddy){const descriptions={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",native:"Start the app in a native Craft window",dashboard:"Start the Dashboard development server",api:"Start the local API development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",browser:"Open the application in a browser instead of its configured native window",site:"Open the marketing site instead of the application",project:"Target a specific project",verbose:"Enable verbose output",detach:"Keep the dev servers running after this process or its shell exits (for `nohup ./buddy dev --detach &`)"};buddy.command("dev [server]",descriptions.dev).option("-f, --frontend",descriptions.frontend).option("-a, --api",descriptions.api).option("-c, --components",descriptions.components).option("-d, --dashboard",descriptions.dashboard).option("-k, --desktop",descriptions.desktop).option("-n, --native",descriptions.native).option("-o, --docs",descriptions.docs).option("-s, --system-tray",descriptions.systemTray).option("-i, --interactive",descriptions.interactive,{default:false}).option("-l, --with-localhost",descriptions.withLocalhost,{default:false}).option("--browser",descriptions.browser,{default:false}).option("--site",descriptions.site,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).option("--detach",descriptions.detach,{default:false}).action(async(server,options)=>{if(options.detach)process.env.STACKS_DEV_DETACH="1";const perf=Bun.nanoseconds();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await checkFrameworkDefaults();const target=server||(options.frontend?"frontend":undefined)||(options.api?"api":undefined)||(options.components?"components":undefined)||(options.dashboard?"dashboard":undefined)||(options.desktop?"desktop":undefined)||(options.native?"native":undefined)||(options.systemTray||options["system-tray"]?"system-tray":undefined)||(options.docs?"docs":undefined);if(target){const serverOptions={...options};const a=await actions();switch(target){case"native":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"frontend":await a.runFrontendDevServer(serverOptions);break;case"api":await a.runApiDevServer(serverOptions);break;case"components":await a.runComponentsDevServer(serverOptions);break;case"dashboard":await a.runDashboardDevServer(serverOptions);break;case"desktop":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"system-tray":await a.runSystemTrayDevServer(serverOptions);break;case"docs":await a.runDocsDevServer(serverOptions);break;default:await log.error(`Unknown server: ${target}`);process.exit(ExitCode.InvalidArgument)}}else if(wantsInteractive(options)){const selectedValue=await prompts.select({message:descriptions.select,choices:interactiveDevChoices.map((choice)=>({value:choice.value,label:choice.title}))});const a=await actions();const handled=await dispatchInteractiveDevSelection(selectedValue,{all:()=>startDevelopmentServer(options,perf),frontend:()=>a.runFrontendDevServer(options),api:()=>a.runApiDevServer(options),dashboard:()=>a.runDashboardDevServer(options),desktop:()=>startDevelopmentServer({...options,native:true},perf),native:()=>startDevelopmentServer({...options,native:true},perf),components:()=>a.runComponentsDevServer(options),docs:()=>a.runDocsDevServer(options)});if(!handled){await log.error("Invalid option during interactive mode");process.exit(ExitCode.InvalidArgument)}}else{await startDevelopmentServer(options,perf)}outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:components",descriptions.components).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:components");const result=await runCommand("bun run dev",{cwd:libsPath("components/stx")});if(options.verbose)log.info("buddy dev:components result",result);if(resultFailed(result)){await outro("While running the dev:components command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:docs",descriptions.docs).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:docs");const result=await(await actions()).runAction(Action.DevDocs,options);if(resultFailed(result)){await outro("While running the dev:docs command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:native",descriptions.native).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:native");await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:desktop",descriptions.desktop).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:desktop");const{hasMacosDesktop}=await import("@stacksjs/desktop-build");if(await hasMacosDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopMacos,options);if(resultFailed(result)){await outro("While building the native macOS app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Opened the native macOS app",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:api",descriptions.api).option("-p, --project [project]",descriptions.project,{default:false}).option("--no-watch-types","Skip the model/config type-regeneration watcher").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const a=await actions();if(options.watchTypes!==false){a.watchTypes(options).catch((err)=>{log.warn("[dev:api] type watcher exited:",err)})}await a.runApiDevServer(options)});buddy.command("dev:frontend",descriptions.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",descriptions.project,{default:false}).option("--site",descriptions.site,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await(await actions()).runFrontendDevServer(options)});buddy.command("dev:dashboard",descriptions.dashboard).alias("dev:admin").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runDashboardDevServer(options)});buddy.command("dev:system-tray",descriptions.systemTray).alias("dev:tray").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runSystemTrayDevServer(options)});onUnknownSubcommand(buddy,"dev")}export async function startDevelopmentServer(_options,_startTime){const options=_options;const startedAt=_startTime;const appUrl=process.env.APP_URL??"stacks.localhost";const nativeMode=resolveDevelopmentLaunch({browser:options.browser,native:options.native,site:options.site})==="native";const entryPath=resolveDevelopmentEntryPath({site:options.site});process.env.STACKS_DEV_ENTRY_PATH=entryPath;const proxyManagedExternally=process.env.STACKS_PROXY_MANAGED==="1";const preferredFrontendPort=Number(process.env.PORT)||3000;const preferredApiPort=Number(process.env.PORT_API)||3008;const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const preferredDashboardPort=Number(process.env.PORT_ADMIN)||3002;if(process.env.STACKS_DEV_NO_KILL!=="1"){await cleanupStaleDevProcesses([preferredFrontendPort,preferredApiPort,preferredDocsPort,preferredDashboardPort])}const portShifts=[];const claimPort=async(label,preferred)=>{if(proxyManagedExternally)return preferred;const port=await findAvailablePort(preferred);if(port!==preferred)portShifts.push(`${label} :${preferred} → :${port}`);return port};const frontendPort=await claimPort("Frontend",preferredFrontendPort);const apiPort=await claimPort("API",preferredApiPort);const docsPort=await claimPort("Docs",preferredDocsPort);const dashboardPort=await claimPort("Dashboard",preferredDashboardPort);process.env.PORT=String(frontendPort);process.env.PORT_API=String(apiPort);process.env.PORT_DOCS=String(docsPort);process.env.PORT_ADMIN=String(dashboardPort);const includeDashboard=process.env.STACKS_DEV_DASHBOARD==="1";const domain=resolvePrettyDevDomain(appUrl,nativeMode);const appLooksCustom=domain!==null;const localhostOnly=process.env.STACKS_DEV_LOCALHOST==="1";const prettyUrlsRequested=appLooksCustom&&!localhostOnly;const systemAuthorized=!prettyUrlsRequested||proxyManagedExternally?true:await canStartPrettyDevProxy();const usePrettyUrls=shouldUsePrettyDevUrls({domain,localhostOnly,proxyManagedExternally,systemAuthorized});const prettySetupRequired=prettyUrlsRequested&&!usePrettyUrls;const hasCustomDomain=usePrettyUrls&&!proxyManagedExternally;const displayedDomain=usePrettyUrls?domain:null;const dashboardDomain=displayedDomain?`dashboard.${displayedDomain}`:null;const frontendBaseUrl=displayedDomain?`https://${displayedDomain}`:`http://localhost:${frontendPort}`;const frontendUrl=developmentUrl(frontendBaseUrl,entryPath);const apiUrl=displayedDomain?`https://${displayedDomain}/api`:`http://localhost:${apiPort}`;const docsUrl=displayedDomain?`https://${displayedDomain}/docs`:`http://localhost:${docsPort}`;const dashboardUrl=dashboardDomain?`https://${dashboardDomain}`:`http://localhost:${dashboardPort}`;process.env.STACKS_PROXY_MANAGED="1";process.env.STACKS_DEV_QUIET="1";console.log();if(prettySetupRequired){console.log(` ${yellow("⚠")} ${yellow("Pretty URL setup required")} ${dim("- using localhost for this session")}`);console.log(` ${dim(" ")}${dim("Run `./buddy setup:ssl` once, then restart `./buddy dev`.")}`);console.log()}if(portShifts.length>0){console.log(` ${yellow("⚠")} ${yellow("Ports in use by another process")} ${dim(`- ${portShifts.join(", ")}`)}`);console.log()}console.log(` ${bold(cyan("stacks"))} ${dim(`v${version}`)} ${dim("starting…")}`);console.log();const rpxTlsPreflight=hasCustomDomain&&domain?prepareRpxTlsForDev({domain,includeDashboard,options}):Promise.resolve();if(localhostOnly&&domain&&!proxyManagedExternally)removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false).catch(()=>{});rpxTlsPreflight.catch(()=>{});let isExiting=false;let closeNativeApp;const SHUTDOWN_GRACE_MS=1500;const cleanup=(signal)=>{if(isExiting)return;isExiting=true;console.log();console.log(` ${bold(cyan("stacks"))} ${dim(`received ${signal} - shutting down the dev server`)}`);if(signal==="SIGHUP")console.log(` ${dim(" ")}${dim("The launching shell went away (a closed terminal, or a CI step that ended). nohup does not prevent this.")}`);closeNativeApp?.();const rpxTeardown=(async()=>{try{await unregisterRpxProxies(activeRpxRegistryIds);activeRpxRegistryIds.length=0;if(hasCustomDomain&&domain)await removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false)}catch{}})();const teardownDeadline=new Promise((resolve)=>setTimeout(resolve,SHUTDOWN_GRACE_MS));Promise.race([rpxTeardown,teardownDeadline]).finally(()=>{try{process.kill(-process.pid,"SIGTERM")}catch{try{process.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{process.kill(0,"SIGKILL")}catch{process.exit(1)}},SHUTDOWN_GRACE_MS).unref()})};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);process.on("SIGHUP",cleanup);const quietOpts={...options,quiet:true};const a=await actions();const ports=[{name:"API",port:apiPort}];const readinessTimeoutMs=30000;let readyAnnounced=false;const nativeUrl=developmentUrl(`http://localhost:${frontendPort}`,entryPath);const nativeWindowReady=nativeMode?waitForPort(frontendPort,readinessTimeoutMs).then(async(ready)=>{if(!ready){log.warn(`Native window skipped because the frontend did not answer within ${readinessTimeoutMs/1000}s`);return}closeNativeApp=await launchNativeAppWindow(nativeUrl,options)}):Promise.resolve();const waitingOn=new Set(ports);const bootStartedMs=Date.now();let progressLines=0;let nextProgressAt=DEV_BOOT_PROGRESS_EVERY_SECONDS;const progress=setInterval(()=>{const elapsed=(Date.now()-bootStartedMs)/1000;if(elapsed<nextProgressAt)return;nextProgressAt+=DEV_BOOT_PROGRESS_EVERY_SECONDS;const line=devBootProgressLine(elapsed,[...waitingOn],options.verbose);if(!line)return;console.log(` ${dim(line)}`);progressLines++},1000);progress.unref?.();Promise.all(ports.map((p)=>waitForPort(p.port,Number.POSITIVE_INFINITY).then(()=>waitingOn.delete(p)))).then(async()=>{clearInterval(progress);if(readyAnnounced)return;readyAnnounced=true;let proxyReachable=false;if(hasCustomDomain&&domain){(async()=>{try{await rpxTlsPreflight;await registerRpxProxiesForDomain({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options})}catch{}})();proxyReachable=await waitForHttpsProxy(443,16000);if(!proxyReachable){console.log(` ${yellow("⚠")} ${yellow("HTTPS proxy not reachable on :443")} - serving ${cyan(`http://localhost:${frontendPort}`)} instead`);console.log(` ${dim(" ")}${dim("rpx needs a valid SUDO_PASSWORD in .env to bind :443; trust the local CA, then restart `./buddy dev`.")}`);if(options.verbose)console.log(` ${dim(" ")}${dim(`Trust CA: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}}eraseDevBootStartingLines(progressLines);printDevReadyBanner({options,nativeMode,hasCustomDomain:!!appLooksCustom&&!localhostOnly,proxyReachable:proxyManagedExternally?true:proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain});if(!nativeMode){const browserUrl=hasCustomDomain&&(proxyManagedExternally||proxyReachable)?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);openDevelopmentBrowser(browserUrl)}if(startedAt){const elapsedMs=(Bun.nanoseconds()-startedAt)/1e6;console.log(` ${dim(`ready in ${(elapsedMs/1000).toFixed(1)}s`)}`);console.log();printDevEngineNotes();console.log()}if(process.env.STACKS_PRINT_ROUTES==="1"){await printRegisteredRoutes(apiPort).catch(()=>{})}}).catch(()=>{});await Promise.all([a.runFrontendDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Frontend: ${error}`)}),a.runApiDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`API: ${error}`)}),a.runDocsDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Docs: ${error}`)}),includeDashboard?a.runDashboardDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Dashboard: ${error}`)}):Promise.resolve(),nativeWindowReady.catch((error)=>{if(options.verbose)log.warn(`Native window: ${error}`)})])}function isComingSoonMode(){if(existsSync(projectPath("storage/framework/coming-soon")))return true;try{const idx=projectPath("resources/views/index.stx");return existsSync(idx)&&/siteMode\s*=\s*['"]coming-soon['"]/.test(readFileSync(idx,"utf8"))}catch{return false}}function blogIsConfigured(){try{const dir=projectPath("content/blog");return existsSync(dir)&&readdirSync(dir).some((f)=>f.endsWith(".md"))}catch{return false}}function printDevReadyBanner(input){const{options,nativeMode,hasCustomDomain,proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain}=input;const verbose=options.verbose??false;const useProxy=hasCustomDomain&&proxyReachable;const feUrl=useProxy?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);const feBaseUrl=useProxy?frontendBaseUrl:`http://localhost:${frontendPort}`;const apUrl=useProxy?apiUrl:`http://localhost:${apiPort}`;const dcUrl=useProxy?docsUrl:`http://localhost:${docsPort}`;const dbUrl=useProxy?dashboardUrl:`http://localhost:${dashboardPort}`;const blogUrl=`${feBaseUrl}/blog`;console.log();const frontendLabel=entryPath==="/"?"Site":"App";console.log(` ${green("➜")} ${bold(frontendLabel.padEnd(8))}: ${cyan(feUrl)}`);if(entryPath!=="/")console.log(` ${dim("➜")} ${dim("Site")}: ${dim(feBaseUrl)}`);if(nativeMode)console.log(` ${green("➜")} ${bold("Native")}: ${cyan(`Craft → ${feUrl}`)}`);console.log(` ${green("➜")} ${bold("API")}: ${cyan(apUrl)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(dcUrl)}`);if(blogIsConfigured())console.log(` ${green("➜")} ${bold("Blog")}: ${cyan(blogUrl)}`);if(includeDashboard)console.log(` ${green("➜")} ${bold("Dashboard")}: ${cyan(dbUrl)}`);if(useProxy){console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`${developmentUrl(`http://localhost:${frontendPort}`,entryPath)} (bypasses the proxy)`)}`);if(includeDashboard&&dashboardDomain)console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`http://localhost:${dashboardPort} (dashboard, bypasses the proxy)`)}`)}if(isComingSoonMode()){console.log();console.log(` ${yellow("●")} ${bold(yellow("Coming soon mode"))} ${dim("- visitors see the holding page; bypass with the coming-soon secret.")}`)}if(verbose&&domain){console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${frontendPort} → ${domain}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/api → localhost:${apiPort}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/docs → localhost:${docsPort}`)}`);if(includeDashboard)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} → ${dashboardDomain}`)}`)}console.log()}function printDevEngineNotes(){const routesFile=stxPath("routes.ts");const routesLabel=relative(projectPath(),routesFile);const hasCssEngine=["config/css.ts","css.config.ts","config/crosswind.ts","crosswind.config.ts"].some((config)=>existsSync(join(projectPath(),config)));if(hasCssEngine)console.log(` ${green("[ts-css]")} ${dim("CSS engine loaded")}`);if(existsSync(routesFile)){try{const source=readFileSync(routesFile,"utf8");const routeCount=(source.match(/pattern:/g)??[]).length;if(routeCount>0)console.log(` ${green("[stx]")} ${dim(`Generated ${routeCount} routes → ${routesLabel}`)}`)}catch{console.log(` ${green("[stx]")} ${dim(`Routes manifest → ${routesLabel}`)}`)}}}async function launchNativeAppWindow(url,options){let createApp;try{const craft=await importCraftSdk();createApp=craft.createApp}catch(error){if(options.verbose)log.warn(`Native window unavailable: ${error}`);console.log(` ${dim("Native window unavailable. Install craft-native or set CRAFT_BIN to a Craft binary.")}
2
2
  `);return}if(!createApp){console.log(` ${dim("Native window unavailable. The Craft SDK did not export createApp.")}
3
3
  `);return}const craftBinaryPath=resolveCraftBinaryPath();if(!craftBinaryPath){console.log(` ${dim("Native window unavailable. Set CRAFT_BIN to a Craft binary, or install Craft in ~/Code/Tools/craft.")}
4
- `);return}const appIconPath=resolveNativeAppIconPath(),app=createApp({url,quiet:!options.verbose,craftPath:craftBinaryPath,window:{title:await resolveNativeAppTitle(),width:1280,height:860,titlebarHidden:!0,webSidebarMaterial:!0,webSidebarWidth:286,webSidebarMaterialOpacity:0.78,...appIconPath&&{icon:appIconPath}}});app.show().catch((error)=>{if(options.verbose)log.warn(`Native window exited: ${error}`)});return()=>app.close()}async function importCraftSdk(){const localCraftSdk=process.env.HOME?`${process.env.HOME}/Code/Tools/craft/packages/typescript/src/index.ts`:void 0;if(localCraftSdk&&existsSync(localCraftSdk))return await import(localCraftSdk);const packageNames=["craft-native","@craft-native/craft","@stacksjs/ts-craft"];let primaryError;for(const packageName of packageNames)try{return await import(packageName)}catch(error){primaryError??=error}throw primaryError}async function cleanupStaleDevProcesses(ports){const projectRoot=projectPath(),actionDevPath=projectPath("storage/framework/core/actions/src/dev/"),pids=new Set;for(const port of ports)for(const pid of await listenerPids(port)){if(pid===process.pid)continue;const command=await commandForPid(pid);if(!command.includes(projectRoot))continue;if(command.includes("storage/framework/core/buddy/src/cli.ts dev")||command.includes("storage/framework/core/actions/src/dev/")||command.includes(actionDevPath))pids.add(pid)}if(pids.size===0)return;for(const pid of pids)try{process.kill(pid,"SIGTERM")}catch{}await new Promise((r)=>setTimeout(r,250));for(const pid of pids)try{process.kill(pid,"SIGKILL")}catch{}await new Promise((r)=>setTimeout(r,150))}async function listenerPids(port){try{const proc=Bun.spawn(["lsof","-nP",`-iTCP:${port}`,"-sTCP:LISTEN","-t"],{stdout:"pipe",stderr:"ignore"}),output=await new Response(proc.stdout).text();await proc.exited;return output.split(/\s+/).map((value)=>Number(value)).filter((pid)=>Number.isInteger(pid)&&pid>0)}catch{return[]}}async function commandForPid(pid){try{const proc=Bun.spawn(["ps","-p",String(pid),"-o","command="],{stdout:"pipe",stderr:"ignore"}),output=await new Response(proc.stdout).text();await proc.exited;return output.trim()}catch{return""}}function resolveCraftBinaryPath(){const home=process.env.HOME;return[process.env.CRAFT_BIN,home?`${home}/Code/Tools/craft/craft`:void 0,home?`${home}/Code/Tools/craft/bin/craft`:void 0,home?`${home}/Code/Tools/craft/packages/zig/zig-out/bin/craft`:void 0,home?`${home}/Documents/Projects/craft/packages/zig/zig-out/bin/craft`:void 0].filter((candidate)=>Boolean(candidate)).find((candidate)=>existsSync(candidate))}function resolveNativeAppIconPath(){return[projectPath("resources/assets/images/app-icon.png"),projectPath("resources/assets/images/icon.png"),projectPath("public/icon.png")].find((candidate)=>existsSync(candidate))}async function resolveNativeAppTitle(){try{const pkg=await Bun.file(projectPath("package.json")).json(),name=typeof pkg.productName==="string"?pkg.productName:pkg.name;if(typeof name==="string"&&name.length>0)return name.split(/[-_\s]+/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}catch{}return"Stacks App"}const METHOD_COLORS={GET:cyan,POST:green,PUT:cyan,PATCH:cyan,DELETE:cyan,OPTIONS:dim};async function printRegisteredRoutes(apiPort){try{const ac=new AbortController,t=setTimeout(()=>ac.abort(),1500),res=await fetch(`http://127.0.0.1:${apiPort}/__routes`,{signal:ac.signal}).catch(()=>null);clearTimeout(t);if(!res||!res.ok)return;const routes=await res.json();if(!Array.isArray(routes)||routes.length===0)return;const sorted=[...routes].sort((a,b)=>a.path.localeCompare(b.path)||a.method.localeCompare(b.method)),longestPath=Math.max(...sorted.map((r)=>r.path.length));console.log(` ${dim("Registered routes")}
5
- `);for(const r of sorted){const method=(METHOD_COLORS[r.method.toUpperCase()]??dim)(r.method.toUpperCase().padEnd(6)),path=r.path.padEnd(longestPath),named=r.name?` ${dim(`(${r.name})`)}`:"";console.log(` ${method} ${path}${named}`)}console.log()}catch{}}async function probeDevServerHttp(port){for(const path of["/__health","/"])if(await new Promise((resolve)=>{const ac=new AbortController,t=setTimeout(()=>ac.abort(),path==="/"?8000:800);fetch(`http://127.0.0.1:${port}${path}`,{signal:ac.signal,redirect:"manual"}).then(()=>{clearTimeout(t);resolve(!0)}).catch(()=>{clearTimeout(t);resolve(!1)})}))return!0;return!1}async function findAvailablePort(preferred,attempts=20){for(let port=preferred;port<preferred+attempts;port++)if(await portIsFree(port))return port;return preferred}async function portIsFree(port){for(const host of["127.0.0.1","::1"])if(await someoneIsListening(port,host))return!1;let server;try{server=Bun.serve({port,hostname:"0.0.0.0",reusePort:!1,fetch:()=>new Response})}catch{return!1}server.stop(!0);return!0}async function someoneIsListening(port,host){const{connect}=await import("node:net");return new Promise((resolve)=>{const socket=connect({port,host}),finish=(listening)=>{socket.destroy();resolve(listening)};socket.setTimeout(300,()=>finish(!1));socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1))})}async function waitForPort(port,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(await probeDevServerHttp(port))return!0;await new Promise((r)=>setTimeout(r,50))}return!1}async function waitForHttpsProxy(port,timeoutMs){const{connect}=await import("node:net"),deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(await new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(v)=>{try{socket.destroy()}catch{}resolve(v)};socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1));setTimeout(()=>finish(!1),800).unref?.()}))return!0;await new Promise((r)=>setTimeout(r,200))}return!1}const RPX_SSL_DIR=join(homedir(),".stacks","ssl"),RPX_ROOT_CA_PATH=join(RPX_SSL_DIR,"rpx-root-ca.crt"),RPX_HOST_CERT_PATH=join(RPX_SSL_DIR,"rpx.localhost.crt");function buildDevelopmentTlsHostnames(domain,includeDashboard){return[domain,...includeDashboard?[`dashboard.${domain}`]:[],"rpx.localhost"]}async function ensureRpxDevelopmentHttps(domain,options,includeDashboard,trustCertificate=!0){const verbose=options.verbose??!1,{buildRegistryTlsProxyOptions,certIncludesSanHostnames,checkExistingCertificates,clearSslConfigCache,forceTrustCertificate,generateCertificate,getRegistryDir,isDaemonRunning,isRootCaTrustedForSsl,readAll,readCertCommonName,stopDaemon,trustRootCaForBrowsers,verifyHttpsChain}=await importDevelopmentRpx(),hostnames=buildDevelopmentTlsHostnames(domain,includeDashboard),entries=await readAll(getRegistryDir(),!1).catch(()=>[]);for(const entry of entries){const host=entry.to?.trim();if(host&&!hostnames.includes(host))hostnames.push(host)}const tlsOptions=buildRegistryTlsProxyOptions(hostnames,domain,verbose),hostnameInCert=certIncludesSanHostnames(RPX_HOST_CERT_PATH,hostnames),cnMatchesApp=readCertCommonName(RPX_HOST_CERT_PATH)===domain;let certRegenerated=!1;if(!await checkExistingCertificates(tlsOptions)||!hostnameInCert||!cnMatchesApp){clearSslConfigCache();await generateCertificate({...tlsOptions,forceRegenerate:!0});certRegenerated=!0}let trusted=isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(!trusted&&trustCertificate){trusted=trustRootCaForBrowsers(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||await forceTrustCertificate(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(trusted)console.log(` ${green("\u2713")} ${dim("HTTPS")}: ${dim("Local CA trusted - reload the browser if you still see a warning")}`);else console.log(` ${yellow("\u26A0")} ${yellow("HTTPS")}: ${yellow(`Local CA not trusted \u2014 run: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}else if(verbose)console.log(` ${green("\u2713")} ${dim("HTTPS")}: ${dim("Local certificate trusted for SSL")}`);const chainOk=existsSync(RPX_ROOT_CA_PATH)?await verifyHttpsChain(domain,RPX_ROOT_CA_PATH):!1;if((certRegenerated||!hostnameInCert||!cnMatchesApp)&&await isDaemonRunning()){await stopDaemon({timeoutMs:8000}).catch(()=>{});if(verbose)log.info("Restarting rpx daemon to load TLS certificates for this app")}else if(!chainOk&&verbose)console.log(` ${dim(" ")}${dim("HTTPS chain not yet valid on :443 - daemon will (re)start after backends are ready")}`)}function resolveRpxDaemonSpawnCwd(){const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return dirname(fromEnv);const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return dirname(bootstrap);return homedir()}async function resolveRpxDaemonSpawnCommand(){const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return[process.execPath,bootstrap];const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return[fromEnv,"daemon:start"];const pkgUrl=import.meta.resolve("@stacksjs/rpx/package.json"),cli=join(dirname(fileURLToPath(pkgUrl)),"dist/bin/cli.js");return[process.execPath,cli,"daemon:start"]}function buildRpxProxySpecs(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard}=input,dashboardDomain=`dashboard.${domain}`;return[{id:`${domain}-frontend`,from:`localhost:${frontendPort}`,to:domain,pathRewrites:[{from:"/api",to:`localhost:${apiPort}`,stripPrefix:!1},{from:"/docs",to:`localhost:${docsPort}`,stripPrefix:!0}]},...includeDashboard?[{id:`${domain}-dashboard`,from:`localhost:${dashboardPort}`,to:dashboardDomain}]:[]]}async function unregisterRpxProxies(ids){if(ids.length===0)return;try{const{removeEntry}=await importDevelopmentRpx();for(const id of ids)await removeEntry(id).catch(()=>{})}catch{}}async function removeStalePublicDomainOverrides(domain,includeDashboard,verbose){const{checkHosts,removeHosts,resolverFilePath,contentLooksLikeRpxResolver}=await importDevelopmentRpx(),hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]],present=await checkHosts(hosts,verbose).catch(()=>hosts.map(()=>!1)),staleHosts=hosts.filter((_,i)=>present[i]===!0);if(staleHosts.length>0){await removeHosts(staleHosts,verbose).catch(()=>{});if((await checkHosts(staleHosts,verbose).catch(()=>staleHosts.map(()=>!0))).some(Boolean))log.warn(`Stale /etc/hosts entries still point ${staleHosts.join(", ")} at loopback. Remove them with: sudo nano /etc/hosts`);else log.info(`Removed stale /etc/hosts entries for ${staleHosts.join(", ")} (left by a previous dev session)`)}if(process.platform!=="darwin")return;const labels=domain.split("."),basename=labels.length>=2?labels.slice(-2).join("."):domain,resolverPath=resolverFilePath(basename);let isRpxManaged=!1;try{isRpxManaged=contentLooksLikeRpxResolver(readFileSync(resolverPath,"utf8"))}catch{}if(!isRpxManaged)return;const quotedPath=`'${resolverPath.replace(/'/g,"'\\''")}'`,rm=process.env.SUDO_PASSWORD?`printf '%s
6
- ' "$SUDO_PASSWORD" | sudo -S rm -f ${quotedPath}`:`sudo -n rm -f ${quotedPath}`;try{execSync(rm,{stdio:["pipe","ignore","ignore"]});log.info(`Removed stale rpx DNS resolver ${resolverPath} (left by a previous dev session)`);execSync("sudo -n dscacheutil -flushcache; sudo -n killall -HUP mDNSResponder; true",{stdio:["pipe","ignore","ignore"]})}catch{log.warn(`A stale rpx DNS resolver still hijacks ${domain}. Remove it with: sudo rm ${resolverPath}`)}}async function prepareRpxTlsForDev(input){const{domain,includeDashboard,options,skipHosts=!1,trustCertificate=!0}=input,verbose=options.verbose??!1,hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]],hostsNeedingFile=hosts.filter((host)=>{const h=host.trim().toLowerCase();return h!=="localhost"&&!h.endsWith(".localhost")&&!h.endsWith(".localhost.")}),{addHosts,setupDevelopmentDns}=await importDevelopmentRpx(),dnsDomains=!skipHosts&&hostsNeedingFile.length>0?hosts:[];if(dnsDomains.length>0){if(!await setupDevelopmentDns({domains:dnsDomains,verbose}).catch(()=>!1)&&verbose)log.warn(`Dev DNS not configured for ${dnsDomains.join(", ")} - falling back to /etc/hosts`)}if(!skipHosts&&hostsNeedingFile.length>0)await addHosts(hostsNeedingFile,verbose).catch((err)=>{log.warn(`Could not update /etc/hosts for ${hostsNeedingFile.join(", ")}: ${err.message}`);log.warn("Add 127.0.0.1 entries manually or set SUDO_PASSWORD in .env")});await ensureRpxDevelopmentHttps(domain,options,includeDashboard,trustCertificate)}export async function setupPrettyDevEnvironment(input){const domain=resolvePrettyDevDomain(input.domain??process.env.APP_URL??"stacks.localhost");if(!domain){log.info("APP_URL already uses localhost; no pretty URL setup is needed");return!0}const rpx=await importDevelopmentRpx();if(!rpx.authorizeSystemAccess({interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0})){log.error("Pretty URL setup needs administrator authorization to bind ports 80 and 443 and trust the local CA");return!1}await prepareRpxTlsForDev({domain,includeDashboard:process.env.STACKS_DEV_DASHBOARD==="1",options:{verbose:input.verbose},skipHosts:input.skipHosts,trustCertificate:!input.skipTrust});const spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(input.verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;await startRpxDaemonIfNeeded({spawnCommand:await resolveRpxDaemonSpawnCommand(),spawnEnv,verbose:input.verbose??!1,stopRpx:rpx.stopDaemon});const ready=await waitForHttpsProxy(443,5000);if(ready)log.success(`Pretty URLs are ready at https://${domain}`);else log.error("rpx did not become reachable on port 443");return ready}async function startRpxDaemonIfNeeded(input){const{ensureDaemonRunning,isDaemonRunning:isRpxUp}=await importDevelopmentRpx();if(await isRpxUp()){if(await waitForHttpsProxy(443,1500))return;await input.stopRpx({timeoutMs:5000}).catch(()=>{})}const spawnOpts={spawnCommand:input.spawnCommand,spawnCwd:resolveRpxDaemonSpawnCwd(),startupTimeoutMs:45000,spawnEnv:input.spawnEnv,verbose:input.verbose};try{await ensureDaemonRunning(spawnOpts)}catch(firstError){await input.stopRpx({timeoutMs:5000}).catch(()=>{});await ensureDaemonRunning(spawnOpts).catch(()=>{throw firstError})}}async function registerRpxProxiesForDomain(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options}=input,verbose=options.verbose??!1,proxies=buildRpxProxySpecs({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard});await unregisterRpxProxies([`${domain}-api`,`${domain}-docs`]);const{getRegistryDir,readAll,stopDaemon:stopRpx,syncDevelopmentDnsFromRegistry,writeEntry}=await importDevelopmentRpx(),spawnCommand=await resolveRpxDaemonSpawnCommand(),spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;try{await startRpxDaemonIfNeeded({spawnCommand,spawnEnv,verbose,stopRpx})}catch(error){const{isDaemonRunning}=await importDevelopmentRpx();if(!await isDaemonRunning())throw error;if(verbose){const message=error instanceof Error?error.message:String(error);console.log(` ${dim(" ")}${dim(`rpx daemon spawn skipped (${message}); reusing existing daemon`)}`)}}const createdAt=new Date().toISOString();for(const proxy of proxies){await writeEntry({id:proxy.id,from:proxy.from,to:proxy.to,cwd:process.cwd(),createdAt,pid:process.pid,pathRewrites:proxy.pathRewrites},void 0,verbose);if(!activeRpxRegistryIds.includes(proxy.id))activeRpxRegistryIds.push(proxy.id);if(verbose)console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`https://${proxy.to} \u2192 ${proxy.from}`)}`)}const registryDir=getRegistryDir(),entries=await readAll(registryDir,verbose).catch(()=>[]);await syncDevelopmentDnsFromRegistry(entries,{verbose,ownerPid:process.pid}).catch((err)=>{if(verbose){const message=err instanceof Error?err.message:String(err);console.log(` ${dim(" ")}${dim(`Dev DNS sync: ${message}`)}`)}})}function wantsInteractive(options){return options.interactive}
4
+ `);return}const appIconPath=resolveNativeAppIconPath();const app=createApp({url,quiet:!options.verbose,craftPath:craftBinaryPath,window:{title:await resolveNativeAppTitle(),width:1280,height:860,titlebarHidden:true,webSidebarMaterial:true,webSidebarWidth:286,webSidebarMaterialOpacity:0.78,...appIconPath&&{icon:appIconPath}}});app.show().catch((error)=>{if(options.verbose)log.warn(`Native window exited: ${error}`)});return()=>app.close()}async function importCraftSdk(){const localCraftSdk=process.env.HOME?`${process.env.HOME}/Code/Tools/craft/packages/typescript/src/index.ts`:undefined;if(localCraftSdk&&existsSync(localCraftSdk))return await import(localCraftSdk);const packageNames=["craft-native","@craft-native/craft","@stacksjs/ts-craft"];let primaryError;for(const packageName of packageNames){try{return await import(packageName)}catch(error){primaryError??=error}}throw primaryError}async function cleanupStaleDevProcesses(ports){const projectRoot=projectPath();const actionDevPath=projectPath("storage/framework/core/actions/src/dev/");const pids=new Set;for(const port of ports){for(const pid of await listenerPids(port)){if(pid===process.pid)continue;const command=await commandForPid(pid);if(!command.includes(projectRoot))continue;const isStacksDevProcess=command.includes("storage/framework/core/buddy/src/cli.ts dev")||command.includes("storage/framework/core/actions/src/dev/")||command.includes(actionDevPath);if(isStacksDevProcess)pids.add(pid)}}if(pids.size===0)return;for(const pid of pids){try{process.kill(pid,"SIGTERM")}catch{}}await new Promise((r)=>setTimeout(r,250));for(const pid of pids){try{process.kill(pid,"SIGKILL")}catch{}}await new Promise((r)=>setTimeout(r,150))}async function listenerPids(port){try{const proc=Bun.spawn(["lsof","-nP",`-iTCP:${port}`,"-sTCP:LISTEN","-t"],{stdout:"pipe",stderr:"ignore"});const output=await new Response(proc.stdout).text();await proc.exited;return output.split(/\s+/).map((value)=>Number(value)).filter((pid)=>Number.isInteger(pid)&&pid>0)}catch{return[]}}async function commandForPid(pid){try{const proc=Bun.spawn(["ps","-p",String(pid),"-o","command="],{stdout:"pipe",stderr:"ignore"});const output=await new Response(proc.stdout).text();await proc.exited;return output.trim()}catch{return""}}function resolveCraftBinaryPath(){const home=process.env.HOME;const candidates=[process.env.CRAFT_BIN,home?`${home}/Code/Tools/craft/craft`:undefined,home?`${home}/Code/Tools/craft/bin/craft`:undefined,home?`${home}/Code/Tools/craft/packages/zig/zig-out/bin/craft`:undefined,home?`${home}/Documents/Projects/craft/packages/zig/zig-out/bin/craft`:undefined].filter((candidate)=>Boolean(candidate));return candidates.find((candidate)=>existsSync(candidate))}function resolveNativeAppIconPath(){const candidates=[projectPath("resources/assets/images/app-icon.png"),projectPath("resources/assets/images/icon.png"),projectPath("public/icon.png")];return candidates.find((candidate)=>existsSync(candidate))}async function resolveNativeAppTitle(){try{const pkg=await Bun.file(projectPath("package.json")).json();const name=typeof pkg.productName==="string"?pkg.productName:pkg.name;if(typeof name==="string"&&name.length>0){return name.split(/[-_\s]+/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}}catch{}return"Stacks App"}const METHOD_COLORS={GET:cyan,POST:green,PUT:cyan,PATCH:cyan,DELETE:cyan,OPTIONS:dim};async function printRegisteredRoutes(apiPort){try{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),1500);const res=await fetch(`http://127.0.0.1:${apiPort}/__routes`,{signal:ac.signal}).catch(()=>null);clearTimeout(t);if(!res||!res.ok)return;const routes=await res.json();if(!Array.isArray(routes)||routes.length===0)return;const sorted=[...routes].sort((a,b)=>a.path.localeCompare(b.path)||a.method.localeCompare(b.method));const longestPath=Math.max(...sorted.map((r)=>r.path.length));console.log(` ${dim("Registered routes")}
5
+ `);for(const r of sorted){const color=METHOD_COLORS[r.method.toUpperCase()]??dim;const method=color(r.method.toUpperCase().padEnd(6));const path=r.path.padEnd(longestPath);const named=r.name?` ${dim(`(${r.name})`)}`:"";console.log(` ${method} ${path}${named}`)}console.log()}catch{}}async function probeDevServerHttp(port){for(const path of["/__health","/"]){const ok=await new Promise((resolve)=>{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),path==="/"?8000:800);fetch(`http://127.0.0.1:${port}${path}`,{signal:ac.signal,redirect:"manual"}).then(()=>{clearTimeout(t);resolve(true)}).catch(()=>{clearTimeout(t);resolve(false)})});if(ok)return true}return false}async function findAvailablePort(preferred,attempts=20){for(let port=preferred;port<preferred+attempts;port++){if(await portIsFree(port))return port}return preferred}async function portIsFree(port){for(const host of["127.0.0.1","::1"]){if(await someoneIsListening(port,host))return false}let server;try{server=Bun.serve({port,hostname:"0.0.0.0",reusePort:false,fetch:()=>new Response})}catch{return false}server.stop(true);return true}async function someoneIsListening(port,host){const{connect}=await import("node:net");return new Promise((resolve)=>{const socket=connect({port,host});const finish=(listening)=>{socket.destroy();resolve(listening)};socket.setTimeout(300,()=>finish(false));socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false))})}async function waitForPort(port,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(await probeDevServerHttp(port))return true;await new Promise((r)=>setTimeout(r,50))}return false}async function waitForHttpsProxy(port,timeoutMs){const{connect}=await import("node:net");const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const ok=await new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"});const finish=(v)=>{try{socket.destroy()}catch{}resolve(v)};socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false));setTimeout(()=>finish(false),800).unref?.()});if(ok)return true;await new Promise((r)=>setTimeout(r,200))}return false}const RPX_SSL_DIR=join(homedir(),".stacks","ssl");const RPX_ROOT_CA_PATH=join(RPX_SSL_DIR,"rpx-root-ca.crt");const RPX_HOST_CERT_PATH=join(RPX_SSL_DIR,"rpx.localhost.crt");function buildDevelopmentTlsHostnames(domain,includeDashboard){return[domain,...includeDashboard?[`dashboard.${domain}`]:[],"rpx.localhost"]}async function ensureRpxDevelopmentHttps(domain,options,includeDashboard,trustCertificate=true){const verbose=options.verbose??false;const{buildRegistryTlsProxyOptions,certIncludesSanHostnames,checkExistingCertificates,clearSslConfigCache,forceTrustCertificate,generateCertificate,getRegistryDir,isDaemonRunning,isRootCaTrustedForSsl,readAll,readCertCommonName,stopDaemon,trustRootCaForBrowsers,verifyHttpsChain}=await importDevelopmentRpx();const hostnames=buildDevelopmentTlsHostnames(domain,includeDashboard);const entries=await readAll(getRegistryDir(),false).catch(()=>[]);for(const entry of entries){const host=entry.to?.trim();if(host&&!hostnames.includes(host))hostnames.push(host)}const tlsOptions=buildRegistryTlsProxyOptions(hostnames,domain,verbose);const hostnameInCert=certIncludesSanHostnames(RPX_HOST_CERT_PATH,hostnames);const cnMatchesApp=readCertCommonName(RPX_HOST_CERT_PATH)===domain;let certRegenerated=false;const existing=await checkExistingCertificates(tlsOptions);if(!existing||!hostnameInCert||!cnMatchesApp){clearSslConfigCache();await generateCertificate({...tlsOptions,forceRegenerate:true});certRegenerated=true}let trusted=isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(!trusted&&trustCertificate){trusted=trustRootCaForBrowsers(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||await forceTrustCertificate(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(trusted)console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local CA trusted - reload the browser if you still see a warning")}`);else console.log(` ${yellow("⚠")} ${yellow("HTTPS")}: ${yellow(`Local CA not trusted — run: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}else if(verbose){console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local certificate trusted for SSL")}`)}const chainOk=existsSync(RPX_ROOT_CA_PATH)?await verifyHttpsChain(domain,RPX_ROOT_CA_PATH):false;if((certRegenerated||!hostnameInCert||!cnMatchesApp)&&await isDaemonRunning()){await stopDaemon({timeoutMs:8000}).catch(()=>{});if(verbose)log.info("Restarting rpx daemon to load TLS certificates for this app")}else if(!chainOk&&verbose){console.log(` ${dim(" ")}${dim("HTTPS chain not yet valid on :443 - daemon will (re)start after backends are ready")}`)}}function resolveRpxDaemonSpawnCwd(){const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return dirname(fromEnv);const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return dirname(bootstrap);return homedir()}async function resolveRpxDaemonSpawnCommand(){const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return[process.execPath,bootstrap];const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return[fromEnv,"daemon:start"];const pkgUrl=import.meta.resolve("@stacksjs/rpx/package.json");const cli=join(dirname(fileURLToPath(pkgUrl)),"dist/bin/cli.js");return[process.execPath,cli,"daemon:start"]}function buildRpxProxySpecs(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard}=input;const dashboardDomain=`dashboard.${domain}`;return[{id:`${domain}-frontend`,from:`localhost:${frontendPort}`,to:domain,pathRewrites:[{from:"/api",to:`localhost:${apiPort}`,stripPrefix:false},{from:"/docs",to:`localhost:${docsPort}`,stripPrefix:true}]},...includeDashboard?[{id:`${domain}-dashboard`,from:`localhost:${dashboardPort}`,to:dashboardDomain}]:[]]}async function unregisterRpxProxies(ids){if(ids.length===0)return;try{const{removeEntry}=await importDevelopmentRpx();for(const id of ids)await removeEntry(id).catch(()=>{})}catch{}}async function removeStalePublicDomainOverrides(domain,includeDashboard,verbose){const{checkHosts,removeHosts,resolverFilePath,contentLooksLikeRpxResolver}=await importDevelopmentRpx();const hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]];const present=await checkHosts(hosts,verbose).catch(()=>hosts.map(()=>false));const staleHosts=hosts.filter((_,i)=>present[i]===true);if(staleHosts.length>0){await removeHosts(staleHosts,verbose).catch(()=>{});const remaining=await checkHosts(staleHosts,verbose).catch(()=>staleHosts.map(()=>true));if(remaining.some(Boolean))log.warn(`Stale /etc/hosts entries still point ${staleHosts.join(", ")} at loopback. Remove them with: sudo nano /etc/hosts`);else log.info(`Removed stale /etc/hosts entries for ${staleHosts.join(", ")} (left by a previous dev session)`)}if(process.platform!=="darwin")return;const labels=domain.split(".");const basename=labels.length>=2?labels.slice(-2).join("."):domain;const resolverPath=resolverFilePath(basename);let isRpxManaged=false;try{isRpxManaged=contentLooksLikeRpxResolver(readFileSync(resolverPath,"utf8"))}catch{}if(!isRpxManaged)return;const quotedPath=`'${resolverPath.replace(/'/g,`'\\''`)}'`;const rm=process.env.SUDO_PASSWORD?`printf '%s
6
+ ' "$SUDO_PASSWORD" | sudo -S rm -f ${quotedPath}`:`sudo -n rm -f ${quotedPath}`;try{execSync(rm,{stdio:["pipe","ignore","ignore"]});log.info(`Removed stale rpx DNS resolver ${resolverPath} (left by a previous dev session)`);execSync("sudo -n dscacheutil -flushcache; sudo -n killall -HUP mDNSResponder; true",{stdio:["pipe","ignore","ignore"]})}catch{log.warn(`A stale rpx DNS resolver still hijacks ${domain}. Remove it with: sudo rm ${resolverPath}`)}}async function prepareRpxTlsForDev(input){const{domain,includeDashboard,options,skipHosts=false,trustCertificate=true}=input;const verbose=options.verbose??false;const hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]];const hostsNeedingFile=hosts.filter((host)=>{const h=host.trim().toLowerCase();return h!=="localhost"&&!h.endsWith(".localhost")&&!h.endsWith(".localhost.")});const{addHosts,setupDevelopmentDns}=await importDevelopmentRpx();const dnsDomains=!skipHosts&&hostsNeedingFile.length>0?hosts:[];if(dnsDomains.length>0){const dnsReady=await setupDevelopmentDns({domains:dnsDomains,verbose}).catch(()=>false);if(!dnsReady&&verbose)log.warn(`Dev DNS not configured for ${dnsDomains.join(", ")} - falling back to /etc/hosts`)}if(!skipHosts&&hostsNeedingFile.length>0){await addHosts(hostsNeedingFile,verbose).catch((err)=>{log.warn(`Could not update /etc/hosts for ${hostsNeedingFile.join(", ")}: ${err.message}`);log.warn("Add 127.0.0.1 entries manually or set SUDO_PASSWORD in .env")})}await ensureRpxDevelopmentHttps(domain,options,includeDashboard,trustCertificate)}export async function setupPrettyDevEnvironment(input){const domain=resolvePrettyDevDomain(input.domain??process.env.APP_URL??"stacks.localhost");if(!domain){log.info("APP_URL already uses localhost; no pretty URL setup is needed");return true}const rpx=await importDevelopmentRpx();if(!rpx.authorizeSystemAccess({interactive:process.stdin.isTTY===true&&process.stdout.isTTY===true})){log.error("Pretty URL setup needs administrator authorization to bind ports 80 and 443 and trust the local CA");return false}await prepareRpxTlsForDev({domain,includeDashboard:process.env.STACKS_DEV_DASHBOARD==="1",options:{verbose:input.verbose},skipHosts:input.skipHosts,trustCertificate:!input.skipTrust});const spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(input.verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;await startRpxDaemonIfNeeded({spawnCommand:await resolveRpxDaemonSpawnCommand(),spawnEnv,verbose:input.verbose??false,stopRpx:rpx.stopDaemon});const ready=await waitForHttpsProxy(443,5000);if(ready)log.success(`Pretty URLs are ready at https://${domain}`);else log.error("rpx did not become reachable on port 443");return ready}async function startRpxDaemonIfNeeded(input){const{ensureDaemonRunning,isDaemonRunning:isRpxUp}=await importDevelopmentRpx();if(await isRpxUp()){if(await waitForHttpsProxy(443,1500))return;await input.stopRpx({timeoutMs:5000}).catch(()=>{})}const spawnOpts={spawnCommand:input.spawnCommand,spawnCwd:resolveRpxDaemonSpawnCwd(),startupTimeoutMs:45000,spawnEnv:input.spawnEnv,verbose:input.verbose};try{await ensureDaemonRunning(spawnOpts)}catch(firstError){await input.stopRpx({timeoutMs:5000}).catch(()=>{});await ensureDaemonRunning(spawnOpts).catch(()=>{throw firstError})}}async function registerRpxProxiesForDomain(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options}=input;const verbose=options.verbose??false;const proxies=buildRpxProxySpecs({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard});await unregisterRpxProxies([`${domain}-api`,`${domain}-docs`]);const{getRegistryDir,readAll,stopDaemon:stopRpx,syncDevelopmentDnsFromRegistry,writeEntry}=await importDevelopmentRpx();const spawnCommand=await resolveRpxDaemonSpawnCommand();const spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;try{await startRpxDaemonIfNeeded({spawnCommand,spawnEnv,verbose,stopRpx})}catch(error){const{isDaemonRunning}=await importDevelopmentRpx();if(!await isDaemonRunning())throw error;if(verbose){const message=error instanceof Error?error.message:String(error);console.log(` ${dim(" ")}${dim(`rpx daemon spawn skipped (${message}); reusing existing daemon`)}`)}}const createdAt=new Date().toISOString();for(const proxy of proxies){await writeEntry({id:proxy.id,from:proxy.from,to:proxy.to,cwd:process.cwd(),createdAt,pid:process.pid,pathRewrites:proxy.pathRewrites},undefined,verbose);if(!activeRpxRegistryIds.includes(proxy.id))activeRpxRegistryIds.push(proxy.id);if(verbose)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`https://${proxy.to} → ${proxy.from}`)}`)}const registryDir=getRegistryDir();const entries=await readAll(registryDir,verbose).catch(()=>[]);await syncDevelopmentDnsFromRegistry(entries,{verbose,ownerPid:process.pid}).catch((err)=>{if(verbose){const message=err instanceof Error?err.message:String(err);console.log(` ${dim(" ")}${dim(`Dev DNS sync: ${message}`)}`)}})}function wantsInteractive(options){return options.interactive}
@@ -1,3 +1,3 @@
1
- import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{renderDnsConfig,resolveLiveRecords,syncDnsConfig}from"@stacksjs/dns";import{ExitCode}from"@stacksjs/types";import{loadProjectDnsConfig}from"../config";export function dns(buddy){const descriptions={dns:"Lists the DNS records for a domain",query:"Host name or IP address to query",type:"Type of the DNS record being queried (A, MX, NS\u2026)",nameserver:"Address of the nameserver to send packets to",class:"Network class of the DNS record being queried (IN, CH, HS)",udp:"Use the DNS protocol over UDP",tcp:"Use the DNS protocol over TCP",tls:"Use the DNS-over-TLS protocol",https:"Use the DNS-over-HTTPS protocol",short:"Short mode: display nothing but the first result",json:"Display the output as JSON",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("dns [domain]",descriptions.dns).option("-q, --query <query>",descriptions.query).option("-t, --type <type>",descriptions.type,{default:"A"}).option("-n, --nameserver <nameserver>",descriptions.nameserver).option("--class <class>",descriptions.class).option("-U, --udp",descriptions.udp).option("-T, --tcp",descriptions.tcp).option("-S, --tls",descriptions.tls).option("-H, --https",descriptions.https).option("-1, --short",descriptions.short,{default:!1}).option("-J, --json",descriptions.json,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{log.debug("Running `buddy dns [domain]` ...",options);const targetDomain=domain||config.app.url;let DnsClient,formatOutput;try{const dnsx=await import("@stacksjs/dnsx");DnsClient=dnsx.DnsClient;formatOutput=dnsx.formatOutput}catch(err){log.error("`buddy dns` needs the @stacksjs/dnsx runtime, but only the type declarations are currently published. Install a build with the JS runtime (or wait for the next dnsx release) and re-run.");log.debug(`[dns] import failure: ${err instanceof Error?err.message:String(err)}`);await log.flush();process.exit(ExitCode.FatalError)}try{const client=new DnsClient({domains:[targetDomain],type:options.type,nameserver:options.nameserver,class:options.class,udp:options.udp,tcp:options.tcp,tls:options.tls,https:options.https,short:options.short,json:options.json,verbose:options.verbose}),startTime=performance.now(),responses=await client.query(),duration=performance.now()-startTime,output=formatOutput(responses,{json:options.json??!1,short:options.short??!1,showDuration:duration,colors:{enabled:!0},rawSeconds:!1});console.log(output)}catch(error){await log.error(`DNS query failed: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});const bareDomain=(input)=>(input||config.app.url||"").replace(/^[a-z]+:\/\//i,"").replace(/[/:].*$/,"");buddy.command("dns:pull [domain]","Print a domain's live DNS records as a config/dns.ts block").option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{const target=bareDomain(domain);log.debug(`Running \`buddy dns:pull ${target}\` ...`,options);const records=await resolveLiveRecords(target);if(!records.length){await log.error(`No DNS records resolved for ${target}.`);process.exit(ExitCode.FatalError)}console.log(renderDnsConfig(target,records));process.exit(ExitCode.Success)});buddy.command("dns:diff [domain]","Show which config/dns.ts records are missing from the live zone").option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{const target=bareDomain(domain);log.debug(`Running \`buddy dns:diff ${target}\` ...`,options);const dnsConfig=await loadProjectDnsConfig(config.dns),{plan,provider}=await syncDnsConfig(target,dnsConfig,{dryRun:!0});for(const item of plan.items){const detail=item.record.type==="TXT"||item.record.type==="MX"?` ${item.record.content}`:` \u2192 ${item.record.content}`,label=item.action==="create"?"+ create":item.action==="skip"?"- skip ":" keep ",why=item.action==="skip"?` (${item.reason})`:"";console.log(` ${label} ${item.record.type.padEnd(5)} ${item.record.name}${detail}${why}`)}const skipped=plan.skip.length?`, ${plan.skip.length} unpublishable`:"";console.log(`
2
- ${plan.create.length} to create, ${plan.keep.length} already present${skipped} (${provider?`registrar: ${provider}`:"public DNS"})`);process.exit(ExitCode.Success)});buddy.command("dns:sync [domain]","Additively sync config/dns.ts to the registrar (creates missing records; never deletes or overwrites)").option("--dry-run","Show the plan without writing any records",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{const target=bareDomain(domain);log.debug(`Running \`buddy dns:sync ${target}\` ...`,options);const dnsConfig=await loadProjectDnsConfig(config.dns),result=await syncDnsConfig(target,dnsConfig,{dryRun:options.dryRun});if(!result.provider&&!options.dryRun){log.warn(`No DNS provider credentials found (e.g. PORKBUN_API_KEY / PORKBUN_SECRET_KEY) - nothing was synced. ${result.plan.create.length} record(s) would be created.`);await log.flush();process.exit(ExitCode.Success)}const failedNames=new Set(result.failures.map((failure)=>`${failure.record.type} ${failure.record.name}`));for(const record of result.plan.create){const verb=!result.applied?"would create":failedNames.has(`${record.type} ${record.name}`)?"FAILED ":"created";console.log(` ${verb} ${record.type.padEnd(5)} ${record.name} \u2192 ${record.content}`)}for(const failure of result.failures)console.log(` ${failure.record.type} ${failure.record.name}: ${failure.reason}`);for(const skipped of result.skipped)console.log(` skipped ${skipped.record.type.padEnd(5)} ${skipped.record.name}: ${skipped.reason}`);const verb=result.applied?"created":"to create",count=result.applied?result.created:result.plan.create.length,skippedNote=result.skipped.length?`, ${result.skipped.length} unpublishable`:"";console.log(`
1
+ import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{renderDnsConfig,resolveLiveRecords,syncDnsConfig}from"@stacksjs/dns";import{ExitCode}from"@stacksjs/types";import{loadProjectDnsConfig}from"../config";export function dns(buddy){const descriptions={dns:"Lists the DNS records for a domain",query:"Host name or IP address to query",type:"Type of the DNS record being queried (A, MX, NS…)",nameserver:"Address of the nameserver to send packets to",class:"Network class of the DNS record being queried (IN, CH, HS)",udp:"Use the DNS protocol over UDP",tcp:"Use the DNS protocol over TCP",tls:"Use the DNS-over-TLS protocol",https:"Use the DNS-over-HTTPS protocol",short:"Short mode: display nothing but the first result",json:"Display the output as JSON",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("dns [domain]",descriptions.dns).option("-q, --query <query>",descriptions.query).option("-t, --type <type>",descriptions.type,{default:"A"}).option("-n, --nameserver <nameserver>",descriptions.nameserver).option("--class <class>",descriptions.class).option("-U, --udp",descriptions.udp).option("-T, --tcp",descriptions.tcp).option("-S, --tls",descriptions.tls).option("-H, --https",descriptions.https).option("-1, --short",descriptions.short,{default:false}).option("-J, --json",descriptions.json,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{log.debug("Running `buddy dns [domain]` ...",options);const targetDomain=domain||config.app.url;let DnsClient;let formatOutput;try{const dnsx=await import("@stacksjs/dnsx");DnsClient=dnsx.DnsClient;formatOutput=dnsx.formatOutput}catch(err){log.error(`\`buddy dns\` needs the @stacksjs/dnsx runtime, but only the type declarations are currently published. Install a build with the JS runtime (or wait for the next dnsx release) and re-run.`);log.debug(`[dns] import failure: ${err instanceof Error?err.message:String(err)}`);await log.flush();process.exit(ExitCode.FatalError)}try{const client=new DnsClient({domains:[targetDomain],type:options.type,nameserver:options.nameserver,class:options.class,udp:options.udp,tcp:options.tcp,tls:options.tls,https:options.https,short:options.short,json:options.json,verbose:options.verbose});const startTime=performance.now();const responses=await client.query();const duration=performance.now()-startTime;const output=formatOutput(responses,{json:options.json??false,short:options.short??false,showDuration:duration,colors:{enabled:true},rawSeconds:false});console.log(output)}catch(error){await log.error(`DNS query failed: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});const bareDomain=(input)=>(input||config.app.url||"").replace(/^[a-z]+:\/\//i,"").replace(/[/:].*$/,"");buddy.command("dns:pull [domain]","Print a domain's live DNS records as a config/dns.ts block").option("--verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{const target=bareDomain(domain);log.debug(`Running \`buddy dns:pull ${target}\` ...`,options);const records=await resolveLiveRecords(target);if(!records.length){await log.error(`No DNS records resolved for ${target}.`);process.exit(ExitCode.FatalError)}console.log(renderDnsConfig(target,records));process.exit(ExitCode.Success)});buddy.command("dns:diff [domain]","Show which config/dns.ts records are missing from the live zone").option("--verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{const target=bareDomain(domain);log.debug(`Running \`buddy dns:diff ${target}\` ...`,options);const dnsConfig=await loadProjectDnsConfig(config.dns);const{plan,provider}=await syncDnsConfig(target,dnsConfig,{dryRun:true});for(const item of plan.items){const detail=item.record.type==="TXT"||item.record.type==="MX"?` ${item.record.content}`:` → ${item.record.content}`;const label=item.action==="create"?"+ create":item.action==="skip"?"- skip ":" keep ";const why=item.action==="skip"?` (${item.reason})`:"";console.log(` ${label} ${item.record.type.padEnd(5)} ${item.record.name}${detail}${why}`)}const skipped=plan.skip.length?`, ${plan.skip.length} unpublishable`:"";console.log(`
2
+ ${plan.create.length} to create, ${plan.keep.length} already present${skipped} (${provider?`registrar: ${provider}`:"public DNS"})`);process.exit(ExitCode.Success)});buddy.command("dns:sync [domain]","Additively sync config/dns.ts to the registrar (creates missing records; never deletes or overwrites)").option("--dry-run","Show the plan without writing any records",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{const target=bareDomain(domain);log.debug(`Running \`buddy dns:sync ${target}\` ...`,options);const dnsConfig=await loadProjectDnsConfig(config.dns);const result=await syncDnsConfig(target,dnsConfig,{dryRun:options.dryRun});if(!result.provider&&!options.dryRun){log.warn(`No DNS provider credentials found (e.g. PORKBUN_API_KEY / PORKBUN_SECRET_KEY) - nothing was synced. ${result.plan.create.length} record(s) would be created.`);await log.flush();process.exit(ExitCode.Success)}const failedNames=new Set(result.failures.map((failure)=>`${failure.record.type} ${failure.record.name}`));for(const record of result.plan.create){const verb=!result.applied?"would create":failedNames.has(`${record.type} ${record.name}`)?"FAILED ":"created";console.log(` ${verb} ${record.type.padEnd(5)} ${record.name} → ${record.content}`)}for(const failure of result.failures)console.log(` ${failure.record.type} ${failure.record.name}: ${failure.reason}`);for(const skipped of result.skipped)console.log(` skipped ${skipped.record.type.padEnd(5)} ${skipped.record.name}: ${skipped.reason}`);const verb=result.applied?"created":"to create";const count=result.applied?result.created:result.plan.create.length;const skippedNote=result.skipped.length?`, ${result.skipped.length} unpublishable`:"";console.log(`
3
3
  dns:sync ${target}: ${count} ${verb}, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}${skippedNote}${result.provider?` (${result.provider})`:""}`);process.exit(result.failed>0?ExitCode.FatalError:ExitCode.Success)});onUnknownSubcommand(buddy,"dns")}
@@ -1,4 +1,4 @@
1
1
  import{execFileSync}from"node:child_process";import{readdirSync,readFileSync,statSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname;function abs(relative){return join(root,relative)}function ignoredPaths(paths){if(!paths.length)return new Set;try{const output=execFileSync("git",["check-ignore","--stdin"],{cwd:root,input:paths.join(`
2
2
  `),encoding:"utf8",stdio:["pipe","pipe","ignore"]});return new Set(output.split(`
3
- `).map((line)=>line.trim()).filter(Boolean))}catch{return new Set}}function walkFiles(dir,extension){let entries;try{entries=readdirSync(abs(dir))}catch{return[]}return entries.flatMap((entry)=>{const full=join(abs(dir),entry);if(statSync(full).isDirectory())return walkFiles(join(dir,entry),extension);if(!entry.endsWith(extension)||entry==="index.ts")return[];return[join(dir,entry)]})}export function countFiles(dir,extension){const files=walkFiles(dir,extension),ignored=ignoredPaths(files);return files.filter((file)=>!ignored.has(file)).length}function countDirs(dir){return readdirSync(abs(dir)).filter((entry)=>statSync(join(abs(dir),entry)).isDirectory()).length}const SKILLS="storage/framework/defaults/ai/skills",AGENTS="AGENTS.md",CLAIMS=[{what:"built-in models",measure:()=>countFiles("storage/framework/defaults/app/Models",".ts"),sites:[{file:AGENTS,pattern:/(\d+) built-in models you can use or override/},{file:AGENTS,pattern:/All (\d+) models \(`User`/},{file:`${SKILLS}/stacks-orm/SKILL.md`,pattern:/(\d+) models/},{file:`${SKILLS}/stacks-auto-imports/SKILL.md`,pattern:/\((\d+) models\)/},{file:AGENTS,pattern:/including the (\d+) built-in `Models\/`/},{file:AGENTS,pattern:/\((\d+) built-ins, grouped into/},{file:`${SKILLS}/stacks-models/SKILL.md`,pattern:/holds (\d+), and that/},{file:`${SKILLS}/stacks-models/SKILL.md`,pattern:/the (\d+) built-in framework models/},{file:`${SKILLS}/stacks-orm/SKILL.md`,pattern:/(\d+) built-in models/}]},{what:"commerce models",measure:()=>countFiles("storage/framework/defaults/app/Models/commerce",".ts"),sites:[{file:`${SKILLS}/stacks-commerce/SKILL.md`,pattern:/and (\d+) models/}]},{what:"components",measure:()=>countFiles("storage/framework/defaults/resources/components",".stx"),sites:[{file:AGENTS,pattern:/widgets \((\d+) components\)/},{file:`${SKILLS}/stacks-dashboard/SKILL.md`,pattern:/(\d+) built-in dashboard components/},{file:`${SKILLS}/stacks-dashboard/SKILL.md`,pattern:/route views, (\d+) components,/}]},{what:"default actions",measure:()=>readFileSync(abs("storage/framework/auto-imports/actions.ts"),"utf-8").split(`
4
- `).filter((line)=>/^\s+'/.test(line)).length,sites:[{file:AGENTS,pattern:/(\d+) default actions/},{file:`${SKILLS}/stacks-actions/SKILL.md`,pattern:/(\d+) default framework actions/}]},{what:"migrations",measure:()=>countFiles("database/migrations",".sql"),sites:[{file:AGENTS,pattern:/(\d+) migrations ship for/},{file:`${SKILLS}/stacks-migrations/SKILL.md`,pattern:/(\d+) built-in migration files/},{file:`${SKILLS}/stacks-migrations/SKILL.md`,pattern:/(\d+) migration files exist by default/},{file:`${SKILLS}/stacks-database/SKILL.md`,pattern:/\((\d+) migration files/}]},{what:"config files",measure:()=>countFiles("config",".ts"),sites:[{file:AGENTS,pattern:/~(\d+) typed config files/}]},{what:"skills",measure:()=>countDirs(SKILLS),sites:[{file:`${SKILLS}/stacks-writing-for-agents/SKILL.md`,pattern:/ships (\d+) skills/}]}];function inspect(){const drift=[];let checked=0;for(const claim of CLAIMS){const actual=claim.measure();for(const site of claim.sites){checked++;const match=readFileSync(abs(site.file),"utf-8").match(site.pattern),stated=match?Number(match[1]):null;if(stated!==actual)drift.push({what:claim.what,file:site.file,stated,actual})}}return{drift,checked}}function write(){let rewritten=0;for(const claim of CLAIMS){const actual=claim.measure();for(const site of claim.sites){const source=readFileSync(abs(site.file),"utf-8"),match=source.match(site.pattern);if(!match||Number(match[1])===actual)continue;const updated=match[0].replace(String(match[1]),String(actual));writeFileSync(abs(site.file),source.replace(match[0],updated),"utf-8");rewritten++}}return rewritten}export async function run(){assertFrameworkRepo(root,"docs:agent-counts");if(process.argv.includes("--write")){const rewritten=write();console.log(rewritten===0?"\u2713 agent-facing counts were already current":`\u2713 updated ${rewritten} count(s); run \`buddy setup:ai\` to refresh the installed copies`);return}const{drift,checked}=inspect();if(drift.length===0){console.log(`\u2713 agent-facing counts are current (${checked} checked)`);return}console.error(`\u2717 ${drift.length} of ${checked} agent-facing count(s) no longer match the tree:`);for(const entry of drift)console.error(entry.stated===null?` ${entry.file}: the ${entry.what} claim is gone - reword the check, or restore the sentence`:` ${entry.file}: says ${entry.stated} ${entry.what}, tree has ${entry.actual}`);console.error("\nRun `buddy docs:agent-counts` to rewrite them from the tree.");if(process.argv.includes("--check"))process.exit(1)}if(import.meta.main)await run();
3
+ `).map((line)=>line.trim()).filter(Boolean))}catch{return new Set}}function walkFiles(dir,extension){let entries;try{entries=readdirSync(abs(dir))}catch{return[]}return entries.flatMap((entry)=>{const full=join(abs(dir),entry);if(statSync(full).isDirectory())return walkFiles(join(dir,entry),extension);if(!entry.endsWith(extension)||entry==="index.ts")return[];return[join(dir,entry)]})}export function countFiles(dir,extension){const files=walkFiles(dir,extension);const ignored=ignoredPaths(files);return files.filter((file)=>!ignored.has(file)).length}function countDirs(dir){return readdirSync(abs(dir)).filter((entry)=>statSync(join(abs(dir),entry)).isDirectory()).length}const SKILLS="storage/framework/defaults/ai/skills";const AGENTS="AGENTS.md";const CLAIMS=[{what:"built-in models",measure:()=>countFiles("storage/framework/defaults/app/Models",".ts"),sites:[{file:AGENTS,pattern:/(\d+) built-in models you can use or override/},{file:AGENTS,pattern:/All (\d+) models \(`User`/},{file:`${SKILLS}/stacks-orm/SKILL.md`,pattern:/(\d+) models/},{file:`${SKILLS}/stacks-auto-imports/SKILL.md`,pattern:/\((\d+) models\)/},{file:AGENTS,pattern:/including the (\d+) built-in `Models\/`/},{file:AGENTS,pattern:/\((\d+) built-ins, grouped into/},{file:`${SKILLS}/stacks-models/SKILL.md`,pattern:/holds (\d+), and that/},{file:`${SKILLS}/stacks-models/SKILL.md`,pattern:/the (\d+) built-in framework models/},{file:`${SKILLS}/stacks-orm/SKILL.md`,pattern:/(\d+) built-in models/}]},{what:"commerce models",measure:()=>countFiles("storage/framework/defaults/app/Models/commerce",".ts"),sites:[{file:`${SKILLS}/stacks-commerce/SKILL.md`,pattern:/and (\d+) models/}]},{what:"components",measure:()=>countFiles("storage/framework/defaults/resources/components",".stx"),sites:[{file:AGENTS,pattern:/widgets \((\d+) components\)/},{file:`${SKILLS}/stacks-dashboard/SKILL.md`,pattern:/(\d+) built-in dashboard components/},{file:`${SKILLS}/stacks-dashboard/SKILL.md`,pattern:/route views, (\d+) components,/}]},{what:"default actions",measure:()=>readFileSync(abs("storage/framework/auto-imports/actions.ts"),"utf-8").split(`
4
+ `).filter((line)=>/^\s+'/.test(line)).length,sites:[{file:AGENTS,pattern:/(\d+) default actions/},{file:`${SKILLS}/stacks-actions/SKILL.md`,pattern:/(\d+) default framework actions/}]},{what:"migrations",measure:()=>countFiles("database/migrations",".sql"),sites:[{file:AGENTS,pattern:/(\d+) migrations ship for/},{file:`${SKILLS}/stacks-migrations/SKILL.md`,pattern:/(\d+) built-in migration files/},{file:`${SKILLS}/stacks-migrations/SKILL.md`,pattern:/(\d+) migration files exist by default/},{file:`${SKILLS}/stacks-database/SKILL.md`,pattern:/\((\d+) migration files/}]},{what:"config files",measure:()=>countFiles("config",".ts"),sites:[{file:AGENTS,pattern:/~(\d+) typed config files/}]},{what:"skills",measure:()=>countDirs(SKILLS),sites:[{file:`${SKILLS}/stacks-writing-for-agents/SKILL.md`,pattern:/ships (\d+) skills/},{file:`docs/skills.md`,pattern:/The (\d+) agent skills Stacks ships/},{file:`docs/skills.md`,pattern:/ships \*\*(\d+) agent skills\*\*/}]}];function inspect(){const drift=[];let checked=0;for(const claim of CLAIMS){const actual=claim.measure();for(const site of claim.sites){checked++;const match=readFileSync(abs(site.file),"utf-8").match(site.pattern);const stated=match?Number(match[1]):null;if(stated!==actual)drift.push({what:claim.what,file:site.file,stated,actual})}}return{drift,checked}}function write(){let rewritten=0;for(const claim of CLAIMS){const actual=claim.measure();for(const site of claim.sites){const source=readFileSync(abs(site.file),"utf-8");const match=source.match(site.pattern);if(!match||Number(match[1])===actual)continue;const updated=match[0].replace(String(match[1]),String(actual));writeFileSync(abs(site.file),source.replace(match[0],updated),"utf-8");rewritten++}}return rewritten}export async function run(){assertFrameworkRepo(root,"docs:agent-counts");if(process.argv.includes("--write")){const rewritten=write();console.log(rewritten===0?"✓ agent-facing counts were already current":`✓ updated ${rewritten} count(s); run \`buddy setup:ai\` to refresh the installed copies`);return}const{drift,checked}=inspect();if(drift.length===0){console.log(`✓ agent-facing counts are current (${checked} checked)`);return}console.error(`✗ ${drift.length} of ${checked} agent-facing count(s) no longer match the tree:`);for(const entry of drift){console.error(entry.stated===null?` ${entry.file}: the ${entry.what} claim is gone - reword the check, or restore the sentence`:` ${entry.file}: says ${entry.stated} ${entry.what}, tree has ${entry.actual}`)}console.error("\nRun `buddy docs:agent-counts` to rewrite them from the tree.");if(process.argv.includes("--check"))process.exit(1)}if(require.main==require.module)await run();