@stacksjs/desktop-build 0.75.600 → 0.75.604

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.
@@ -36,7 +36,7 @@ export declare function stacksAgentHandler(options: StacksAgentHandlerOptions):
36
36
  * route module by absolute path so the bundler can follow it: whatever that
37
37
  * module imports is inside the built app.
38
38
  */
39
- export declare function renderAgentEntry(options?: { agentEntry?: string, launcherModule?: string, routes?: Array<{ file: string, prefix?: string, middleware?: string[] }>, actions?: Record<string, string> }): string;
39
+ export declare function renderAgentEntry(options?: { agentEntry?: string, launcherModule?: string, routes?: Array<{ file: string, prefix?: string, middleware?: string[] }>, actions?: Record<string, string>, middleware?: Record<string, string> }): string;
40
40
  /**
41
41
  * Lock, log, agent, host; resolves with the exit code once the window's
42
42
  * process ends (or 0 at once when another copy is already running, which
@@ -93,6 +93,7 @@ export declare interface StacksAgentHandlerOptions {
93
93
  appRoutes: boolean
94
94
  routes?: AgentRouteFile[]
95
95
  actions?: Record<string, () => Promise<{ default?: unknown }>>
96
+ middleware?: Record<string, () => Promise<{ default?: unknown }>>
96
97
  }
97
98
  export declare interface RunDesktopAgentAppOptions {
98
99
  manifest: DesktopAgentManifest
@@ -1,9 +1,12 @@
1
1
  import{appendFileSync,existsSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{format}from"node:util";import{startDesktopAgent}from"./agent";export const AGENT_MANIFEST="desktop-agent.json";export const AGENT_MANIFEST_ENV="STACKS_DESKTOP_AGENT_MANIFEST";export const AGENT_DATA_DIR_ENV="STACKS_DESKTOP_DATA_DIR";export const AGENT_RESOURCES_ENV="STACKS_DESKTOP_RESOURCES";export function desktopResource(name,env=process.env){try{const resources=JSON.parse(env[AGENT_RESOURCES_ENV]??"{}");return typeof resources[name]==="string"?resources[name]:undefined}catch{return}}export function desktopAgentPaths(appName,home=homedir()){const dataDir=join(home,"Library","Application Support",appName);return{dataDir,portFile:join(dataDir,"agent.port"),lockFile:join(dataDir,"agent.pid"),logFile:join(home,"Library","Logs",`${appName}.log`)}}export function acquireInstanceLock(lockFile,pid=process.pid){mkdirSync(dirname(lockFile),{recursive:true});if(existsSync(lockFile)){const holder=Number(readFileSync(lockFile,"utf8").trim());if(holder&&holder!==pid){try{process.kill(holder,0);return false}catch(error){if(error.code==="EPERM")return false}}}writeFileSync(lockFile,String(pid));return true}export function releaseInstanceLock(lockFile,pid=process.pid){try{if(readFileSync(lockFile,"utf8").trim()===String(pid))rmSync(lockFile)}catch{}}export function logToFileWhenDetached(logFile,isTTY=Boolean(process.stdout.isTTY)){if(isTTY)return false;mkdirSync(dirname(logFile),{recursive:true});for(const level of["log","info","warn","error","debug"]){console[level]=(...args)=>{try{appendFileSync(logFile,`${new Date().toISOString()} ${level==="log"?"":`[${level}] `}${format(...args)}
2
- `)}catch{}}}return true}export function findAgentManifest(execPath=process.execPath,env=process.env){if(env[AGENT_MANIFEST_ENV])return resolve(env[AGENT_MANIFEST_ENV]);const bundled=join(dirname(execPath),"..","Resources",AGENT_MANIFEST);return existsSync(bundled)?bundled:null}export function readAgentManifest(file){const manifest=JSON.parse(readFileSync(file,"utf8"));const base=dirname(file);const at=(path)=>isAbsolute(path)?path:resolve(base,path);return{...manifest,host:at(manifest.host),nativeBundle:at(manifest.nativeBundle),...manifest.staticDir?{staticDir:at(manifest.staticDir)}:{},...manifest.resources?{resources:Object.fromEntries(Object.entries(manifest.resources).map(([name,path])=>[name,at(path)]))}:{}}}export function agentHostCommand(manifest,agentUrl){return[manifest.host,"--api-url",agentUrl,"--native-bundle",manifest.nativeBundle,...manifest.hostArguments]}export async function stacksAgentHandler(options){try{const{overridesReady}=await import("@stacksjs/config");await overridesReady}catch(error){console.warn(`[agent] config not loaded: ${error instanceof Error?error.message:String(error)}`)}if(options.appRoutes){try{const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports()}catch(error){console.warn(`[agent] models and framework globals not injected: ${error instanceof Error?error.message:String(error)}`)}}const{provideActions,route,serverResponse}=await import("@stacksjs/router");if(options.actions)provideActions(options.actions);const module=options.entry?await options.entry():undefined;if(typeof module?.default==="function")return module.default;if(options.appRoutes){const fromProject=(request)=>serverResponse(request);return fromProject}for(const file of options.routes??[]){if(file.prefix||file.middleware?.length)await route.group({prefix:file.prefix,middleware:file.middleware?.length?file.middleware:undefined},async()=>{await file.load()});else await file.load()}const bundled=(request)=>route.handleRequest(request);return bundled}export function renderAgentEntry(options={}){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const entry=options.agentEntry?`() => import(${JSON.stringify(options.agentEntry)})`:"undefined";const routes=options.routes?.length?`[
2
+ `)}catch{}}}return true}export function findAgentManifest(execPath=process.execPath,env=process.env){if(env[AGENT_MANIFEST_ENV])return resolve(env[AGENT_MANIFEST_ENV]);const bundled=join(dirname(execPath),"..","Resources",AGENT_MANIFEST);return existsSync(bundled)?bundled:null}export function readAgentManifest(file){const manifest=JSON.parse(readFileSync(file,"utf8"));const base=dirname(file);const at=(path)=>isAbsolute(path)?path:resolve(base,path);return{...manifest,host:at(manifest.host),nativeBundle:at(manifest.nativeBundle),...manifest.staticDir?{staticDir:at(manifest.staticDir)}:{},...manifest.resources?{resources:Object.fromEntries(Object.entries(manifest.resources).map(([name,path])=>[name,at(path)]))}:{}}}export function agentHostCommand(manifest,agentUrl){return[manifest.host,"--api-url",agentUrl,"--native-bundle",manifest.nativeBundle,...manifest.hostArguments]}export async function stacksAgentHandler(options){try{const{overridesReady}=await import("@stacksjs/config");await overridesReady}catch(error){console.warn(`[agent] config not loaded: ${error instanceof Error?error.message:String(error)}`)}if(options.appRoutes){try{const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports()}catch(error){console.warn(`[agent] models and framework globals not injected: ${error instanceof Error?error.message:String(error)}`)}}const{provideActions,provideMiddleware,route,serverResponse}=await import("@stacksjs/router");if(options.actions)provideActions(options.actions);if(options.middleware)provideMiddleware(options.middleware);const module=options.entry?await options.entry():undefined;if(typeof module?.default==="function")return module.default;if(options.appRoutes){const fromProject=(request)=>serverResponse(request);return fromProject}for(const file of options.routes??[]){if(file.prefix||file.middleware?.length)await route.group({prefix:file.prefix,middleware:file.middleware?.length?file.middleware:undefined},async()=>{await file.load()});else await file.load()}const bundled=(request)=>route.handleRequest(request);return bundled}export function renderAgentEntry(options={}){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const entry=options.agentEntry?`() => import(${JSON.stringify(options.agentEntry)})`:"undefined";const routes=options.routes?.length?`[
3
3
  ${options.routes.map((file)=>` { load: () => import(${JSON.stringify(file.file)})${file.prefix?`, prefix: ${JSON.stringify(file.prefix)}`:""}${file.middleware?.length?`, middleware: ${JSON.stringify(file.middleware)}`:""} },`).join(`
4
4
  `)}
5
5
  ]`:"[]";const actionEntries=Object.entries(options.actions??{});const actions=actionEntries.length?`{
6
6
  ${actionEntries.map(([name,file])=>` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`).join(`
7
+ `)}
8
+ }`:"{}";const middlewareEntries=Object.entries(options.middleware??{});const middleware=middlewareEntries.length?`{
9
+ ${middlewareEntries.map(([name,file])=>` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`).join(`
7
10
  `)}
8
11
  }`:"{}";return`// Written by buddy build:desktop and buddy dev:desktop (macos.agent). Do not edit.
9
12
  import process from 'node:process'
@@ -17,7 +20,7 @@ if (!file) {
17
20
  const manifest = readAgentManifest(file)
18
21
  process.exit(await runDesktopAgentApp({
19
22
  manifest,
20
- handler: () => stacksAgentHandler({ entry: ${entry}, appRoutes: manifest.appRoutes, routes: ${routes}, actions: ${actions} }),
23
+ handler: () => stacksAgentHandler({ entry: ${entry}, appRoutes: manifest.appRoutes, routes: ${routes}, actions: ${actions}, middleware: ${middleware} }),
21
24
  }))
22
25
  `}export async function runDesktopAgentApp(options){const{manifest}=options;if((options.argv??process.argv.slice(2)).includes("--version")){if(!existsSync(manifest.host)){console.error(`[${manifest.appName}] the AppKit host is missing: ${manifest.host}`);return 1}return Bun.spawnSync([manifest.host,"--version"],{stdout:"inherit",stderr:"inherit"}).exitCode??1}const paths=options.paths??desktopAgentPaths(manifest.appName);const tag=`[${manifest.appName}]`;if(options.logWhenDetached!==false)logToFileWhenDetached(paths.logFile);if(!acquireInstanceLock(paths.lockFile)){console.log(`${tag} already running`);return 0}if(!existsSync(manifest.host)){console.error(`${tag} the AppKit host is missing: ${manifest.host}`);releaseInstanceLock(paths.lockFile);return 1}if(!existsSync(manifest.nativeBundle)){console.error(`${tag} the native screens are missing: ${manifest.nativeBundle}`);releaseInstanceLock(paths.lockFile);return 1}let agent;let handlerReady;try{if(manifest.projectRoot&&manifest.appRoutes)process.chdir(manifest.projectRoot);process.env[AGENT_DATA_DIR_ENV]=paths.dataDir;process.env[AGENT_RESOURCES_ENV]=JSON.stringify(manifest.resources??{});const ready=options.handler();handlerReady=ready;ready.catch(()=>{});agent=await startDesktopAgent({handler:async(request)=>(await ready)(request),name:manifest.appName,version:manifest.version,port:manifest.port,portFile:paths.portFile,staticDir:manifest.staticDir})}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.stack??error.message:String(error)}`);releaseInstanceLock(paths.lockFile);return 1}console.log(`${tag} ${manifest.version} serving on ${agent.url}`);const command=agentHostCommand(manifest,agent.url);const host=options.spawn?options.spawn(command):(()=>{const child=Bun.spawn(command,{stdio:["ignore","inherit","pipe"]});new Response(child.stderr).text().then((stderr)=>{const lines=stderr.split(`
23
26
  `).filter((line)=>line.trim());if(lines.length)console.error(`[craft] ${lines.join(`
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/desktop-build",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.600",
5
+ "version": "0.75.604",
6
6
  "description": "Build and launch Craft desktop applications for Stacks",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -73,17 +73,17 @@
73
73
  "prepublishOnly": "bun run build"
74
74
  },
75
75
  "dependencies": {
76
- "@stacksjs/config": "0.75.600",
77
- "@stacksjs/router": "0.75.600",
78
- "@stacksjs/server": "0.75.600",
79
- "@stacksjs/storage": "0.75.600",
76
+ "@stacksjs/config": "0.75.604",
77
+ "@stacksjs/router": "0.75.604",
78
+ "@stacksjs/server": "0.75.604",
79
+ "@stacksjs/storage": "0.75.604",
80
80
  "craft-native": ">=0.0.505"
81
81
  },
82
82
  "peerDependencies": {
83
- "@stacksjs/config": "0.75.600",
84
- "@stacksjs/router": "0.75.600",
85
- "@stacksjs/server": "0.75.600",
86
- "@stacksjs/storage": "0.75.600"
83
+ "@stacksjs/config": "0.75.604",
84
+ "@stacksjs/router": "0.75.604",
85
+ "@stacksjs/server": "0.75.604",
86
+ "@stacksjs/storage": "0.75.604"
87
87
  },
88
88
  "peerDependenciesMeta": {
89
89
  "@stacksjs/config": {
@@ -100,7 +100,7 @@
100
100
  }
101
101
  },
102
102
  "devDependencies": {
103
- "@stacksjs/build": "0.75.600",
103
+ "@stacksjs/build": "0.75.604",
104
104
  "better-dx": "^0.2.39"
105
105
  }
106
106
  }