@sixb/desktop 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/generate.ts", "../src/identity.ts", "../src/run.ts", "../src/mac-icon.ts", "../src/shell/window.ts"],
4
+ "sourcesContent": [
5
+ "import { mkdir, readdir, rm } from \"node:fs/promises\"\nimport { createRequire } from \"node:module\"\nimport { dirname, join } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { type DesktopAppOptions, desktopDir, writeDesktopApp } from \"./generate\"\nimport { bundleIdentifier } from \"./identity\"\nimport { run } from \"./run\"\n\nexport type { DesktopAppOptions } from \"./generate\"\n\nexport interface DesktopWindow {\n /** Resolves with Electron's exit code once the user quits it. */\n readonly exited: Promise<number>\n close(): void\n}\n\nexport interface DesktopBuild {\n /** What to hand to users: a zip of the app on macOS, the app's folder elsewhere. */\n readonly path: string\n /** Whether it was signed and notarized, and so opens without a warning. */\n readonly signed: boolean\n}\n\nconst packageRequire = createRequire(import.meta.url)\n// From the package's `src`, like the shell: see `SHELL_SOURCE_DIR`.\nconst PACKAGER_SCRIPT = fileURLToPath(new URL(\"../src/packager.mjs\", import.meta.url))\n\n/** Opens the app in a desktop window. `sixb dev --desktop` calls this. */\nexport async function openDesktopApp(options: DesktopAppOptions): Promise<DesktopWindow> {\n const app = await writeDesktopApp(options)\n // Chromium writes plenty to stderr when all is well, so it goes to a file, named if the window\n // quits on its own with an error.\n const log = join(dirname(app.dir), \"electron.log\")\n const electron = Bun.spawn([electronBinary(), app.dir], {\n stdio: [\"ignore\", \"ignore\", Bun.file(log)],\n })\n let closing = false\n const exited = electron.exited.then((code) => {\n if (code !== 0 && !closing) {\n console.error(`[SixbDesktop] The desktop window quit with exit code ${code}. See ${log}.`)\n }\n return code\n })\n return {\n exited,\n close: () => {\n closing = true\n electron.kill()\n },\n }\n}\n\n/** Packages the app for this machine's platform. `sixb desktop build` calls this. */\nexport async function buildDesktopApp(options: DesktopAppOptions): Promise<DesktopBuild> {\n const app = await writeDesktopApp(options)\n const out = desktopDir(options.projectRoot, \"dist\")\n await rm(out, { recursive: true, force: true })\n\n const mac = process.platform === \"darwin\"\n const notarize = mac ? appleNotarization() : null\n const packaged = await packageApp({\n dir: app.dir,\n name: app.name,\n out,\n appBundleId: bundleIdentifier(options.appUrl),\n appVersion: app.version,\n electronVersion: (packageRequire(\"electron/package.json\") as { readonly version: string })\n .version,\n ...(mac && app.icon ? { icon: await macIcon(app.icon) } : {}),\n // Signs with the Developer ID certificate in the keychain, which notarization requires.\n ...(notarize ? { osxSign: {}, osxNotarize: notarize } : {}),\n })\n if (!mac) return { path: packaged, signed: false }\n\n const name = (await readdir(packaged)).find((entry) => entry.endsWith(\".app\"))\n if (!name) throw new Error(`[SixbDesktop] The packaged app is missing from ${packaged}.`)\n const bundle = join(packaged, name)\n // Packaging breaks the ad-hoc signature Electron ships with. macOS calls a downloaded app with a\n // broken signature damaged, and offers no way to open it; signed ad hoc, it can be allowed.\n if (!notarize) {\n await run([\"codesign\", \"--force\", \"--deep\", \"--sign\", \"-\", bundle], \"Could not sign the app.\")\n }\n // `ditto`, not `zip`: it keeps the bundle's symlinks, and with them its signature.\n const zip = `${packaged}.zip`\n await run([\"ditto\", \"-c\", \"-k\", \"--keepParent\", bundle, zip], \"Could not zip the app.\")\n return { path: zip, signed: notarize !== null }\n}\n\n/**\n * An App Store Connect API key, which notarizes the app so macOS opens it without a warning.\n * Without one, the app is built unsigned.\n */\nfunction appleNotarization(): {\n readonly appleApiKey: string\n readonly appleApiKeyId: string\n readonly appleApiIssuer: string\n} | null {\n const { APPLE_API_KEY, APPLE_API_KEY_ID, APPLE_API_ISSUER } = process.env\n if (!APPLE_API_KEY && !APPLE_API_KEY_ID && !APPLE_API_ISSUER) return null\n if (!APPLE_API_KEY || !APPLE_API_KEY_ID || !APPLE_API_ISSUER) {\n throw new Error(\n \"[SixbDesktop] Set all of APPLE_API_KEY, APPLE_API_KEY_ID and APPLE_API_ISSUER to sign the \" +\n \"macOS app, or none of them to build it unsigned.\"\n )\n }\n return {\n appleApiKey: APPLE_API_KEY,\n appleApiKeyId: APPLE_API_KEY_ID,\n appleApiIssuer: APPLE_API_ISSUER,\n }\n}\n\n/**\n * The packager wants `.icns`: every size macOS shows, scaled from the 1024-pixel icon, in one file.\n * `sips` and `iconutil` ship with every Mac. Written beside the app, not in it: everything in the\n * app's directory ships inside the bundle.\n */\nasync function macIcon(png: string): Promise<string> {\n const desktop = dirname(dirname(png))\n const iconset = join(desktop, \"icon.iconset\")\n await rm(iconset, { recursive: true, force: true })\n await mkdir(iconset)\n const sizes = [16, 32, 128, 256, 512].flatMap((points) => [\n { name: `icon_${points}x${points}.png`, pixels: points },\n { name: `icon_${points}x${points}@2x.png`, pixels: points * 2 },\n ])\n await Promise.all(\n sizes.map(({ name, pixels }) =>\n run(\n [\"sips\", \"-z\", `${pixels}`, `${pixels}`, png, \"--out\", join(iconset, name)],\n \"Could not scale the icon.\"\n )\n )\n )\n const icns = join(desktop, \"icon.icns\")\n await run([\"iconutil\", \"-c\", \"icns\", iconset, \"-o\", icns], \"Could not convert the icon.\")\n return icns\n}\n\n/**\n * Runs `@electron/packager` into `options.out`, which starts empty, and resolves with the one\n * directory it wrote there. Under Electron's own binary, which doubles as the Node the packager was\n * written for: under Bun, the packager fails whenever it verifies a download (its checksum\n * dependency does not load).\n */\nasync function packageApp(\n options: { readonly out: string } & Record<string, unknown>\n): Promise<string> {\n const packager = Bun.spawn(\n [electronBinary(), PACKAGER_SCRIPT, JSON.stringify({ ...options, quiet: true })],\n {\n stdio: [\"ignore\", \"inherit\", \"inherit\"],\n // Without the second, Electron's file system reads the `app.asar` the packager writes as a\n // directory.\n env: { ...process.env, ELECTRON_RUN_AS_NODE: \"1\", ELECTRON_NO_ASAR: \"1\" },\n }\n )\n if ((await packager.exited) !== 0) {\n throw new Error(\"[SixbDesktop] Packaging failed. See the output above.\")\n }\n const [written] = await readdir(options.out)\n if (!written) throw new Error(`[SixbDesktop] The packager wrote nothing to ${options.out}.`)\n return join(options.out, written)\n}\n\n// Outside Electron, `require(\"electron\")` is the path of the binary its install script fetched.\nfunction electronBinary(): string {\n try {\n return packageRequire(\"electron\") as string\n } catch {\n const electronDir = dirname(packageRequire.resolve(\"electron/package.json\"))\n throw new Error(\n \"[SixbDesktop] Electron's binary is missing: its install script did not run. \" +\n `Run \\`bun run --cwd ${electronDir} postinstall\\`, then try again.`\n )\n }\n}\n",
6
+ "import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { readAppIdentity } from \"./identity\"\nimport { drawMacIcon } from \"./mac-icon\"\nimport { run } from \"./run\"\nimport type { ShellConfig } from \"./shell/navigation\"\nimport { HIDDEN_TITLE_BAR_PRELOAD } from \"./shell/window\"\n\nexport interface DesktopAppOptions {\n /** The Sixb project. The desktop app is generated under its `.sixb/desktop`. */\n readonly projectRoot: string\n /** Where the app is served. The window opens it; the desktop app takes its name and icon from it. */\n readonly appUrl: string\n /** The project's API. Its sign-in pages are where the window is approved. */\n readonly apiOrigin: string\n}\n\n/** The Electron app `writeDesktopApp` generated, and what it is called. */\nexport interface GeneratedApp {\n readonly dir: string\n readonly name: string\n readonly version: string\n /** The app's icon in `dir`, when it declares one. */\n readonly icon: string | null\n}\n\n// Read from the package's `src`, which ships, whether this module runs from `src` or `dist`.\nconst SHELL_SOURCE_DIR = fileURLToPath(new URL(\"../src/shell\", import.meta.url))\n\n/** Where a project's desktop app is generated (`app`) and packaged (`dist`). */\nexport function desktopDir(projectRoot: string, part: \"app\" | \"dist\"): string {\n return join(projectRoot, \".sixb\", \"desktop\", part)\n}\n\n/**\n * Writes the Electron app that opens `appUrl` into the project's `.sixb/desktop/app`. The directory\n * is build-owned, like the rest of `.sixb`: it is cleared on every call.\n */\nexport async function writeDesktopApp(options: DesktopAppOptions): Promise<GeneratedApp> {\n const identity = await readAppIdentity(options.appUrl)\n const version = await readProjectVersion(options.projectRoot)\n const dir = desktopDir(options.projectRoot, \"app\")\n await rm(dir, { recursive: true, force: true })\n await mkdir(dir, { recursive: true })\n\n const config: ShellConfig = {\n name: identity.name,\n appUrl: new URL(options.appUrl).href,\n apiOrigin: new URL(options.apiOrigin).origin,\n }\n const manifest = {\n name: \"sixb-desktop-app\",\n // Names the folder the window's cookies are kept in, so each app has its own sign-in.\n productName: identity.name,\n version,\n private: true,\n main: \"main.js\",\n }\n const icon = identity.icon ? await writeIcon(dir, identity.icon) : null\n const template = await readFile(join(SHELL_SOURCE_DIR, \"index.html\"), \"utf-8\")\n await Promise.all([\n writeFile(join(dir, \"package.json\"), `${JSON.stringify(manifest, null, 2)}\\n`),\n writeFile(join(dir, \"shell.json\"), `${JSON.stringify(config, null, 2)}\\n`),\n writeFile(join(dir, \"preload.js\"), HIDDEN_TITLE_BAR_PRELOAD),\n writeFile(join(dir, \"index.html\"), renderShellPage(template, { ...config, icon: !!icon })),\n ])\n\n // Electron loads plain JavaScript. A child process, because an in-process `Bun.build()` that\n // wedges takes its caller down with it.\n await run(\n [\n process.execPath,\n \"build\",\n join(SHELL_SOURCE_DIR, \"main.ts\"),\n \"--target=node\",\n \"--format=cjs\",\n \"--external=electron\",\n `--outfile=${join(dir, \"main.js\")}`,\n ],\n \"Could not compile the desktop shell.\"\n )\n return { dir, name: identity.name, version, icon }\n}\n\n/** The page the window shows while the app loads, and when it cannot reach the app. */\nexport function renderShellPage(\n template: string,\n page: { readonly name: string; readonly appUrl: string; readonly icon: boolean }\n): string {\n const initial = Array.from(page.name.trim())[0]?.toUpperCase() ?? \"\"\n const markup: Record<string, string> = {\n name: escapeHtml(page.name),\n host: escapeHtml(new URL(page.appUrl).host),\n appUrl: escapeHtml(page.appUrl),\n // The app's icon, or the first letter of its name standing in for one.\n mark: page.icon\n ? '<img class=\"mark\" src=\"icon.png\" alt=\"\" />'\n : `<div class=\"mark\" aria-hidden=\"true\">${escapeHtml(initial)}</div>`,\n }\n return template.replaceAll(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => markup[key] ?? \"\")\n}\n\n/** Writes the app's icon into `dir` as `icon.png`; on macOS, drawn the way macOS draws app icons. */\nasync function writeIcon(dir: string, png: Uint8Array): Promise<string> {\n const icon = join(dir, \"icon.png\")\n if (process.platform !== \"darwin\") {\n await writeFile(icon, png)\n return icon\n }\n // The original goes beside the app, not in it: everything in the app's directory ships.\n const source = join(dir, \"..\", \"icon-source.png\")\n await writeFile(source, png)\n await drawMacIcon(source, icon)\n return icon\n}\n\nasync function readProjectVersion(projectRoot: string): Promise<string> {\n try {\n const manifest: unknown = JSON.parse(await readFile(join(projectRoot, \"package.json\"), \"utf-8\"))\n const version = (manifest as { readonly version?: unknown } | null)?.version\n return typeof version === \"string\" ? version : \"0.0.0\"\n } catch {\n return \"0.0.0\"\n }\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n}\n",
7
+ "/** What the desktop app takes from the web app it opens. */\nexport interface AppIdentity {\n /** The app's name: `metadata.title` in `app/layout.tsx`. */\n readonly name: string\n /**\n * The app's maskable icon, such as `app/public/icon-maskable-512.png`, or else its largest PNG\n * icon, such as `app/public/icon-512.png`.\n */\n readonly icon: Uint8Array | null\n}\n\n/**\n * Reads the app's web app manifest, the one a browser installs the app from. The desktop app is\n * the same app installed another way, so it takes the same name and icon and has no settings of\n * its own.\n */\nexport async function readAppIdentity(appUrl: string): Promise<AppIdentity> {\n const manifestUrl = new URL(\"/app.webmanifest\", appUrl)\n const manifest: unknown = await (await fetchFromApp(manifestUrl)).json()\n const { name, icons } = (typeof manifest === \"object\" && manifest !== null ? manifest : {}) as {\n readonly name?: unknown\n readonly icons?: unknown\n }\n\n const iconUrl = desktopIcon(icons, manifestUrl)\n return {\n name: typeof name === \"string\" && name.trim() ? name.trim() : \"Sixb\",\n icon: iconUrl ? new Uint8Array(await (await fetchFromApp(iconUrl)).arrayBuffer()) : null,\n }\n}\n\n/**\n * The app's id on the desktop, from the address it opens: `https://orders.acme.com` becomes\n * `com.acme.orders`. Each deployment gets its own, so a staging build installs beside production.\n */\nexport function bundleIdentifier(appUrl: string): string {\n const labels = new URL(appUrl).hostname\n .split(\".\")\n .reverse()\n .map((label) => label.toLowerCase().replaceAll(/[^a-z0-9-]/g, \"-\"))\n .filter(Boolean)\n return (labels.length > 1 ? labels : [\"local\", ...labels]).join(\".\")\n}\n\n// A maskable icon is drawn to its edges for a platform to cut its own shape from, which is what\n// macOS does with it. Any other icon may carry its own shape and margins.\nfunction desktopIcon(icons: unknown, manifestUrl: URL): URL | null {\n let best: { readonly url: URL; readonly rank: readonly [number, number] } | null = null\n for (const icon of Array.isArray(icons) ? icons : []) {\n if (typeof icon !== \"object\" || icon === null) continue\n const { src, sizes, type, purpose } = icon as Record<string, unknown>\n if (typeof src !== \"string\") continue\n const url = new URL(src, manifestUrl)\n if (type === undefined ? !url.pathname.endsWith(\".png\") : type !== \"image/png\") continue\n\n const maskable = typeof purpose === \"string\" && purpose.split(/\\s+/).includes(\"maskable\")\n const size = Math.max(\n 0,\n ...(typeof sizes === \"string\" ? sizes.split(/\\s+/) : []).map(\n (entry) => Number.parseInt(entry, 10) || 0\n )\n )\n const rank = [maskable ? 1 : 0, size] as const\n if (!best || rank[0] > best.rank[0] || (rank[0] === best.rank[0] && rank[1] > best.rank[1])) {\n best = { url, rank }\n }\n }\n return best?.url ?? null\n}\n\nasync function fetchFromApp(url: URL): Promise<Response> {\n let response: Response\n try {\n response = await fetch(url)\n } catch (error) {\n throw new Error(\n `[SixbDesktop] Could not reach ${url} (${error instanceof Error ? error.message : error}). ` +\n \"The desktop app takes its name and icon from the app, so the app must be running there.\"\n )\n }\n if (!response.ok) throw new Error(`[SixbDesktop] ${url} answered ${response.status}.`)\n return response\n}\n",
8
+ "/** Runs a command to completion, quietly unless it fails: then it throws `failure` and its errors. */\nexport async function run(command: readonly string[], failure: string): Promise<void> {\n const child = Bun.spawn([...command], {\n stdio: [\"ignore\", \"ignore\", \"pipe\"],\n timeout: 120_000,\n })\n const [exitCode, errors] = await Promise.all([child.exited, new Response(child.stderr).text()])\n if (exitCode !== 0) {\n throw new Error(`[SixbDesktop] ${failure}${errors.trim() ? `\\n${errors.trim()}` : \"\"}`)\n }\n}\n",
9
+ "import { run } from \"./run\"\n\n/**\n * Draws `png` the way macOS draws app icons, into `out`: on Apple's grid, a rounded square of 824\n * pixels with continuous corners in a canvas of 1024, over the soft shadow Apple's own icons have.\n * An icon drawn to its edges otherwise stands larger than every other icon in the Dock.\n */\nexport async function drawMacIcon(png: string, out: string): Promise<void> {\n await run(\n [\"osascript\", \"-l\", \"JavaScript\", \"-e\", MAC_ICON_SCRIPT, png, out],\n \"Could not draw the macOS icon.\"\n )\n}\n\n// AppKit, through the JavaScript `osascript` runs, which every Mac has. The corner is the curve\n// UIKit rounds continuous corners with; with this radius it matches the outline of Apple's Notes\n// icon to a few pixels, and the shadow matches its shadow.\nconst MAC_ICON_SCRIPT = `\nObjC.import(\"AppKit\")\nObjC.import(\"CoreGraphics\")\n\nfunction run([input, output]) {\n const canvas = 1024\n const body = 824\n const radius = 185.4\n const min = (canvas - body) / 2\n const max = min + body\n\n // One corner, as offsets in radii from the edge it leaves and the edge it joins.\n const corner = [\n [[1.52866483, 0]],\n [[0.66993427, 0.065496], [1.08849323, 0], [0.86840689, 0.02065986]],\n [[0.63149399, 0.074911]],\n [[0.074911, 0.63149399], [0.37282392, 0.16906933], [0.16906933, 0.37282392]],\n [[0.065496, 0.66993427]],\n [[0, 1.52866483], [0.02065986, 0.86840689], [0, 1.08849323]],\n ]\n const corners = [\n ([u, v]) => $.NSMakePoint(max - u * radius, max - v * radius),\n ([u, v]) => $.NSMakePoint(max - v * radius, min + u * radius),\n ([u, v]) => $.NSMakePoint(min + u * radius, min + v * radius),\n ([u, v]) => $.NSMakePoint(min + v * radius, max - u * radius),\n ]\n const shape = $.NSBezierPath.bezierPath\n shape.moveToPoint(corners[3]([0, 1.52866483]))\n for (const at of corners) {\n for (const [to, c1, c2] of corner) {\n if (c1) shape.curveToPointControlPoint1ControlPoint2(at(to), at(c1), at(c2))\n else shape.lineToPoint(at(to))\n }\n }\n shape.closePath\n\n const image = $.NSImage.alloc.initWithContentsOfFile(input)\n if (image.isNil()) throw new Error(\"Cannot read \" + input)\n const bitmap = $.NSBitmapImageRep.alloc\n .initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(\n null, canvas, canvas, 8, 4, true, false, $.NSDeviceRGBColorSpace, 0, 0\n )\n const context = $.NSGraphicsContext.graphicsContextWithBitmapImageRep(bitmap)\n $.NSGraphicsContext.setCurrentContext(context)\n context.setImageInterpolation($.NSImageInterpolationHigh)\n\n const shadow = $.NSShadow.alloc.init\n shadow.setShadowOffset($.NSMakeSize(0, -8))\n shadow.setShadowBlurRadius(30)\n shadow.setShadowColor($.NSColor.colorWithWhiteAlpha(0, 0.22))\n shadow.set\n // A layer, so the shadow falls from the clipped icon and not from the clip.\n $.CGContextBeginTransparencyLayer(context.CGContext, null)\n shape.addClip\n image.drawInRectFromRectOperationFraction(\n $.NSMakeRect(min, min, body, body), $.NSZeroRect, $.NSCompositingOperationSourceOver, 1\n )\n $.CGContextEndTransparencyLayer(context.CGContext)\n context.flushGraphics\n\n const png = bitmap.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $.NSDictionary.dictionary)\n if (!png.writeToFileAtomically(output, true)) throw new Error(\"Cannot write \" + output)\n}\n`\n",
10
+ "import type { ShellConfig } from \"./navigation\"\n\n/**\n * Whether the window itself may show `url`: only the app and the API that serves its sign-in\n * pages. Anything else a page links to opens in the user's browser instead.\n */\nexport function mayNavigate(config: ShellConfig, url: string): boolean {\n try {\n const { origin } = new URL(url)\n return origin === new URL(config.appUrl).origin || origin === new URL(config.apiOrigin).origin\n } catch {\n return false\n }\n}\n\n/**\n * Whether `url` is on the app's own origin. Camera, location and the like are the app's to ask for,\n * and not a frame it embeds from elsewhere.\n */\nexport function isAppUrl(config: ShellConfig, url: string): boolean {\n try {\n return new URL(url).origin === new URL(config.appUrl).origin\n } catch {\n return false\n }\n}\n\n/**\n * What the window paints before a page has: the loading page's own background, so the window\n * opens, and passes from that page to the app, without a flash of white.\n */\nexport const WINDOW_BACKGROUND = { light: \"#fafafa\", dark: \"#0a0a0a\" } as const\n\n/** The band at the top of a window without a title bar where macOS draws the window controls. */\nexport const CONTROLS_HEIGHT_PX = 36\n\n/**\n * Styles for a window without a title bar, inserted into every page it shows.\n *\n * The page reaches the top edge, under the window controls, so two things a title bar did have\n * to come from the page: somewhere to grab the window, and room for the controls.\n * - `#sixb-desktop-drag` (added by the preload) is the drag handle: a strip across the top, above\n * the page. It ignores the pointer, and every control is cut out of the draggable area, so\n * buttons and links under the strip still take their clicks and the space between them moves\n * the window. Something clickable that is none of the things listed here needs\n * `-webkit-app-region: no-drag` of its own.\n * - The shared sidebar is moved down so most apps need nothing. Other layouts can use\n * `html[data-sixb-desktop]` and `--sixb-desktop-controls-height`, which the preload sets.\n */\nexport const HIDDEN_TITLE_BAR_CSS = [\n `#sixb-desktop-drag{position:fixed;top:0;left:0;right:0;height:${CONTROLS_HEIGHT_PX}px;`,\n \"z-index:2147483647;pointer-events:none;-webkit-app-region:drag}\",\n `${[\n \"a\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"label\",\n \"[role=button]\",\n \"[role=link]\",\n \"[role=tab]\",\n \"[role=menuitem]\",\n \"[role=switch]\",\n \"[role=checkbox]\",\n \"[role=combobox]\",\n \"[contenteditable]\",\n \"[tabindex]:not([tabindex='-1'])\",\n ].join(\",\")}{-webkit-app-region:no-drag}`,\n `[data-slot=\"sidebar-inner\"]{padding-top:calc(${CONTROLS_HEIGHT_PX}px - 0.5rem)}`,\n].join(\"\")\n\n/**\n * The preload of a window without a title bar: runs in every page before the page's own scripts.\n *\n * It marks `<html>` the moment the element exists, so an app can read the mark on its first\n * render, and adds the drag handle once there is a body to hold it. Written to a file by\n * `writeDesktopApp`, which is why it is source text and not a function.\n */\nexport const HIDDEN_TITLE_BAR_PRELOAD = `(() => {\n const mark = () => {\n const root = document.documentElement\n if (!root) return false\n root.dataset.sixbDesktop = \"inset\"\n root.style.setProperty(\"--sixb-desktop-controls-height\", \"${CONTROLS_HEIGHT_PX}px\")\n return true\n }\n if (!mark()) {\n const observer = new MutationObserver(() => {\n if (mark()) observer.disconnect()\n })\n observer.observe(document, { childList: true })\n }\n\n const addHandle = () => {\n if (!document.body || document.getElementById(\"sixb-desktop-drag\")) return\n const handle = document.createElement(\"div\")\n handle.id = \"sixb-desktop-drag\"\n handle.setAttribute(\"aria-hidden\", \"true\")\n // First in the body, not last: the draggable area is built in document order, so a control\n // is only cut out of it if it comes after the handle.\n document.body.prepend(handle)\n }\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", addHandle, { once: true })\n } else {\n addHandle()\n }\n})()\n`\n"
11
+ ],
12
+ "mappings": ";;AAAA,kBAAS,uBAAgB;AACzB;AACA,0BAAkB;AAClB,0BAAS;;;ACHT;AACA;AACA;;;ACcA,eAAsB,eAAe,CAAC,QAAsC;AAAA,EAC1E,MAAM,cAAc,IAAI,IAAI,oBAAoB,MAAM;AAAA,EACtD,MAAM,WAAoB,OAAO,MAAM,aAAa,WAAW,GAAG,KAAK;AAAA,EACvE,QAAQ,MAAM,UAAW,OAAO,aAAa,YAAY,aAAa,OAAO,WAAW,CAAC;AAAA,EAKzF,MAAM,UAAU,YAAY,OAAO,WAAW;AAAA,EAC9C,OAAO;AAAA,IACL,MAAM,OAAO,SAAS,YAAY,KAAK,KAAK,IAAI,KAAK,KAAK,IAAI;AAAA,IAC9D,MAAM,UAAU,IAAI,WAAW,OAAO,M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AAG,MAAM,aACjB,IACE,CAAC,QAAQ,MAAM,GAAG,UAAU,GAAG,UAAU,KAAK,SAAS,MAAK,SAAS,IAAI,CAAC,GAC1E,2BACF,CACF,CACF;AAAA,EACA,MAAM,OAAO,MAAK,SAAS,WAAW;AAAA,EACtC,MAAM,IAAI,CAAC,YAAY,MAAM,QAAQ,SAAS,MAAM,IAAI,GAAG,6BAA6B;AAAA,EACxF,OAAO;AAAA;AAST,eAAe,UAAU,CACvB,SACiB;AAAA,EACjB,MAAM,WAAW,IAAI,MACnB,CAAC,eAAe,GAAG,iBAAiB,KAAK,UAAU,KAAK,SAAS,OAAO,KAAK,CAAC,CAAC,GAC/E;AAAA,IACE,OAAO,CAAC,UAAU,WAAW,SAAS;AAAA,IAGtC,KAAK,KAAK,QAAQ,KAAK,sBAAsB,KAAK,kBAAkB,IAAI;AAAA,EAC1E,CACF;AAAA,EACA,IAAK,MAAM,SAAS,WAAY,GAAG;AAAA,IACjC,MAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAAA,EACA,OAAO,WAAW,MAAM,QAAQ,QAAQ,GAAG;AAAA,EAC3C,IAAI,CAAC;AAAA,IAAS,MAAM,IAAI,MAAM,+CAA+C,QAAQ,MAAM;AAAA,EAC3F,OAAO,MAAK,QAAQ,KAAK,OAAO;AAAA;AAIlC,SAAS,cAAc,GAAW;AAAA,EAChC,IAAI;AAAA,IACF,OAAO,eAAe,UAAU;AAAA,IAChC,MAAM;AAAA,IACN,MAAM,cAAc,QAAQ,eAAe,QAAQ,uBAAuB,CAAC;AAAA,IAC3E,MAAM,IAAI,MACR,iFACE,uBAAuB,4CAC3B;AAAA;AAAA;",
13
+ "debugId": "30FED6904B68AC4164756E2164756E21",
14
+ "names": []
15
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Draws `png` the way macOS draws app icons, into `out`: on Apple's grid, a rounded square of 824
3
+ * pixels with continuous corners in a canvas of 1024, over the soft shadow Apple's own icons have.
4
+ * An icon drawn to its edges otherwise stands larger than every other icon in the Dock.
5
+ */
6
+ export declare function drawMacIcon(png: string, out: string): Promise<void>;
7
+ //# sourceMappingURL=mac-icon.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mac-icon.d.ts","sourceRoot":"","sources":["../src/mac-icon.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKzE"}
package/dist/run.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** Runs a command to completion, quietly unless it fails: then it throws `failure` and its errors. */
2
+ export declare function run(command: readonly string[], failure: string): Promise<void>;
3
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,wBAAsB,GAAG,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CASpF"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/shell/main.ts"],"names":[],"mappings":""}
@@ -0,0 +1,39 @@
1
+ /** What the shell was built to open. Written into the app by `writeDesktopApp`. */
2
+ export interface ShellConfig {
3
+ /** Shown in the title bar, and to the user approving this window's sign-in. */
4
+ readonly name: string;
5
+ /** The app, such as `https://app.example.com/`. */
6
+ readonly appUrl: string;
7
+ readonly apiOrigin: string;
8
+ }
9
+ export interface NavigationState {
10
+ /** Approval pages already opened, so a waiting page that reloads opens its browser tab once. */
11
+ readonly openedCodes: Set<string>;
12
+ lastSignIn: {
13
+ readonly url: string;
14
+ readonly at: number;
15
+ } | null;
16
+ }
17
+ export type NavigationStep =
18
+ /** Send the window somewhere else instead. */
19
+ {
20
+ readonly kind: "load";
21
+ readonly url: string;
22
+ }
23
+ /** Hand a URL to the system browser. */
24
+ | {
25
+ readonly kind: "open-external";
26
+ readonly url: string;
27
+ };
28
+ export declare function createNavigationState(): NavigationState;
29
+ /**
30
+ * Decides what the shell does about a navigation of its window.
31
+ *
32
+ * The window is a browser the user cannot finish a sign-in in: a magic link opens in their own
33
+ * browser, and identity providers turn embedded ones away. So the app's ordinary sign-in redirect
34
+ * becomes a request to be approved from the system browser, and the approval page opens there.
35
+ */
36
+ export declare function nextNavigationStep(config: ShellConfig, state: NavigationState, navigatedTo: string, now?: number): NavigationStep | null;
37
+ /** Only web addresses leave for the system browser; a page cannot make the shell launch programs. */
38
+ export declare function isWebUrl(value: string): boolean;
39
+ //# sourceMappingURL=navigation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"navigation.d.ts","sourceRoot":"","sources":["../../src/shell/navigation.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,MAAM,WAAW,WAAW;IAC1B,+EAA+E;IAC/E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,mDAAmD;IACnD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAC3B;AAED,MAAM,WAAW,eAAe;IAC9B,gGAAgG;IAChG,QAAQ,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IACjC,UAAU,EAAE;QAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAA;CACjE;AAED,MAAM,MAAM,cAAc;AACxB,8CAA8C;AAC5C;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CAAE;AACjD,wCAAwC;GACtC;IAAE,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAA;AAM5D,wBAAgB,qBAAqB,IAAI,eAAe,CAEvD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,WAAW,EACnB,KAAK,EAAE,eAAe,EACtB,WAAW,EAAE,MAAM,EACnB,GAAG,GAAE,MAAmB,GACvB,cAAc,GAAG,IAAI,CAgCvB;AAED,qGAAqG;AACrG,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO/C"}
@@ -0,0 +1,44 @@
1
+ import type { ShellConfig } from "./navigation";
2
+ /**
3
+ * Whether the window itself may show `url`: only the app and the API that serves its sign-in
4
+ * pages. Anything else a page links to opens in the user's browser instead.
5
+ */
6
+ export declare function mayNavigate(config: ShellConfig, url: string): boolean;
7
+ /**
8
+ * Whether `url` is on the app's own origin. Camera, location and the like are the app's to ask for,
9
+ * and not a frame it embeds from elsewhere.
10
+ */
11
+ export declare function isAppUrl(config: ShellConfig, url: string): boolean;
12
+ /**
13
+ * What the window paints before a page has: the loading page's own background, so the window
14
+ * opens, and passes from that page to the app, without a flash of white.
15
+ */
16
+ export declare const WINDOW_BACKGROUND: {
17
+ readonly light: "#fafafa";
18
+ readonly dark: "#0a0a0a";
19
+ };
20
+ /** The band at the top of a window without a title bar where macOS draws the window controls. */
21
+ export declare const CONTROLS_HEIGHT_PX = 36;
22
+ /**
23
+ * Styles for a window without a title bar, inserted into every page it shows.
24
+ *
25
+ * The page reaches the top edge, under the window controls, so two things a title bar did have
26
+ * to come from the page: somewhere to grab the window, and room for the controls.
27
+ * - `#sixb-desktop-drag` (added by the preload) is the drag handle: a strip across the top, above
28
+ * the page. It ignores the pointer, and every control is cut out of the draggable area, so
29
+ * buttons and links under the strip still take their clicks and the space between them moves
30
+ * the window. Something clickable that is none of the things listed here needs
31
+ * `-webkit-app-region: no-drag` of its own.
32
+ * - The shared sidebar is moved down so most apps need nothing. Other layouts can use
33
+ * `html[data-sixb-desktop]` and `--sixb-desktop-controls-height`, which the preload sets.
34
+ */
35
+ export declare const HIDDEN_TITLE_BAR_CSS: string;
36
+ /**
37
+ * The preload of a window without a title bar: runs in every page before the page's own scripts.
38
+ *
39
+ * It marks `<html>` the moment the element exists, so an app can read the mark on its first
40
+ * render, and adds the drag handle once there is a body to hold it. Written to a file by
41
+ * `writeDesktopApp`, which is why it is source text and not a function.
42
+ */
43
+ export declare const HIDDEN_TITLE_BAR_PRELOAD = "(() => {\n const mark = () => {\n const root = document.documentElement\n if (!root) return false\n root.dataset.sixbDesktop = \"inset\"\n root.style.setProperty(\"--sixb-desktop-controls-height\", \"36px\")\n return true\n }\n if (!mark()) {\n const observer = new MutationObserver(() => {\n if (mark()) observer.disconnect()\n })\n observer.observe(document, { childList: true })\n }\n\n const addHandle = () => {\n if (!document.body || document.getElementById(\"sixb-desktop-drag\")) return\n const handle = document.createElement(\"div\")\n handle.id = \"sixb-desktop-drag\"\n handle.setAttribute(\"aria-hidden\", \"true\")\n // First in the body, not last: the draggable area is built in document order, so a control\n // is only cut out of it if it comes after the handle.\n document.body.prepend(handle)\n }\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", addHandle, { once: true })\n } else {\n addHandle()\n }\n})()\n";
44
+ //# sourceMappingURL=window.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"window.d.ts","sourceRoot":"","sources":["../../src/shell/window.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAE/C;;;GAGG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAOrE;AAED;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAMlE;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB;;;CAAiD,CAAA;AAE/E,iGAAiG;AACjG,eAAO,MAAM,kBAAkB,KAAK,CAAA;AAEpC;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,oBAAoB,QAsBvB,CAAA;AAEV;;;;;;GAMG;AACH,eAAO,MAAM,wBAAwB,ohCA8BpC,CAAA"}
@@ -0,0 +1,5 @@
1
+ // Written by scripts/build-package.ts, and published on purpose.
2
+ // Bun applies the nearest tsconfig paths map to every import it resolves, node_modules
3
+ // included. An empty map here keeps a consumer's aliases from sending a module in this
4
+ // directory back into a second copy of its own source.
5
+ { "compilerOptions": { "paths": {} } }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@sixb/desktop",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Ship a Sixb project's app as a desktop app",
5
+ "keywords": [
6
+ "sixb",
7
+ "bun",
8
+ "desktop",
9
+ "electron"
10
+ ],
11
+ "homepage": "https://sixb.ai",
12
+ "bugs": {
13
+ "url": "https://github.com/sixb-ai/sixb/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/sixb-ai/sixb.git",
18
+ "directory": "packages/desktop"
19
+ },
20
+ "author": "Sixb contributors",
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "bun": "./src/index.ts",
28
+ "import": "./dist/index.js",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "build": "bun ../../scripts/build-package.ts",
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "bun test",
36
+ "prepack": "bun run build"
37
+ },
38
+ "dependencies": {
39
+ "@electron/packager": "^20.3.0",
40
+ "electron": "^44.9.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/bun": "latest",
44
+ "typescript": "^5.7.0"
45
+ },
46
+ "license": "MIT",
47
+ "engines": {
48
+ "bun": ">=1.4.2"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "files": [
54
+ "dist",
55
+ "src",
56
+ "README.md",
57
+ "LICENSE"
58
+ ]
59
+ }
@@ -0,0 +1,134 @@
1
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { fileURLToPath } from "node:url"
4
+ import { readAppIdentity } from "./identity"
5
+ import { drawMacIcon } from "./mac-icon"
6
+ import { run } from "./run"
7
+ import type { ShellConfig } from "./shell/navigation"
8
+ import { HIDDEN_TITLE_BAR_PRELOAD } from "./shell/window"
9
+
10
+ export interface DesktopAppOptions {
11
+ /** The Sixb project. The desktop app is generated under its `.sixb/desktop`. */
12
+ readonly projectRoot: string
13
+ /** Where the app is served. The window opens it; the desktop app takes its name and icon from it. */
14
+ readonly appUrl: string
15
+ /** The project's API. Its sign-in pages are where the window is approved. */
16
+ readonly apiOrigin: string
17
+ }
18
+
19
+ /** The Electron app `writeDesktopApp` generated, and what it is called. */
20
+ export interface GeneratedApp {
21
+ readonly dir: string
22
+ readonly name: string
23
+ readonly version: string
24
+ /** The app's icon in `dir`, when it declares one. */
25
+ readonly icon: string | null
26
+ }
27
+
28
+ // Read from the package's `src`, which ships, whether this module runs from `src` or `dist`.
29
+ const SHELL_SOURCE_DIR = fileURLToPath(new URL("../src/shell", import.meta.url))
30
+
31
+ /** Where a project's desktop app is generated (`app`) and packaged (`dist`). */
32
+ export function desktopDir(projectRoot: string, part: "app" | "dist"): string {
33
+ return join(projectRoot, ".sixb", "desktop", part)
34
+ }
35
+
36
+ /**
37
+ * Writes the Electron app that opens `appUrl` into the project's `.sixb/desktop/app`. The directory
38
+ * is build-owned, like the rest of `.sixb`: it is cleared on every call.
39
+ */
40
+ export async function writeDesktopApp(options: DesktopAppOptions): Promise<GeneratedApp> {
41
+ const identity = await readAppIdentity(options.appUrl)
42
+ const version = await readProjectVersion(options.projectRoot)
43
+ const dir = desktopDir(options.projectRoot, "app")
44
+ await rm(dir, { recursive: true, force: true })
45
+ await mkdir(dir, { recursive: true })
46
+
47
+ const config: ShellConfig = {
48
+ name: identity.name,
49
+ appUrl: new URL(options.appUrl).href,
50
+ apiOrigin: new URL(options.apiOrigin).origin,
51
+ }
52
+ const manifest = {
53
+ name: "sixb-desktop-app",
54
+ // Names the folder the window's cookies are kept in, so each app has its own sign-in.
55
+ productName: identity.name,
56
+ version,
57
+ private: true,
58
+ main: "main.js",
59
+ }
60
+ const icon = identity.icon ? await writeIcon(dir, identity.icon) : null
61
+ const template = await readFile(join(SHELL_SOURCE_DIR, "index.html"), "utf-8")
62
+ await Promise.all([
63
+ writeFile(join(dir, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`),
64
+ writeFile(join(dir, "shell.json"), `${JSON.stringify(config, null, 2)}\n`),
65
+ writeFile(join(dir, "preload.js"), HIDDEN_TITLE_BAR_PRELOAD),
66
+ writeFile(join(dir, "index.html"), renderShellPage(template, { ...config, icon: !!icon })),
67
+ ])
68
+
69
+ // Electron loads plain JavaScript. A child process, because an in-process `Bun.build()` that
70
+ // wedges takes its caller down with it.
71
+ await run(
72
+ [
73
+ process.execPath,
74
+ "build",
75
+ join(SHELL_SOURCE_DIR, "main.ts"),
76
+ "--target=node",
77
+ "--format=cjs",
78
+ "--external=electron",
79
+ `--outfile=${join(dir, "main.js")}`,
80
+ ],
81
+ "Could not compile the desktop shell."
82
+ )
83
+ return { dir, name: identity.name, version, icon }
84
+ }
85
+
86
+ /** The page the window shows while the app loads, and when it cannot reach the app. */
87
+ export function renderShellPage(
88
+ template: string,
89
+ page: { readonly name: string; readonly appUrl: string; readonly icon: boolean }
90
+ ): string {
91
+ const initial = Array.from(page.name.trim())[0]?.toUpperCase() ?? ""
92
+ const markup: Record<string, string> = {
93
+ name: escapeHtml(page.name),
94
+ host: escapeHtml(new URL(page.appUrl).host),
95
+ appUrl: escapeHtml(page.appUrl),
96
+ // The app's icon, or the first letter of its name standing in for one.
97
+ mark: page.icon
98
+ ? '<img class="mark" src="icon.png" alt="" />'
99
+ : `<div class="mark" aria-hidden="true">${escapeHtml(initial)}</div>`,
100
+ }
101
+ return template.replaceAll(/\{\{(\w+)\}\}/g, (_match, key: string) => markup[key] ?? "")
102
+ }
103
+
104
+ /** Writes the app's icon into `dir` as `icon.png`; on macOS, drawn the way macOS draws app icons. */
105
+ async function writeIcon(dir: string, png: Uint8Array): Promise<string> {
106
+ const icon = join(dir, "icon.png")
107
+ if (process.platform !== "darwin") {
108
+ await writeFile(icon, png)
109
+ return icon
110
+ }
111
+ // The original goes beside the app, not in it: everything in the app's directory ships.
112
+ const source = join(dir, "..", "icon-source.png")
113
+ await writeFile(source, png)
114
+ await drawMacIcon(source, icon)
115
+ return icon
116
+ }
117
+
118
+ async function readProjectVersion(projectRoot: string): Promise<string> {
119
+ try {
120
+ const manifest: unknown = JSON.parse(await readFile(join(projectRoot, "package.json"), "utf-8"))
121
+ const version = (manifest as { readonly version?: unknown } | null)?.version
122
+ return typeof version === "string" ? version : "0.0.0"
123
+ } catch {
124
+ return "0.0.0"
125
+ }
126
+ }
127
+
128
+ function escapeHtml(value: string): string {
129
+ return value
130
+ .replaceAll("&", "&amp;")
131
+ .replaceAll("<", "&lt;")
132
+ .replaceAll(">", "&gt;")
133
+ .replaceAll('"', "&quot;")
134
+ }
@@ -0,0 +1,83 @@
1
+ /** What the desktop app takes from the web app it opens. */
2
+ export interface AppIdentity {
3
+ /** The app's name: `metadata.title` in `app/layout.tsx`. */
4
+ readonly name: string
5
+ /**
6
+ * The app's maskable icon, such as `app/public/icon-maskable-512.png`, or else its largest PNG
7
+ * icon, such as `app/public/icon-512.png`.
8
+ */
9
+ readonly icon: Uint8Array | null
10
+ }
11
+
12
+ /**
13
+ * Reads the app's web app manifest, the one a browser installs the app from. The desktop app is
14
+ * the same app installed another way, so it takes the same name and icon and has no settings of
15
+ * its own.
16
+ */
17
+ export async function readAppIdentity(appUrl: string): Promise<AppIdentity> {
18
+ const manifestUrl = new URL("/app.webmanifest", appUrl)
19
+ const manifest: unknown = await (await fetchFromApp(manifestUrl)).json()
20
+ const { name, icons } = (typeof manifest === "object" && manifest !== null ? manifest : {}) as {
21
+ readonly name?: unknown
22
+ readonly icons?: unknown
23
+ }
24
+
25
+ const iconUrl = desktopIcon(icons, manifestUrl)
26
+ return {
27
+ name: typeof name === "string" && name.trim() ? name.trim() : "Sixb",
28
+ icon: iconUrl ? new Uint8Array(await (await fetchFromApp(iconUrl)).arrayBuffer()) : null,
29
+ }
30
+ }
31
+
32
+ /**
33
+ * The app's id on the desktop, from the address it opens: `https://orders.acme.com` becomes
34
+ * `com.acme.orders`. Each deployment gets its own, so a staging build installs beside production.
35
+ */
36
+ export function bundleIdentifier(appUrl: string): string {
37
+ const labels = new URL(appUrl).hostname
38
+ .split(".")
39
+ .reverse()
40
+ .map((label) => label.toLowerCase().replaceAll(/[^a-z0-9-]/g, "-"))
41
+ .filter(Boolean)
42
+ return (labels.length > 1 ? labels : ["local", ...labels]).join(".")
43
+ }
44
+
45
+ // A maskable icon is drawn to its edges for a platform to cut its own shape from, which is what
46
+ // macOS does with it. Any other icon may carry its own shape and margins.
47
+ function desktopIcon(icons: unknown, manifestUrl: URL): URL | null {
48
+ let best: { readonly url: URL; readonly rank: readonly [number, number] } | null = null
49
+ for (const icon of Array.isArray(icons) ? icons : []) {
50
+ if (typeof icon !== "object" || icon === null) continue
51
+ const { src, sizes, type, purpose } = icon as Record<string, unknown>
52
+ if (typeof src !== "string") continue
53
+ const url = new URL(src, manifestUrl)
54
+ if (type === undefined ? !url.pathname.endsWith(".png") : type !== "image/png") continue
55
+
56
+ const maskable = typeof purpose === "string" && purpose.split(/\s+/).includes("maskable")
57
+ const size = Math.max(
58
+ 0,
59
+ ...(typeof sizes === "string" ? sizes.split(/\s+/) : []).map(
60
+ (entry) => Number.parseInt(entry, 10) || 0
61
+ )
62
+ )
63
+ const rank = [maskable ? 1 : 0, size] as const
64
+ if (!best || rank[0] > best.rank[0] || (rank[0] === best.rank[0] && rank[1] > best.rank[1])) {
65
+ best = { url, rank }
66
+ }
67
+ }
68
+ return best?.url ?? null
69
+ }
70
+
71
+ async function fetchFromApp(url: URL): Promise<Response> {
72
+ let response: Response
73
+ try {
74
+ response = await fetch(url)
75
+ } catch (error) {
76
+ throw new Error(
77
+ `[SixbDesktop] Could not reach ${url} (${error instanceof Error ? error.message : error}). ` +
78
+ "The desktop app takes its name and icon from the app, so the app must be running there."
79
+ )
80
+ }
81
+ if (!response.ok) throw new Error(`[SixbDesktop] ${url} answered ${response.status}.`)
82
+ return response
83
+ }