@stacksjs/desktop-build 0.75.695 → 0.75.701
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/update-install.d.ts
CHANGED
|
@@ -86,6 +86,7 @@ export declare interface DesktopUpdaterOptions {
|
|
|
86
86
|
appName?: string
|
|
87
87
|
channel?: string
|
|
88
88
|
beforeUpdate?: BeforeDesktopUpdate
|
|
89
|
+
beforeInstall?: BeforeDesktopInstall
|
|
89
90
|
target?: DesktopUpdateTarget
|
|
90
91
|
fetcher?: DesktopFetcher
|
|
91
92
|
installation?: DesktopInstallation
|
|
@@ -119,9 +120,9 @@ export type InstallDesktopUpdateResult = | { status: 'installed', relaunch: () =
|
|
|
119
120
|
/** Nothing was installed: the app says this instead. */
|
|
120
121
|
| { status: 'notice', message: string }
|
|
121
122
|
/**
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
* to make the person confirm first (a license whose updates ended before this
|
|
125
|
-
* version: it would run, but as the free tier).
|
|
123
|
+
* Decide whether a verified update is eligible during a feed check.
|
|
124
|
+
* Return `{ refuse }` to disable installation or `{ warn }` to require confirmation.
|
|
126
125
|
*/
|
|
127
126
|
export type BeforeDesktopUpdate = (manifest: DesktopUpdateManifest, current: { version: string }) => void | undefined | { refuse: string } | { warn: string } | Promise<void | undefined | { refuse: string } | { warn: string }>;
|
|
127
|
+
/** Prepare the live app after the artifact is verified and before replacing the installed version. Throw to stop the install. */
|
|
128
|
+
export type BeforeDesktopInstall = (manifest: DesktopUpdateManifest, current: { version: string }) => void | Promise<void>;
|
package/dist/update-install.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,readdirSync,renameSync,rmSync}from"node:fs";import{basename,dirname,join}from"node:path";import process from"node:process";import{errorBody}from"@stacksjs/router/error-body";import{updateFeedUrl}from"./update-feed";import{checkForDesktopUpdate,stageDesktopUpdate}from"./updater";export function detectInstallation(options={}){const platform=options.platform??process.platform;const execPath=options.execPath??process.execPath;const env=options.env??process.env;const name=basename(execPath).toLowerCase();if(name==="bun"||name==="bun.exe")return{kind:"unmanaged",executable:execPath};if(platform==="darwin"){const bundle=execPath.match(/^(.*\.app)\/Contents\/MacOS\/[^/]+$/);return bundle?{kind:"macos-bundle",path:bundle[1],executable:execPath}:{kind:"unmanaged",executable:execPath}}if(platform==="win32")return{kind:"windows-msi",executable:execPath};if(env.APPIMAGE)return{kind:"linux-appimage",path:env.APPIMAGE,executable:env.APPIMAGE};return execPath.startsWith("/usr/")||execPath.startsWith("/opt/")?{kind:"linux-package",executable:execPath}:{kind:"unmanaged",executable:execPath}}const runCommand=(command)=>{const result=Bun.spawnSync(command,{stdout:"pipe",stderr:"pipe"});return{exitCode:result.exitCode??1,stdout:result.stdout.toString(),stderr:result.stderr.toString()}};const spawnDetached=(command)=>{Bun.spawn(command,{stdio:["ignore","ignore","ignore"],detached:true}).unref()};export function macosSigner(bundle,run=runCommand){const described=run(["codesign","-dv","--verbose=4",bundle]);const text=`${described.stdout}
|
|
2
|
-
${described.stderr}`;const teamId=text.match(/^TeamIdentifier=(.+)$/m)?.[1]?.trim();const identifier=text.match(/^Identifier=(.+)$/m)?.[1]?.trim();return{...teamId&&teamId!=="not set"?{teamId}:{},...identifier?{identifier}:{}}}export function assertMacosBundleTrusted(current,next,options={}){const run=options.run??runCommand;const verified=run(["codesign","--verify","--deep","--strict",next]);const running=macosSigner(current,run);const incoming=macosSigner(next,run);if(!running.teamId){if(!options.allowUnsigned)throw new Error("The running app is not signed with a Developer ID, so an update cannot be checked against it.");return}if(verified.exitCode!==0)throw new Error(`The update's signature is not valid: ${(verified.stderr||verified.stdout).trim()}`);if(incoming.teamId!==running.teamId)throw new Error(`The update is signed by ${incoming.teamId??"no one"}, not by this app's team ${running.teamId}.`);if(incoming.identifier!==running.identifier)throw new Error(`The update is a different app (${incoming.identifier??"unknown"}), not ${running.identifier}.`)}const dittoExtract=(archive,into)=>{const result=runCommand(["ditto","-x","-k",archive,into]);if(result.exitCode!==0)throw new Error(`Unpacking the update failed: ${result.stderr.trim()}`)};export function swapMacosBundle(options){const{bundle}=options;const scratch=mkdtempSync(join(dirname(bundle),".update-"));const aside=`${bundle}.previous-${process.pid}`;try{(options.extract??dittoExtract)(options.archive,scratch);const unpacked=readdirSync(scratch).filter((entry)=>entry.endsWith(".app"));if(unpacked.length!==1)throw new Error(`The update archive holds ${unpacked.length} apps; it has to hold exactly one.`);const next=join(scratch,unpacked[0]);assertMacosBundleTrusted(bundle,next,{run:options.run,allowUnsigned:options.allowUnsigned});renameSync(bundle,aside);try{renameSync(next,bundle)}catch(error){renameSync(aside,bundle);throw error}rmSync(aside,{recursive:true,force:true})}finally{rmSync(scratch,{recursive:true,force:true})}}export function replaceAppImage(staged,appImage){const incoming=`${appImage}.update-${process.pid}`;try{copyFileSync(staged,incoming);chmodSync(incoming,493);renameSync(incoming,appImage)}catch(error){rmSync(incoming,{force:true});throw error}}export function windowsSigner(file,run=runCommand){const script=`$s = Get-AuthenticodeSignature -LiteralPath '${file.replace(/'/g,"''")}'; Write-Output $s.Status; if ($s.SignerCertificate) { Write-Output $s.SignerCertificate.Subject }`;const result=run(["powershell.exe","-NoProfile","-NonInteractive","-Command",script]);const[status,subject]=result.stdout.split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);return{valid:result.exitCode===0&&status==="Valid",...subject?{subject}:{}}}export function assertWindowsInstallerTrusted(executable,installer,options={}){const running=windowsSigner(executable,options.run);if(!running.valid){if(options.allowUnsigned===false)throw new Error("The running app is not Authenticode-signed, so an update cannot be checked against it.");return}const incoming=windowsSigner(installer,options.run);if(!incoming.valid)throw new Error("The update installer is not validly signed.");if(incoming.subject!==running.subject)throw new Error(`The update is signed by ${incoming.subject??"no one"}, not by this app's publisher ${running.subject}.`)}export function installDesktopUpdate(options){const installation=options.installation??detectInstallation();const spawn=options.spawn??spawnDetached;const pid=options.pid??process.pid;const name=options.appName??"The app";switch(installation.kind){case"macos-bundle":{swapMacosBundle({archive:options.staged,bundle:installation.path,extract:options.extract,run:options.run,allowUnsigned:options.allowUnsigned});return{status:"installed",relaunch:()=>spawn(["open","-n",installation.path,"--args",`--wait-pid=${pid}`])}}case"linux-appimage":{replaceAppImage(options.staged,installation.path);return{status:"installed",relaunch:()=>spawn([installation.path,`--wait-pid=${pid}`])}}case"windows-msi":{assertWindowsInstallerTrusted(installation.executable,options.staged,{run:options.run,allowUnsigned:options.allowUnsigned});spawn(["cmd.exe","/d","/s","/c",`msiexec /i "${options.staged}" /passive /norestart && start "" "${installation.executable}" --wait-pid=${pid}`]);return{status:"installing"}}case"linux-package":return{status:"notice",message:`${name} ${options.manifest.version} is available. This copy was installed as a system package: update it with your package manager, or download the new package from ${new URL(options.manifest.url).origin}.`};default:return{status:"notice",message:`${name} ${options.manifest.version} is available, but this copy was not installed in a way that can update itself.`}}}const ARTIFACT_NAMES={darwin:"update.zip",win32:"update.msi",linux:"update.AppImage"};export function createDesktopUpdater(options){const installation=options.installation??detectInstallation();const target=options.target??{platform:process.platform,architecture:process.arch};const selfUpdating=["macos-bundle","windows-msi","linux-appimage"].includes(installation.kind);let state="idle";let manifest=null;let warning;let message;let error;let relaunch;let busy;const status=()=>({currentVersion:options.currentVersion,state,installKind:installation.kind,selfUpdating,...manifest?{version:manifest.version,...manifest.notes?{notes:manifest.notes}:{},...manifest.publishedAt?{publishedAt:manifest.publishedAt}:{}}:{},...warning?{warning}:{},...message?{message}:{},...error?{error}:{}});const once=(work)=>{busy??=work().catch((failure)=>{state="error";error=failure instanceof Error?failure.message:String(failure)}).then(()=>{busy=undefined;return status()});return busy};return{status,check:()=>once(async()=>{if(state==="installed"||state==="installing")return;state="checking";error=warning=message=undefined;manifest=await checkForDesktopUpdate({currentVersion:options.currentVersion,manifestUrl:updateFeedUrl(options.feedUrl,target,{channel:options.channel,currentVersion:options.currentVersion}),trustedKeys:options.trustedKeys,fetcher:options.fetcher,target});if(!manifest){state="current";return}const verdict=await options.beforeUpdate?.(manifest,{version:options.currentVersion});if(verdict&&"refuse"in verdict){state="refused";message=verdict.refuse;return}if(verdict&&"warn"in verdict)warning=verdict.warn;state="available"}),install:(install={})=>once(async()=>{if(state!=="available"||!manifest)throw new Error("There is no update to install. Check first.");if(warning&&!install.acknowledge)throw new Error(warning);if(!selfUpdating){const outcome=(options.install??installDesktopUpdate)({staged:"",manifest,appName:options.appName,installation});message=outcome.status==="notice"?outcome.message:undefined;return}const directory=join(options.updatesDir,manifest.version);mkdirSync(directory,{recursive:true});const staged=await stageDesktopUpdate(manifest,join(directory,ARTIFACT_NAMES[target.platform]??"update.bin"),options.fetcher,options.trustedKeys,target);const outcome=(options.install??installDesktopUpdate)({staged:staged.path,manifest,appName:options.appName,installation,allowUnsigned:options.allowUnsigned});if(outcome.status==="notice"){message=outcome.message;return}state=outcome.status;if(outcome.status==="installed"){relaunch=outcome.relaunch;rmSync(directory,{recursive:true,force:true})}}),async relaunchIfInstalled(){relaunch?.();relaunch=undefined}}}export const UPDATE_PATH="/__desktop/update";export function updateRequestHandler(updater){const json=(body,status=200)=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}});return async(request)=>{if(new URL(request.url).pathname!==UPDATE_PATH)return;if(request.method==="GET")return json(updater.status());if(request.method!=="POST")return json(errorBody({error:"Method Not Allowed",message:"Read the status with GET, or POST an action.",status:405}),405);const body=await request.json().catch(()=>null);if(body?.action==="check")return json(await updater.check());if(body?.action==="install")return json(await updater.install({acknowledge:body.acknowledge===true}));return json(errorBody({error:"Bad Request",message:'Send { action: "check" } or { action: "install" }.',status:400}),400)}}export function isMacosBundle(path){return path.endsWith(".app")&&existsSync(join(path,"Contents","MacOS"))}
|
|
2
|
+
${described.stderr}`;const teamId=text.match(/^TeamIdentifier=(.+)$/m)?.[1]?.trim();const identifier=text.match(/^Identifier=(.+)$/m)?.[1]?.trim();return{...teamId&&teamId!=="not set"?{teamId}:{},...identifier?{identifier}:{}}}export function assertMacosBundleTrusted(current,next,options={}){const run=options.run??runCommand;const verified=run(["codesign","--verify","--deep","--strict",next]);const running=macosSigner(current,run);const incoming=macosSigner(next,run);if(!running.teamId){if(!options.allowUnsigned)throw new Error("The running app is not signed with a Developer ID, so an update cannot be checked against it.");return}if(verified.exitCode!==0)throw new Error(`The update's signature is not valid: ${(verified.stderr||verified.stdout).trim()}`);if(incoming.teamId!==running.teamId)throw new Error(`The update is signed by ${incoming.teamId??"no one"}, not by this app's team ${running.teamId}.`);if(incoming.identifier!==running.identifier)throw new Error(`The update is a different app (${incoming.identifier??"unknown"}), not ${running.identifier}.`)}const dittoExtract=(archive,into)=>{const result=runCommand(["ditto","-x","-k",archive,into]);if(result.exitCode!==0)throw new Error(`Unpacking the update failed: ${result.stderr.trim()}`)};export function swapMacosBundle(options){const{bundle}=options;const scratch=mkdtempSync(join(dirname(bundle),".update-"));const aside=`${bundle}.previous-${process.pid}`;try{(options.extract??dittoExtract)(options.archive,scratch);const unpacked=readdirSync(scratch).filter((entry)=>entry.endsWith(".app"));if(unpacked.length!==1)throw new Error(`The update archive holds ${unpacked.length} apps; it has to hold exactly one.`);const next=join(scratch,unpacked[0]);assertMacosBundleTrusted(bundle,next,{run:options.run,allowUnsigned:options.allowUnsigned});renameSync(bundle,aside);try{renameSync(next,bundle)}catch(error){renameSync(aside,bundle);throw error}rmSync(aside,{recursive:true,force:true})}finally{rmSync(scratch,{recursive:true,force:true})}}export function replaceAppImage(staged,appImage){const incoming=`${appImage}.update-${process.pid}`;try{copyFileSync(staged,incoming);chmodSync(incoming,493);renameSync(incoming,appImage)}catch(error){rmSync(incoming,{force:true});throw error}}export function windowsSigner(file,run=runCommand){const script=`$s = Get-AuthenticodeSignature -LiteralPath '${file.replace(/'/g,"''")}'; Write-Output $s.Status; if ($s.SignerCertificate) { Write-Output $s.SignerCertificate.Subject }`;const result=run(["powershell.exe","-NoProfile","-NonInteractive","-Command",script]);const[status,subject]=result.stdout.split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);return{valid:result.exitCode===0&&status==="Valid",...subject?{subject}:{}}}export function assertWindowsInstallerTrusted(executable,installer,options={}){const running=windowsSigner(executable,options.run);if(!running.valid){if(options.allowUnsigned===false)throw new Error("The running app is not Authenticode-signed, so an update cannot be checked against it.");return}const incoming=windowsSigner(installer,options.run);if(!incoming.valid)throw new Error("The update installer is not validly signed.");if(incoming.subject!==running.subject)throw new Error(`The update is signed by ${incoming.subject??"no one"}, not by this app's publisher ${running.subject}.`)}export function installDesktopUpdate(options){const installation=options.installation??detectInstallation();const spawn=options.spawn??spawnDetached;const pid=options.pid??process.pid;const name=options.appName??"The app";switch(installation.kind){case"macos-bundle":{swapMacosBundle({archive:options.staged,bundle:installation.path,extract:options.extract,run:options.run,allowUnsigned:options.allowUnsigned});return{status:"installed",relaunch:()=>spawn(["open","-n",installation.path,"--args",`--wait-pid=${pid}`])}}case"linux-appimage":{replaceAppImage(options.staged,installation.path);return{status:"installed",relaunch:()=>spawn([installation.path,`--wait-pid=${pid}`])}}case"windows-msi":{assertWindowsInstallerTrusted(installation.executable,options.staged,{run:options.run,allowUnsigned:options.allowUnsigned});spawn(["cmd.exe","/d","/s","/c",`msiexec /i "${options.staged}" /passive /norestart && start "" "${installation.executable}" --wait-pid=${pid}`]);return{status:"installing"}}case"linux-package":return{status:"notice",message:`${name} ${options.manifest.version} is available. This copy was installed as a system package: update it with your package manager, or download the new package from ${new URL(options.manifest.url).origin}.`};default:return{status:"notice",message:`${name} ${options.manifest.version} is available, but this copy was not installed in a way that can update itself.`}}}const ARTIFACT_NAMES={darwin:"update.zip",win32:"update.msi",linux:"update.AppImage"};export function createDesktopUpdater(options){const installation=options.installation??detectInstallation();const target=options.target??{platform:process.platform,architecture:process.arch};const selfUpdating=["macos-bundle","windows-msi","linux-appimage"].includes(installation.kind);let state="idle";let manifest=null;let warning;let message;let error;let relaunch;let busy;const status=()=>({currentVersion:options.currentVersion,state,installKind:installation.kind,selfUpdating,...manifest?{version:manifest.version,...manifest.notes?{notes:manifest.notes}:{},...manifest.publishedAt?{publishedAt:manifest.publishedAt}:{}}:{},...warning?{warning}:{},...message?{message}:{},...error?{error}:{}});const once=(work)=>{busy??=work().catch((failure)=>{state="error";error=failure instanceof Error?failure.message:String(failure)}).then(()=>{busy=undefined;return status()});return busy};return{status,check:()=>once(async()=>{if(state==="installed"||state==="installing")return;state="checking";error=warning=message=undefined;manifest=await checkForDesktopUpdate({currentVersion:options.currentVersion,manifestUrl:updateFeedUrl(options.feedUrl,target,{channel:options.channel,currentVersion:options.currentVersion}),trustedKeys:options.trustedKeys,fetcher:options.fetcher,target});if(!manifest){state="current";return}const verdict=await options.beforeUpdate?.(manifest,{version:options.currentVersion});if(verdict&&"refuse"in verdict){state="refused";message=verdict.refuse;return}if(verdict&&"warn"in verdict)warning=verdict.warn;state="available"}),install:(install={})=>once(async()=>{if(state!=="available"||!manifest)throw new Error("There is no update to install. Check first.");if(warning&&!install.acknowledge)throw new Error(warning);if(!selfUpdating){const outcome=(options.install??installDesktopUpdate)({staged:"",manifest,appName:options.appName,installation});message=outcome.status==="notice"?outcome.message:undefined;return}const directory=join(options.updatesDir,manifest.version);mkdirSync(directory,{recursive:true});const staged=await stageDesktopUpdate(manifest,join(directory,ARTIFACT_NAMES[target.platform]??"update.bin"),options.fetcher,options.trustedKeys,target);await options.beforeInstall?.(manifest,{version:options.currentVersion});const outcome=(options.install??installDesktopUpdate)({staged:staged.path,manifest,appName:options.appName,installation,allowUnsigned:options.allowUnsigned});if(outcome.status==="notice"){message=outcome.message;return}state=outcome.status;if(outcome.status==="installed"){relaunch=outcome.relaunch;rmSync(directory,{recursive:true,force:true})}}),async relaunchIfInstalled(){relaunch?.();relaunch=undefined}}}export const UPDATE_PATH="/__desktop/update";export function updateRequestHandler(updater){const json=(body,status=200)=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}});return async(request)=>{if(new URL(request.url).pathname!==UPDATE_PATH)return;if(request.method==="GET")return json(updater.status());if(request.method!=="POST")return json(errorBody({error:"Method Not Allowed",message:"Read the status with GET, or POST an action.",status:405}),405);const body=await request.json().catch(()=>null);if(body?.action==="check")return json(await updater.check());if(body?.action==="install")return json(await updater.install({acknowledge:body.acknowledge===true}));return json(errorBody({error:"Bad Request",message:'Send { action: "check" } or { action: "install" }.',status:400}),400)}}export function isMacosBundle(path){return path.endsWith(".app")&&existsSync(join(path,"Contents","MacOS"))}
|
package/dist/webview-agent.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** A portable filename contained in the workspace's data directory. */
|
|
2
|
+
export declare function validWebviewDatabaseFilename(filename: string): boolean;
|
|
1
3
|
/**
|
|
2
4
|
* The rules every request passes before the app or the views see it. Kept
|
|
3
5
|
* apart from the server so both ways of serving views (the agent's own server
|
|
@@ -75,6 +77,7 @@ export declare interface WebviewAgentOptions {
|
|
|
75
77
|
version?: string
|
|
76
78
|
views: WebviewViews
|
|
77
79
|
handler?: WebviewHandler
|
|
80
|
+
initialize?: (context: WebviewAgentContext) => Promise<void>
|
|
78
81
|
port?: number
|
|
79
82
|
portFile?: string
|
|
80
83
|
dataDir?: string
|
package/dist/webview-agent.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{timingSafeEqual}from"node:crypto";import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,posix,win32}from"node:path";import process from"node:process";import{internalServerErrorBody}from"@stacksjs/router/error-body";import{isAgentHost,newAgentToken,rememberedPort,sessionCookie,staticContentType,staticFileResponse}from"./agent";export const INSTANCE_PATH="/__desktop/instance";export const INSTANCE_HEADER="x-desktop-instance";const ASSET_PREFIXES=["/_stx/","/assets/"];function sameSecret(given,expected){if(!given)return false;const left=Buffer.from(given);const right=Buffer.from(expected);return left.length===right.length&&timingSafeEqual(left,right)}function matchesPath(pathname,patterns){return patterns.some((pattern)=>pattern.endsWith("/")?pathname.startsWith(pattern):pathname===pattern)}const LAUNCH_TOKEN_TTL_MS=60000;export function createWebviewGate(options){const cookieName=options.cookieName??"stacks_desktop";const session=newAgentToken();const pending=new Map;const refusal=`Open ${options.appName??"the app"} to use this.`;return{cookieName,mint(){const token=newAgentToken();pending.set(token,Date.now()+LAUNCH_TOKEN_TTL_MS);return token},check(request){const url=new URL(request.url);if(!isAgentHost(request.headers.get("host"),options.port()))return{response:new Response("Forbidden",{status:403})};if(url.pathname===INSTANCE_PATH){if(request.method!=="POST"||!options.instanceSecret||!sameSecret(request.headers.get(INSTANCE_HEADER),options.instanceSecret))return{response:new Response("Forbidden",{status:403})};return{allow:"instance"}}const offered=url.searchParams.get("session");if(offered!==null){const expires=pending.get(offered);pending.delete(offered);if(request.method!=="GET"||expires===undefined||expires<Date.now())return{response:new Response(refusal,{status:401})};url.searchParams.delete("session");return{response:new Response(null,{status:302,headers:{location:`${url.pathname}${url.search}`,"set-cookie":sessionCookie(cookieName,session),"cache-control":"no-store"}})}}const cookies=request.headers.get("cookie");if(cookies&&cookies.split(/;\s*/).includes(`${cookieName}=${session}`))return{allow:"window"};if(options.publicPaths?.length&&matchesPath(url.pathname,options.publicPaths))return{allow:"public"};if(request.method==="GET"&&matchesPath(url.pathname,ASSET_PREFIXES))return{allow:"asset"};return{response:new Response(refusal,{status:401})}}}}export function portIsFree(port){try{Bun.listen({hostname:"127.0.0.1",port,socket:{data(){}}}).stop(true);return true}catch{return false}}export function pickAgentPort(options={}){const wanted=options.port??rememberedPort(options.portFile);let port=wanted&&portIsFree(wanted)?wanted:0;if(!port){const probe=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){}}});port=probe.port;probe.stop(true)}rememberPort(options.portFile,port);return port}function rememberPort(portFile,port){if(!portFile)return;try{mkdirSync(dirname(portFile),{recursive:true});writeFileSync(portFile,String(port))}catch{}}export function desktopAppPaths(appName,options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const slug=appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app";let dataDir;let logFile;const path=platform==="win32"?win32:posix;if(platform==="darwin"){dataDir=path.join(home,"Library","Application Support",appName);logFile=path.join(home,"Library","Logs",`${appName}.log`)}else if(platform==="win32"){dataDir=path.join(env.APPDATA||path.join(home,"AppData","Roaming"),appName);logFile=path.join(dataDir,"logs",`${appName}.log`)}else{dataDir=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),slug);logFile=path.join(env.XDG_STATE_HOME||path.join(home,".local","state"),slug,`${slug}.log`)}return{dataDir,portFile:path.join(dataDir,"agent.port"),lockFile:path.join(dataDir,"agent.lock"),logFile,updatesDir:path.join(dataDir,"updates")}}export function widenedPath(options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const current=env.PATH??env.Path??"";const path=platform==="win32"?win32:posix;const delimiter=platform==="win32"?";":":";const added=platform==="win32"?[path.join(home,".bun","bin"),path.join(env.LOCALAPPDATA||path.join(home,"AppData","Local"),"Microsoft","WinGet","Links"),path.join(home,"scoop","shims"),path.join(env.ProgramFiles||"C:\\Program Files","Git","cmd")]:[path.join(home,".local","bin"),path.join(home,".bun","bin"),path.join(home,".npm-global","bin"),path.join(home,".cargo","bin"),...platform==="darwin"?["/opt/homebrew/bin"]:["/home/linuxbrew/.linuxbrew/bin","/snap/bin"],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"];const seen=new Set;return[...added,...current.split(delimiter)].filter((entry)=>{if(!entry||seen.has(entry))return false;seen.add(entry);return true}).join(delimiter)}export function applyWidenedPath(){const path=widenedPath();process.env.PATH=path;if(process.platform==="win32"&&process.env.Path!==undefined)process.env.Path=path}function embeddedFileResponse(files,pathname){let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}for(const candidate of clean==="/index"?["/index.html"]:[`${clean}.html`,`${clean}/index.html`,clean]){const file=files[candidate];if(!file)continue;const ownType=staticContentType(file);const headers={"content-type":ownType==="application/octet-stream"?staticContentType(candidate):ownType};if(candidate.endsWith(".html"))headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}async function readSecondInstance(request){const body=await request.json().catch(()=>null);if(!body||!Array.isArray(body.args)||!body.args.every((arg)=>typeof arg==="string"))return null;return{args:body.args,cwd:typeof body.cwd==="string"?body.cwd:"",...typeof body.url==="string"?{url:body.url}:{}}}export async function startWebviewAgent(options){let port=0;const gate=createWebviewGate({port:()=>port,cookieName:options.cookieName,publicPaths:options.publicPaths,instanceSecret:options.instanceSecret,appName:options.appName});let markReady;const windowReady=new Promise((resolve)=>{markReady=resolve});const context=()=>({appName:options.appName,version:options.version??"0.0.0",origin:`http://127.0.0.1:${port}`,port,dataDir:options.dataDir??""});async function before(request){const decision=gate.check(request);if("response"in decision)return decision.response;if(decision.allow==="instance"){const launch=await readSecondInstance(request);if(!launch)return new Response("Bad request",{status:400});try{await options.onSecondInstance?.(launch)}catch(error){console.error(`[agent] second instance: ${error instanceof Error?error.message:String(error)}`)}return new Response(null,{status:204})}if(decision.allow==="asset")return;if(decision.allow==="window")markReady();if(!options.handler)return decision.allow==="public"?new Response("Not found",{status:404}):undefined;try{const answer=await options.handler(request,context());if(answer instanceof Response)return answer}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${new URL(request.url).pathname}: ${message}`);return new Response(JSON.stringify(internalServerErrorBody()),{status:500,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}return decision.allow==="public"?new Response("Not found",{status:404}):undefined}const launchUrl=(path="/")=>{const url=new URL(path,`http://127.0.0.1:${port}`);url.searchParams.set("session",gate.mint());return url.toString()};const views=options.views;if(views.kind==="stx"){port=pickAgentPort({port:options.port,portFile:options.portFile});const serve=views.serve??(await import(Bun.resolveSync("bun-plugin-stx/serve",views.root))).serve;let stxServer;const{componentsDir,additionalComponentsDirs=[]}=webviewComponentDirs(views.components);serve({patterns:[views.dir],port,quiet:true,...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{},onRequest:(request,server)=>{stxServer=server;return before(request)}});for(let attempt=0;attempt<200;attempt++){try{await fetch(`http://127.0.0.1:${port}/`,{redirect:"manual"});break}catch{await Bun.sleep(25)}}return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{stxServer?.stop(true)}}}const fetchHandler=async(request)=>{const answered=await before(request);if(answered)return answered;const pathname=new URL(request.url).pathname;const page=request.method!=="GET"&&request.method!=="HEAD"?null:views.kind==="static"?staticFileResponse(views.dir,pathname):views.kind==="embedded"?embeddedFileResponse(views.files,pathname):null;return page??new Response("Not found",{status:404})};const listen=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch:fetchHandler});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=listen(wanted)}catch(error){if(wanted===0)throw error;server=listen(0)}port=server.port??0;rememberPort(options.portFile,port);return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{server.stop(true)}}}export function webviewComponentDirs(components=[]){const[componentsDir,...additionalComponentsDirs]=components;return{...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{}}}
|
|
1
|
+
import{timingSafeEqual}from"node:crypto";import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,posix,win32}from"node:path";import process from"node:process";import{internalServerErrorBody}from"@stacksjs/router/error-body";import{isAgentHost,newAgentToken,rememberedPort,sessionCookie,staticContentType,staticFileResponse}from"./agent";export function validWebviewDatabaseFilename(filename){return typeof filename==="string"&&filename.length>0&&!/[<>:"/\\|?*]|[ .]$/.test(filename)&&!Array.from(filename).some((character)=>character.charCodeAt(0)<32)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(filename)}export const INSTANCE_PATH="/__desktop/instance";export const INSTANCE_HEADER="x-desktop-instance";const ASSET_PREFIXES=["/_stx/","/assets/"];function sameSecret(given,expected){if(!given)return false;const left=Buffer.from(given);const right=Buffer.from(expected);return left.length===right.length&&timingSafeEqual(left,right)}function matchesPath(pathname,patterns){return patterns.some((pattern)=>pattern.endsWith("/")?pathname.startsWith(pattern):pathname===pattern)}const LAUNCH_TOKEN_TTL_MS=60000;export function createWebviewGate(options){const cookieName=options.cookieName??"stacks_desktop";const session=newAgentToken();const pending=new Map;const refusal=`Open ${options.appName??"the app"} to use this.`;return{cookieName,mint(){const token=newAgentToken();pending.set(token,Date.now()+LAUNCH_TOKEN_TTL_MS);return token},check(request){const url=new URL(request.url);if(!isAgentHost(request.headers.get("host"),options.port()))return{response:new Response("Forbidden",{status:403})};if(url.pathname===INSTANCE_PATH){if(request.method!=="POST"||!options.instanceSecret||!sameSecret(request.headers.get(INSTANCE_HEADER),options.instanceSecret))return{response:new Response("Forbidden",{status:403})};return{allow:"instance"}}const offered=url.searchParams.get("session");if(offered!==null){const expires=pending.get(offered);pending.delete(offered);if(request.method!=="GET"||expires===undefined||expires<Date.now())return{response:new Response(refusal,{status:401})};url.searchParams.delete("session");return{response:new Response(null,{status:302,headers:{location:`${url.pathname}${url.search}`,"set-cookie":sessionCookie(cookieName,session),"cache-control":"no-store"}})}}const cookies=request.headers.get("cookie");if(cookies&&cookies.split(/;\s*/).includes(`${cookieName}=${session}`))return{allow:"window"};if(options.publicPaths?.length&&matchesPath(url.pathname,options.publicPaths))return{allow:"public"};if(request.method==="GET"&&matchesPath(url.pathname,ASSET_PREFIXES))return{allow:"asset"};return{response:new Response(refusal,{status:401})}}}}export function portIsFree(port){try{Bun.listen({hostname:"127.0.0.1",port,socket:{data(){}}}).stop(true);return true}catch{return false}}export function pickAgentPort(options={}){const wanted=options.port??rememberedPort(options.portFile);let port=wanted&&portIsFree(wanted)?wanted:0;if(!port){const probe=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){}}});port=probe.port;probe.stop(true)}rememberPort(options.portFile,port);return port}function rememberPort(portFile,port){if(!portFile)return;try{mkdirSync(dirname(portFile),{recursive:true});writeFileSync(portFile,String(port))}catch{}}export function desktopAppPaths(appName,options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const slug=appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app";let dataDir;let logFile;const path=platform==="win32"?win32:posix;if(platform==="darwin"){dataDir=path.join(home,"Library","Application Support",appName);logFile=path.join(home,"Library","Logs",`${appName}.log`)}else if(platform==="win32"){dataDir=path.join(env.APPDATA||path.join(home,"AppData","Roaming"),appName);logFile=path.join(dataDir,"logs",`${appName}.log`)}else{dataDir=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),slug);logFile=path.join(env.XDG_STATE_HOME||path.join(home,".local","state"),slug,`${slug}.log`)}return{dataDir,portFile:path.join(dataDir,"agent.port"),lockFile:path.join(dataDir,"agent.lock"),logFile,updatesDir:path.join(dataDir,"updates")}}export function widenedPath(options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const current=env.PATH??env.Path??"";const path=platform==="win32"?win32:posix;const delimiter=platform==="win32"?";":":";const added=platform==="win32"?[path.join(home,".bun","bin"),path.join(env.LOCALAPPDATA||path.join(home,"AppData","Local"),"Microsoft","WinGet","Links"),path.join(home,"scoop","shims"),path.join(env.ProgramFiles||"C:\\Program Files","Git","cmd")]:[path.join(home,".local","bin"),path.join(home,".bun","bin"),path.join(home,".npm-global","bin"),path.join(home,".cargo","bin"),...platform==="darwin"?["/opt/homebrew/bin"]:["/home/linuxbrew/.linuxbrew/bin","/snap/bin"],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"];const seen=new Set;return[...added,...current.split(delimiter)].filter((entry)=>{if(!entry||seen.has(entry))return false;seen.add(entry);return true}).join(delimiter)}export function applyWidenedPath(){const path=widenedPath();process.env.PATH=path;if(process.platform==="win32"&&process.env.Path!==undefined)process.env.Path=path}function embeddedFileResponse(files,pathname){let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}for(const candidate of clean==="/index"?["/index.html"]:[`${clean}.html`,`${clean}/index.html`,clean]){const file=files[candidate];if(!file)continue;const ownType=staticContentType(file);const headers={"content-type":ownType==="application/octet-stream"?staticContentType(candidate):ownType};if(candidate.endsWith(".html"))headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}async function readSecondInstance(request){const body=await request.json().catch(()=>null);if(!body||!Array.isArray(body.args)||!body.args.every((arg)=>typeof arg==="string"))return null;return{args:body.args,cwd:typeof body.cwd==="string"?body.cwd:"",...typeof body.url==="string"?{url:body.url}:{}}}export async function startWebviewAgent(options){let port=0;let initialized=!options.initialize;const gate=createWebviewGate({port:()=>port,cookieName:options.cookieName,publicPaths:options.publicPaths,instanceSecret:options.instanceSecret,appName:options.appName});let markReady;const windowReady=new Promise((resolve)=>{markReady=resolve});const context=()=>({appName:options.appName,version:options.version??"0.0.0",origin:`http://127.0.0.1:${port}`,port,dataDir:options.dataDir??""});async function initialize(){await options.initialize?.(context());initialized=true}async function before(request){if(!initialized)return new Response("The desktop workspace is starting.",{status:503,headers:{"cache-control":"no-store"}});const decision=gate.check(request);if("response"in decision)return decision.response;if(decision.allow==="instance"){const launch=await readSecondInstance(request);if(!launch)return new Response("Bad request",{status:400});try{await options.onSecondInstance?.(launch)}catch(error){console.error(`[agent] second instance: ${error instanceof Error?error.message:String(error)}`)}return new Response(null,{status:204})}if(decision.allow==="asset")return;if(decision.allow==="window")markReady();if(!options.handler)return decision.allow==="public"?new Response("Not found",{status:404}):undefined;try{const answer=await options.handler(request,context());if(answer instanceof Response)return answer}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${new URL(request.url).pathname}: ${message}`);return new Response(JSON.stringify(internalServerErrorBody()),{status:500,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}return decision.allow==="public"?new Response("Not found",{status:404}):undefined}const launchUrl=(path="/")=>{const url=new URL(path,`http://127.0.0.1:${port}`);url.searchParams.set("session",gate.mint());return url.toString()};const views=options.views;if(views.kind==="stx"){port=pickAgentPort({port:options.port,portFile:options.portFile});await initialize();const serve=views.serve??(await import(Bun.resolveSync("bun-plugin-stx/serve",views.root))).serve;let stxServer;const{componentsDir,additionalComponentsDirs=[]}=webviewComponentDirs(views.components);serve({patterns:[views.dir],port,quiet:true,...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{},onRequest:(request,server)=>{stxServer=server;return before(request)}});for(let attempt=0;attempt<200;attempt++){try{await fetch(`http://127.0.0.1:${port}/`,{redirect:"manual"});break}catch{await Bun.sleep(25)}}return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{stxServer?.stop(true)}}}const fetchHandler=async(request)=>{const answered=await before(request);if(answered)return answered;const pathname=new URL(request.url).pathname;const page=request.method!=="GET"&&request.method!=="HEAD"?null:views.kind==="static"?staticFileResponse(views.dir,pathname):views.kind==="embedded"?embeddedFileResponse(views.files,pathname):null;return page??new Response("Not found",{status:404})};const listen=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch:fetchHandler});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=listen(wanted)}catch(error){if(wanted===0)throw error;server=listen(0)}port=server.port??0;try{await initialize()}catch(error){server.stop(true);throw error}rememberPort(options.portFile,port);return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{server.stop(true)}}}export function webviewComponentDirs(components=[]){const[componentsDir,...additionalComponentsDirs]=components;return{...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{}}}
|
package/dist/webview-app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,desktopLauncherCompileArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";import{desktopUpdatesProblems}from"./update-signing";import{webviewComponentDirs}from"./webview-agent";import{OPTIONAL_CRAFT_FLAGS,WEBVIEW_RUNTIME_NAME}from"./webview-launcher";export const DESKTOP_TARGETS=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];export const WEBVIEW_DEFAULTS={views:"resources/desktop",output:"storage/framework/desktop/webview",width:1280,height:800,minimumSystemVersion:"13.0",category:"public.app-category.developer-tools"};export async function hasWebviewDesktop(root){return Boolean((await loadDesktopConfig(root))?.webview)}export async function loadWebviewDesktop(root,packageVersion="0.0.0"){const config=await loadDesktopConfig(root);return config?.webview?resolveWebviewDesktop(config.webview,packageVersion):null}export function resolveWebviewDesktop(config,packageVersion="0.0.0",env=process.env){const version=config.version??packageVersion;return{...config,version,buildNumber:String(config.buildNumber??env.DESKTOP_BUILD_NUMBER??"").trim()||version.replace(/-.*$/,""),window:{...config.window,title:config.window?.title??config.appName,width:config.window?.width??WEBVIEW_DEFAULTS.width,height:config.window?.height??WEBVIEW_DEFAULTS.height},agent:{...config.agent,views:config.agent?.views??WEBVIEW_DEFAULTS.views},output:config.output??WEBVIEW_DEFAULTS.output,executable:config.appName.replace(/[^\w .-]+/g,"").trim()||"App",slug:config.appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app"}}export function validateWebviewDesktop(config){const errors=[];if(!config.appName?.trim())errors.push("webview.appName is required");if(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(config.appId??""))errors.push(`webview.appId must be reverse-DNS, like org.example.app (got ${JSON.stringify(config.appId)})`);const versionValid=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version);if(!versionValid)errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);if((versionValid||config.buildNumber!==config.version)&&!/^\d+(\.\d+){0,2}$/.test(config.buildNumber))errors.push(`webview.buildNumber must be one to three dot-separated integers, as CFBundleVersion is (got ${JSON.stringify(config.buildNumber)})`);for(const scheme of config.urlSchemes??[]){if(!/^[a-z][a-z0-9+.-]*$/i.test(scheme))errors.push(`webview.urlSchemes: ${JSON.stringify(scheme)} is not a URL scheme`)}if(config.updates)errors.push(...desktopUpdatesProblems(config.updates,"webview.updates"));return errors}export function hostDesktopTarget(){return`${process.platform}-${process.arch}`}export function parseDesktopTargets(input,host=hostDesktopTarget()){if(!input?.trim())return[host];if(input.trim()==="all")return[...DESKTOP_TARGETS];const targets=input.split(",").map((part)=>part.trim()).filter(Boolean).map((part)=>{const name=part.replace(/^macos-/,"darwin-").replace(/^windows-/,"win32-");if(!DESKTOP_TARGETS.includes(name))throw new Error(`Unknown desktop target ${JSON.stringify(part)}. Targets: ${DESKTOP_TARGETS.join(", ")}, or all.`);return name});return[...new Set(targets)]}export function splitDesktopTarget(target){const[platform,architecture]=target.split("-");return{platform,architecture}}export function bunCompileTarget(target){const{platform,architecture}=splitDesktopTarget(target);return`bun-${platform==="win32"?"windows":platform}-${architecture}`}export function webviewCompileArgs(options){const cross=options.target!==(options.host??hostDesktopTarget());const[command,...args]=desktopLauncherCompileArgs(options);return[command,...cross?[`--target=${bunCompileTarget(options.target)}`]:[],...options.target.startsWith("win32-")?["--windows-hide-console"]:[],...args]}export function webviewRuntimeFor(config,target,options){const configured=configuredWebviewRuntime(config,target,options);if(configured)return configured;throw new Error(`No Craft runtime for ${target}. Unpack that platform's Craft release and name its binary in desktop.webview.runtime['${target}'] or CRAFT_BIN_${target.replace("-","_").toUpperCase()}.`)}export function isWrapperScript(file){return readFileSync(file).subarray(0,2).toString()==="#!"}export function nativeHostRuntime(hostRuntime){const found=hostRuntime();if(isWrapperScript(found))throw new Error(`The Craft on this machine is a wrapper script, not a native binary: ${found}. Name the native binary in CRAFT_BIN, or let the build fetch the published runtime.`);return found}export function configuredWebviewRuntime(config,target,options){const env=options.env??process.env;const variable=`CRAFT_BIN_${target.replace("-","_").toUpperCase()}`;const named=config.runtime?.[target]??env[variable];if(named){const file=isAbsolute(named)?named:resolve(options.root,named);if(!existsSync(file))throw new Error(`The Craft runtime for ${target} does not exist: ${file}`);return file}if(target===(options.host??hostDesktopTarget())&&options.hostRuntime)return options.hostRuntime();return null}export function probeCraftFlags(runtime,flags=OPTIONAL_CRAFT_FLAGS){const binary=readFileSync(runtime);return flags.filter((flag)=>binary.includes(flag))}export function webviewManifest(config,options){return{appName:config.appName,appId:config.appId,version:config.version,runtime:options.runtime,window:{title:config.window.title,width:config.window.width,height:config.window.height,...config.window.darkMode!==undefined?{darkMode:config.window.darkMode}:{},...options.development||config.window.devtools?{devtools:true}:{},...config.window.titlebarHidden?{titlebarHidden:true}:{},...config.window.arguments?.length?{arguments:config.window.arguments}:{}},...config.agent.port?{port:config.agent.port}:{},...config.agent.startPath?{startPath:config.agent.startPath}:{},...config.agent.publicPaths?.length?{publicPaths:config.agent.publicPaths}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.updates&&!options.development?{updates:{feedUrl:config.updates.feedUrl,publicKeys:config.updates.publicKeys,...config.updates.channel?{channel:config.updates.channel}:{},...config.updates.checkEveryHours!==undefined?{checkEveryHours:config.updates.checkEveryHours}:{}}}:{},...options.runtimeFlags?.length?{runtimeFlags:options.runtimeFlags}:{},...options.sourceRevision?{sourceRevision:options.sourceRevision}:{}}}export function collectViewFiles(directory){const files={};const walk=(current)=>{for(const entry of readdirSync(current).sort()){if(entry===".DS_Store")continue;const file=join(current,entry);if(statSync(file).isDirectory())walk(file);else files[`/${relative(directory,file).split(sep).join("/")}`]=file}};if(existsSync(directory))walk(directory);return files}export const BUN_HARDENED_ENTITLEMENTS={"com.apple.security.cs.allow-jit":true,"com.apple.security.cs.allow-unsigned-executable-memory":true,"com.apple.security.cs.disable-library-validation":true};export function renderWebviewEntitlements(config){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
1
|
+
import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,desktopLauncherCompileArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";import{desktopUpdatesProblems}from"./update-signing";import{validWebviewDatabaseFilename,webviewComponentDirs}from"./webview-agent";import{OPTIONAL_CRAFT_FLAGS,WEBVIEW_RUNTIME_NAME}from"./webview-launcher";export const DESKTOP_TARGETS=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];export const WEBVIEW_DEFAULTS={views:"resources/desktop",output:"storage/framework/desktop/webview",width:1280,height:800,minimumSystemVersion:"13.0",category:"public.app-category.developer-tools"};export async function hasWebviewDesktop(root){return Boolean((await loadDesktopConfig(root))?.webview)}export async function loadWebviewDesktop(root,packageVersion="0.0.0"){const config=await loadDesktopConfig(root);return config?.webview?resolveWebviewDesktop(config.webview,packageVersion):null}export function resolveWebviewDesktop(config,packageVersion="0.0.0",env=process.env){const version=config.version??packageVersion;return{...config,version,buildNumber:String(config.buildNumber??env.DESKTOP_BUILD_NUMBER??"").trim()||version.replace(/-.*$/,""),window:{...config.window,title:config.window?.title??config.appName,width:config.window?.width??WEBVIEW_DEFAULTS.width,height:config.window?.height??WEBVIEW_DEFAULTS.height},agent:{...config.agent,views:config.agent?.views??WEBVIEW_DEFAULTS.views},output:config.output??WEBVIEW_DEFAULTS.output,executable:config.appName.replace(/[^\w .-]+/g,"").trim()||"App",slug:config.appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app"}}export function validateWebviewDesktop(config){const errors=[];if(!config.appName?.trim())errors.push("webview.appName is required");if(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(config.appId??""))errors.push(`webview.appId must be reverse-DNS, like org.example.app (got ${JSON.stringify(config.appId)})`);const versionValid=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version);if(!versionValid)errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);if((versionValid||config.buildNumber!==config.version)&&!/^\d+(\.\d+){0,2}$/.test(config.buildNumber))errors.push(`webview.buildNumber must be one to three dot-separated integers, as CFBundleVersion is (got ${JSON.stringify(config.buildNumber)})`);for(const scheme of config.urlSchemes??[]){if(!/^[a-z][a-z0-9+.-]*$/i.test(scheme))errors.push(`webview.urlSchemes: ${JSON.stringify(scheme)} is not a URL scheme`)}if(config.updates)errors.push(...desktopUpdatesProblems(config.updates,"webview.updates"));const database=config.agent.database;if(database&&typeof database==="object"&&database.filename!==undefined&&!validWebviewDatabaseFilename(database.filename))errors.push("webview.agent.database.filename must be a filename within the app data directory");return errors}export function hostDesktopTarget(){return`${process.platform}-${process.arch}`}export function parseDesktopTargets(input,host=hostDesktopTarget()){if(!input?.trim())return[host];if(input.trim()==="all")return[...DESKTOP_TARGETS];const targets=input.split(",").map((part)=>part.trim()).filter(Boolean).map((part)=>{const name=part.replace(/^macos-/,"darwin-").replace(/^windows-/,"win32-");if(!DESKTOP_TARGETS.includes(name))throw new Error(`Unknown desktop target ${JSON.stringify(part)}. Targets: ${DESKTOP_TARGETS.join(", ")}, or all.`);return name});return[...new Set(targets)]}export function splitDesktopTarget(target){const[platform,architecture]=target.split("-");return{platform,architecture}}export function bunCompileTarget(target){const{platform,architecture}=splitDesktopTarget(target);return`bun-${platform==="win32"?"windows":platform}-${architecture}`}export function webviewCompileArgs(options){const cross=options.target!==(options.host??hostDesktopTarget());const[command,...args]=desktopLauncherCompileArgs(options);return[command,...cross?[`--target=${bunCompileTarget(options.target)}`]:[],...options.target.startsWith("win32-")?["--windows-hide-console"]:[],...args]}export function webviewRuntimeFor(config,target,options){const configured=configuredWebviewRuntime(config,target,options);if(configured)return configured;throw new Error(`No Craft runtime for ${target}. Unpack that platform's Craft release and name its binary in desktop.webview.runtime['${target}'] or CRAFT_BIN_${target.replace("-","_").toUpperCase()}.`)}export function isWrapperScript(file){return readFileSync(file).subarray(0,2).toString()==="#!"}export function nativeHostRuntime(hostRuntime){const found=hostRuntime();if(isWrapperScript(found))throw new Error(`The Craft on this machine is a wrapper script, not a native binary: ${found}. Name the native binary in CRAFT_BIN, or let the build fetch the published runtime.`);return found}export function configuredWebviewRuntime(config,target,options){const env=options.env??process.env;const variable=`CRAFT_BIN_${target.replace("-","_").toUpperCase()}`;const named=config.runtime?.[target]??env[variable];if(named){const file=isAbsolute(named)?named:resolve(options.root,named);if(!existsSync(file))throw new Error(`The Craft runtime for ${target} does not exist: ${file}`);return file}if(target===(options.host??hostDesktopTarget())&&options.hostRuntime)return options.hostRuntime();return null}export function probeCraftFlags(runtime,flags=OPTIONAL_CRAFT_FLAGS){const binary=readFileSync(runtime);return flags.filter((flag)=>binary.includes(flag))}export function webviewManifest(config,options){return{appName:config.appName,appId:config.appId,version:config.version,runtime:options.runtime,window:{title:config.window.title,width:config.window.width,height:config.window.height,...config.window.darkMode!==undefined?{darkMode:config.window.darkMode}:{},...options.development||config.window.devtools?{devtools:true}:{},...config.window.titlebarHidden?{titlebarHidden:true}:{},...config.window.arguments?.length?{arguments:config.window.arguments}:{}},...config.agent.port?{port:config.agent.port}:{},...config.agent.startPath?{startPath:config.agent.startPath}:{},...config.agent.publicPaths?.length?{publicPaths:config.agent.publicPaths}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.updates&&!options.development?{updates:{feedUrl:config.updates.feedUrl,publicKeys:config.updates.publicKeys,...config.updates.channel?{channel:config.updates.channel}:{},...config.updates.checkEveryHours!==undefined?{checkEveryHours:config.updates.checkEveryHours}:{}}}:{},...options.runtimeFlags?.length?{runtimeFlags:options.runtimeFlags}:{},...options.sourceRevision?{sourceRevision:options.sourceRevision}:{}}}export function collectViewFiles(directory){const files={};const walk=(current)=>{for(const entry of readdirSync(current).sort()){if(entry===".DS_Store")continue;const file=join(current,entry);if(statSync(file).isDirectory())walk(file);else files[`/${relative(directory,file).split(sep).join("/")}`]=file}};if(existsSync(directory))walk(directory);return files}export const BUN_HARDENED_ENTITLEMENTS={"com.apple.security.cs.allow-jit":true,"com.apple.security.cs.allow-unsigned-executable-memory":true,"com.apple.security.cs.disable-library-validation":true};export function renderWebviewEntitlements(config){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0">
|
|
4
4
|
${plistValue({...BUN_HARDENED_ENTITLEMENTS,...config.macos?.entitlements})}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { desktopAppPaths } from './webview-agent';
|
|
2
2
|
import type { AgentBundleFiles, StacksAgentHandlerOptions } from './agent-launcher';
|
|
3
|
-
import type { BeforeDesktopUpdate, DesktopUpdater } from './update-install';
|
|
3
|
+
import type { BeforeDesktopInstall, BeforeDesktopUpdate, DesktopUpdater } from './update-install';
|
|
4
4
|
import type { BundledConfig } from '@stacksjs/config/sources';
|
|
5
5
|
import type { SecondInstanceLaunch, WebviewAgent, WebviewAgentContext, WebviewHandler, WebviewViews } from './webview-agent';
|
|
6
6
|
/** A module's default export, as a `WebviewAgentModule`: a bare function is its `fetch`. */
|
|
@@ -82,6 +82,7 @@ export declare function appRouteHandler(handler: (request: Request) => Response
|
|
|
82
82
|
export declare function renderWebviewEntry(options: {
|
|
83
83
|
manifest: WebviewAppManifest
|
|
84
84
|
agentEntry?: string
|
|
85
|
+
prepareEntry?: string
|
|
85
86
|
|
|
86
87
|
viewFiles?: Record<string, string>
|
|
87
88
|
|
|
@@ -90,6 +91,7 @@ export declare function renderWebviewEntry(options: {
|
|
|
90
91
|
launcherModule?: string
|
|
91
92
|
|
|
92
93
|
migrations?: Record<string, string>
|
|
94
|
+
databaseFilename?: string
|
|
93
95
|
|
|
94
96
|
migrationRunner?: string
|
|
95
97
|
|
|
@@ -147,6 +149,7 @@ export declare interface WebviewAgentModule {
|
|
|
147
149
|
start?: (context: WebviewAgentContext & { launch: SecondInstanceLaunch, updater?: DesktopUpdater }) => void | Promise<void>
|
|
148
150
|
secondInstance?: (launch: SecondInstanceLaunch) => void | Promise<void>
|
|
149
151
|
beforeUpdate?: BeforeDesktopUpdate
|
|
152
|
+
beforeInstall?: BeforeDesktopInstall
|
|
150
153
|
stop?: () => void | Promise<void>
|
|
151
154
|
}
|
|
152
155
|
/** What the lock file holds: enough for a second launch to reach the first. */
|
|
@@ -163,6 +166,7 @@ export declare interface RunWebviewAppOptions {
|
|
|
163
166
|
manifest: WebviewAppManifest
|
|
164
167
|
views: WebviewViews
|
|
165
168
|
module?: () => Promise<unknown>
|
|
169
|
+
prepare?: WebviewAgentPreparation
|
|
166
170
|
embeddedRuntime?: string
|
|
167
171
|
argv?: string[]
|
|
168
172
|
paths?: ReturnType<typeof desktopAppPaths>
|
|
@@ -176,6 +180,8 @@ export declare interface RunWebviewAppOptions {
|
|
|
176
180
|
}
|
|
177
181
|
/** What `runWebviewApp` needs to bring the app's database up to date. */
|
|
178
182
|
export declare interface WebviewDatabase {
|
|
183
|
+
filename?: string
|
|
179
184
|
migrations: Record<string, string>
|
|
180
185
|
migrate: (options: { databasePath: string, migrations: Record<string, string> }) => { applied: string[] }
|
|
181
186
|
}
|
|
187
|
+
export type WebviewAgentPreparation = (context: WebviewAgentContext & { databasePath?: string }) => void | Promise<void>;
|
package/dist/webview-launcher.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{newAgentToken}from"./agent";import{agentBundleSource,logToFileWhenDetached,stacksAgentHandler}from"./agent-launcher";import{createDesktopUpdater,updateRequestHandler}from"./update-install";import{applyWidenedPath,desktopAppPaths,INSTANCE_HEADER,INSTANCE_PATH,startWebviewAgent}from"./webview-agent";export const OPTIONAL_CRAFT_FLAGS=["--single-instance","--deep-link","--app-name"];export const WEBVIEW_RUNTIME_NAME="craft-runtime";export const WAIT_PID_FLAG="--wait-pid=";export function agentModuleOf(loaded){const value=loaded&&typeof loaded==="object"&&"default"in loaded?loaded.default:loaded;if(typeof value==="function")return{fetch:value};return value&&typeof value==="object"?value:{}}function readInstance(lockFile){try{const record=JSON.parse(readFileSync(lockFile,"utf8"));return Number.isInteger(record.pid)&&typeof record.secret==="string"?{pid:record.pid,port:Number(record.port)||0,secret:record.secret}:null}catch{return null}}function isAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function writeInstance(lockFile,record){mkdirSync(dirname(lockFile),{recursive:true});const temporary=`${lockFile}.${record.pid}`;writeFileSync(temporary,JSON.stringify(record),{mode:384});renameSync(temporary,lockFile)}export function acquireWebviewInstance(lockFile,pid=process.pid){const holder=readInstance(lockFile);if(holder&&holder.pid!==pid&&isAlive(holder.pid))return{acquired:false,holder};const record={pid,port:0,secret:newAgentToken()};writeInstance(lockFile,record);return{acquired:true,record}}export function publishInstancePort(lockFile,record,port){record.port=port;writeInstance(lockFile,record)}export function releaseWebviewInstance(lockFile,pid=process.pid){if(readInstance(lockFile)?.pid===pid)rmSync(lockFile,{force:true})}export function parseLaunchArguments(argv,urlSchemes=[]){const args=[];let url;let waitPid;for(const arg of argv){if(arg.startsWith(WAIT_PID_FLAG)){const pid=Number(arg.slice(WAIT_PID_FLAG.length));if(Number.isInteger(pid)&&pid>0)waitPid=pid;continue}if(arg.startsWith("-psn_"))continue;if(!url&&urlSchemes.some((scheme)=>arg.toLowerCase().startsWith(`${scheme.toLowerCase()}:`))){url=arg;continue}args.push(arg)}return{args,...url?{url}:{},...waitPid?{waitPid}:{}}}export async function forwardToInstance(lockFile,launch,options={}){const fetcher=options.fetcher??fetch;for(let attempt=0;attempt<(options.attempts??40);attempt++){const holder=readInstance(lockFile);if(!holder||!isAlive(holder.pid))return false;if(holder.port){try{const response=await fetcher(`http://127.0.0.1:${holder.port}${INSTANCE_PATH}`,{method:"POST",headers:{"content-type":"application/json",[INSTANCE_HEADER]:holder.secret},body:JSON.stringify(launch)});if(response.status===204)return true}catch{}}await Bun.sleep(options.delayMs??125)}return false}export function craftWindowCommand(manifest,runtime,url,launch={}){const{window}=manifest;const has=(flag)=>manifest.runtimeFlags?.includes(flag)===true;return[runtime,"--url",url,"--title",window.title,"--width",String(window.width),"--height",String(window.height),...has("--app-name")?["--app-name",manifest.appName]:[],...has("--single-instance")?["--single-instance",manifest.appId,...(launch.args??[]).flatMap((arg)=>["--instance-arg",arg])]:[],...launch.url&&has("--deep-link")?["--deep-link",launch.url]:[],...window.devtools?[]:["--no-devtools"],...window.darkMode===true?["--dark"]:window.darkMode===false?["--light"]:[],...window.titlebarHidden?["--titlebar-hidden"]:[],...window.arguments??[]]}export function resolveWebviewRuntime(manifest,options){const platform=options.platform??process.platform;const name=platform==="win32"?`${WEBVIEW_RUNTIME_NAME}.exe`:WEBVIEW_RUNTIME_NAME;if(manifest.runtime==="beside")return join(dirname(options.execPath??process.execPath),name);if(manifest.runtime!=="embedded")return manifest.runtime;if(!options.embedded)throw new Error("This app was built with an embedded Craft runtime, but none was compiled in.");const bytes=readFileSync(options.embedded);const digest=createHash("sha256").update(bytes).digest("hex");const target=join(options.dataDir,"runtime",digest.slice(0,16),name);const current=existsSync(target)?createHash("sha256").update(readFileSync(target)).digest("hex"):"";if(current!==digest){mkdirSync(dirname(target),{recursive:true});const temporary=`${target}.${process.pid}`;writeFileSync(temporary,bytes,{mode:493});renameSync(temporary,target)}if(platform!=="win32")chmodSync(target,493);return target}async function waitForExit(pid,timeoutMs=15000){const until=Date.now()+timeoutMs;while(isAlive(pid)&&Date.now()<until)await Bun.sleep(100)}function defaultArgv(){return process.argv.slice(2)}function spawnCraft(command,env){const child=Bun.spawn(command,{env:{...process.env,...env},stdio:["ignore","inherit","pipe"]});new Response(child.stderr).text().then((stderr)=>{const lines=stderr.split(`
|
|
1
|
+
import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{newAgentToken}from"./agent";import{agentBundleSource,logToFileWhenDetached,stacksAgentHandler}from"./agent-launcher";import{createDesktopUpdater,updateRequestHandler}from"./update-install";import{applyWidenedPath,desktopAppPaths,INSTANCE_HEADER,INSTANCE_PATH,startWebviewAgent,validWebviewDatabaseFilename}from"./webview-agent";export const OPTIONAL_CRAFT_FLAGS=["--single-instance","--deep-link","--app-name"];export const WEBVIEW_RUNTIME_NAME="craft-runtime";export const WAIT_PID_FLAG="--wait-pid=";export function agentModuleOf(loaded){const value=loaded&&typeof loaded==="object"&&"default"in loaded?loaded.default:loaded;if(typeof value==="function")return{fetch:value};return value&&typeof value==="object"?value:{}}function readInstance(lockFile){try{const record=JSON.parse(readFileSync(lockFile,"utf8"));return Number.isInteger(record.pid)&&typeof record.secret==="string"?{pid:record.pid,port:Number(record.port)||0,secret:record.secret}:null}catch{return null}}function isAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function writeInstance(lockFile,record){mkdirSync(dirname(lockFile),{recursive:true});const temporary=`${lockFile}.${record.pid}`;writeFileSync(temporary,JSON.stringify(record),{mode:384});renameSync(temporary,lockFile)}export function acquireWebviewInstance(lockFile,pid=process.pid){const holder=readInstance(lockFile);if(holder&&holder.pid!==pid&&isAlive(holder.pid))return{acquired:false,holder};const record={pid,port:0,secret:newAgentToken()};writeInstance(lockFile,record);return{acquired:true,record}}export function publishInstancePort(lockFile,record,port){record.port=port;writeInstance(lockFile,record)}export function releaseWebviewInstance(lockFile,pid=process.pid){if(readInstance(lockFile)?.pid===pid)rmSync(lockFile,{force:true})}export function parseLaunchArguments(argv,urlSchemes=[]){const args=[];let url;let waitPid;for(const arg of argv){if(arg.startsWith(WAIT_PID_FLAG)){const pid=Number(arg.slice(WAIT_PID_FLAG.length));if(Number.isInteger(pid)&&pid>0)waitPid=pid;continue}if(arg.startsWith("-psn_"))continue;if(!url&&urlSchemes.some((scheme)=>arg.toLowerCase().startsWith(`${scheme.toLowerCase()}:`))){url=arg;continue}args.push(arg)}return{args,...url?{url}:{},...waitPid?{waitPid}:{}}}export async function forwardToInstance(lockFile,launch,options={}){const fetcher=options.fetcher??fetch;for(let attempt=0;attempt<(options.attempts??40);attempt++){const holder=readInstance(lockFile);if(!holder||!isAlive(holder.pid))return false;if(holder.port){try{const response=await fetcher(`http://127.0.0.1:${holder.port}${INSTANCE_PATH}`,{method:"POST",headers:{"content-type":"application/json",[INSTANCE_HEADER]:holder.secret},body:JSON.stringify(launch)});if(response.status===204)return true}catch{}}await Bun.sleep(options.delayMs??125)}return false}export function craftWindowCommand(manifest,runtime,url,launch={}){const{window}=manifest;const has=(flag)=>manifest.runtimeFlags?.includes(flag)===true;return[runtime,"--url",url,"--title",window.title,"--width",String(window.width),"--height",String(window.height),...has("--app-name")?["--app-name",manifest.appName]:[],...has("--single-instance")?["--single-instance",manifest.appId,...(launch.args??[]).flatMap((arg)=>["--instance-arg",arg])]:[],...launch.url&&has("--deep-link")?["--deep-link",launch.url]:[],...window.devtools?[]:["--no-devtools"],...window.darkMode===true?["--dark"]:window.darkMode===false?["--light"]:[],...window.titlebarHidden?["--titlebar-hidden"]:[],...window.arguments??[]]}export function resolveWebviewRuntime(manifest,options){const platform=options.platform??process.platform;const name=platform==="win32"?`${WEBVIEW_RUNTIME_NAME}.exe`:WEBVIEW_RUNTIME_NAME;if(manifest.runtime==="beside")return join(dirname(options.execPath??process.execPath),name);if(manifest.runtime!=="embedded")return manifest.runtime;if(!options.embedded)throw new Error("This app was built with an embedded Craft runtime, but none was compiled in.");const bytes=readFileSync(options.embedded);const digest=createHash("sha256").update(bytes).digest("hex");const target=join(options.dataDir,"runtime",digest.slice(0,16),name);const current=existsSync(target)?createHash("sha256").update(readFileSync(target)).digest("hex"):"";if(current!==digest){mkdirSync(dirname(target),{recursive:true});const temporary=`${target}.${process.pid}`;writeFileSync(temporary,bytes,{mode:493});renameSync(temporary,target)}if(platform!=="win32")chmodSync(target,493);return target}async function waitForExit(pid,timeoutMs=15000){const until=Date.now()+timeoutMs;while(isAlive(pid)&&Date.now()<until)await Bun.sleep(100)}function defaultArgv(){return process.argv.slice(2)}function spawnCraft(command,env){const child=Bun.spawn(command,{env:{...process.env,...env},stdio:["ignore","inherit","pipe"]});new Response(child.stderr).text().then((stderr)=>{const lines=stderr.split(`
|
|
2
2
|
`).filter((line)=>line.trim());if(lines.length)console.error(`[craft] ${lines.join(`
|
|
3
|
-
`)}`)});return{exited:child.exited,kill:()=>child.kill()}}export async function runWebviewApp(options){const{manifest}=options;const paths=options.paths??desktopAppPaths(manifest.appName);const tag=`[${manifest.appName}]`;const loggingToFile=options.logWhenDetached!==false&&logToFileWhenDetached(paths.logFile);const launch=parseLaunchArguments(options.argv??defaultArgv(),manifest.urlSchemes);const incoming={args:launch.args,cwd:process.cwd(),...launch.url?{url:launch.url}:{}};const spawn=options.spawn??spawnCraft;if(launch.waitPid)await waitForExit(launch.waitPid);let runtime;try{runtime=resolveWebviewRuntime(manifest,{embedded:options.embeddedRuntime,dataDir:paths.dataDir});if(!existsSync(runtime))throw new Error(`the Craft runtime is missing: ${runtime}`)}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.message:String(error)}`);return 1}const lock=acquireWebviewInstance(paths.lockFile);if(!lock.acquired){const reached=await forwardToInstance(paths.lockFile,incoming);if((options.platform??process.platform)!=="darwin"&&manifest.runtimeFlags?.includes("--single-instance"))await spawn(craftWindowCommand(manifest,runtime,"about:blank",incoming),{}).exited.catch(()=>0);console.log(reached?`${tag} already running; handed over`:`${tag} already running`);return 0}applyWidenedPath();let module={};let agent;let serving;let updater;try{
|
|
3
|
+
`)}`)});return{exited:child.exited,kill:()=>child.kill()}}export async function runWebviewApp(options){const{manifest}=options;const paths=options.paths??desktopAppPaths(manifest.appName);const tag=`[${manifest.appName}]`;const loggingToFile=options.logWhenDetached!==false&&logToFileWhenDetached(paths.logFile);const launch=parseLaunchArguments(options.argv??defaultArgv(),manifest.urlSchemes);const incoming={args:launch.args,cwd:process.cwd(),...launch.url?{url:launch.url}:{}};const spawn=options.spawn??spawnCraft;if(launch.waitPid)await waitForExit(launch.waitPid);let runtime;try{runtime=resolveWebviewRuntime(manifest,{embedded:options.embeddedRuntime,dataDir:paths.dataDir});if(!existsSync(runtime))throw new Error(`the Craft runtime is missing: ${runtime}`)}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.message:String(error)}`);return 1}const lock=acquireWebviewInstance(paths.lockFile);if(!lock.acquired){const reached=await forwardToInstance(paths.lockFile,incoming);if((options.platform??process.platform)!=="darwin"&&manifest.runtimeFlags?.includes("--single-instance"))await spawn(craftWindowCommand(manifest,runtime,"about:blank",incoming),{}).exited.catch(()=>0);console.log(reached?`${tag} already running; handed over`:`${tag} already running`);return 0}applyWidenedPath();let module={};let agent;let serving;let updater;let answerUpdate;let answerApp;try{const filename=options.database?.filename??"database.sqlite";if(!validWebviewDatabaseFilename(filename))throw new Error("The desktop database must use a filename within the app data directory.");const databasePath=options.database?join(paths.dataDir,filename):undefined;const initialize=async(context)=>{if(context)await options.prepare?.({...context,databasePath});if(options.database&&databasePath){const{applied}=options.database.migrate({databasePath,migrations:options.database.migrations});if(applied.length)console.log(`${tag} applied ${applied.length} migration(s) to ${databasePath}`);process.env.DB_CONNECTION="sqlite";process.env.DB_DATABASE_PATH=databasePath}if(options.config)await loadBundledConfig(options.config);module=options.module?agentModuleOf(await options.module()):{};if(manifest.updates){updater=createDesktopUpdater({appName:manifest.appName,currentVersion:manifest.version,feedUrl:manifest.updates.feedUrl,trustedKeys:manifest.updates.publicKeys,channel:manifest.updates.channel,updatesDir:paths.updatesDir,beforeUpdate:module.beforeUpdate,beforeInstall:module.beforeInstall})}answerUpdate=updater?updateRequestHandler(updater):undefined;answerApp=options.app?appRouteHandler(await stacksAgentHandler({appRoutes:false,...options.app}),(await import("@stacksjs/router")).isUnmatchedRouteResponse):undefined;const{describeConfigSource,settledConfigSource}=await import("@stacksjs/config/sources");const source=await settledConfigSource();if(source)console.log(`${tag} ${describeConfigSource(source)}`)};if(!options.prepare)await initialize();agent=await startWebviewAgent({appName:manifest.appName,version:manifest.version,views:options.views,port:manifest.port,portFile:paths.portFile,dataDir:paths.dataDir,publicPaths:manifest.publicPaths,instanceSecret:lock.record.secret,initialize:options.prepare?initialize:undefined,handler:async(request,context)=>await answerUpdate?.(request)??await module.fetch?.(request,context)??answerApp?.(request),onSecondInstance:(next)=>module.secondInstance?.(next)});serving=agent;publishInstancePort(paths.lockFile,lock.record,agent.port);await module.start?.({appName:manifest.appName,version:manifest.version,origin:agent.origin,port:agent.port,dataDir:paths.dataDir,launch:incoming,...updater?{updater}:{}})}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.stack??error.message:String(error)}`);serving?.stop();await showFailureWindow({manifest,runtime,reason:error instanceof Error?error.message:String(error),...loggingToFile?{logFile:paths.logFile}:{},spawn,launch:incoming}).catch((shown)=>console.error(`${tag} could not show why: ${shown instanceof Error?shown.message:String(shown)}`));releaseWebviewInstance(paths.lockFile);return 1}options.onAgent?.(agent);console.log(`${tag} ${manifest.version} serving on ${agent.origin}`);const window=spawn(craftWindowCommand(manifest,runtime,agent.launchUrl(manifest.startPath),incoming),{CRAFT_RELAUNCH_EXECUTABLE:process.execPath,CRAFT_RELAUNCH_ARGS:JSON.stringify([...process.execPath.endsWith("bun")||process.execPath.endsWith("bun.exe")?[process.argv[1]??""]:[],`${WAIT_PID_FLAG}${process.pid}`])});const hours=manifest.updates?.checkEveryHours??24;let timer;if(updater&&hours>0){const check=()=>{updater.check().catch(()=>{})};agent.windowReady.then(check);timer=setInterval(check,hours*3600000);timer.unref?.()}let stopped=false;const stop=async()=>{if(stopped)return;stopped=true;if(timer)clearInterval(timer);window.kill();try{await module.stop?.()}catch(error){console.error(`${tag} stop: ${error instanceof Error?error.message:String(error)}`)}agent.stop();releaseWebviewInstance(paths.lockFile)};const signals=process.platform==="win32"?["SIGINT","SIGTERM"]:["SIGTERM","SIGINT","SIGHUP"];const onSignal=()=>{stop().then(()=>process.exit(0))};for(const signal of signals)process.on(signal,onSignal);const code=await window.exited;console.log(`${tag} window closed (${code})`);for(const signal of signals)process.off(signal,onSignal);await stop();await updater?.relaunchIfInstalled();return 0}export function renderFailurePage(options){const escape=(text)=>text.replace(/[&<>"']/g,(char)=>`&#${char.charCodeAt(0)};`);const name=escape(options.appName);return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="utf-8">
|
|
@@ -22,13 +22,15 @@ import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkd
|
|
|
22
22
|
</body>
|
|
23
23
|
</html>
|
|
24
24
|
`}export async function showFailureWindow(options){const page=renderFailurePage({appName:options.manifest.appName,reason:options.reason,...options.logFile?{logFile:options.logFile}:{}});const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(page,{headers:{"content-type":"text/html; charset=utf-8","content-security-policy":"default-src 'none'; style-src 'unsafe-inline'","cache-control":"no-store"}})});try{const{window}=options.manifest;const manifest={...options.manifest,window:{title:`${options.manifest.appName} could not start`,width:560,height:340,...window.darkMode!==undefined?{darkMode:window.darkMode}:{}}};await options.spawn(craftWindowCommand(manifest,options.runtime,`http://127.0.0.1:${server.port}/`,{args:options.launch?.args??[]}),{}).exited}finally{server.stop(true)}}export async function loadBundledConfig(config){const{configSource,registerBundledConfig}=await import("@stacksjs/config/sources");registerBundledConfig(config);await(await import("@stacksjs/config")).overridesReady;const failed=configSource()?.failed??[];if(failed.length)throw new Error(`config failed to load: ${failed.map((file)=>`config/${file.name}.ts: ${file.error}`).join("; ")}`)}export function appRouteHandler(handler,unmatched){return async(request)=>{const response=await handler(request);return await unmatched(response,request)?undefined:response}}export function renderWebviewEntry(options){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const bundled=options.routes?.length?agentBundleSource(options):undefined;const files=Object.entries(options.viewFiles??{});const imports=files.map(([,file],index)=>`import view${index} from ${JSON.stringify(file)} with { type: 'file' }`);const migrations=options.migrations?Object.entries(options.migrations):undefined;if(migrations){imports.push(`import { migrateCompiledDatabase } from ${JSON.stringify(options.migrationRunner??"@stacksjs/database/compiled-migrations")}`);migrations.forEach(([,file],index)=>imports.push(`import migration${index} from ${JSON.stringify(file)} with { type: 'text' }`))}const database=migrations?`
|
|
25
|
-
database: {
|
|
25
|
+
database: {${options.databaseFilename?`
|
|
26
|
+
filename: ${JSON.stringify(options.databaseFilename)},`:""}
|
|
26
27
|
migrations: {
|
|
27
28
|
${migrations.map(([name],index)=>` ${JSON.stringify(name)}: migration${index},`).join(`
|
|
28
29
|
`)}
|
|
29
30
|
},
|
|
30
31
|
migrate: migrateCompiledDatabase,
|
|
31
|
-
},`:"";const
|
|
32
|
+
},`:"";const prepare=options.prepareEntry?`
|
|
33
|
+
prepare: async context => (await import(${JSON.stringify(options.prepareEntry)})).default(context),`:"";const configFiles=Object.entries(options.configFiles??{});const config=configFiles.length?`
|
|
32
34
|
config: {
|
|
33
35
|
${configFiles.map(([name,file])=>` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`).join(`
|
|
34
36
|
`)}
|
|
@@ -54,6 +56,6 @@ process.exit(await runWebviewApp({
|
|
|
54
56
|
`)},
|
|
55
57
|
middleware: ${bundled.middleware.replace(/\n/g,`
|
|
56
58
|
`)},
|
|
57
|
-
},`:""}${database}${config}
|
|
59
|
+
},`:""}${prepare}${database}${config}
|
|
58
60
|
}))
|
|
59
61
|
`}export function webviewAgentEntry(root,entry){if(entry){const file=isAbsolute(entry)?entry:resolve(root,entry);if(!existsSync(file))throw new Error(`desktop.webview.agent.entry does not exist: ${file}`);return file}const conventional=join(root,"app/Desktop/Agent.ts");return existsSync(conventional)?conventional:undefined}export function copyExecutable(from,to){mkdirSync(dirname(to),{recursive:true});copyFileSync(from,to);if(process.platform!=="win32")chmodSync(to,493)}
|
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.
|
|
5
|
+
"version": "0.75.701",
|
|
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.
|
|
77
|
-
"@stacksjs/router": "0.75.
|
|
78
|
-
"@stacksjs/server": "0.75.
|
|
79
|
-
"@stacksjs/storage": "0.75.
|
|
76
|
+
"@stacksjs/config": "0.75.701",
|
|
77
|
+
"@stacksjs/router": "0.75.701",
|
|
78
|
+
"@stacksjs/server": "0.75.701",
|
|
79
|
+
"@stacksjs/storage": "0.75.701",
|
|
80
80
|
"craft-native": ">=0.0.505"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
|
-
"@stacksjs/config": "0.75.
|
|
84
|
-
"@stacksjs/router": "0.75.
|
|
85
|
-
"@stacksjs/server": "0.75.
|
|
86
|
-
"@stacksjs/storage": "0.75.
|
|
83
|
+
"@stacksjs/config": "0.75.701",
|
|
84
|
+
"@stacksjs/router": "0.75.701",
|
|
85
|
+
"@stacksjs/server": "0.75.701",
|
|
86
|
+
"@stacksjs/storage": "0.75.701"
|
|
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.
|
|
103
|
+
"@stacksjs/build": "0.75.701",
|
|
104
104
|
"better-dx": "^0.2.39"
|
|
105
105
|
}
|
|
106
106
|
}
|