@stacksjs/desktop-build 0.75.556 → 0.75.558
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/craft-runtime.d.ts +52 -0
- package/dist/craft-runtime.js +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/update-feed.d.ts +24 -0
- package/dist/update-feed.js +1 -1
- package/dist/webview-agent.d.ts +8 -0
- package/dist/webview-agent.js +1 -1
- package/dist/webview-app.d.ts +15 -0
- package/dist/webview-app.js +6 -2
- package/package.json +10 -10
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { DesktopTargetName } from '@stacksjs/types';
|
|
2
|
+
/** The archive Craft publishes for a target, or null when it publishes none. */
|
|
3
|
+
export declare function craftRuntimeAsset(target: DesktopTargetName): string | null;
|
|
4
|
+
/** The runtime's file name inside that archive. */
|
|
5
|
+
export declare function craftRuntimeBinaryName(target: DesktopTargetName): string;
|
|
6
|
+
/**
|
|
7
|
+
* The companions found beside a Windows runtime that the app does not
|
|
8
|
+
* already name, so a build includes `WebView2Loader.dll` without being told.
|
|
9
|
+
*/
|
|
10
|
+
export declare function windowsRuntimeCompanions(runtime: string, alreadyNamed?: readonly string[]): string[];
|
|
11
|
+
/** A release manifest, checked for the shape this reads. Throws on anything else. */
|
|
12
|
+
export declare function parseCraftReleaseManifest(text: string, tag: string): CraftReleaseManifest;
|
|
13
|
+
/**
|
|
14
|
+
* The Craft runtime for `target`, from `directory` when the version kept
|
|
15
|
+
* there is the one asked for, else downloaded from that Craft release,
|
|
16
|
+
* verified and unpacked there.
|
|
17
|
+
*/
|
|
18
|
+
export declare function fetchCraftRuntime(options: FetchCraftRuntimeOptions): Promise<CraftRuntime>;
|
|
19
|
+
/** The version of the `craft-native` package a project resolves, which names the Craft release its runtimes come from. */
|
|
20
|
+
export declare function installedCraftVersion(root: string): string | null;
|
|
21
|
+
/**
|
|
22
|
+
* The Craft web view runtime for a platform this machine cannot supply
|
|
23
|
+
* itself. A desktop build copies each target's own Craft binary into the app;
|
|
24
|
+
* the host's comes from the installed Craft, and the others are the archives
|
|
25
|
+
* Craft publishes with every release (`craft-<os>-<arch>.zip`), fetched here
|
|
26
|
+
* once and kept.
|
|
27
|
+
*
|
|
28
|
+
* What is unpacked is only ever the file the release's own
|
|
29
|
+
* `release-manifest.json` describes: the archive's size and SHA-256 are
|
|
30
|
+
* checked against it first. That catches a truncated or swapped download; it
|
|
31
|
+
* is the same trust as installing Craft from that release, no more.
|
|
32
|
+
*/
|
|
33
|
+
export declare const CRAFT_RELEASE_REPOSITORY: 'craft-native/craft';
|
|
34
|
+
/** Files a Windows app needs beside the runtime, when they sit beside it: Craft ships `WebView2Loader.dll` in its archive. */
|
|
35
|
+
export declare const WINDOWS_RUNTIME_COMPANIONS: readonly ['WebView2Loader.dll'];
|
|
36
|
+
export declare interface CraftReleaseManifest {
|
|
37
|
+
tag: string
|
|
38
|
+
assets: Array<{ name: string, size: number, sha256: string }>
|
|
39
|
+
}
|
|
40
|
+
export declare interface FetchCraftRuntimeOptions {
|
|
41
|
+
target: DesktopTargetName
|
|
42
|
+
version: string
|
|
43
|
+
directory: string
|
|
44
|
+
fetcher?: (url: string) => Promise<Response>
|
|
45
|
+
unpack?: (archive: string, directory: string) => void
|
|
46
|
+
onFetch?: (url: string) => void
|
|
47
|
+
}
|
|
48
|
+
export declare interface CraftRuntime {
|
|
49
|
+
binary: string
|
|
50
|
+
version: string
|
|
51
|
+
fetched: boolean
|
|
52
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash}from"node:crypto";import{existsSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";export const CRAFT_RELEASE_REPOSITORY="craft-native/craft";export function craftRuntimeAsset(target){const names={"darwin-arm64":"craft-darwin-arm64.zip","darwin-x64":"craft-darwin-x64.zip","linux-x64":"craft-linux-x64.zip","win32-x64":"craft-windows-x64.zip"};return names[target]??null}export function craftRuntimeBinaryName(target){return target.startsWith("win32-")?"craft.exe":"craft"}export const WINDOWS_RUNTIME_COMPANIONS=["WebView2Loader.dll"];export function windowsRuntimeCompanions(runtime,alreadyNamed=[]){const named=new Set(alreadyNamed.map((file)=>file.split(/[\\/]/).pop().toLowerCase()));return WINDOWS_RUNTIME_COMPANIONS.filter((name)=>!named.has(name.toLowerCase())).map((name)=>join(dirname(runtime),name)).filter((file)=>existsSync(file))}export function parseCraftReleaseManifest(text,tag){let parsed;try{parsed=JSON.parse(text)}catch{throw new Error(`Craft ${tag}: release-manifest.json is not JSON`)}const manifest=parsed;if(manifest?.tag!==tag)throw new Error(`Craft ${tag}: release-manifest.json is for ${String(manifest?.tag)}`);if(!Array.isArray(manifest.assets))throw new Error(`Craft ${tag}: release-manifest.json lists no assets`);for(const asset of manifest.assets){if(typeof asset?.name!=="string"||!Number.isSafeInteger(asset.size)||typeof asset.sha256!=="string"||!/^[0-9a-f]{64}$/.test(asset.sha256))throw new Error(`Craft ${tag}: release-manifest.json has an asset without a name, size and SHA-256`)}return manifest}function unpackArchive(archive,directory){const attempts=[["unzip","-oq",archive,"-d",directory],["tar","-xf",archive,"-C",directory]];let failure="";for(const command of attempts){try{const result=Bun.spawnSync(command,{stdout:"ignore",stderr:"pipe"});if(result.exitCode===0)return;failure=result.stderr.toString().trim()||`${command[0]} exited with ${result.exitCode}`}catch(error){failure=error instanceof Error?error.message:String(error)}}throw new Error(`Could not unpack ${archive}: ${failure}`)}export async function fetchCraftRuntime(options){const{target,directory}=options;const version=options.version.replace(/^v/,"");if(!/^\d+\.\d+\.\d+(?:-[\w.]+)?$/.test(version))throw new Error(`Not a Craft version: ${options.version}`);const tag=`v${version}`;const asset=craftRuntimeAsset(target);if(!asset)throw new Error(`Craft publishes no runtime for ${target}. Build one there and name it in desktop.webview.runtime['${target}'].`);const binary=join(directory,craftRuntimeBinaryName(target));const stamp=join(directory,".craft-version");if(existsSync(binary)&&existsSync(stamp)&&readFileSync(stamp,"utf8").split(" ")[0]===tag)return{binary,version,fetched:false};const fetcher=options.fetcher??((url)=>fetch(url));const base=`https://github.com/${CRAFT_RELEASE_REPOSITORY}/releases/download/${tag}`;const get=async(name)=>{const url=`${base}/${name}`;options.onFetch?.(url);let response;try{response=await fetcher(url)}catch(error){throw new Error(`Could not download ${url}: ${error instanceof Error?error.message:String(error)}`)}if(!response.ok)throw new Error(`Could not download ${url}: HTTP ${response.status}`);return response};const manifest=parseCraftReleaseManifest(await(await get("release-manifest.json")).text(),tag);const listed=manifest.assets.find((entry)=>entry.name===asset);if(!listed)throw new Error(`Craft ${tag} lists no ${asset} in its release manifest.`);const bytes=new Uint8Array(await(await get(asset)).arrayBuffer());const sha256=createHash("sha256").update(bytes).digest("hex");if(bytes.byteLength!==listed.size||sha256!==listed.sha256)throw new Error(`${asset} from Craft ${tag} is not the published file: got ${bytes.byteLength} bytes, sha256 ${sha256}; the release manifest says ${listed.size} bytes, sha256 ${listed.sha256}.`);const staging=`${directory}.fetching`;rmSync(staging,{recursive:true,force:true});mkdirSync(staging,{recursive:true});try{const archive=join(staging,asset);writeFileSync(archive,bytes);(options.unpack??unpackArchive)(archive,staging);rmSync(archive,{force:true});if(!existsSync(join(staging,craftRuntimeBinaryName(target))))throw new Error(`${asset} from Craft ${tag} has no ${craftRuntimeBinaryName(target)} inside (it has: ${readdirSync(staging).join(", ")||"nothing"}).`);writeFileSync(join(staging,".craft-version"),`${tag} ${sha256}`);rmSync(directory,{recursive:true,force:true});mkdirSync(dirname(directory),{recursive:true});renameSync(staging,directory)}finally{rmSync(staging,{recursive:true,force:true})}return{binary,version,fetched:true}}export function installedCraftVersion(root){for(const from of[root,import.meta.dir]){try{let folder=dirname(Bun.resolveSync("craft-native",from));for(let depth=0;depth<6;depth++,folder=dirname(folder)){const file=join(folder,"package.json");if(!existsSync(file))continue;const pkg=JSON.parse(readFileSync(file,"utf8"));if(pkg.name==="craft-native"&&pkg.version)return pkg.version}}catch{}}return null}
|
package/dist/index.d.ts
CHANGED
|
@@ -365,6 +365,7 @@ export * from './update-install';
|
|
|
365
365
|
export * from './webview-agent';
|
|
366
366
|
export * from './webview-launcher';
|
|
367
367
|
export * from './webview-app';
|
|
368
|
+
export * from './craft-runtime';
|
|
368
369
|
export * from './support';
|
|
369
370
|
export * from './macos-app';
|
|
370
371
|
export * from './macos-bundle';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{closeSync,existsSync,openSync,readSync,statSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{craftBinaryNotFoundMessage,resolveCraftBinary as resolveCraftNativeBinary}from"craft-native";export*from"./agent";export*from"./agent-launcher";export*from"./invites";export*from"./updater";export*from"./update-signing";export*from"./update-feed";export*from"./update-install";export*from"./webview-agent";export*from"./webview-launcher";export*from"./webview-app";export*from"./support";export*from"./macos-app";export*from"./macos-bundle";export function resolveCraftBinary(explicit=process.env.CRAFT_BIN){return resolveCraftNativeBinary(explicit)}export function resolveCraftExecutable(explicit=process.env.CRAFT_BIN,findOnPath=(binary)=>Bun.which(binary)){const resolved=resolveCraftBinary(explicit);if(resolved!=="craft")return resolved;const executable=findOnPath(resolved);if(!executable)throw new Error(craftBinaryNotFoundMessage(resolved));return executable}export const USERLAND_LAUNCHER="app/Desktop/launcher.ts";export function hasUserlandDesktopLauncher(projectRoot=process.cwd()){return existsSync(join(projectRoot,USERLAND_LAUNCHER))}export function desktopLauncherCompileArgs(options){return["build","--compile",...options.minify===false?[]:["--minify"],...options.bytecode===false?[]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",options.entry,"--outfile",options.outfile]}export function resolveDesktopLauncher(projectRoot=process.cwd()){const userland=join(projectRoot,USERLAND_LAUNCHER);if(existsSync(userland))return userland;const here=dirname(fileURLToPath(import.meta.url));const candidates=[join(here,"launcher.ts"),join(here,"launcher.js")];const launcher=candidates.find((candidate)=>existsSync(candidate));if(!launcher){throw new Error("Desktop launcher entrypoint not found. Reinstall @stacksjs/desktop - the package must ship dist/launcher.js.")}return launcher}export const RESERVED_PLIST_KEYS=new Set(["CFBundleName","CFBundleDisplayName","CFBundleIdentifier","CFBundleVersion","CFBundleShortVersionString","CFBundleExecutable","CFBundlePackageType","CFBundleInfoDictionaryVersion","CFBundleIconFile"]);export function xmlEscape(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}export function plistValue(value,indent=""){if(typeof value==="string")return`<string>${xmlEscape(value)}</string>`;if(typeof value==="boolean")return value?"<true/>":"<false/>";if(typeof value==="number"){if(!Number.isFinite(value))throw new Error(`Unsupported Info.plist number: ${value}`);return Number.isInteger(value)?`<integer>${value}</integer>`:`<real>${value}</real>`}if(Array.isArray(value)){if(value.length===0)return"<array/>";const items=value.map((item)=>`${indent} ${plistValue(item,`${indent} `)}`).join(`
|
|
1
|
+
import{closeSync,existsSync,openSync,readSync,statSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{craftBinaryNotFoundMessage,resolveCraftBinary as resolveCraftNativeBinary}from"craft-native";export*from"./agent";export*from"./agent-launcher";export*from"./invites";export*from"./updater";export*from"./update-signing";export*from"./update-feed";export*from"./update-install";export*from"./webview-agent";export*from"./webview-launcher";export*from"./webview-app";export*from"./craft-runtime";export*from"./support";export*from"./macos-app";export*from"./macos-bundle";export function resolveCraftBinary(explicit=process.env.CRAFT_BIN){return resolveCraftNativeBinary(explicit)}export function resolveCraftExecutable(explicit=process.env.CRAFT_BIN,findOnPath=(binary)=>Bun.which(binary)){const resolved=resolveCraftBinary(explicit);if(resolved!=="craft")return resolved;const executable=findOnPath(resolved);if(!executable)throw new Error(craftBinaryNotFoundMessage(resolved));return executable}export const USERLAND_LAUNCHER="app/Desktop/launcher.ts";export function hasUserlandDesktopLauncher(projectRoot=process.cwd()){return existsSync(join(projectRoot,USERLAND_LAUNCHER))}export function desktopLauncherCompileArgs(options){return["build","--compile",...options.minify===false?[]:["--minify"],...options.bytecode===false?[]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",options.entry,"--outfile",options.outfile]}export function resolveDesktopLauncher(projectRoot=process.cwd()){const userland=join(projectRoot,USERLAND_LAUNCHER);if(existsSync(userland))return userland;const here=dirname(fileURLToPath(import.meta.url));const candidates=[join(here,"launcher.ts"),join(here,"launcher.js")];const launcher=candidates.find((candidate)=>existsSync(candidate));if(!launcher){throw new Error("Desktop launcher entrypoint not found. Reinstall @stacksjs/desktop - the package must ship dist/launcher.js.")}return launcher}export const RESERVED_PLIST_KEYS=new Set(["CFBundleName","CFBundleDisplayName","CFBundleIdentifier","CFBundleVersion","CFBundleShortVersionString","CFBundleExecutable","CFBundlePackageType","CFBundleInfoDictionaryVersion","CFBundleIconFile"]);export function xmlEscape(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}export function plistValue(value,indent=""){if(typeof value==="string")return`<string>${xmlEscape(value)}</string>`;if(typeof value==="boolean")return value?"<true/>":"<false/>";if(typeof value==="number"){if(!Number.isFinite(value))throw new Error(`Unsupported Info.plist number: ${value}`);return Number.isInteger(value)?`<integer>${value}</integer>`:`<real>${value}</real>`}if(Array.isArray(value)){if(value.length===0)return"<array/>";const items=value.map((item)=>`${indent} ${plistValue(item,`${indent} `)}`).join(`
|
|
2
2
|
`);return`<array>
|
|
3
3
|
${items}
|
|
4
4
|
${indent}</array>`}if(value&&typeof value==="object"){const entries=Object.entries(value);if(entries.length===0)return"<dict/>";const body=entries.map(([key,val])=>`${indent} <key>${xmlEscape(key)}</key>${plistValue(val,`${indent} `)}`).join(`
|
package/dist/update-feed.d.ts
CHANGED
|
@@ -64,6 +64,16 @@ export declare function answerUpdateArtifact(options: AnswerUpdateArtifactOption
|
|
|
64
64
|
* answers 404.
|
|
65
65
|
*/
|
|
66
66
|
export declare function answerUpdateFeed(options: AnswerUpdateFeedOptions): Promise<Response>;
|
|
67
|
+
/** The storage key of a channel's release.json. */
|
|
68
|
+
export declare function releaseRecordKey(location: { channel?: string, prefix?: string }): string;
|
|
69
|
+
/**
|
|
70
|
+
* The record after a release run. A release is often made in several runs,
|
|
71
|
+
* the Mac from a Mac and the Linux and Windows installers from where they
|
|
72
|
+
* were built: a run for the same version and channel keeps the targets it did
|
|
73
|
+
* not publish and replaces the ones it did. A different version, a different
|
|
74
|
+
* channel, or a stored record that cannot be read starts a new one.
|
|
75
|
+
*/
|
|
76
|
+
export declare function mergeReleaseRecord(stored: string | null | undefined, next: ReleaseRecord): ReleaseRecord;
|
|
67
77
|
/**
|
|
68
78
|
* Where a release's artifacts and manifests live, and the feed an app reads
|
|
69
79
|
* them through. One manifest per channel, platform and architecture, at a
|
|
@@ -126,5 +136,19 @@ export declare interface AnswerUpdateFeedOptions {
|
|
|
126
136
|
updates?: { disk?: string, prefix?: string, channel?: string }
|
|
127
137
|
store?: UpdateStore
|
|
128
138
|
}
|
|
139
|
+
/** One platform and architecture of a release, as release.json lists it. */
|
|
140
|
+
export declare interface ReleaseRecordTarget {
|
|
141
|
+
target: string
|
|
142
|
+
update: { url: string, sha256: string, bytes: number }
|
|
143
|
+
downloads: Array<{ name: string, url: string, sha256: string, bytes: number }>
|
|
144
|
+
}
|
|
145
|
+
/** release.json: every platform's installers for one version on one channel. What a download page reads. */
|
|
146
|
+
export declare interface ReleaseRecord {
|
|
147
|
+
version: string
|
|
148
|
+
channel: string
|
|
149
|
+
sourceRevision: string
|
|
150
|
+
publishedAt: string
|
|
151
|
+
targets: ReleaseRecordTarget[]
|
|
152
|
+
}
|
|
129
153
|
declare type UpdatesConfig = { disk?: string, prefix?: string, channel?: string }
|
|
130
154
|
export {};
|
package/dist/update-feed.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{existsSync,readFileSync}from"node:fs";import{basename,join}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{describeArtifact,signUpdateManifest}from"./update-signing";import{compareVersions,validateUpdateManifest}from"./updater";export const UPDATE_PLATFORMS=["darwin","linux","win32"];export const DEFAULT_UPDATE_PREFIX="desktop-updates";function checkedLocation(location){const channel=location.channel||"stable";const prefix=(location.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"");if(!UPDATE_PLATFORMS.includes(location.platform))throw new Error(`Unknown desktop platform: ${location.platform}`);if(!/^[a-z0-9_]+$/.test(location.architecture))throw new Error(`Unknown desktop architecture: ${location.architecture}`);if(!/^[a-z0-9][a-z0-9._-]*$/i.test(channel))throw new Error(`Invalid release channel: ${channel}`);return{platform:location.platform,architecture:location.architecture,channel,prefix}}export function updateManifestKey(location){const at=checkedLocation(location);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/latest.json`}export function updateArtifactKey(location,version,fileName){const at=checkedLocation(location);if(!/^\w[\w.+-]*$/.test(version)||!/^\w[\w.+ -]*$/.test(fileName))throw new Error(`Invalid artifact name: ${version}/${fileName}`);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/${version}/${fileName}`}export function updateFeedUrl(feedUrl,target,query={}){const url=new URL(`${feedUrl.replace(/\/+$/,"")}/${target.platform}/${target.architecture}`);if(query.channel&&query.channel!=="stable")url.searchParams.set("channel",query.channel);if(query.currentVersion)url.searchParams.set("current",query.currentVersion);return url.toString()}export function updateArtifactUrl(feedUrl,location,version,fileName){const key=updateArtifactKey({...location,prefix:""},version,fileName);return`${feedUrl.replace(/\/+$/,"")}/files/${key.replace(/^\/+/,"").split("/").map(encodeURIComponent).join("/")}`}export function artifactUrlProblem(url){let parsed;try{parsed=new URL(url)}catch{return`${url} is not a URL`}if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return`${url} is not an http(s) URL`;const host=parsed.hostname.toLowerCase().replace(/^\[|\]$/g,"");const local=host==="localhost"||host.endsWith(".localhost")||host.endsWith(".test")||host.endsWith(".local")||host==="::1"||host==="0.0.0.0"||/^127\./.test(host);return local?`${url} is on this machine (${host}): no installed app could download it`:null}export async function storageUpdateStore(disk){const{Storage}=await import("@stacksjs/storage");const adapter=Storage.disk(disk);return{read:async(key)=>await adapter.fileExists(key)?adapter.readToString(key):null,write:async(key,contents)=>{await adapter.write(key,typeof contents==="string"?contents:Buffer.from(contents))},publicUrl:(key)=>adapter.publicUrl(key),open:async(key)=>{if(!await adapter.fileExists(key))return null;const size=await adapter.fileSize(key);return{size,stream:async(range)=>{const whole=typeof adapter.getStream==="function"?await adapter.getStream(key):new Blob([await adapter.readToUint8Array(key)]).stream();return range?sliceStream(whole,range.start,range.end):whole}}}}}export function sliceStream(source,start,end){const reader=source.getReader();let offset=0;return new ReadableStream({async pull(controller){while(true){if(offset>end){await reader.cancel();controller.close();return}const{done,value}=await reader.read();if(done){controller.close();return}const from=Math.max(start-offset,0);const to=Math.min(end+1-offset,value.byteLength);offset+=value.byteLength;if(to>from){controller.enqueue(value.subarray(from,to));return}}},cancel:(reason)=>reader.cancel(reason)})}export async function publishedArtifactUrl(options,version,fileName){const key=updateArtifactKey(options,version,fileName);if(options.artifactBaseUrl)return`${options.artifactBaseUrl.replace(/\/+$/,"")}/${key.split("/").map(encodeURIComponent).join("/")}`;if(options.feedUrl)return updateArtifactUrl(options.feedUrl,options,version,fileName);return options.store.publicUrl(key)}export async function publishDesktopUpdate(options){const{size,sha256}=await describeArtifact(options.artifact);const artifactKey=updateArtifactKey(options,options.version,basename(options.artifact));const url=await publishedArtifactUrl(options,options.version,basename(options.artifact));await options.store.write(artifactKey,readFileSync(options.artifact));const unsigned={version:options.version,url,sha256,size,sourceRevision:options.sourceRevision,platform:options.platform,architecture:options.architecture,publishedAt:options.publishedAt??new Date().toISOString(),...options.notes?{notes:options.notes}:{}};const manifest=signUpdateManifest(unsigned,options.privateKey,options.keyId);await options.store.write(updateManifestKey(options),`${JSON.stringify(manifest,null,2)}
|
|
2
|
-
`);return manifest}const feedHeaders={"content-type":"application/json; charset=utf-8","cache-control":"no-store"};export async function serveUpdateFeed(options){let key;try{key=updateManifestKey(options)}catch(error){return new Response(JSON.stringify({error:error instanceof Error?error.message:String(error)}),{status:404,headers:feedHeaders})}const stored=await options.store.read(key);if(!stored)return new Response(JSON.stringify({error:"No update has been published for this platform."}),{status:404,headers:feedHeaders});let manifest;try{manifest=validateUpdateManifest(JSON.parse(stored))}catch{return new Response(JSON.stringify({error:"The published update manifest is not valid."}),{status:500,headers:feedHeaders})}if(options.currentVersion){try{if(compareVersions(manifest.version,options.currentVersion)<=0)return new Response(null,{status:204,headers:{"cache-control":"no-store"}})}catch{}}return new Response(stored,{headers:feedHeaders})}const artifactTypes={zip:"application/zip",dmg:"application/x-apple-diskimage",msi:"application/x-msi",exe:"application/vnd.microsoft.portable-executable",appimage:"application/vnd.appimage",deb:"application/vnd.debian.binary-package",rpm:"application/x-rpm"};function refused(status,error,headers={}){return new Response(JSON.stringify({error}),{status,headers:{...feedHeaders,...headers}})}export function parseByteRange(header,size){if(!header)return null;const match=/^bytes=(\d*)-(\d*)$/.exec(header.trim());if(!match||!match[1]&&!match[2])return null;if(!match[1]){const last=Number(match[2]);if(!last||!size)return false;return{start:Math.max(size-last,0),end:size-1}}const start=Number(match[1]);const end=match[2]?Math.min(Number(match[2]),size-1):size-1;if(start>=size||start>end)return false;return{start,end}}export async function serveUpdateArtifact(options){const missing=()=>refused(404,"No such release artifact.");const split=/^([a-z0-9]+)-([a-z0-9_]+)$/.exec(options.target);if(!split)return missing();let key;try{key=updateArtifactKey({platform:split[1],architecture:split[2],channel:options.channel,prefix:options.prefix},options.version,options.file)}catch{return missing()}if(!options.store.open)return missing();const stored=await options.store.open(key);if(!stored)return missing();const range=parseByteRange(options.range,stored.size);if(range===false)return refused(416,"The requested range is outside the file.",{"content-range":`bytes */${stored.size}`});const length=range?range.end-range.start+1:stored.size;const headers={"content-type":artifactTypes[options.file.slice(options.file.lastIndexOf(".")+1).toLowerCase()]??"application/octet-stream","content-length":String(length),"content-disposition":`attachment; filename="${options.file}"`,"accept-ranges":"bytes","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff"};if(range)headers["content-range"]=`bytes ${range.start}-${range.end}/${stored.size}`;const body=options.method?.toUpperCase()==="HEAD"?null:await stored.stream(range??undefined);return new Response(body,{status:range?206:200,headers})}async function projectUpdates(root){const file=join(root??process.cwd(),"config/desktop.ts");return existsSync(file)?(await import(pathToFileURL(file).href)).default?.webview?.updates:undefined}export async function answerUpdateArtifact(options){const updates=options.updates??(options.store?undefined:await projectUpdates(options.root));if(!updates&&!options.store)return refused(404,"This app publishes no desktop updates.");return serveUpdateArtifact({...options,store:options.store??await storageUpdateStore(updates?.disk),prefix:updates?.prefix})}export async function answerUpdateFeed(options){let updates=options.updates;if(!updates&&!options.store){updates=await projectUpdates(options.root);if(!updates)return new Response(JSON.stringify({error:"This app publishes no desktop updates."}),{status:404,headers:feedHeaders})}return serveUpdateFeed({store:options.store??await storageUpdateStore(updates?.disk),platform:options.platform,architecture:options.architecture,channel:options.channel||updates?.channel,prefix:updates?.prefix,currentVersion:options.currentVersion})}
|
|
2
|
+
`);return manifest}const feedHeaders={"content-type":"application/json; charset=utf-8","cache-control":"no-store"};export async function serveUpdateFeed(options){let key;try{key=updateManifestKey(options)}catch(error){return new Response(JSON.stringify({error:error instanceof Error?error.message:String(error)}),{status:404,headers:feedHeaders})}const stored=await options.store.read(key);if(!stored)return new Response(JSON.stringify({error:"No update has been published for this platform."}),{status:404,headers:feedHeaders});let manifest;try{manifest=validateUpdateManifest(JSON.parse(stored))}catch{return new Response(JSON.stringify({error:"The published update manifest is not valid."}),{status:500,headers:feedHeaders})}if(options.currentVersion){try{if(compareVersions(manifest.version,options.currentVersion)<=0)return new Response(null,{status:204,headers:{"cache-control":"no-store"}})}catch{}}return new Response(stored,{headers:feedHeaders})}const artifactTypes={zip:"application/zip",dmg:"application/x-apple-diskimage",msi:"application/x-msi",exe:"application/vnd.microsoft.portable-executable",appimage:"application/vnd.appimage",deb:"application/vnd.debian.binary-package",rpm:"application/x-rpm"};function refused(status,error,headers={}){return new Response(JSON.stringify({error}),{status,headers:{...feedHeaders,...headers}})}export function parseByteRange(header,size){if(!header)return null;const match=/^bytes=(\d*)-(\d*)$/.exec(header.trim());if(!match||!match[1]&&!match[2])return null;if(!match[1]){const last=Number(match[2]);if(!last||!size)return false;return{start:Math.max(size-last,0),end:size-1}}const start=Number(match[1]);const end=match[2]?Math.min(Number(match[2]),size-1):size-1;if(start>=size||start>end)return false;return{start,end}}export async function serveUpdateArtifact(options){const missing=()=>refused(404,"No such release artifact.");const split=/^([a-z0-9]+)-([a-z0-9_]+)$/.exec(options.target);if(!split)return missing();let key;try{key=updateArtifactKey({platform:split[1],architecture:split[2],channel:options.channel,prefix:options.prefix},options.version,options.file)}catch{return missing()}if(!options.store.open)return missing();const stored=await options.store.open(key);if(!stored)return missing();const range=parseByteRange(options.range,stored.size);if(range===false)return refused(416,"The requested range is outside the file.",{"content-range":`bytes */${stored.size}`});const length=range?range.end-range.start+1:stored.size;const headers={"content-type":artifactTypes[options.file.slice(options.file.lastIndexOf(".")+1).toLowerCase()]??"application/octet-stream","content-length":String(length),"content-disposition":`attachment; filename="${options.file}"`,"accept-ranges":"bytes","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff"};if(range)headers["content-range"]=`bytes ${range.start}-${range.end}/${stored.size}`;const body=options.method?.toUpperCase()==="HEAD"?null:await stored.stream(range??undefined);return new Response(body,{status:range?206:200,headers})}async function projectUpdates(root){const file=join(root??process.cwd(),"config/desktop.ts");return existsSync(file)?(await import(pathToFileURL(file).href)).default?.webview?.updates:undefined}export async function answerUpdateArtifact(options){const updates=options.updates??(options.store?undefined:await projectUpdates(options.root));if(!updates&&!options.store)return refused(404,"This app publishes no desktop updates.");return serveUpdateArtifact({...options,store:options.store??await storageUpdateStore(updates?.disk),prefix:updates?.prefix})}export async function answerUpdateFeed(options){let updates=options.updates;if(!updates&&!options.store){updates=await projectUpdates(options.root);if(!updates)return new Response(JSON.stringify({error:"This app publishes no desktop updates."}),{status:404,headers:feedHeaders})}return serveUpdateFeed({store:options.store??await storageUpdateStore(updates?.disk),platform:options.platform,architecture:options.architecture,channel:options.channel||updates?.channel,prefix:updates?.prefix,currentVersion:options.currentVersion})}export function releaseRecordKey(location){const channel=location.channel||"stable";if(!/^[a-z0-9][a-z0-9._-]*$/i.test(channel))throw new Error(`Invalid release channel: ${channel}`);return`${(location.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"")}/${channel}/release.json`}export function mergeReleaseRecord(stored,next){let previous=null;try{previous=stored?JSON.parse(stored):null}catch{previous=null}if(!previous||previous.version!==next.version||previous.channel!==next.channel||!Array.isArray(previous.targets))return next;const published=new Set(next.targets.map((item)=>item.target));const kept=previous.targets.filter((item)=>typeof item?.target==="string"&&item.update&&Array.isArray(item.downloads)&&!published.has(item.target));return{...next,targets:[...kept,...next.targets].sort((a,b)=>a.target.localeCompare(b.target))}}
|
package/dist/webview-agent.d.ts
CHANGED
|
@@ -32,6 +32,14 @@ export declare function widenedPath(options?: { platform?: string, home?: string
|
|
|
32
32
|
/** Set this process's PATH (and so its children's) to `widenedPath()`. */
|
|
33
33
|
export declare function applyWidenedPath(): void;
|
|
34
34
|
export declare function startWebviewAgent(options: WebviewAgentOptions): Promise<WebviewAgent>;
|
|
35
|
+
/**
|
|
36
|
+
* How stx is told where an app's components are: the first directory is the
|
|
37
|
+
* one it looks in first, the rest follow in order. `buddy dev:desktop`
|
|
38
|
+
* (stx's server) and `buddy build:desktop` (stx's static build) both read
|
|
39
|
+
* the list through here, so a component name defined twice resolves to the
|
|
40
|
+
* same file in the window you develop in and the app you ship.
|
|
41
|
+
*/
|
|
42
|
+
export declare function webviewComponentDirs(components?: readonly string[]): { componentsDir?: string, additionalComponentsDirs?: string[] };
|
|
35
43
|
export declare const INSTANCE_PATH: '/__desktop/instance';
|
|
36
44
|
export declare const INSTANCE_HEADER: 'x-desktop-instance';
|
|
37
45
|
/**
|
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{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 headers={"content-type":staticContentType(candidate)};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({error:message}),{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
|
|
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{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 headers={"content-type":staticContentType(candidate)};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({error:message}),{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}:{}}}
|
package/dist/webview-app.d.ts
CHANGED
|
@@ -27,6 +27,13 @@ export declare function webviewCompileArgs(options: { entry: string, outfile: st
|
|
|
27
27
|
* somewhere and named here.
|
|
28
28
|
*/
|
|
29
29
|
export declare function webviewRuntimeFor(config: Pick<WebviewDesktopConfig, 'runtime'>, target: DesktopTargetName, options: { root: string, env?: Record<string, string | undefined>, host?: DesktopTargetName, hostRuntime?: () => string }): string;
|
|
30
|
+
/**
|
|
31
|
+
* The runtime a project or this machine already has for a target, or null
|
|
32
|
+
* when neither does: the one named in the config or the environment, else the
|
|
33
|
+
* host's own Craft for the host's target. `buddy build:desktop` fetches the
|
|
34
|
+
* published runtime for a target this answers null for.
|
|
35
|
+
*/
|
|
36
|
+
export declare function configuredWebviewRuntime(config: Pick<WebviewDesktopConfig, 'runtime'>, target: DesktopTargetName, options: { root: string, env?: Record<string, string | undefined>, host?: DesktopTargetName, hostRuntime?: () => string }): string | null;
|
|
30
37
|
/**
|
|
31
38
|
* Which of the optional flags a Craft binary understands, read from the binary
|
|
32
39
|
* itself: a flag it parses is a string inside it. Nothing is run, so this
|
|
@@ -71,6 +78,14 @@ export declare function releaseArtifactNames(config: Pick<ResolvedWebviewDesktop
|
|
|
71
78
|
* they have.
|
|
72
79
|
*/
|
|
73
80
|
export declare function releaseVersionProblem(version: string, published: string | null | undefined, compare: (left: string, right: string) => number): string | undefined;
|
|
81
|
+
/** `webview.agent.components`, as absolute directories, in the order the config lists them. */
|
|
82
|
+
export declare function resolveWebviewComponents(root: string, components: readonly string[] | undefined): string[];
|
|
83
|
+
/**
|
|
84
|
+
* The script `buddy build:desktop` runs to render an app's views to static
|
|
85
|
+
* files. It hands stx the same component directories, in the same order, as
|
|
86
|
+
* the server `buddy dev:desktop` starts.
|
|
87
|
+
*/
|
|
88
|
+
export declare function renderViewsBuildScript(options: { appName: string, root: string, viewsDir: string, outDir: string, components?: readonly string[] }): string;
|
|
74
89
|
/**
|
|
75
90
|
* `desktop.webview` resolved, and the pieces `buddy build:desktop` puts
|
|
76
91
|
* together for it: which targets, how each is compiled, and what each
|
package/dist/webview-app.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";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"){return{...config,version:config.version??packageVersion,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)})`);if(!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version))errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);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){try{const url=new URL(config.updates.feedUrl);if(url.protocol!=="https:"&&!["localhost","127.0.0.1"].includes(url.hostname))errors.push("webview.updates.feedUrl must be https")}catch{errors.push(`webview.updates.feedUrl is not a URL (got ${JSON.stringify(config.updates.feedUrl)})`)}const keys=Object.entries(config.updates.publicKeys??{});if(!keys.length)errors.push("webview.updates.publicKeys needs at least one key (run `buddy desktop:update:keypair`)");for(const[id,key]of keys){if(!key.startsWith("ed25519-public:"))errors.push(`webview.updates.publicKeys.${id} is not a public key (it starts with ed25519-public:)`)}}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());return["build","--compile",...options.minify===false?[]:["--minify"],...cross?[`--target=${bunCompileTarget(options.target)}`]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",...options.target.startsWith("win32-")?["--windows-hide-console"]:[],options.entry,"--outfile",options.outfile]}export function webviewRuntimeFor(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();
|
|
1
|
+
import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";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"){return{...config,version:config.version??packageVersion,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)})`);if(!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version))errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);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){try{const url=new URL(config.updates.feedUrl);if(url.protocol!=="https:"&&!["localhost","127.0.0.1"].includes(url.hostname))errors.push("webview.updates.feedUrl must be https")}catch{errors.push(`webview.updates.feedUrl is not a URL (got ${JSON.stringify(config.updates.feedUrl)})`)}const keys=Object.entries(config.updates.publicKeys??{});if(!keys.length)errors.push("webview.updates.publicKeys needs at least one key (run `buddy desktop:update:keypair`)");for(const[id,key]of keys){if(!key.startsWith("ed25519-public:"))errors.push(`webview.updates.publicKeys.${id} is not a public key (it starts with ed25519-public:)`)}}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());return["build","--compile",...options.minify===false?[]:["--minify"],...cross?[`--target=${bunCompileTarget(options.target)}`]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",...options.target.startsWith("win32-")?["--windows-hide-console"]:[],options.entry,"--outfile",options.outfile]}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 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})}
|
|
5
5
|
</plist>
|
|
6
|
-
`}export function renderWebviewInfoPlist(config,options={}){const schemes=config.urlSchemes??[];return renderInfoPlist({appName:config.appName,bundleId:config.macos?.bundleId??config.appId,version:config.version,executable:config.executable,iconFile:options.iconFile,ownsLauncher:true,declared:{LSMinimumSystemVersion:config.macos?.minimumSystemVersion??WEBVIEW_DEFAULTS.minimumSystemVersion,LSApplicationCategoryType:config.macos?.category??WEBVIEW_DEFAULTS.category,...schemes.length?{CFBundleURLTypes:[{CFBundleURLName:config.appId,CFBundleURLSchemes:schemes}]}:{},...config.macos?.usageDescriptions,...config.macos?.infoPlist}})}export function assembleWebviewMacosApp(options){const{config}=options;const run=options.run??runBundleCommand;const identity=options.signingIdentity??"-";const appPath=join(options.output,`${config.appName}.app`);const macos=join(appPath,"Contents","MacOS");const resources=join(appPath,"Contents","Resources");rmSync(appPath,{recursive:true,force:true});mkdirSync(macos,{recursive:true});mkdirSync(resources,{recursive:true});const executable=join(macos,config.executable);const runtime=join(macos,WEBVIEW_RUNTIME_NAME);copyFileSync(options.agent,executable);copyFileSync(options.runtime,runtime);chmodSync(executable,493);chmodSync(runtime,493);let iconFile;if(config.icon){const icon=resolve(options.root,config.icon);if(!existsSync(icon))throw new Error(`webview.icon does not exist: ${icon}`);if(icon.endsWith(".icns"))copyFileSync(icon,join(resources,"AppIcon.icns"));else makeIcns(icon,join(resources,"AppIcon.icns"),options.output,run);iconFile="AppIcon"}const plist=renderWebviewInfoPlist(config,{iconFile});writeFileSync(join(appPath,"Contents","Info.plist"),plist.xml);const entitlementsPath=join(options.output,`${config.appName}.entitlements`);writeFileSync(entitlementsPath,renderWebviewEntitlements(config));run(codesignArgs({identity,target:runtime}));run(codesignArgs({identity,target:appPath,entitlements:entitlementsPath}));return{appPath,entitlementsPath,ignoredPlistKeys:plist.ignored}}export function webviewPackageConfig(config,target,staged){const{platform,architecture}=splitDesktopTarget(target);const base={name:config.appName,version:config.version,...config.description?{description:config.description}:{},...config.publisher?{author:config.publisher}:{},...config.homepage?{homepage:config.homepage}:{},bundleId:config.appId,binaryPath:staged.binary,...staged.icon?{iconPath:staged.icon}:{},outDir:staged.outDir};if(platform==="win32"){return{...base,platforms:["windows"],windows:{msi:true,zip:true,architecture,...staged.additionalFiles?.length?{additionalFiles:staged.additionalFiles}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.windows?.certificatePath?{certificatePath:config.windows.certificatePath,...staged.certificatePassword?{certificatePassword:staged.certificatePassword}:{}}:{}}}}return{...base,platforms:["linux"],linux:{appImage:true,deb:true,rpm:true,categories:config.linux?.categories??["Development"],...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.linux?.debDependencies?{debDependencies:config.linux.debDependencies}:{},...config.linux?.rpmDependencies?{rpmDependencies:config.linux.rpmDependencies}:{}}}}export function nativeBuildSteps(target){const{platform}=splitDesktopTarget(target);if(platform==="darwin")return"The .app is assembled and signed with codesign, notarized with notarytool and imaged with hdiutil: macOS only.";if(platform==="win32")return"The MSI is built with WiX (candle, light) and signed with signtool: Windows only.";return"The AppImage (appimagetool), deb (dpkg-deb) and rpm (rpmbuild) are built with Linux tools: Linux only."}export function signtoolArgs(options){return["signtool.exe","sign","/f",options.certificatePath,...options.certificatePassword?["/p",options.certificatePassword]:[],"/fd","SHA256","/tr",options.timestampUrl??"http://timestamp.digicert.com","/td","SHA256",options.file]}export function releaseArtifactNames(config,target){const{platform,architecture}=splitDesktopTarget(target);const base=`${config.appName.replace(/[^\w.-]+/g,"-")}-${config.version}-${architecture}`;if(platform==="darwin")return{update:`${base}.zip`,downloads:[`${base}.dmg`]};if(platform==="win32")return{update:`${base}.msi`,downloads:[]};return{update:`${base}.AppImage`,downloads:[`${base}.deb`,`${base}.rpm`]}}export function releaseVersionProblem(version,published,compare){if(!published)return;const order=compare(version,published);if(order===0)return`${version} is already published. Bump the version; a published build is never replaced under the same number.`;if(order<0)return`${published} is already published, which is newer than ${version}.`;return}
|
|
6
|
+
`}export function renderWebviewInfoPlist(config,options={}){const schemes=config.urlSchemes??[];return renderInfoPlist({appName:config.appName,bundleId:config.macos?.bundleId??config.appId,version:config.version,executable:config.executable,iconFile:options.iconFile,ownsLauncher:true,declared:{LSMinimumSystemVersion:config.macos?.minimumSystemVersion??WEBVIEW_DEFAULTS.minimumSystemVersion,LSApplicationCategoryType:config.macos?.category??WEBVIEW_DEFAULTS.category,...schemes.length?{CFBundleURLTypes:[{CFBundleURLName:config.appId,CFBundleURLSchemes:schemes}]}:{},...config.macos?.usageDescriptions,...config.macos?.infoPlist}})}export function assembleWebviewMacosApp(options){const{config}=options;const run=options.run??runBundleCommand;const identity=options.signingIdentity??"-";const appPath=join(options.output,`${config.appName}.app`);const macos=join(appPath,"Contents","MacOS");const resources=join(appPath,"Contents","Resources");rmSync(appPath,{recursive:true,force:true});mkdirSync(macos,{recursive:true});mkdirSync(resources,{recursive:true});const executable=join(macos,config.executable);const runtime=join(macos,WEBVIEW_RUNTIME_NAME);copyFileSync(options.agent,executable);copyFileSync(options.runtime,runtime);chmodSync(executable,493);chmodSync(runtime,493);let iconFile;if(config.icon){const icon=resolve(options.root,config.icon);if(!existsSync(icon))throw new Error(`webview.icon does not exist: ${icon}`);if(icon.endsWith(".icns"))copyFileSync(icon,join(resources,"AppIcon.icns"));else makeIcns(icon,join(resources,"AppIcon.icns"),options.output,run);iconFile="AppIcon"}const plist=renderWebviewInfoPlist(config,{iconFile});writeFileSync(join(appPath,"Contents","Info.plist"),plist.xml);const entitlementsPath=join(options.output,`${config.appName}.entitlements`);writeFileSync(entitlementsPath,renderWebviewEntitlements(config));run(codesignArgs({identity,target:runtime}));run(codesignArgs({identity,target:appPath,entitlements:entitlementsPath}));return{appPath,entitlementsPath,ignoredPlistKeys:plist.ignored}}export function webviewPackageConfig(config,target,staged){const{platform,architecture}=splitDesktopTarget(target);const base={name:config.appName,version:config.version,...config.description?{description:config.description}:{},...config.publisher?{author:config.publisher}:{},...config.homepage?{homepage:config.homepage}:{},bundleId:config.appId,binaryPath:staged.binary,...staged.icon?{iconPath:staged.icon}:{},outDir:staged.outDir};if(platform==="win32"){return{...base,platforms:["windows"],windows:{msi:true,zip:true,architecture,...staged.additionalFiles?.length?{additionalFiles:staged.additionalFiles}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.windows?.certificatePath?{certificatePath:config.windows.certificatePath,...staged.certificatePassword?{certificatePassword:staged.certificatePassword}:{}}:{}}}}return{...base,platforms:["linux"],linux:{appImage:true,deb:true,rpm:true,categories:config.linux?.categories??["Development"],...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.linux?.debDependencies?{debDependencies:config.linux.debDependencies}:{},...config.linux?.rpmDependencies?{rpmDependencies:config.linux.rpmDependencies}:{}}}}export function nativeBuildSteps(target){const{platform}=splitDesktopTarget(target);if(platform==="darwin")return"The .app is assembled and signed with codesign, notarized with notarytool and imaged with hdiutil: macOS only.";if(platform==="win32")return"The MSI is built with WiX (candle, light) and signed with signtool: Windows only.";return"The AppImage (appimagetool), deb (dpkg-deb) and rpm (rpmbuild) are built with Linux tools: Linux only."}export function signtoolArgs(options){return["signtool.exe","sign","/f",options.certificatePath,...options.certificatePassword?["/p",options.certificatePassword]:[],"/fd","SHA256","/tr",options.timestampUrl??"http://timestamp.digicert.com","/td","SHA256",options.file]}export function releaseArtifactNames(config,target){const{platform,architecture}=splitDesktopTarget(target);const base=`${config.appName.replace(/[^\w.-]+/g,"-")}-${config.version}-${architecture}`;if(platform==="darwin")return{update:`${base}.zip`,downloads:[`${base}.dmg`]};if(platform==="win32")return{update:`${base}.msi`,downloads:[]};return{update:`${base}.AppImage`,downloads:[`${base}.deb`,`${base}.rpm`]}}export function releaseVersionProblem(version,published,compare){if(!published)return;const order=compare(version,published);if(order===0)return`${version} is already published. Bump the version; a published build is never replaced under the same number.`;if(order<0)return`${published} is already published, which is newer than ${version}.`;return}export function resolveWebviewComponents(root,components){return(components??[]).map((directory)=>resolve(root,directory))}export function renderViewsBuildScript(options){const pages=relative(options.root,options.viewsDir);const site={name:options.appName,url:"http://127.0.0.1",pagesDir:pages,outDir:options.outDir,publicDir:join(pages,"public"),...webviewComponentDirs(resolveWebviewComponents(options.root,options.components)),sitemap:false,robots:false};return`// Written by buddy build:desktop. Do not edit.
|
|
7
|
+
import { buildStaticSite } from '@stacksjs/stx'
|
|
8
|
+
|
|
9
|
+
await buildStaticSite(${JSON.stringify(site,null,2)})
|
|
10
|
+
`}
|
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.558",
|
|
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.558",
|
|
77
|
+
"@stacksjs/router": "0.75.558",
|
|
78
|
+
"@stacksjs/server": "0.75.558",
|
|
79
|
+
"@stacksjs/storage": "0.75.558",
|
|
80
80
|
"craft-native": ">=0.0.499"
|
|
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.558",
|
|
84
|
+
"@stacksjs/router": "0.75.558",
|
|
85
|
+
"@stacksjs/server": "0.75.558",
|
|
86
|
+
"@stacksjs/storage": "0.75.558"
|
|
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.558",
|
|
104
104
|
"better-dx": "^0.2.24"
|
|
105
105
|
}
|
|
106
106
|
}
|