@niscorp/cli 0.2.3 → 0.3.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shell-site.ts","../src/routes.ts"],"names":["pad"],"mappings":";;;;;;;;;;;;AA+CO,IAAM,YAAA,GAAe,uBAAA;AAsB5B,IAAM,eAAA,GAAkB,CAAC,KAAA,KAA0B,KAAA,CAAM,QAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,QAAQ,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM,CAAA;AAIrH,IAAM,WAAA,GAAc,CAAC,QAAA,EAAkB,MAAA,EAAgB,aAAqC,EAAC,EAAG,OAAO,YAAA,KAAyB;AACrI,EAAA,MAAM,OAAA,GAAU,OAAO,OAAA,CAAQ,UAAU,EACtC,GAAA,CAAI,CAAC,CAAC,IAAA,EAAM,KAAK,MAAM,CAAA,CAAA,EAAI,IAAI,KAAK,eAAA,CAAgB,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA,CAC7D,KAAK,EAAE,CAAA;AACV,EAAA,OACE,QAAA,CAEG,OAAA,CAAQ,IAAA,EAAM,MAAM,IAAA,CAAK,QAAQ,SAAA,EAAW,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,MAAA,CAAQ,CAAC,EACrE,OAAA,CAAQ,eAAA,EAAiB,CAAC,KAAA,EAAO,QAAA,KAAsB,OAAA,KAAY,EAAA,GAAK,KAAA,GAAQ,CAAA,KAAA,EAAQ,QAAQ,CAAA,EAAG,OAAO,CAAA,CAAA,CAAI,CAAA;AAErH;AAsIA,IAAM,GAAA,GAAM,CAAC,IAAA,EAAc,KAAA,KAA0B,IAAA,GAAO,GAAA,CAAI,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAA,GAAQ,IAAA,CAAK,MAAM,CAAC,CAAA;AAEhG,IAAM,eAAA,GAAkB,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spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// AN APP WITH ITS OWN SHELL, DRAWN AHEAD OF TIME.\n//\n// The shell lives in the page. A build runs the app's own boot where there is\n// no browser, waits for the screen to be whole, and has the app's adapter draw\n// it to markup; the page's boot then picks that markup up and from there the\n// app is what it always was. No server holds a shell at any point.\n//\n// A file is a claim — \"this is the page\" — so a build does not write one it has\n// not checked. Per path, and each one FAILS the build:\n//\n// drawn the app booted and its screen drew to markup that is not empty\n// whole nothing was still loading when it was drawn\n// same twice a second boot draws the same markup, byte for byte, and says\n// the same head — or the page's own boot would not match what\n// the file says\n// adopted inside a DOM, a third boot picks the markup up and the\n// adapter complains about nothing\n//\n// And one that holds by construction: the boot is handed a path and nothing\n// else, so a file is only ever the screen as nobody in particular sees it.\n//\n// What a build cannot fail on, it reports: what the screen opened with (those\n// answers are in the markup as they were at build), what it can still call, and\n// what it waits on.\n//\n// THE HEAD OF EACH FILE IS ITS SCREEN'S OWN. What a screen says about itself —\n// a head node in a layout (nova's `nova:head`) — is read off the same shell the\n// markup was drawn from and written into the template's <head>; a path whose\n// screen has none goes out with the template's. Where a file lives is not the\n// screen's to say: with a `site` in the config, each path is given its own\n// canonical address.\n// ═══════════════════════════════════════════════════════════════\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n // the whole document; the template as it is when the screen could not be drawn\n html: string;\n // every check that did not hold — empty is a file that may be written\n problems: readonly string[];\n // the actions on the first screen\n actions: readonly string[];\n // endpoints answered while the screen opened: their answers are in the markup\n // as they were when it was drawn\n opensWith: readonly string[];\n // endpoints the first screen can still call once it is in the page\n callsLater: readonly string[];\n // channels the first screen waits on\n listens: readonly string[];\n // the head the first screen had, and the action it stood in — absent when\n // the file's head is the template's own\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\n// The screen, in the app's own index.html: inside the empty root, with whatever\n// the kit would have put on <html>.\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\n// What the first screen is made of, read off the definitions of what is mounted.\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\n// A drawn screen as the document it goes out in: the screen in the root, and\n// what it says about itself in the head.\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.head, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\n// One boot, one draw, and the app let go again.\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// ── adopted ──\n//\n// The one check that needs a browser's world. A DOM has to exist BEFORE the\n// app's modules load (an adapter decides what it is running in when it is\n// imported), so it runs in a process of its own: ./adopt stands a DOM up, loads\n// the same config, and for each path puts the markup in a root and makes the\n// app's own `adopt` call over a fresh boot.\n\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\n// Every path, checked.\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n // only what is worth adopting: a screen that drew, whole\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\n// Where two draws part, in a few words — enough to find it.\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const headed = routes.some((route) => route.head !== undefined);\n const headNote = (route: ShellRouteReport): string =>\n route.head === undefined ? 'head: the template’s own' : `head: its own, said by ${route.head.action ?? 'the shell’s chrome'}`;\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\n// ── served ──\n//\n// The same draw, per request: the first answer to a path is its screen, and\n// everything else in the built folder is a file. No checks here — a build made\n// them; a screen that will not draw goes out as the template, and the page's\n// own boot paints it as it did before any of this existed.\n//\n// What a browser may keep of all this, and how it travels, is not said here:\n// `start` puts that around this handler (./site), as it does around moss's.\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n // How big it is and when it last changed — what `start` needs to say\n // what a browser may keep, and to answer \"has it changed?\" (./site).\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n // a name with an extension that is not there is a missing file, not a page\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The paths an app has, where each one's file goes, and the table a build\n// prints. Pure: no server, no disk — the command hands these what it found.\n// ═══════════════════════════════════════════════════════════════\n\n// What a build learned about one path (moss's `ExportedDocument`, without the\n// markup).\nexport type RouteReport = {\n path: string;\n // the page the path led to; absent: the app's own shell\n page?: string;\n drawn: boolean;\n // something on it can still happen — it wants a server behind it\n live: boolean;\n why: readonly string[];\n // reads whose answers are in the markup as they were when it was drawn\n drawnWith: readonly string[];\n settled: boolean;\n // the head the screen had, and the action it stood in — absent when the\n // document's head is the template's own\n head?: { action?: string };\n};\n\n// `/`, and every page whose path names no parameter. A parameterised page has\n// as many paths as there are rows; those are the app's to list.\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\n// Where a path's file goes under the output directory: `/` is index.html, and\n// every other path is a folder with an index.html in it — what every static\n// host serves for that path without being told to.\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\n// The table. One row per path: whether a file is the whole of it, or a server\n// has to stand behind it — and, in the build's own words, why.\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const headed = routes.some((route) => route.head !== undefined);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [route.head === undefined ? 'head: the template’s own' : `head: its own, said by ${route.head.action ?? 'the shell’s chrome'}`] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
1
+ {"version":3,"sources":["../src/shell-site.ts","../src/routes.ts"],"names":["pad"],"mappings":";;;;;;;;;;;;AAgDO,IAAM,YAAA,GAAe,uBAAA;AAsB5B,IAAM,eAAA,GAAkB,CAAC,KAAA,KAA0B,KAAA,CAAM,QAAQ,IAAA,EAAM,OAAO,CAAA,CA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AAS,CAAC,CAAC,CAAA,OAAA,CAAS,CAAA;AAC/H,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,IAAA,MAAM,IAAA,GAAO,CAAA,EAAG,GAAA,CAAI,IAAI,CAAA,CAAA,EAAIA,IAAAA,CAAI,GAAA,CAAI,IAAA,EAAM,MAAA,CAAO,IAAA,GAAO,CAAC,CAAC,CAAA,EAAGA,IAAAA,CAAI,GAAA,CAAI,IAAA,EAAM,MAAA,CAAO,IAAA,GAAO,CAAC,CAAC,CAAA,EAAGA,IAAAA,CAAI,GAAA,CAAI,MAAA,EAAQ,MAAA,CAAO,MAAA,GAAS,CAAC,CAAC,CAAA,CAAA;AAChI,IAAA,MAAM,CAAC,KAAA,EAAO,GAAG,IAAI,CAAA,GAAI,CAAC,GAAI,GAAA,CAAI,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,IAAI,KAAA,GAAQ,CAAC,gCAAgC,CAAA,EAAI,GAAG,IAAI,IAAI,CAAA;AACjH,IAAA,KAAA,CAAM,KAAK,CAAA,EAAG,IAAI,CAAA,EAAG,KAAA,IAAS,EAAE,CAAA,CAAE,CAAA;AAClC,IAAA,KAAA,MAAW,IAAA,IAAQ,IAAA,EAAM,KAAA,CAAM,IAAA,CAAK,CAAA,EAAG,GAAA,CAAI,MAAA,CAAO,IAAA,CAAK,MAAM,CAAC,CAAA,EAAG,IAAI,CAAA,CAAE,CAAA;AAAA,EACzE;AACA,EAAA,KAAA,CAAM,KAAK,EAAE,CAAA;AACb,EAAA,KAAA,CAAM,KAAK,sFAAiF,CAAA;AAC5F,EAAA,KAAA,CAAM,KAAK,2EAAsE,CAAA;AACjF,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"index.cjs","sourcesContent":["import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// AN APP WITH ITS OWN SHELL, DRAWN AHEAD OF TIME.\n//\n// The shell lives in the page. A build runs the app's own boot where there is\n// no browser, waits for the screen to be whole, and has the app's adapter draw\n// it to markup; the page's boot then picks that markup up and from there the\n// app is what it always was. No server holds a shell at any point.\n//\n// A file is a claim — \"this is the page\" — so a build does not write one it has\n// not checked. Per path, and each one FAILS the build:\n//\n// drawn the app booted and its screen drew to markup that is not empty\n// whole nothing was still loading when it was drawn\n// same twice a second boot draws the same markup, byte for byte, and says\n// the same head — or the page's own boot would not match what\n// the file says\n// adopted inside a DOM, a third boot picks the markup up and the\n// adapter complains about nothing\n//\n// And one that holds by construction: the boot is handed a path and nothing\n// else, so a file is only ever the screen as nobody in particular sees it.\n//\n// What a build cannot fail on, it reports: what the screen opened with (those\n// answers are in the markup as they were at build), what it can still call, and\n// what it waits on.\n//\n// THE HEAD OF EACH FILE IS ITS SCREEN'S OWN. A page's <head> is a node in a\n// layout (nova's `nova:head`, holding the elements a head holds). It is read\n// off the same shell the markup was drawn from and written into the template's\n// <head>; a path whose screen has none goes out with the template's. A head\n// that holds what it may not — something that runs, or styles — FAILS the\n// build like any other check. With a `site` in the config, each path is given\n// its own canonical address.\n// ═══════════════════════════════════════════════════════════════\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n // the whole document; the template as it is when the screen could not be drawn\n html: string;\n // every check that did not hold — empty is a file that may be written\n problems: readonly string[];\n // the actions on the first screen\n actions: readonly string[];\n // endpoints answered while the screen opened: their answers are in the markup\n // as they were when it was drawn\n opensWith: readonly string[];\n // endpoints the first screen can still call once it is in the page\n callsLater: readonly string[];\n // channels the first screen waits on\n listens: readonly string[];\n // what the first screen's head held, and the actions that said it — absent\n // when the screen has no head and the file's is the template's own\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\n// The screen, in the app's own index.html: inside the empty root, with whatever\n// the kit would have put on <html>.\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\n// What the first screen is made of, read off the definitions of what is mounted.\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\n// A drawn screen as the document it goes out in: the screen in the root, and\n// what it says about itself in the head.\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\n// One boot, one draw, and the app let go again.\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// ── adopted ──\n//\n// The one check that needs a browser's world. A DOM has to exist BEFORE the\n// app's modules load (an adapter decides what it is running in when it is\n// imported), so it runs in a process of its own: ./adopt stands a DOM up, loads\n// the same config, and for each path puts the markup in a root and makes the\n// app's own `adopt` call over a fresh boot.\n\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\n// Every path, checked.\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n // only what is worth adopting: a screen that drew, whole\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\n// Where two draws part, in a few words — enough to find it.\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\n// ── served ──\n//\n// The same draw, per request: the first answer to a path is its screen, and\n// everything else in the built folder is a file. No checks here — a build made\n// them; a screen that will not draw goes out as the template, and the page's\n// own boot paints it as it did before any of this existed.\n//\n// What a browser may keep of all this, and how it travels, is not said here:\n// `start` puts that around this handler (./site), as it does around moss's.\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n // How big it is and when it last changed — what `start` needs to say\n // what a browser may keep, and to answer \"has it changed?\" (./site).\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n // a name with an extension that is not there is a missing file, not a page\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The paths an app has, where each one's file goes, and the table a build\n// prints. Pure: no server, no disk — the command hands these what it found.\n// ═══════════════════════════════════════════════════════════════\n\n// What a build learned about one path (moss's `ExportedDocument`, without the\n// markup).\nexport type RouteReport = {\n path: string;\n // the page the path led to; absent: the app's own shell\n page?: string;\n drawn: boolean;\n // something on it can still happen — it wants a server behind it\n live: boolean;\n why: readonly string[];\n // reads whose answers are in the markup as they were when it was drawn\n drawnWith: readonly string[];\n settled: boolean;\n // what the screen's head held, and the actions that said it — absent when\n // the screen has no head and the document's is the template's own\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\n// `/`, and every page whose path names no parameter. A parameterised page has\n// as many paths as there are rows; those are the app's to list.\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\n// Where a path's file goes under the output directory: `/` is index.html, and\n// every other path is a folder with an index.html in it — what every static\n// host serves for that path without being told to.\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\n// The table. One row per path: whether a file is the whole of it, or a server\n// has to stand behind it — and, in the build's own words, why.\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
package/dist/index.d.cts CHANGED
@@ -59,7 +59,8 @@ type RouteReport = {
59
59
  drawnWith: readonly string[];
60
60
  settled: boolean;
61
61
  head?: {
62
- action?: string;
62
+ elements: readonly unknown[];
63
+ actions: readonly string[];
63
64
  };
64
65
  };
65
66
  declare const defaultPaths: (pages: readonly {
package/dist/index.d.ts CHANGED
@@ -59,7 +59,8 @@ type RouteReport = {
59
59
  drawnWith: readonly string[];
60
60
  settled: boolean;
61
61
  head?: {
62
- action?: string;
62
+ elements: readonly unknown[];
63
+ actions: readonly string[];
63
64
  };
64
65
  };
65
66
  declare const defaultPaths: (pages: readonly {
package/dist/index.js CHANGED
@@ -19,8 +19,9 @@ var shellRouteTable = (routes) => {
19
19
  const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;
20
20
  const lines = [` ${pad("Route", width)}First screen`];
21
21
  const indent = " ".repeat(width + 2);
22
- const headed = routes.some((route) => route.head !== void 0);
23
- const headNote = (route) => route.head === void 0 ? "head: the template\u2019s own" : `head: its own, said by ${route.head.action ?? "the shell\u2019s chrome"}`;
22
+ const says = (route) => (route.head?.elements.length ?? 0) > 0;
23
+ const headed = routes.some(says);
24
+ const headNote = (route) => says(route) ? `head: its own, said by ${route.head?.actions.join(", ") || "the shell\u2019s chrome"}` : "head: the template\u2019s own";
24
25
  for (const route of routes) {
25
26
  const ok = route.problems.length === 0;
26
27
  const notes = ok ? [
@@ -52,7 +53,8 @@ var fileOf = (path) => {
52
53
  };
53
54
  var pad2 = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
54
55
  var routeTable = (routes) => {
55
- const headed = routes.some((route) => route.head !== void 0);
56
+ const says = (route) => (route.head?.elements.length ?? 0) > 0;
57
+ const headed = routes.some(says);
56
58
  const rows = routes.map((route) => {
57
59
  const mark = !route.drawn ? "\u2717" : route.live ? "\u25CF" : "\u25CB";
58
60
  const what = route.page === void 0 ? "the app" : `page ${route.page}`;
@@ -62,7 +64,7 @@ var routeTable = (routes) => {
62
64
  ...route.drawn && !route.settled ? ["it was still loading when the wait ran out \u2014 drawn with what it had"] : [],
63
65
  ...route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(", ")} \u2014 as it answered at build`] : []
64
66
  ];
65
- const head = headed && route.drawn ? [route.head === void 0 ? "head: the template\u2019s own" : `head: its own, said by ${route.head.action ?? "the shell\u2019s chrome"}`] : [];
67
+ const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(", ") || "the shell\u2019s chrome"}` : "head: the template\u2019s own"] : [];
66
68
  return { mark, path: route.path, what, served, notes, head };
67
69
  });
68
70
  const widths = {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shell-site.ts","../src/routes.ts"],"names":["pad"],"mappings":";;;;;;;;;;AA+CO,IAAM,YAAA,GAAe,uBAAA;AAsB5B,IAAM,eAAA,GAAkB,CAAC,KAAA,KAA0B,KAAA,CAAM,QAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,QAAQ,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM,CAAA;AAIrH,IAAM,WAAA,GAAc,CAAC,QAAA,EAAkB,MAAA,EAAgB,aAAqC,EAAC,EAAG,OAAO,YAAA,KAAyB;AACrI,EAAA,MAAM,OAAA,GAAU,OAAO,OAAA,CAAQ,UAAU,EACtC,GAAA,CAAI,CAAC,CAAC,IAAA,EAAM,KAAK,MAAM,CAAA,CAAA,EAAI,IAAI,KAAK,eAAA,CAAgB,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA,CAC7D,KAAK,EAAE,CAAA;AACV,EAAA,OACE,QAAA,CAEG,OAAA,CAAQ,IAAA,EAAM,MAAM,IAAA,CAAK,QAAQ,SAAA,EAAW,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,MAAA,CAAQ,CAAC,EACrE,OAAA,CAAQ,eAAA,EAAiB,CAAC,KAAA,EAAO,QAAA,KAAsB,OAAA,KAAY,EAAA,GAAK,KAAA,GAAQ,CAAA,KAAA,EAAQ,QAAQ,CAAA,EAAG,OAAO,CAAA,CAAA,CAAI,CAAA;AAErH;AAsIA,IAAM,GAAA,GAAM,CAAC,IAAA,EAAc,KAAA,KAA0B,IAAA,G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AAiF,CAAA;AAC5F,EAAA,KAAA,CAAM,KAAK,2EAAsE,CAAA;AACjF,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"index.js","sourcesContent":["import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// AN APP WITH ITS OWN SHELL, DRAWN AHEAD OF TIME.\n//\n// The shell lives in the page. A build runs the app's own boot where there is\n// no browser, waits for the screen to be whole, and has the app's adapter draw\n// it to markup; the page's boot then picks that markup up and from there the\n// app is what it always was. No server holds a shell at any point.\n//\n// A file is a claim — \"this is the page\" — so a build does not write one it has\n// not checked. Per path, and each one FAILS the build:\n//\n// drawn the app booted and its screen drew to markup that is not empty\n// whole nothing was still loading when it was drawn\n// same twice a second boot draws the same markup, byte for byte, and says\n// the same head — or the page's own boot would not match what\n// the file says\n// adopted inside a DOM, a third boot picks the markup up and the\n// adapter complains about nothing\n//\n// And one that holds by construction: the boot is handed a path and nothing\n// else, so a file is only ever the screen as nobody in particular sees it.\n//\n// What a build cannot fail on, it reports: what the screen opened with (those\n// answers are in the markup as they were at build), what it can still call, and\n// what it waits on.\n//\n// THE HEAD OF EACH FILE IS ITS SCREEN'S OWN. What a screen says about itself —\n// a head node in a layout (nova's `nova:head`) — is read off the same shell the\n// markup was drawn from and written into the template's <head>; a path whose\n// screen has none goes out with the template's. Where a file lives is not the\n// screen's to say: with a `site` in the config, each path is given its own\n// canonical address.\n// ═══════════════════════════════════════════════════════════════\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n // the whole document; the template as it is when the screen could not be drawn\n html: string;\n // every check that did not hold — empty is a file that may be written\n problems: readonly string[];\n // the actions on the first screen\n actions: readonly string[];\n // endpoints answered while the screen opened: their answers are in the markup\n // as they were when it was drawn\n opensWith: readonly string[];\n // endpoints the first screen can still call once it is in the page\n callsLater: readonly string[];\n // channels the first screen waits on\n listens: readonly string[];\n // the head the first screen had, and the action it stood in — absent when\n // the file's head is the template's own\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\n// The screen, in the app's own index.html: inside the empty root, with whatever\n// the kit would have put on <html>.\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\n// What the first screen is made of, read off the definitions of what is mounted.\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\n// A drawn screen as the document it goes out in: the screen in the root, and\n// what it says about itself in the head.\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.head, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\n// One boot, one draw, and the app let go again.\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// ── adopted ──\n//\n// The one check that needs a browser's world. A DOM has to exist BEFORE the\n// app's modules load (an adapter decides what it is running in when it is\n// imported), so it runs in a process of its own: ./adopt stands a DOM up, loads\n// the same config, and for each path puts the markup in a root and makes the\n// app's own `adopt` call over a fresh boot.\n\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\n// Every path, checked.\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n // only what is worth adopting: a screen that drew, whole\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\n// Where two draws part, in a few words — enough to find it.\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const headed = routes.some((route) => route.head !== undefined);\n const headNote = (route: ShellRouteReport): string =>\n route.head === undefined ? 'head: the template’s own' : `head: its own, said by ${route.head.action ?? 'the shell’s chrome'}`;\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\n// ── served ──\n//\n// The same draw, per request: the first answer to a path is its screen, and\n// everything else in the built folder is a file. No checks here — a build made\n// them; a screen that will not draw goes out as the template, and the page's\n// own boot paints it as it did before any of this existed.\n//\n// What a browser may keep of all this, and how it travels, is not said here:\n// `start` puts that around this handler (./site), as it does around moss's.\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n // How big it is and when it last changed — what `start` needs to say\n // what a browser may keep, and to answer \"has it changed?\" (./site).\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n // a name with an extension that is not there is a missing file, not a page\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The paths an app has, where each one's file goes, and the table a build\n// prints. Pure: no server, no disk — the command hands these what it found.\n// ═══════════════════════════════════════════════════════════════\n\n// What a build learned about one path (moss's `ExportedDocument`, without the\n// markup).\nexport type RouteReport = {\n path: string;\n // the page the path led to; absent: the app's own shell\n page?: string;\n drawn: boolean;\n // something on it can still happen — it wants a server behind it\n live: boolean;\n why: readonly string[];\n // reads whose answers are in the markup as they were when it was drawn\n drawnWith: readonly string[];\n settled: boolean;\n // the head the screen had, and the action it stood in — absent when the\n // document's head is the template's own\n head?: { action?: string };\n};\n\n// `/`, and every page whose path names no parameter. A parameterised page has\n// as many paths as there are rows; those are the app's to list.\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\n// Where a path's file goes under the output directory: `/` is index.html, and\n// every other path is a folder with an index.html in it — what every static\n// host serves for that path without being told to.\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\n// The table. One row per path: whether a file is the whole of it, or a server\n// has to stand behind it — and, in the build's own words, why.\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const headed = routes.some((route) => route.head !== undefined);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [route.head === undefined ? 'head: the template’s own' : `head: its own, said by ${route.head.action ?? 'the shell’s chrome'}`] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
1
+ {"version":3,"sources":["../src/shell-site.ts","../src/routes.ts"],"names":["pad"],"mappings":";;;;;;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} from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// AN APP WITH ITS OWN SHELL, DRAWN AHEAD OF TIME.\n//\n// The shell lives in the page. A build runs the app's own boot where there is\n// no browser, waits for the screen to be whole, and has the app's adapter draw\n// it to markup; the page's boot then picks that markup up and from there the\n// app is what it always was. No server holds a shell at any point.\n//\n// A file is a claim — \"this is the page\" — so a build does not write one it has\n// not checked. Per path, and each one FAILS the build:\n//\n// drawn the app booted and its screen drew to markup that is not empty\n// whole nothing was still loading when it was drawn\n// same twice a second boot draws the same markup, byte for byte, and says\n// the same head — or the page's own boot would not match what\n// the file says\n// adopted inside a DOM, a third boot picks the markup up and the\n// adapter complains about nothing\n//\n// And one that holds by construction: the boot is handed a path and nothing\n// else, so a file is only ever the screen as nobody in particular sees it.\n//\n// What a build cannot fail on, it reports: what the screen opened with (those\n// answers are in the markup as they were at build), what it can still call, and\n// what it waits on.\n//\n// THE HEAD OF EACH FILE IS ITS SCREEN'S OWN. A page's <head> is a node in a\n// layout (nova's `nova:head`, holding the elements a head holds). It is read\n// off the same shell the markup was drawn from and written into the template's\n// <head>; a path whose screen has none goes out with the template's. A head\n// that holds what it may not — something that runs, or styles — FAILS the\n// build like any other check. With a `site` in the config, each path is given\n// its own canonical address.\n// ═══════════════════════════════════════════════════════════════\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n // the whole document; the template as it is when the screen could not be drawn\n html: string;\n // every check that did not hold — empty is a file that may be written\n problems: readonly string[];\n // the actions on the first screen\n actions: readonly string[];\n // endpoints answered while the screen opened: their answers are in the markup\n // as they were when it was drawn\n opensWith: readonly string[];\n // endpoints the first screen can still call once it is in the page\n callsLater: readonly string[];\n // channels the first screen waits on\n listens: readonly string[];\n // what the first screen's head held, and the actions that said it — absent\n // when the screen has no head and the file's is the template's own\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\n// The screen, in the app's own index.html: inside the empty root, with whatever\n// the kit would have put on <html>.\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\n// What the first screen is made of, read off the definitions of what is mounted.\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\n// A drawn screen as the document it goes out in: the screen in the root, and\n// what it says about itself in the head.\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\n// One boot, one draw, and the app let go again.\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// ── adopted ──\n//\n// The one check that needs a browser's world. A DOM has to exist BEFORE the\n// app's modules load (an adapter decides what it is running in when it is\n// imported), so it runs in a process of its own: ./adopt stands a DOM up, loads\n// the same config, and for each path puts the markup in a root and makes the\n// app's own `adopt` call over a fresh boot.\n\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\n// Every path, checked.\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n // only what is worth adopting: a screen that drew, whole\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\n// Where two draws part, in a few words — enough to find it.\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\n// ── served ──\n//\n// The same draw, per request: the first answer to a path is its screen, and\n// everything else in the built folder is a file. No checks here — a build made\n// them; a screen that will not draw goes out as the template, and the page's\n// own boot paints it as it did before any of this existed.\n//\n// What a browser may keep of all this, and how it travels, is not said here:\n// `start` puts that around this handler (./site), as it does around moss's.\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n // How big it is and when it last changed — what `start` needs to say\n // what a browser may keep, and to answer \"has it changed?\" (./site).\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n // a name with an extension that is not there is a missing file, not a page\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The paths an app has, where each one's file goes, and the table a build\n// prints. Pure: no server, no disk — the command hands these what it found.\n// ═══════════════════════════════════════════════════════════════\n\n// What a build learned about one path (moss's `ExportedDocument`, without the\n// markup).\nexport type RouteReport = {\n path: string;\n // the page the path led to; absent: the app's own shell\n page?: string;\n drawn: boolean;\n // something on it can still happen — it wants a server behind it\n live: boolean;\n why: readonly string[];\n // reads whose answers are in the markup as they were when it was drawn\n drawnWith: readonly string[];\n settled: boolean;\n // what the screen's head held, and the actions that said it — absent when\n // the screen has no head and the document's is the template's own\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\n// `/`, and every page whose path names no parameter. A parameterised page has\n// as many paths as there are rows; those are the app's to list.\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\n// Where a path's file goes under the output directory: `/` is index.html, and\n// every other path is a folder with an index.html in it — what every static\n// host serves for that path without being told to.\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\n// The table. One row per path: whether a file is the whole of it, or a server\n// has to stand behind it — and, in the build's own words, why.\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
@@ -0,0 +1,3 @@
1
+ export { configFileOf, isProject, isShellProject, loadProject } from './chunk-DTDMQJAO.js';
2
+ //# sourceMappingURL=project-O5OEDRXN.js.map
3
+ //# sourceMappingURL=project-O5OEDRXN.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"project-RTSKTGE3.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"project-O5OEDRXN.js"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@niscorp/cli",
3
- "version": "0.2.3",
3
+ "version": "0.3.1",
4
4
  "description": "nisc — the command for a nisc application: dev, build, export, start. One config file says how the app boots and how its pages are drawn; the command does the rest.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -23,7 +23,8 @@
23
23
  "types": "./dist/index.d.cts",
24
24
  "default": "./dist/index.cjs"
25
25
  }
26
- }
26
+ },
27
+ "./package.json": "./package.json"
27
28
  },
28
29
  "files": [
29
30
  "bin",
@@ -38,8 +39,8 @@
38
39
  "node": ">=22.12"
39
40
  },
40
41
  "peerDependencies": {
41
- "@niscorp/nova": "^0.1.4",
42
- "@niscorp/moss": "^0.2.4"
42
+ "@niscorp/moss": "^0.3.2",
43
+ "@niscorp/nova": "^0.2.1"
43
44
  },
44
45
  "peerDependenciesMeta": {
45
46
  "@niscorp/moss": {
@@ -57,8 +58,8 @@
57
58
  "tsup": "^8.5.1",
58
59
  "typescript": "^6.0.2",
59
60
  "vitest": "^4.1.2",
60
- "@niscorp/moss": "^0.2.4",
61
- "@niscorp/nova": "^0.1.4"
61
+ "@niscorp/moss": "^0.3.2",
62
+ "@niscorp/nova": "^0.2.1"
62
63
  },
63
64
  "scripts": {
64
65
  "build": "tsup",
@@ -1,3 +0,0 @@
1
- export { configFileOf, isProject, isShellProject, loadProject } from './chunk-DFB5BOHX.js';
2
- //# sourceMappingURL=project-RTSKTGE3.js.map
3
- //# sourceMappingURL=project-RTSKTGE3.js.map