@niscorp/moss 0.3.2 → 0.4.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.
- package/CHANGELOG.md +155 -0
- package/DESIGN.md +84 -19
- package/DOCS.md +170 -35
- package/README.md +2 -2
- package/dist/{chunk-J72N3EMJ.js → chunk-4T6KAXBP.js} +45 -27
- package/dist/chunk-4T6KAXBP.js.map +1 -0
- package/dist/{chunk-ZOEUEMDX.js → chunk-HOZID4EM.js} +131 -16
- package/dist/chunk-HOZID4EM.js.map +1 -0
- package/dist/{chunk-ZP3C53AC.js → chunk-R3QMJ3JF.js} +744 -661
- package/dist/chunk-R3QMJ3JF.js.map +1 -0
- package/dist/chunk-U3UR5AOQ.js +103 -0
- package/dist/chunk-U3UR5AOQ.js.map +1 -0
- package/dist/client/node.cjs +1 -1
- package/dist/client/node.cjs.map +1 -1
- package/dist/client/node.js +1 -1
- package/dist/client/node.js.map +1 -1
- package/dist/client.cjs +60 -26
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +6 -1
- package/dist/client.d.ts +6 -1
- package/dist/client.js +2 -2
- package/dist/{document-D9khv9jI.d.cts → document-DhWxieUc.d.cts} +22 -3
- package/dist/{document-D9khv9jI.d.ts → document-DhWxieUc.d.ts} +22 -3
- package/dist/index.cjs +786 -583
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -3
- package/dist/index.d.ts +19 -3
- package/dist/index.js +2 -2
- package/dist/node.cjs +379 -230
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +2 -1
- package/dist/node.d.ts +2 -1
- package/dist/node.js +3 -3
- package/dist/terminal/index.cjs +60 -26
- package/dist/terminal/index.cjs.map +1 -1
- package/dist/terminal/index.js +2 -2
- package/dist/vite.cjs +103 -28
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +14 -9
- package/dist/vite.js.map +1 -1
- package/package.json +12 -12
- package/dist/chunk-J72N3EMJ.js.map +0 -1
- package/dist/chunk-SUVDISEG.js +0 -64
- package/dist/chunk-SUVDISEG.js.map +0 -1
- package/dist/chunk-ZOEUEMDX.js.map +0 -1
- package/dist/chunk-ZP3C53AC.js.map +0 -1
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite.ts"],"names":[],"mappings":";;;;;;;AAkEA,IAAM,aAAA,GAAgB,yEAAA;AACtB,IAAM,kBAAA,GAAqB,GAAA;AAI3B,IAAM,MAAA,GAAS,OAAO,MAAA,KAAkC;AACtD,EAAA,MAAA,CAAO,GAAA,CAAI,MAAA,CAAO,MAAA,CAAO,IAAA,EAAK;AAC9B,EAAA,MAAA,CAAO,MAAA,CAAO,IAAI,KAAA,KAAU,MAAY,OAAO,GAAA,CAAI,MAAA,CAAO,OAAM,CAAA,GAAI;AACtE,CAAA;AAEA,IAAM,IAAA,GAAO,CAAC,KAAA,KAA4B,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AAExF,IAAM,OAAA,GAAU,CAAC,OAAA,MAAqC;AAAA,EAC3D,IAAA,EAAM,UAAA;AAAA,EACN,KAAA,EAAO,OAAA;AAAA,EACP,eAAA,EAAiB,CAAC,IAAA,KAAwB;AACxC,IAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,MAAA;AAC/B,IAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,aAAA;AAC/B,IAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,UAAA;AAC/B,IAAA,MAAM,IAAA,GAAO,CAAC,EAAA,KAAiD,IAAA,CAAK,cAAc,EAAE,CAAA;AAEpF,IAAA,MAAM,OAAO,YAA6B;AACxC,MAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAA;AAClC,MAAA,OAAO,EAAE,GAAA,EAAK,QAAA,EA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AA,MAAW,CAAC,IAAA,EAAM,KAAK,CAAA,IAAK,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,OAAO,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,IAAA,EAAM,KAAK,CAAA;AACnF,QAAA,GAAA,CAAI,GAAA,CAAI,KAAK,IAAI,CAAA;AAAA,MACnB,CAAC,CAAA,CAEA,KAAA,CAAM,MAAM,MAAM,CAAA;AAAA,IACvB,CAAC,CAAA;AAAA,EACH;AACF,CAAA","file":"vite.js","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport type { Plugin, ViteDevServer } from 'vite';\nimport { getRequestListener } from '@hono/node-server';\nimport { renderDocument } from './document';\nimport type { DocumentConfig } from './document';\nimport { attachSocket, MOSS_PATHS } from './node';\nimport type { MossServer } from './server';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/moss/vite — the app server inside vite's dev process.\n//\n// One `nisc dev`, no proxy, no second terminal: the app boots in vite's own\n// process, through vite's own module loading (`ssrLoadModule`), so the boot it\n// runs is the source on disk and an edit is a fresh boot. What it does, in the\n// order a request meets it:\n//\n// the socket attached ONCE, delegating to whichever server is current —\n// a re-boot swaps what it delegates to, never the handler\n// /dev/as/:who a signed-in URL, when the app can mint a dev token\n// a page `/`, or a path one of the manifest's pages answers: index.html\n// through vite first (its client, the framework's refresh\n// preamble), then the screen drawn into it (`renderDocument`)\n// moss's paths /api, /catalog, /operator, /integrations — the app server's\n// the rest vite's: source files, assets, its own urls\n//\n// A change under one of the watched directories re-boots the whole app — a\n// fresh database, fresh seed, fresh shells — then reloads the page so the\n// browser reconnects to the new server. The outgoing server keeps answering\n// until the new one is up, so a broken edit does not take the dev server down,\n// and is then let go, timers included.\n// ═══════════════════════════════════════════════════════════════\n\nexport type DevApp = {\n server: MossServer;\n // how to let it go (default: `server.close()`)\n close?: () => void | Promise<void>;\n // How one of its screens is drawn. Absent: pages go out as vite's index.html,\n // undrawn, and the terminal paints them as it always did.\n draw?: DocumentConfig['draw'];\n htmlAttributes?: DocumentConfig['htmlAttributes'];\n site?: DocumentConfig['site'];\n tokenKey?: string;\n // A dev-only signed-in URL: `/dev/as/<who>` stores the token this returns —\n // where the wire keeps it and in the cookie copy a page is drawn by — and\n // goes to `/`. `null` is nobody of that name. It lives in vite's middleware\n // and nowhere else, so it cannot ship.\n signIn?: (who: string) => string | null | Promise<string | null>;\n};\n\nexport type MossDevOptions = {\n // Stand the app up. `load` is vite's own module loader: what it loads is the\n // source as it is on disk now, with the app's aliases resolved.\n app: (load: (id: string) => Promise<Record<string, unknown>>) => Promise<DevApp>;\n // Which edits re-boot the app (default: anything under src/app, src/server,\n // src/db or src/ui — the kit is in it because the SERVER holds the component\n // registry too — and the nisc config).\n watch?: RegExp;\n // The page template, relative to vite's root (default `index.html`).\n index?: string;\n // The paths the app server answers (default: moss's own).\n owned?: RegExp;\n // The name in vite's log (default `moss`).\n label?: string;\n};\n\nconst DEFAULT_WATCH = /([\\\\/]src[\\\\/](app|server|db|ui)[\\\\/])|([\\\\/]nisc\\.config\\.[cm]?[jt]s$)/;\nconst REBOOT_DEBOUNCE_MS = 200;\n\ntype Booted = { app: DevApp; listener: ReturnType<typeof getRequestListener> };\n\nconst retire = async (booted: Booted): Promise<void> => {\n booted.app.server.socket.stop();\n await (booted.app.close ?? ((): void => booted.app.server.close()))();\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\nexport const mossDev = (options: MossDevOptions): Plugin => ({\n name: 'moss-dev',\n apply: 'serve',\n configureServer: (vite: ViteDevServer) => {\n const label = options.label ?? 'moss';\n const watch = options.watch ?? DEFAULT_WATCH;\n const owned = options.owned ?? MOSS_PATHS;\n const load = (id: string): Promise<Record<string, unknown>> => vite.ssrLoadModule(id);\n\n const boot = async (): Promise<Booted> => {\n const app = await options.app(load);\n return { app, listener: getRequestListener(app.server.fetch) };\n };\n let current = boot();\n current.catch((error: unknown) => vite.config.logger.error(`[${label}] the app did not boot: ${said(error)}`, { timestamp: true }));\n\n if (vite.httpServer !== null) {\n attachSocket(\n vite.httpServer,\n Object.assign(async (url: string, connection: Parameters<MossServer['socket']>[1]) => (await current).app.server.socket(url, connection), {\n // whichever server is current owns the revalidation timer; this handler owns none\n stop: (): void => void current.then(({ app }) => app.server.socket.stop(), () => undefined),\n }),\n );\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const reboot = (file: string): void => {\n if (!watch.test(file)) return;\n clearTimeout(timer);\n timer = setTimeout(() => {\n const outgoing = current;\n current = boot();\n current.then(\n () => {\n void outgoing.then(retire, () => undefined);\n vite.config.logger.info(`[${label}] app server re-booted`, { timestamp: true });\n vite.ws.send({ type: 'full-reload' });\n },\n (error: unknown) => {\n // the old server goes on answering until an edit boots\n current = outgoing;\n vite.config.logger.error(`[${label}] re-boot failed: ${said(error)}`, { timestamp: true });\n },\n );\n }, REBOOT_DEBOUNCE_MS);\n };\n vite.watcher.on('change', reboot);\n vite.watcher.on('add', reboot);\n vite.watcher.on('unlink', reboot);\n vite.httpServer?.once('close', () => void current.then(retire, () => undefined));\n\n vite.middlewares.use((req, res, next) => {\n const url = req.url ?? '/';\n const path = url.split('?')[0] ?? '/';\n\n const who = /^\\/dev\\/as\\/([\\w.@%-]+)$/.exec(path)?.[1];\n if (who !== undefined) {\n void current\n .then(async ({ app }) => {\n if (app.signIn === undefined) {\n next();\n return;\n }\n const token = await app.signIn(decodeURIComponent(who));\n const key = JSON.stringify(app.tokenKey ?? 'nisc.token');\n res.setHeader('content-type', 'text/html; charset=utf-8');\n res.end(\n token === null\n ? `<p>nobody called ${who.replace(/[<&\"]/g, '')}</p>`\n : `<script>localStorage.setItem(${key},${JSON.stringify(token)});document.cookie=encodeURIComponent(${key})+'='+encodeURIComponent(${JSON.stringify(token)})+'; Path=/; SameSite=Lax';location.replace('/')</script>`,\n );\n })\n .catch(() => {\n res.statusCode = 500;\n res.end('the dev sign-in failed');\n });\n return;\n }\n\n if (owned.test(path)) {\n void current.then(({ listener }) => listener(req, res)).catch(() => {\n res.statusCode = 503;\n res.end('the app server did not boot — see the dev server’s log');\n });\n return;\n }\n\n if (req.method !== 'GET') {\n next();\n return;\n }\n void current\n .then(async ({ app }) => {\n if (app.draw === undefined || (path !== '/' && path !== '/index.html' && app.server.page(path) === undefined)) {\n next();\n return;\n }\n const template = await vite.transformIndexHtml(url, await readFile(resolve(vite.config.root, options.index ?? 'index.html'), 'utf8'));\n const page = await renderDocument({\n server: app.server,\n template,\n request: { path: path === '/index.html' ? '/' : path, cookie: req.headers.cookie ?? null },\n draw: app.draw,\n ...(app.htmlAttributes !== undefined ? { htmlAttributes: app.htmlAttributes } : {}),\n ...(app.site !== undefined ? { site: app.site } : {}),\n ...(app.tokenKey !== undefined ? { tokenKey: app.tokenKey } : {}),\n });\n res.statusCode = 200;\n res.setHeader('content-type', 'text/html; charset=utf-8');\n for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);\n res.end(page.html);\n })\n // not drawn is not broken: vite serves index.html as it always did\n .catch(() => next());\n });\n },\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/vite.ts"],"names":[],"mappings":";;;;;;;AAmEA,IAAM,aAAA,GAAgB,yEAAA;AACtB,IAAM,kBAAA,GAAqB,GAAA;AAI3B,IAAM,MAAA,GAAS,OAAO,MAAA,KAAkC;AACtD,EAAA,MAAA,CAAO,GAAA,CAAI,MAAA,CAAO,MAAA,CAAO,IAAA,EAAK;AAC9B,EAAA,MAAA,CAAO,MAAA,CAAO,IAAI,KAAA,KAAU,MAAY,OAAO,GAAA,CAAI,MAAA,CAAO,OAAM,CAAA,GAAI;AACtE,CAAA;AAEA,IAAM,IAAA,GAAO,CAAC,KAAA,KAA4B,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AAExF,IAAM,OAAA,GAAU,CAAC,OAAA,MAAqC;AAAA,EAC3D,IAAA,EAAM,UAAA;AAAA,EACN,KAAA,EAAO,OAAA;AAAA,EACP,e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AAA,UAChC,QAAQ,GAAA,CAAI,MAAA;AAAA,UACZ,QAAA;AAAA,UACA,SAAS,EAAE,IAAA,EAAM,IAAA,KAAS,aAAA,GAAgB,MAAM,IAAA,EAAM,MAAA,EAAQ,GAAA,CAAI,OAAA,CAAQ,UAAU,IAAA,EAAM,IAAA,EAAM,GAAA,CAAI,OAAA,CAAQ,QAAQ,IAAA,EAAK;AAAA,UACzH,MAAM,GAAA,CAAI,IAAA;AAAA,UACV,GAAI,IAAI,cAAA,KAAmB,MAAA,GAAY,EAAE,cAAA,EAAgB,GAAA,CAAI,cAAA,EAAe,GAAI,EAAC;AAAA,UACjF,GAAI,IAAI,IAAA,KAAS,MAAA,GAAY,EAAE,IAAA,EAAM,GAAA,CAAI,IAAA,EAAK,GAAI,EAAC;AAAA,UACnD,GAAI,IAAI,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,EAAU,GAAA,CAAI,QAAA,EAAS,GAAI;AAAC,SAChE,CAAA;AACD,QAAA,GAAA,CAAI,UAAA,GAAa,GAAA;AACjB,QAAA,GAAA,CAAI,SAAA,CAAU,gBAAgB,0BAA0B,CAAA;AACxD,QAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,CAAA,IAAK,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,OAAO,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,IAAA,EAAM,KAAK,CAAA;AACnF,QAAA,GAAA,CAAI,GAAA,CAAI,KAAK,IAAI,CAAA;AAAA,MACnB,CAAC,CAAA,CAEA,KAAA,CAAM,MAAM,MAAM,CAAA;AAAA,IACvB,CAAC,CAAA;AAAA,EACH;AACF,CAAA","file":"vite.js","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport type { Plugin, ViteDevServer } from 'vite';\nimport { getRequestListener } from '@hono/node-server';\nimport { renderDocument } from './document';\nimport type { DocumentConfig } from './document';\nimport { attachSocket, MOSS_PATHS } from './node';\nimport { sessionCookies } from './session-cookie';\nimport type { MossServer } from './server';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/moss/vite — the app server inside vite's dev process.\n//\n// One `nisc dev`, no proxy, no second terminal: the app boots in vite's own\n// process, through vite's own module loading (`ssrLoadModule`), so the boot it\n// runs is the source on disk and an edit is a fresh boot. What it does, in the\n// order a request meets it:\n//\n// the socket attached ONCE, delegating to whichever server is current —\n// a re-boot swaps what it delegates to, never the handler\n// /dev/as/:who a signed-in URL, when the app can mint a dev token\n// a page `/`, or a path one of the manifest's pages answers: index.html\n// through vite first (its client, the framework's refresh\n// preamble), then the screen drawn into it (`renderDocument`)\n// moss's paths /api, /catalog, /operator, /integrations — the app server's\n// the rest vite's: source files, assets, its own urls\n//\n// A change under one of the watched directories re-boots the whole app — a\n// fresh database, fresh seed, fresh shells — then reloads the page so the\n// browser reconnects to the new server. The outgoing server keeps answering\n// until the new one is up, so a broken edit does not take the dev server down,\n// and is then let go, timers included.\n// ═══════════════════════════════════════════════════════════════\n\nexport type DevApp = {\n server: MossServer;\n // how to let it go (default: `server.close()`)\n close?: () => void | Promise<void>;\n // How one of its screens is drawn. Absent: pages go out as vite's index.html,\n // undrawn, and the terminal paints them as it always did.\n draw?: DocumentConfig['draw'];\n htmlAttributes?: DocumentConfig['htmlAttributes'];\n site?: DocumentConfig['site'];\n tokenKey?: string;\n // A dev-only signed-in URL: `/dev/as/<who>` puts the token this returns in\n // the browser's own session cookie (session-cookie.ts) — as a sign-in the\n // app answers over HTTP would — and goes to `/`. `null` is nobody of that\n // name. It lives in vite's middleware and nowhere else, so it cannot ship.\n signIn?: (who: string) => string | null | Promise<string | null>;\n};\n\nexport type MossDevOptions = {\n // Stand the app up. `load` is vite's own module loader: what it loads is the\n // source as it is on disk now, with the app's aliases resolved.\n app: (load: (id: string) => Promise<Record<string, unknown>>) => Promise<DevApp>;\n // Which edits re-boot the app (default: anything under src/app, src/server,\n // src/db or src/ui — the kit is in it because the SERVER holds the component\n // registry too — and the nisc config).\n watch?: RegExp;\n // The page template, relative to vite's root (default `index.html`).\n index?: string;\n // The paths the app server answers (default: moss's own).\n owned?: RegExp;\n // The name in vite's log (default `moss`).\n label?: string;\n};\n\nconst DEFAULT_WATCH = /([\\\\/]src[\\\\/](app|server|db|ui)[\\\\/])|([\\\\/]nisc\\.config\\.[cm]?[jt]s$)/;\nconst REBOOT_DEBOUNCE_MS = 200;\n\ntype Booted = { app: DevApp; listener: ReturnType<typeof getRequestListener> };\n\nconst retire = async (booted: Booted): Promise<void> => {\n booted.app.server.socket.stop();\n await (booted.app.close ?? ((): void => booted.app.server.close()))();\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\nexport const mossDev = (options: MossDevOptions): Plugin => ({\n name: 'moss-dev',\n apply: 'serve',\n configureServer: (vite: ViteDevServer) => {\n const label = options.label ?? 'moss';\n const watch = options.watch ?? DEFAULT_WATCH;\n const owned = options.owned ?? MOSS_PATHS;\n const load = (id: string): Promise<Record<string, unknown>> => vite.ssrLoadModule(id);\n\n const boot = async (): Promise<Booted> => {\n const app = await options.app(load);\n return { app, listener: getRequestListener(app.server.fetch) };\n };\n let current = boot();\n current.catch((error: unknown) => vite.config.logger.error(`[${label}] the app did not boot: ${said(error)}`, { timestamp: true }));\n\n if (vite.httpServer !== null) {\n attachSocket(\n vite.httpServer,\n Object.assign(async (url: string, connection: Parameters<MossServer['socket']>[1]) => (await current).app.server.socket(url, connection), {\n // whichever server is current owns the revalidation timer; this handler owns none\n stop: (): void => void current.then(({ app }) => app.server.socket.stop(), () => undefined),\n }),\n );\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const reboot = (file: string): void => {\n if (!watch.test(file)) return;\n clearTimeout(timer);\n timer = setTimeout(() => {\n const outgoing = current;\n current = boot();\n current.then(\n () => {\n void outgoing.then(retire, () => undefined);\n vite.config.logger.info(`[${label}] app server re-booted`, { timestamp: true });\n vite.ws.send({ type: 'full-reload' });\n },\n (error: unknown) => {\n // the old server goes on answering until an edit boots\n current = outgoing;\n vite.config.logger.error(`[${label}] re-boot failed: ${said(error)}`, { timestamp: true });\n },\n );\n }, REBOOT_DEBOUNCE_MS);\n };\n vite.watcher.on('change', reboot);\n vite.watcher.on('add', reboot);\n vite.watcher.on('unlink', reboot);\n vite.httpServer?.once('close', () => void current.then(retire, () => undefined));\n\n vite.middlewares.use((req, res, next) => {\n const url = req.url ?? '/';\n const path = url.split('?')[0] ?? '/';\n\n const who = /^\\/dev\\/as\\/([\\w.@%-]+)$/.exec(path)?.[1];\n if (who !== undefined) {\n void current\n .then(async ({ app }) => {\n if (app.signIn === undefined) {\n next();\n return;\n }\n const token = await app.signIn(decodeURIComponent(who));\n if (token === null) {\n res.setHeader('content-type', 'text/html; charset=utf-8');\n res.end(`<p>nobody called ${who.replace(/[<&\"]/g, '')}</p>`);\n return;\n }\n const scheme = (req.socket as { encrypted?: boolean }).encrypted === true ? 'https' : 'http';\n res.statusCode = 302;\n res.setHeader('set-cookie', sessionCookies(`${scheme}://${req.headers.host ?? 'localhost'}`, token, app.tokenKey !== undefined ? { key: app.tokenKey } : {}));\n res.setHeader('location', '/');\n res.end();\n })\n .catch(() => {\n res.statusCode = 500;\n res.end('the dev sign-in failed');\n });\n return;\n }\n\n if (owned.test(path)) {\n void current.then(({ listener }) => listener(req, res)).catch(() => {\n res.statusCode = 503;\n res.end('the app server did not boot — see the dev server’s log');\n });\n return;\n }\n\n if (req.method !== 'GET') {\n next();\n return;\n }\n void current\n .then(async ({ app }) => {\n if (app.draw === undefined || (path !== '/' && path !== '/index.html' && app.server.page(path) === undefined)) {\n next();\n return;\n }\n const template = await vite.transformIndexHtml(url, await readFile(resolve(vite.config.root, options.index ?? 'index.html'), 'utf8'));\n const page = await renderDocument({\n server: app.server,\n template,\n request: { path: path === '/index.html' ? '/' : path, cookie: req.headers.cookie ?? null, host: req.headers.host ?? null },\n draw: app.draw,\n ...(app.htmlAttributes !== undefined ? { htmlAttributes: app.htmlAttributes } : {}),\n ...(app.site !== undefined ? { site: app.site } : {}),\n ...(app.tokenKey !== undefined ? { tokenKey: app.tokenKey } : {}),\n });\n res.statusCode = 200;\n res.setHeader('content-type', 'text/html; charset=utf-8');\n for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);\n res.end(page.html);\n })\n // not drawn is not broken: vite serves index.html as it always did\n .catch(() => next());\n });\n },\n});\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niscorp/moss",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "moss — the nisc app server: serves existence (catalog, scoped vex, the socket), derived from artifacts",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -172,12 +172,12 @@
|
|
|
172
172
|
"zod": "^4.2.0",
|
|
173
173
|
"vue": "^3.5.0",
|
|
174
174
|
"vite": ">=6",
|
|
175
|
-
"@niscorp/
|
|
176
|
-
"@niscorp/
|
|
177
|
-
"@niscorp/
|
|
178
|
-
"@niscorp/
|
|
179
|
-
"@niscorp/vex": "^0.
|
|
180
|
-
"@niscorp/
|
|
175
|
+
"@niscorp/nova": "^0.3.0",
|
|
176
|
+
"@niscorp/prism": "^0.3.0",
|
|
177
|
+
"@niscorp/strata": "^0.1.5",
|
|
178
|
+
"@niscorp/tide": "^0.1.5",
|
|
179
|
+
"@niscorp/vex": "^0.3.0",
|
|
180
|
+
"@niscorp/charter": "^0.1.2"
|
|
181
181
|
},
|
|
182
182
|
"peerDependenciesMeta": {
|
|
183
183
|
"vite": {
|
|
@@ -213,11 +213,11 @@
|
|
|
213
213
|
"vue": "^3.5.43",
|
|
214
214
|
"zod": "^4.6.5",
|
|
215
215
|
"@niscorp/charter": "^0.1.2",
|
|
216
|
-
"@niscorp/nova": "^0.
|
|
217
|
-
"@niscorp/
|
|
218
|
-
"@niscorp/
|
|
219
|
-
"@niscorp/
|
|
220
|
-
"@niscorp/vex": "^0.
|
|
216
|
+
"@niscorp/nova": "^0.3.0",
|
|
217
|
+
"@niscorp/prism": "^0.3.0",
|
|
218
|
+
"@niscorp/strata": "^0.1.5",
|
|
219
|
+
"@niscorp/tide": "^0.1.5",
|
|
220
|
+
"@niscorp/vex": "^0.3.0"
|
|
221
221
|
},
|
|
222
222
|
"scripts": {
|
|
223
223
|
"build": "node -e \"fs.rmSync('dist',{recursive:true,force:true})\" && tsup",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/index.ts"],"names":[],"mappings":";;;AAoFO,IAAM,mBAAA,GAAsB;AAK5B,IAAM,oBAAA,GAAuB,CAAC,GAAA,GAAwC,QAAA,KAA2C;AACtH,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,GAAA,CAAI,cAAA,CAAe,mBAAmB,CAAA,EAAG,WAAA;AACtD,IAAA,IAAI,SAAS,KAAA,CAAA,IAAa,IAAA,KAAS,IAAA,IAAQ,IAAA,KAAS,IAAI,OAAO,KAAA,CAAA;AAC/D,IAAA,MAAM,MAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AACvC,IAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,OAAO,MAAA,KAAW,UAAU,OAAO,KAAA,CAAA;AAC1D,IAAA,MAAM,EAAE,KAAA,EAAO,KAAA,EAAO,MAAM,SAAA,EAAW,IAAA,EAAM,MAAK,GAAI,MAAA;AACtD,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,IAAK,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,SAAA,KAAc,WAAW,OAAO,KAAA,CAAA;AACnH,IAAA,OAAO;AAAA,MACL,KAAA;AAAA,MACA,KAAA;AAAA,MACA,SAAA;AAAA,MACA,GAAI,OAAO,IAAA,KAAS,WAAW,EAAE,IAAA,KAAS,EAAC;AAAA,MAC3C,GAAI,OAAO,IAAA,KAAS,WAAW,EAAE,IAAA,KAAS,EAA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AO,MAAM;AACX,MAAA,IAAI,QAAA,EAAU;AAId,MAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,MAAA,KAAW,MAAA,EAAQ;AACxC,QAAA,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,EAAS,CAAA;AACtB,QAAA;AAAA,MACF;AAIA,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,QAAA,GAAW,CAAA;AACX,MAAA,OAAA,EAAQ;AAAA,IACV,CAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,GAAS,QAAA;AACT,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,MAAA,EAAQ,KAAA,EAAM;AAAA,IAChB;AAAA,GACF;AACF","file":"chunk-J72N3EMJ.js","sourcesContent":["import type { NovaEvent, RenderNode } from '@niscorp/nova';\nimport { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, PROTOCOL, PROTOCOL_MIN } from '../socket';\nimport { applyDelta, frameHash } from '../delta';\nimport type { DeltaOp } from '../delta';\n\n// ═══════════════════════════════════════════════════════════════\n// The wire — moss's protocol client, the other end of ../socket. Plain\n// code: a token slot, a websocket with reconnect, and session lifecycle —\n// a `session` message (login redeemed server-side) stores the token and\n// reconnects authenticated; a 4403 close clears it and reconnects\n// anonymous (the lock screen is the anonymous principal's application,\n// served like everything else). Rendering the snapshot is the app's\n// (framework's) business; nothing framework-shaped lives here.\n//\n// The wire never reaches for globals: everything host-shaped — where the\n// token lives, how a socket is constructed, what url \"here\" means — comes\n// in as a `WireEnv`. `browserEnv` (the default) is localStorage + location;\n// `./node` ships `nodeEnv` (a token file, an explicit url). The socket API\n// itself is WHATWG-standard in every host (browser, Node ≥22, Bun), so an\n// env only constructs it.\n// ═══════════════════════════════════════════════════════════════\n\n// Where the session token lives between connects.\nexport type WireTokenStore = {\n load: () => string | null;\n save: (token: string) => void;\n clear: () => void;\n};\n\n// The host seam: what the wire would otherwise take from globals.\nexport type WireEnv = {\n tokens: WireTokenStore;\n // construct a socket for this url — `new WebSocket(url)` in every host\n socket: (url: string) => WebSocket;\n // the socket url when `config.url` is absent\n defaultUrl: () => string;\n};\n\nexport type WireConfig = {\n // The socket url; default: `env.defaultUrl()`.\n url?: string;\n // The host environment; default: `browserEnv()`.\n env?: WireEnv;\n // Accept canvas frames as DELTAS against the last frame received (default:\n // off). Both ends have to want it: this tells the server the terminal can\n // rebuild them, and the server sends them only if `runtime.shellFrameDelta`\n // is on and the delta is decisively smaller. Nothing else about the terminal\n // changes — the snapshot it renders is identical either way. See DOCS.md\n // § Frame deltas.\n delta?: boolean;\n // The screen the page already shows — the snapshot a server-rendered\n // document carries (`readDocumentSnapshot`). The wire starts from it instead\n // of from nothing, so the first render matches the HTML and the first frames\n // off the socket confirm it rather than paint it. Absent, or made for\n // somebody else (see `DocumentSnapshot.principal`): the wire starts empty, as\n // it always has.\n initial?: DocumentSnapshot;\n // The path this terminal is on, named on the socket so the server can tell a\n // page's terminal from the app's (a page is served a shell of its own, for\n // this connection alone). Default: the path the page's snapshot was drawn\n // for; a page that was not drawn on the server passes `location.pathname`.\n path?: string;\n};\n\n// What a server-rendered document carries beside its HTML.\nexport type DocumentSnapshot = {\n frame: RenderNode[];\n trees: Record<string, RenderNode[]>;\n // The id seed an anonymous page's shell was built under; named on the first\n // connect so the socket's shell mints the same instance ids.\n seed?: string;\n // Whether the page was rendered for a signed-in principal. A page rendered\n // for nobody is not this terminal's screen if it holds a token, and the other\n // way round — the wire then starts empty rather than from the wrong screen.\n principal: boolean;\n // The path it was drawn for.\n path?: string;\n // False when nothing on the drawn screen can still happen: the trees are the\n // whole of it, and the wire opens no socket at all (status `static`). Absent\n // is live — a page that does not say is not concluded finished.\n live?: boolean;\n};\n\n// The id of the element a document carries its snapshot in.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\n// Read the snapshot out of the page, if it has one. Never throws: a page\n// without one, or with one that does not parse, is a page that was not\n// server-rendered, and the terminal starts the way it always has.\nexport const readDocumentSnapshot = (doc: Pick<Document, 'getElementById'> = document): DocumentSnapshot | undefined => {\n try {\n const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;\n if (text === undefined || text === null || text === '') return undefined;\n const parsed: unknown = JSON.parse(text);\n if (parsed === null || typeof parsed !== 'object') return undefined;\n const { frame, trees, seed, principal, path, live } = parsed as Record<string, unknown>;\n if (!Array.isArray(frame) || trees === null || typeof trees !== 'object' || typeof principal !== 'boolean') return undefined;\n return {\n frame: frame as RenderNode[],\n trees: trees as Record<string, RenderNode[]>,\n principal,\n ...(typeof seed === 'string' ? { seed } : {}),\n ...(typeof path === 'string' ? { path } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n } catch {\n return undefined;\n }\n};\n\nexport type WireSnapshot = {\n // the frame: the canvas ARRANGEMENT — a served layout whose CanvasSlot\n // markers resolve against `trees`\n frame: RenderNode[];\n // the current tree per canvas id\n trees: ReadonlyMap<string, RenderNode[]>;\n};\n\n// The socket's health, as a renderer needs it: `connecting` (a connect is in\n// flight or scheduled), `open`, `closed` (lost; a retry will flip it back to\n// connecting). Status changes notify subscribers like snapshot changes do —\n// a terminal that renders nothing on a dead socket is indistinguishable from\n// a working terminal rendering an empty app, so the state must be readable.\n// `incompatible`: this terminal and the server speak protocols the other\n// cannot (see PROTOCOL in ../socket). Terminal state — the wire stops retrying,\n// because every retry would speak the same protocol again.\n// `static`: the page was drawn on the server and nothing on it can still\n// happen, so no socket was opened. Not a fault and not a wait — `reset` (or a\n// token arriving) connects after all.\nexport type WireStatus = 'connecting' | 'open' | 'closed' | 'incompatible' | 'static';\n\nexport type Wire = {\n subscribe: (listener: () => void) => () => void;\n snapshot: () => WireSnapshot;\n status: () => WireStatus;\n // an event from inside a canvas, tagged with the canvas it came from\n dispatch: (canvasId: string, event: NovaEvent) => void;\n publish: (channel: string, payload?: unknown) => void;\n // Ask the server to throw this session's shell away and serve a fresh one —\n // the escape from a wedged shell, and the only one that can work. The shell\n // is SERVER state keyed by principal: dropping the token here would just\n // hand us a throwaway anonymous shell, and signing back in would reattach\n // to the same wreck. On a dead socket this reconnects instead, which is the\n // same recovery one layer down.\n reset: () => void;\n // Undo the shell's last navigation. Fire-and-forget by design: what comes\n // back is whatever canvases moved, over the same stream every other change\n // arrives on — the terminal never holds a location to keep in step.\n back: () => void;\n // Jump to an ancestor already on a canvas's stack — one message the shell\n // executes atomically, rather than N back gestures racing each other.\n popTo: (canvas: string, instance: string) => void;\n dispose: () => void;\n};\n\ntype ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n | { type: 'resync' }\n | { type: 'reset' }\n | { type: 'back' }\n | { type: 'popTo'; canvas: string; instance: string };\n\nconst EMPTY: WireSnapshot = { frame: [], trees: new Map() };\n\n// The browser host: token in localStorage, url derived from location, the\n// page's WebSocket. The try/catches keep a storage-less context (private\n// mode, sandboxed iframe) alive — the session just lives for this page only.\n//\n// `cookie: true` keeps a COPY of the token in a cookie of the same name, written\n// and cleared with the stored one. A page request carries cookies and nothing\n// else, so this is what lets a server render the document for whoever is asking.\n// The cookie is only ever read to render a page: every other surface still wants\n// the token itself (the socket's URL, a Bearer header), so it adds no way in.\nexport const browserEnv = (config: { tokenKey?: string; cookie?: boolean } = {}): WireEnv => {\n const tokenKey = config.tokenKey ?? 'nisc.token';\n const mirror = (token: string | null): void => {\n if (config.cookie !== true) return;\n try {\n const secure = window.location.protocol === 'https:' ? '; Secure' : '';\n document.cookie =\n token === null\n ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}`\n : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;\n } catch {\n /* no document, or cookies refused — the page is simply rendered for nobody */\n }\n };\n return {\n tokens: {\n load: () => {\n try {\n const token = window.localStorage.getItem(tokenKey);\n // Level the copy with the stored one — a token put there by something\n // other than this wire (a sign-in handoff page) reaches the cookie on\n // the first load after it, and a token that is gone takes its copy along.\n mirror(token);\n return token;\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n window.localStorage.setItem(tokenKey, token);\n } catch {\n /* storage unavailable — the session lives for this page only */\n }\n mirror(token);\n },\n clear: () => {\n try {\n window.localStorage.removeItem(tokenKey);\n } catch {\n /* nothing stored, nothing to clear */\n }\n mirror(null);\n },\n },\n socket: (url) => new WebSocket(url),\n defaultUrl: () => {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}/socket`;\n },\n };\n};\n\nexport const createWire = (config: WireConfig = {}): Wire => {\n const env = config.env ?? browserEnv();\n\n let token = env.tokens.load();\n // The page's own snapshot, when it was rendered for who this terminal is —\n // signed in and holding a token, or neither. Anything else is somebody else's\n // screen and is not started from.\n const initial = config.initial !== undefined && config.initial.principal === (token !== null) ? config.initial : undefined;\n let snapshot: WireSnapshot = initial === undefined ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };\n // Named on the FIRST connect only: it belongs to the page's own shell, and a\n // later connect (a retry, another principal) is not that shell.\n let seed = initial?.seed;\n const path = config.path ?? config.initial?.path;\n let status: WireStatus = 'connecting';\n // Set by a protocol mismatch in either direction; ends the reconnect loop.\n let incompatible = false;\n let socket: WebSocket | null = null;\n let retry: ReturnType<typeof setTimeout> | undefined;\n // Consecutive failed connects — resets to 0 the moment one opens. Drives the\n // reconnect backoff so a dead server is polled ever more slowly, not every\n // second forever.\n let attempts = 0;\n let disposed = false;\n const listeners = new Set<() => void>();\n const publishSnapshot = (next: WireSnapshot): void => {\n snapshot = next;\n for (const listener of listeners) listener();\n };\n const setStatus = (next: WireStatus): void => {\n if (status === next) return;\n status = next;\n for (const listener of listeners) listener();\n };\n\n const url = (): string => config.url ?? env.defaultUrl();\n\n // Only on an OPEN socket, and never queued — the posture `back` and `popTo`\n // always had, now everybody's. A page rendered server-side is on screen\n // before the socket is, so there is a moment in which something can be\n // pressed with nothing to send it over: that press is dropped, not held. An\n // intention replayed against a screen that may have moved is worse than one\n // lost, and a browser socket that is still connecting throws on `send`.\n const send = (message: ClientMessage): void => {\n if (socket === null || status !== 'open') return;\n socket.send(JSON.stringify(message));\n };\n\n // The last `render` message TEXT per canvas — the base a delta is written\n // against, byte for byte as the server holds it. Only populated when deltas\n // are on; cleared on every connect, because attaching serves whole frames and\n // a base carried across a reconnect is a base the server never assumed.\n const bases = new Map<string, string>();\n\n const connect = (): void => {\n if (disposed) return;\n setStatus('connecting');\n bases.clear();\n const params: string[] = [];\n if (token !== null) params.push(`token=${encodeURIComponent(token)}`);\n params.push(`protocol=${PROTOCOL}`);\n if (config.delta === true) params.push('delta=1');\n if (seed !== undefined) params.push(`seed=${encodeURIComponent(seed)}`);\n seed = undefined;\n if (path !== undefined) params.push(`path=${encodeURIComponent(path)}`);\n const ws = env.socket(`${url()}${params.length > 0 ? `?${params.join('&')}` : ''}`);\n socket = ws;\n // A connection that opens is a healthy connection: forget the backoff.\n ws.onopen = () => {\n attempts = 0;\n setStatus('open');\n };\n ws.onmessage = (e) => {\n const text = String(e.data);\n const data = JSON.parse(text) as {\n type: string;\n canvas?: string;\n tree?: RenderNode[];\n ops?: DeltaOp[];\n hash?: number;\n protocol?: number;\n token?: string;\n code?: string;\n message?: string;\n };\n if (data.type === 'render' && data.canvas !== undefined && data.tree !== undefined) {\n if (config.delta === true) bases.set(data.canvas, text);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });\n } else if (data.type === 'render-delta' && data.canvas !== undefined && data.ops !== undefined && data.hash !== undefined) {\n // Rebuild, then PROVE it. Anything short of the server's own checksum\n // and we would be rendering a frame nobody authored — so every failure\n // here takes the one exit that always works: ask for whole frames.\n // Never a thrown error and never a partial apply; a terminal that goes\n // blank on a bad delta is worse than one that costs a round trip.\n const base = bases.get(data.canvas);\n let rebuilt: string | null = null;\n if (base !== undefined) {\n try {\n const candidate = applyDelta(base, data.ops);\n rebuilt = frameHash(candidate) === data.hash ? candidate : null;\n } catch {\n rebuilt = null;\n }\n }\n if (rebuilt === null) {\n console.warn(`[moss/wire] canvas \"${data.canvas}\": delta did not rebuild the server's frame — resyncing.`);\n bases.delete(data.canvas);\n send({ type: 'resync' });\n return;\n }\n const frame = JSON.parse(rebuilt) as { canvas: string; tree: RenderNode[] };\n bases.set(data.canvas, rebuilt);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });\n } else if (data.type === 'frame' && data.tree !== undefined) {\n publishSnapshot({ ...snapshot, frame: data.tree });\n } else if (data.type === 'session' && typeof data.token === 'string') {\n // Login redeemed server-side: become that principal.\n become(data.token);\n } else if (data.type === 'error') {\n // Diagnostics, not authority — surfaced, never swallowed: a wire that\n // silently stops updating is the worst thing to debug. `invalid_token`\n // arrives here too, from the server's revalidation pass, and it is\n // worth the line: the AUTHORITY is the 4401 close that follows (see\n // onclose), and this is the breadcrumb saying the session expired\n // rather than the network dropping.\n console.warn(`[moss/wire] server error${data.code !== undefined ? ` (${data.code})` : ''}: ${data.message ?? ''}`);\n } else if (data.type === 'hello' && (data.protocol ?? 1) < PROTOCOL_MIN) {\n // The other half of the handshake: the server checked this terminal on\n // the upgrade; this checks the server. One that predates the question\n // sends no `protocol` and speaks 1.\n console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}–${PROTOCOL}. The server has not been updated yet.`);\n incompatible = true;\n ws.close();\n } else if (data.type !== 'hello' && data.type !== 'catalog') {\n // hello/catalog are known and deliberately ignored (the terminal is\n // grant-blind — it renders what it is served, never what it may do);\n // anything else is protocol drift worth a shout.\n console.warn(`[moss/wire] unhandled server message: ${data.type}`);\n }\n };\n // The socket is ephemeral, the shell is durable: reconnect re-sends\n // current state. Two application close codes are recoveries, not retries —\n // SIGNED_OUT (a deliberate revoke) and INVALID_TOKEN (the stored token went\n // stale; retrying WITH it would loop forever) both drop the token and\n // reconnect anonymous (the served lock screen). Every other close backs off\n // and retries carrying the current token.\n ws.onclose = (e) => {\n if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {\n incompatible = true;\n setStatus('incompatible');\n return;\n }\n setStatus('closed');\n if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {\n become(null);\n return;\n }\n if (!disposed) scheduleReconnect();\n };\n };\n\n // Exponential backoff with jitter, capped: a dead server is polled ever more\n // slowly (never faster than ~½s, never slower than the cap), and the jitter\n // spreads a thundering herd of terminals reconnecting on the same outage.\n const RECONNECT_CAP_MS = 30_000;\n const scheduleReconnect = (): void => {\n const ceiling = Math.min(RECONNECT_CAP_MS, 1000 * 2 ** attempts);\n attempts += 1;\n const delay = ceiling / 2 + Math.random() * (ceiling / 2);\n retry = setTimeout(connect, delay);\n };\n\n // A different principal — possibly none — is a different application:\n // store the token, blank the screen, reconnect.\n const become = (next: string | null): void => {\n if (next === null) env.tokens.clear();\n else env.tokens.save(next);\n token = next;\n clearTimeout(retry);\n attempts = 0; // a new principal is a fresh session — start backoff clean\n publishSnapshot(EMPTY);\n const old = socket;\n socket = null;\n if (old !== null) {\n old.onclose = null;\n old.close();\n }\n connect();\n };\n\n // A drawn page with nothing left to happen needs no socket. Everything that\n // would later need one — `reset`, a token arriving — connects by itself.\n if (initial?.live === false) status = 'static';\n else connect();\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n snapshot: () => snapshot,\n status: () => status,\n dispatch: (canvasId, event) => send({ type: 'event', canvas: canvasId, event: event as unknown as Record<string, unknown> }),\n publish: (channel, payload) => send(payload === undefined ? { type: 'publish', channel } : { type: 'publish', channel, payload }),\n // Only on an open socket, and deliberately not queued: a back pressed while\n // the connection is down is a gesture about a screen the person is no\n // longer being served, and replaying it on reconnect would move them\n // somewhere they asked to go some seconds and one outage ago.\n back: () => {\n if (socket === null || status !== 'open') return;\n send({ type: 'back' });\n },\n // Same posture as `back`: only on an open socket, never queued. A jump\n // replayed on reconnect would move somebody to where they wanted to be\n // one outage ago.\n popTo: (canvas: string, instance: string) => {\n if (socket === null || status !== 'open') return;\n send({ type: 'popTo', canvas, instance });\n },\n reset: () => {\n if (disposed) return;\n // Open: ask the server, and the fresh frame arrives on this same socket.\n // Asked of our OWN status rather than `readyState`, because the socket\n // is whatever the host env constructed and the status is ours.\n if (socket !== null && status === 'open') {\n send({ type: 'reset' });\n return;\n }\n // Not open: the backoff may have us waiting half a minute for a retry,\n // and somebody pressing reset is telling us they are waiting NOW. Jump\n // the queue — reattaching re-sends the current trees anyway.\n clearTimeout(retry);\n attempts = 0;\n connect();\n },\n dispose: () => {\n disposed = true;\n status = 'closed'; // sync truth for late readers; no notification after dispose\n clearTimeout(retry);\n socket?.close();\n },\n };\n};\n"]}
|
package/dist/chunk-SUVDISEG.js
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { renderDocument, createServer } from './chunk-ZP3C53AC.js';
|
|
2
|
-
import { readFile } from 'fs/promises';
|
|
3
|
-
import { relative, extname, join } from 'path';
|
|
4
|
-
import { serve as serve$1 } from '@hono/node-server';
|
|
5
|
-
import { serveStatic } from '@hono/node-server/serve-static';
|
|
6
|
-
import { WebSocketServer } from 'ws';
|
|
7
|
-
|
|
8
|
-
var attachSocket = (httpServer, accept, path = "/socket", options) => {
|
|
9
|
-
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: options?.compression ?? true });
|
|
10
|
-
httpServer.on("upgrade", (req, socket, head) => {
|
|
11
|
-
const url = req.url ?? "/";
|
|
12
|
-
if (new URL(url, "http://nisc.local").pathname !== path) return;
|
|
13
|
-
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
14
|
-
accept(url, {
|
|
15
|
-
send: (text) => ws.send(text),
|
|
16
|
-
close: (code, reason) => ws.close(code, reason),
|
|
17
|
-
onMessage: (fn) => ws.on("message", (data) => fn(String(data))),
|
|
18
|
-
onClose: (fn) => ws.on("close", () => fn())
|
|
19
|
-
}).catch((error) => {
|
|
20
|
-
console.error("[moss/node] a connection escaped accept:", error);
|
|
21
|
-
try {
|
|
22
|
-
ws.close(1011, "accept failed");
|
|
23
|
-
} catch {
|
|
24
|
-
}
|
|
25
|
-
});
|
|
26
|
-
});
|
|
27
|
-
});
|
|
28
|
-
};
|
|
29
|
-
var MOSS_PATHS = /^\/(api|catalog|socket|operator|integrations)(\/|$)/;
|
|
30
|
-
var mountSite = (server, config) => {
|
|
31
|
-
const { dist, owned = MOSS_PATHS, ...drawing } = config;
|
|
32
|
-
const root = relative(process.cwd(), dist) || ".";
|
|
33
|
-
const files = serveStatic({ root });
|
|
34
|
-
server.use("/*", async (c, next) => {
|
|
35
|
-
const path = c.req.path;
|
|
36
|
-
if (owned.test(path) || path === "/" || path === "/index.html" || server.page(path) !== void 0) return next();
|
|
37
|
-
return files(c, next);
|
|
38
|
-
});
|
|
39
|
-
server.get("*", async (c) => {
|
|
40
|
-
if (owned.test(c.req.path)) return c.notFound();
|
|
41
|
-
if (extname(c.req.path) !== "" && c.req.path !== "/index.html" && server.page(c.req.path) === void 0) return c.notFound();
|
|
42
|
-
const template = await readFile(join(dist, "index.html"), "utf8");
|
|
43
|
-
const page = await renderDocument({
|
|
44
|
-
...drawing,
|
|
45
|
-
server,
|
|
46
|
-
template,
|
|
47
|
-
request: { path: c.req.path === "/index.html" ? "/" : c.req.path, cookie: c.req.header("cookie") ?? null }
|
|
48
|
-
});
|
|
49
|
-
return c.html(page.html, 200, page.headers);
|
|
50
|
-
});
|
|
51
|
-
};
|
|
52
|
-
var serve = async (app, runtime) => {
|
|
53
|
-
const server = await createServer(app, runtime);
|
|
54
|
-
const port = runtime.port ?? 8787;
|
|
55
|
-
const httpServer = serve$1({ fetch: server.fetch, port });
|
|
56
|
-
attachSocket(httpServer, server.socket, "/socket", { ...runtime.socketCompression !== void 0 ? { compression: runtime.socketCompression } : {} });
|
|
57
|
-
console.log(`moss serving http://localhost:${port}`);
|
|
58
|
-
console.log(`surfaces: GET /catalog \xB7 GET|POST /api/vex \xB7 GET|POST /api/<resource>/vex \xB7 ws://localhost:${port}/socket`);
|
|
59
|
-
return server;
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
export { MOSS_PATHS, attachSocket, mountSite, serve };
|
|
63
|
-
//# sourceMappingURL=chunk-SUVDISEG.js.map
|
|
64
|
-
//# sourceMappingURL=chunk-SUVDISEG.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/node.ts"],"names":["listen"],"mappings":";;;;;;;AAgCO,IAAM,eAAe,CAC1B,UAAA,EACA,MAAA,EACA,IAAA,GAAO,WACP,OAAA,KACS;AACT,EAAA,MAAM,GAAA,GAAM,IAAI,eAAA,CAAgB,EAAE,QAAA,EAAU,MAAM,iBAAA,EAAmB,OAAA,EAAS,WAAA,IAAe,IAAA,EAAM,CAAA;AACnG,EAAA,UAAA,CAAW,EAAA,CAAG,SAAA,EAAW,CAAC,GAAA,EAAK,QAAQ,IAAA,KAAS;AAC9C,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,IAAO,GAAA;AAGvB,IAAA,IAAI,IAAI,GAAA,CAAI,GAAA,EAAK,mBAAmB,CAAA,CAAE,aAAa,IAAA,EAAM;AACzD,IAAA,GAAA,CAAI,aAAA,CAAc,GAAA,EAAK,MAAA,EAAQ,IAAA,EAAM,CAAC,EAAA,KAAO;AAK3C,MAAA,MAAA,CAAO,GAAA,EAAK;AAAA,QACV,IAAA,EAAM,CAAC,IAAA,KAAS,EAAA,CAAG,KAAK,IAAI,CAAA;AAAA,QAC5B,OAAO,CAAC,IAAA,EAAM,WAAW,EAAA,CAAG,KAAA,CAAM,MAAM,MAAM,CAAA;AAAA,QAC9C,SAAA,EAAW,CAAC,EAAA,KAAO,EAAA,CAAG,EAAA,CAAG,SAAA,EAAW,CAAC,IAAA,KAAS,EAAA,CAAG,MAAA,CAAO,IAAI,CAAC,CAAC,CAAA;AAAA,QAC9D,OAAA,EAAS,CAAC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C,IAAI,CAAA,CAAE,CAAA;AACnD,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,oGAAA,EAA8F,IAAI,CAAA,OAAA,CAAS,CAAA;AACvH,EAAA,OAAO,MAAA;AACT","file":"chunk-SUVDISEG.js","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { extname, join, relative } from 'node:path';\nimport { serve as listen } from '@hono/node-server';\nimport { serveStatic } from '@hono/node-server/serve-static';\nimport { WebSocketServer } from 'ws';\nimport type { IncomingMessage } from 'node:http';\nimport type { Duplex } from 'node:stream';\nimport { createServer } from './server';\nimport type { MossServer } from './server';\nimport type { NiscApp } from './app';\nimport type { NiscRuntime } from './runtime';\nimport type { SocketAccept } from './socket';\nimport { renderDocument } from './document';\nimport type { DocumentConfig } from './document';\n\n// ═══════════════════════════════════════════════════════════════\n// The Node entry — runtime-specific by design: the transport is a seam, so\n// the Bun flip swaps this file, never the app. Two exports: the\n// websocket transport for hosts that run their own listener (the dev\n// checks, vite), and the batteries-included `serve`.\n// ═══════════════════════════════════════════════════════════════\n\n// Anything that emits Node upgrade events — http.Server structurally, so\n// the @hono/node-server return type needs no narrowing.\ntype Upgradeable = {\n on: (event: 'upgrade', handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => void) => unknown;\n};\n\n// The `ws` half of the transport seam: RFC 6455 stays library-handled\n// (permessage-deflate on by default — see `runtime.socketCompression`); the\n// protocol above the seam is nisc's own (../socket.ts) and identical on every\n// runtime.\nexport const attachSocket = (\n httpServer: Upgradeable,\n accept: SocketAccept,\n path = '/socket',\n options?: { compression?: boolean | Record<string, unknown> },\n): void => {\n const wss = new WebSocketServer({ noServer: true, perMessageDeflate: options?.compression ?? true });\n httpServer.on('upgrade', (req, socket, head) => {\n const url = req.url ?? '/';\n // Not ours: leave it for whichever other listener owns it (vite's HMR\n // upgrade rides the same server in dev).\n if (new URL(url, 'http://nisc.local').pathname !== path) return;\n wss.handleUpgrade(req, socket, head, (ws) => {\n // accept promises to handle its own failures (see socket.ts). This is\n // the floor under that promise: an await added there without a guard\n // degrades to one logged close here instead of an unhandled rejection\n // taking every session on the box down with it.\n accept(url, {\n send: (text) => ws.send(text),\n close: (code, reason) => ws.close(code, reason),\n onMessage: (fn) => ws.on('message', (data) => fn(String(data))),\n onClose: (fn) => ws.on('close', () => fn()),\n }).catch((error: unknown) => {\n console.error('[moss/node] a connection escaped accept:', error);\n try {\n ws.close(1011, 'accept failed');\n } catch {\n // already gone\n }\n });\n });\n });\n};\n\n// THE BUILT TERMINAL, served by the same process as the app — one origin, so the\n// socket is `/socket` wherever the page came from.\n//\n// `dist` is what the app's bundler wrote: index.html and its assets. Every GET\n// that nothing registered earlier answers is a file from it, or a PAGE:\n// index.html with the caller's screen drawn into it (./document) — the app's own\n// for `/`, one of the manifest's pages for a path that leads to one. index.html\n// itself is never served as a file: it is the template, and goes out drawn.\n//\n// A name with an extension that is neither a file in `dist` nor a page of the\n// manifest is a MISSING FILE, and is answered 404 — not with a screen. A browser\n// holding a page from before a deploy asks for that page's script by its old\n// name; what it needs back is \"gone\", not a document that is not a script.\n//\n// Register the app's own routes FIRST; this is the catch-all. `owned` names the\n// prefixes that are never a page (default: moss's own surfaces) — an unknown\n// path under one is a 404, not a screen.\nexport type SiteConfig = Pick<DocumentConfig, 'draw' | 'htmlAttributes' | 'site' | 'tokenKey' | 'waitMs'> & {\n dist: string;\n owned?: RegExp;\n};\n\n// The paths the app server answers itself; everything else is the site's.\nexport const MOSS_PATHS = /^\\/(api|catalog|socket|operator|integrations)(\\/|$)/;\n\nexport const mountSite = (server: MossServer, config: SiteConfig): void => {\n const { dist, owned = MOSS_PATHS, ...drawing } = config;\n // serveStatic resolves `root` against the working directory.\n const root = relative(process.cwd(), dist) || '.';\n const files = serveStatic({ root });\n server.use('/*', async (c, next) => {\n const path = c.req.path;\n if (owned.test(path) || path === '/' || path === '/index.html' || server.page(path) !== undefined) return next();\n return files(c, next);\n });\n server.get('*', async (c) => {\n if (owned.test(c.req.path)) return c.notFound();\n // the static server above found no such file, and no page is at this path\n if (extname(c.req.path) !== '' && c.req.path !== '/index.html' && server.page(c.req.path) === undefined) return c.notFound();\n const template = await readFile(join(dist, 'index.html'), 'utf8');\n const page = await renderDocument({\n ...drawing,\n server,\n template,\n request: { path: c.req.path === '/index.html' ? '/' : c.req.path, cookie: c.req.header('cookie') ?? null },\n });\n return c.html(page.html, 200, page.headers);\n });\n};\n\nexport const serve = async (app: NiscApp, runtime: NiscRuntime & { port?: number }): Promise<MossServer> => {\n const server = await createServer(app, runtime);\n const port = runtime.port ?? 8787;\n const httpServer = listen({ fetch: server.fetch, port });\n attachSocket(httpServer, server.socket, '/socket', { ...(runtime.socketCompression !== undefined ? { compression: runtime.socketCompression } : {}) });\n console.log(`moss serving http://localhost:${port}`);\n console.log(`surfaces: GET /catalog · GET|POST /api/vex · GET|POST /api/<resource>/vex · ws://localhost:${port}/socket`);\n return server;\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/telemetry.ts","../src/socket.ts","../src/delta.ts"],"names":[],"mappings":";;;AA0DO,IAAM,YAAY,CAAC,SAAA,KACxB,cAAc,MAAA,GACV,MAAA,GACA,CAAC,IAAA,KAAS;AACR,EAAA,IAAI;AACF,IAAA,SAAA,CAAU,KAAK,IAAI,CAAA;AAAA,EACrB,SAAS,GAAA,EAAK;AACZ,IAAA,OAAA,CAAQ,KAAA,CAAM,oBAAoB,GAAG,CAAA;AAAA,EACvC;AACF;AAON,IAAM,YAAA,GAAe,MAAe,OAAO,WAAA,KAAgB,cAAc,WAAA,CAAY,GAAA,EAAI,GAAI,IAAA,CAAK,GAAA,EAAI;AAE/F,IAAM,YAAY,MAAiB;AACxC,EAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,GAAA,EAAI,GAAI,GAAA;AACnC,EAAA,MAAM,KAAK,YAAA,EAAa;AACxB,EAAA,OAAO,EAAE,eAAe,WAAA,EAAa,MAAM,iBAAiB,YAAA,EAAa,GAAI,MAA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A,EAAA,IAAM,MAAA;AAAA,EACR;AACA,EAAA,IAAI,YAAY,EAAA,EAAI,GAAA,CAAI,KAAK,CAAC,CAAA,EAAG,OAAO,CAAC,CAAA;AACzC,EAAA,OAAO,GAAA;AACT;AAKO,IAAM,UAAA,GAAa,CAAC,IAAA,EAAc,GAAA,KAAoC;AAC3E,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,MAAM,GAAA,EAAK;AACpB,IAAA,IAAI,EAAA,CAAG,CAAC,CAAA,KAAM,CAAA,EAAG;AACf,MAAA,GAAA,IAAO,GAAG,CAAC,CAAA;AACX,MAAA;AAAA,IACF;AACA,IAAA,MAAM,GAAG,MAAA,EAAQ,MAAM,CAAA,GAAI,EAAA;AAC3B,IAAA,IAAI,SAAS,CAAA,IAAK,MAAA,GAAS,KAAK,MAAA,GAAS,MAAA,GAAS,KAAK,MAAA,EAAQ;AAC7D,MAAA,MAAM,IAAI,MAAM,CAAA,iBAAA,EAAoB,MAAM,IAAI,MAAM,CAAA,sBAAA,EAAyB,IAAA,CAAK,MAAM,CAAA,CAAE,CAAA;AAAA,IAC5F;AACA,IAAA,GAAA,IAAO,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,MAAA,GAAS,MAAM,CAAA;AAAA,EAC3C;AACA,EAAA,OAAO,GAAA;AACT;AAUO,IAAM,SAAA,GAAY,CAAC,IAAA,KAAyB;AACjD,EAAA,IAAI,IAAA,GAAO,UAAA;AACX,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,MAAA,EAAQ,KAAK,CAAA,EAAG;AACvC,IAAA,IAAA,IAAQ,IAAA,CAAK,WAAW,CAAC,CAAA;AACzB,IAAA,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,QAAU,CAAA;AAAA,EACnC;AACA,EAAA,OAAO,IAAA,KAAS,CAAA;AAClB","file":"chunk-ZOEUEMDX.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════\n// Telemetry — moss's one observability surface, and the SOLE owner of the\n// span shape. Every service a Midas deployment runs is a moss process; moss\n// is the choke point every engine fact passes through, so moss is where a\n// deployment learns how long a vex execution took, which fingerprint is slow,\n// how often a policy refuses, how many shells are resident. Instrumenting here\n// means a service written tomorrow is observed the day it boots, with no code\n// in the service — the same argument the engine boundary makes for queries.\n//\n// The sink is a deployment decision, not an application one, so the hook lives\n// on the runtime (runtime.ts) beside the other operational knobs. Unset, no\n// span is ever built: every emission site guards on `emit !== undefined`, and\n// an optional call short-circuits its argument, so a hot path with no sink\n// allocates nothing.\n//\n// STRUCTURAL FACTS ONLY. A span carries identifiers and measurements — a\n// fingerprint, a duration, a status — never a payload, a context value, a row,\n// or a principal beyond presence (`hasPrincipal`). The stream must be safe to\n// ship to a third-party backend without a privacy review per span. moss builds\n// every span here from what a seam reports; a seam reports facts, moss decides\n// what of them is safe to name.\n// ═══════════════════════════════════════════════════════════════\n\n// The span, shaped after the OpenTelemetry data model — not the SDK, just the\n// shape, so any OTLP backend ingests a JSON mapping of it with no translation.\nexport type TelemetrySpan = {\n // 'vex.execute' | 'fn.call' | 'shell.build' | 'socket.upgrade' |\n // 'socket.close' | 'integration.call' | …\n name: string;\n // Epoch nanoseconds, millisecond-anchored with a sub-millisecond monotonic\n // span between them. JS numbers cannot hold epoch nanos exactly — the low\n // ~8 bits are lossy — which is far below the millisecond scale of what is\n // measured here, and an exporter re-quantises anyway.\n startUnixNano: number;\n endUnixNano: number;\n // 'refused' is a policy/intake NO — a normal outcome, distinct from a fault.\n status: 'ok' | 'error' | 'refused';\n // Identifiers and measurements. Never a payload, name, address, or context\n // value; a principal appears only as `hasPrincipal`.\n attributes: Record<string, string | number | boolean>;\n // Trace stitching — unused in v1 (no cross-process traceparent yet), carried\n // so a sampler and a propagator can arrive without a shape change.\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n};\n\n// The runtime hook. `emit` is fire-and-forget: never awaited, and wrapped\n// (`emitterOf`) so a slow or throwing sink costs the request nothing.\nexport type Telemetry = {\n emit: (span: TelemetrySpan) => void;\n};\n\nexport type Emit = (span: TelemetrySpan) => void;\n\n// The one safe emitter every seam derives. `undefined` when no sink is\n// configured — the signal each site guards on to build no span at all. When a\n// sink is present, its throw is contained here, never the caller's.\nexport const emitterOf = (telemetry: Telemetry | undefined): Emit | undefined =>\n telemetry === undefined\n ? undefined\n : (span) => {\n try {\n telemetry.emit(span);\n } catch (err) {\n console.error('[moss:telemetry]', err);\n }\n };\n\n// A span's clock: the start stamped once, elapsed read on demand — so one clock\n// serves both a short handshake span and a whole-connection span from the same\n// origin. Millisecond-anchored start, sub-millisecond monotonic elapsed.\nexport type SpanClock = { startUnixNano: number; endUnixNano: () => number };\n\nconst elapsedClock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nexport const spanClock = (): SpanClock => {\n const startUnixNano = Date.now() * 1e6;\n const t0 = elapsedClock();\n return { startUnixNano, endUnixNano: () => startUnixNano + (elapsedClock() - t0) * 1e6 };\n};\n","import { DefinitionValidationError } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport type { Catalog } from './principal';\nimport type { DeltaOp } from './delta';\nimport type { ShellHost } from './shells';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\n\n// ═══════════════════════════════════════════════════════════════\n// The socket — the authority channel (DESIGN.md § The socket), protocol layer.\n//\n// The socket invents nothing: JSON frames, every canvas-bound message\n// carries its canvas id, reconnect just re-sends current state. This\n// module is transport-blind — it speaks through the four-function\n// `Connection` seam; the RFC 6455 plumbing lives with each runtime's\n// entry (`ws` on Node in ./node, Bun-native later) and is never\n// hand-written.\n//\n// What rides it: connection lifecycle, token auth at upgrade, the CATALOG\n// channel (`hello` on connect — the resolved application + its version\n// token; equal hash, equal application), and the canvas streams (`render`\n// down, `event` up) fed by the server shell host. An app whose manifest\n// declares no shell has no streams, and an event envelope aimed at one is\n// answered honestly with `no_shell` rather than silently dropped.\n//\n// Identity is asked twice: once at upgrade, and then on a timer for as long\n// as the connection lives (see DEFAULT_REVALIDATE_MS). The second is what\n// lets a `session` verifier's expiry mean anything here — the HTTP surfaces\n// re-ask on every request, and a socket that asked once would be the hole\n// every long-lived credential leaks through.\n// ═══════════════════════════════════════════════════════════════\n\n// The transport seam — what a runtime's websocket must provide. Four\n// functions; everything above them is identical on every runtime.\nexport type Connection = {\n send: (text: string) => void;\n close: (code?: number, reason?: string) => void;\n onMessage: (fn: (text: string) => void) => void;\n onClose: (fn: () => void) => void;\n};\n\n// ── The envelope ──\nexport type ServerMessage =\n | { type: 'hello'; protocol: number; principal: string | null; catalog: { actions: readonly string[]; hash: string } }\n | { type: 'catalog'; actions: readonly string[]; hash: string }\n // the shell's canvas ARRANGEMENT — a rendered layout whose CanvasSlot\n // markers the terminal resolves against its per-canvas trees\n | { type: 'frame'; tree: RenderNode[] }\n | { type: 'render'; canvas: string; tree: RenderNode[] }\n // The same render, as a DELTA against the last frame this connection was\n // sent for this canvas. Only ever sent to a terminal that asked for deltas\n // (`?delta=1` on the upgrade) and only when a previous frame exists, so a\n // terminal that does not understand this never receives one.\n //\n // `hash` is over the rebuilt message text: a terminal that applies the ops\n // and does not land on it has diverged, and asks for a whole frame instead\n // of rendering something the server never meant.\n | { type: 'render-delta'; canvas: string; ops: DeltaOp[]; hash: number }\n // session GRANT (login succeeded server-side): store the token and\n // reconnect authenticated — the twin of the 4403 SIGNED_OUT revoke\n | { type: 'session'; token: string }\n | { type: 'error'; code: string; message: string; canvas?: string };\n\nexport type ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n // RESYNC: this terminal's frame for a canvas is not what the server thinks\n // it is — a delta failed its checksum, or arrived with no base to apply it\n // to. Answered with whole frames, which is the state both ends can always\n // agree on. Distinct from `reset`: the SHELL is fine, only this connection's\n // copy of it drifted, so nothing is torn down.\n | { type: 'resync' }\n // BACK: undo this session's last navigation. It names no canvas for the same\n // reason `reset` does not — back is one gesture over the whole shell, and the\n // terminal that sends it has no idea which canvas moved last (it is served\n // trees, not stacks). Protocol-level, so a browser's back button, a TUI's\n // Escape and a REPL word are the same message on one wire, and the app has to\n // author nothing to receive it.\n | { type: 'back' }\n // POP TO: jump straight to an ancestor already on a canvas's stack. Back\n // undoes ONE navigation; a breadcrumb that names a screen three levels down\n // is one intention, not three gestures. Sending three `back`s instead raced\n // the browser's own history repair and dropped presses — the shell can walk\n // its own stack atomically, so it should be asked to.\n | { type: 'popTo'; canvas: string; instance: string }\n // RESET: throw this session's shell away and serve its replacement. The one\n // message that names no canvas, deliberately — it is the recovery for a\n // shell whose canvases are the broken thing, so it must not have to travel\n // through one. Protocol-level, not app-level: no action declares it, no\n // charter grants it, and it reaches a terminal whose every surface is dead.\n | { type: 'reset' };\n\n// The wire protocol this server speaks, and the oldest a terminal may speak to\n// it. A terminal says which it speaks on the upgrade (`?protocol=N`, beside the\n// token — known before the first frame is sent); one that says nothing speaks 1,\n// which is every terminal built before the question existed. Outside the range\n// the connection is refused with a sentence and CLOSE_PROTOCOL_MISMATCH, never\n// served frames it would misread. Bump PROTOCOL when a message changes shape;\n// raise PROTOCOL_MIN only when the server stops speaking an old one.\nexport const PROTOCOL = 1;\nexport const PROTOCOL_MIN = 1;\n\n// Application close code: the token did not resolve to a principal.\nexport const CLOSE_INVALID_TOKEN = 4401;\n// Application close code: the session ended (sign-out, from any of the\n// principal's terminals) — the terminal clears its token instead of\n// reconnecting.\nexport const CLOSE_SIGNED_OUT = 4403;\n// Application close code: the server could not open a session for THIS\n// connection — commonest cause: a definition failing validation reached the\n// live catalog (a dev edit mid-reload). The refusal is this terminal's alone;\n// the process and every other session stay up, and reconnecting later is\n// reasonable — the next build is attempted fresh.\nexport const CLOSE_SHELL_FAILED = 4500;\n// Application close code: terminal and server speak protocols the other cannot\n// (see PROTOCOL). Not a retry: reconnecting speaks the same protocol again. A\n// browser terminal needs a reload to fetch the current build; the preceding\n// `error` says which side is behind (`client_too_old` / `server_too_old`).\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport type SocketContext = {\n session: (token: string) => string | null | Promise<string | null>;\n catalog: (principal: string | null) => Catalog | Promise<Catalog>;\n // The shell host — when the manifest declares a shell, events route into\n // the session's server shell and render frames flow back.\n shells?: ShellHost;\n // WHICH HOST A PATH LEADS TO. A terminal on a page names the path it is on\n // (`?path=`); this answers with that page's host and the input its path\n // carries, or undefined for a path that is the app's. Absent: every\n // connection is the app's, as before pages existed.\n page?: (path: string) => { host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // How often a LIVE connection's credential is re-verified. Default\n // `DEFAULT_REVALIDATE_MS`; `0` or `Infinity` disables it, and a token\n // checked once at upgrade is then trusted for the life of the connection.\n revalidateMs?: number;\n // The deployment's telemetry sink, if any — a `socket.upgrade` span per\n // connection admitted or refused, and a `socket.close` span carrying the\n // whole connection's lifetime. See telemetry.ts.\n telemetry?: Telemetry;\n};\n\n// ── Revalidation ──\n// The HTTP surfaces re-ask \"who is this\" on every request; the socket asked\n// once, at upgrade, and never again. That asymmetry is why an app could not\n// give its tokens an expiry that meant anything: the verifier seam is\n// perfectly able to say a token has died (return null), but on a live socket\n// nobody was listening for the answer.\n//\n// It also failed in a shape worth naming. The server shell's own wire rides\n// the HTTP middleware carrying the session's token, so an expired credential\n// used to leave the socket open and cheerful — frames flowing, screen alive —\n// while every endpoint the shell called came back 401. A live interface whose\n// every load silently fails is strictly worse than a lock screen.\n//\n// The recovery for this already existed and is untouched: a `4401` close is a\n// recovery, not a retry, and the terminal drops its token and reconnects\n// anonymous onto the served lock screen. All that was missing was something\n// asking the question. This is that.\nexport const DEFAULT_REVALIDATE_MS = 60 * 1000;\n\n// One accept per new connection: authenticate (the token rides the upgrade\n// URL — browsers cannot set websocket headers; absent = the anonymous\n// principal, invalid = closed with 4401), then say hello with the resolved\n// catalog and settle into the message loop. `stop` ends revalidation, for\n// hosts that outlive their server (dev checks, embedded tools) — the timer is\n// unref'd, so a plain process needn't call it.\nexport type SocketAccept = ((url: string, connection: Connection) => Promise<void>) & { stop: () => void };\n\nconst parse = (text: string): Record<string, unknown> | null => {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport const createSocket = (ctx: SocketContext): SocketAccept => {\n const emit = emitterOf(ctx.telemetry);\n // Every live connection, with the credential it authenticated under (null =\n // anonymous, which has nothing that can expire). One structure: the future\n // catalog-push fan-out wants the keys, revalidation wants the values.\n const live = new Map<Connection, { token: string; principal: string } | null>();\n\n const expire = (connection: Connection): void => {\n // Diagnostics before authority, as at upgrade — the close code is what\n // the terminal acts on; this is what a person reads in a log.\n connection.send(JSON.stringify({ type: 'error', code: 'invalid_token', message: 'The session token no longer resolves to this principal.' } satisfies ServerMessage));\n connection.close(CLOSE_INVALID_TOKEN, 'session expired');\n live.delete(connection);\n };\n\n const revalidate = async (): Promise<void> => {\n for (const [connection, credential] of [...live]) {\n if (credential === null) continue; // anonymous — nothing to expire\n let resolved: string | null;\n try {\n resolved = await ctx.session(credential.token);\n } catch {\n // The verifier is unreachable — a database blip, a network hiccup.\n // That is not evidence a session ended, and signing everybody out on\n // it would turn a transient fault into an outage. Ask again next pass.\n continue;\n }\n // Unchanged is the overwhelmingly common answer. A token that stops\n // resolving has expired or been revoked; one that resolves to somebody\n // ELSE is not the session that attached, and both are the same close.\n if (resolved === credential.principal) continue;\n if (!live.has(connection)) continue; // it closed while we were awaiting\n expire(connection);\n }\n };\n\n const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {\n sweeper = setInterval(() => void revalidate(), revalidateMs);\n // Revalidation must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n // REFUSING ONE SESSION MUST NEVER COST THE OTHERS. Every await in the body\n // below can throw — the verifier on a database blip, the shell build on a\n // definition that fails validation — and the runtime transport calls accept\n // without awaiting it, so an escaped rejection is an unhandled one and Node\n // kills the whole process: one bad definition, every session on the box\n // disconnected. So accept NEVER rejects. A failure to open this session is\n // answered to this terminal — a sentence naming the failing definitions\n // when there are any, then a 4500 close — and logged where somebody can\n // read it. The durable map is only written after a successful build, so a\n // refused terminal poisons nothing: the next connect builds fresh.\n const accept = async (url: string, connection: Connection): Promise<void> => {\n const send = (message: ServerMessage): void => connection.send(JSON.stringify(message));\n try {\n await open(url, connection, send);\n } catch (error) {\n console.error('[moss/socket] refused a session:', error);\n live.delete(connection);\n const failures =\n error instanceof DefinitionValidationError\n ? ((error.context as { failures?: { id: string }[] } | undefined)?.failures ?? []).map((f) => f.id)\n : [];\n const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(', ')}` : String(error);\n try {\n send({ type: 'error', code: 'session_failed', message: `This session could not be opened — ${detail}. The refusal is this terminal's alone; the server is up.` });\n connection.close(CLOSE_SHELL_FAILED, 'session failed');\n } catch {\n // The transport is already gone — there is nobody left to tell.\n }\n }\n };\n\n const open = async (url: string, connection: Connection, send: (message: ServerMessage) => void): Promise<void> => {\n // One clock stamped at the handshake serves both the short `socket.upgrade`\n // span and the whole-connection `socket.close` span from the same origin.\n const upClock = emit === undefined ? undefined : spanClock();\n const params = new URL(url, 'http://nisc.local').searchParams;\n const spoken = Number(params.get('protocol') ?? '1');\n if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {\n const behind = spoken > PROTOCOL ? 'server' : 'client';\n send({\n type: 'error',\n code: `${behind}_too_old`,\n message: `This terminal speaks protocol ${params.get('protocol') ?? '1'}; this server speaks ${PROTOCOL_MIN}–${PROTOCOL}. ${behind === 'client' ? 'Reload the terminal to get the current build.' : 'The server has not been updated yet.'}`,\n });\n connection.close(CLOSE_PROTOCOL_MISMATCH, 'protocol mismatch');\n return;\n }\n const token = params.get('token');\n let principal: string | null = null;\n if (token !== null && token !== '') {\n principal = await ctx.session(token);\n if (principal === null) {\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'refused', attributes: { hasPrincipal: false } });\n }\n send({ type: 'error', code: 'invalid_token', message: 'The session token did not resolve to a principal.' });\n connection.close(CLOSE_INVALID_TOKEN, 'invalid token');\n return;\n }\n }\n\n // Remembered WITH its credential — revalidation has to re-ask the same\n // question this connection was admitted on, and the token is not\n // recoverable from anything else here.\n live.set(connection, token !== null && token !== '' && principal !== null ? { token, principal } : null);\n connection.onClose(() => live.delete(connection));\n // The connection's whole life, closed by the same clock — how long\n // terminals stay, and under a principal or anonymous. Registered here so it\n // fires however the connection ends (graceful, expiry, transport drop).\n if (emit !== undefined && upClock !== undefined) {\n const hadPrincipal = principal !== null;\n connection.onClose(() => emit({ name: 'socket.close', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: hadPrincipal } }));\n }\n\n // The catalog channel: the application, resolved for YOU, on every\n // (re)connect — reconnect re-sends current state, no replay machinery.\n const { ids, hash } = await ctx.catalog(principal);\n send({ type: 'hello', protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });\n\n // The canvas streams: attach to the session's shell (durable per\n // principal — the shell outlives this connection) and it re-sends the\n // current trees; every change fans out to every attached connection.\n // Frame deltas are OPT-IN by the terminal, on the upgrade URL beside the\n // token — browsers cannot set websocket headers, and the capability has to\n // be known before the first frame is sent. A terminal that says nothing is\n // served whole frames forever, which is what every terminal built before\n // this existed does.\n const wantsDelta = params.get('delta') === '1';\n\n // An anonymous terminal whose page was rendered server-side names the id\n // seed that page's shell was built under, so this connection's throwaway\n // shell mints the same instance ids and its first frames match the page.\n // Shape-checked, never trusted further: it only ever names ids inside the\n // caller's own shell.\n const named = params.get('seed');\n const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : undefined;\n\n // The path the terminal is on decides which shell it is served: a page's,\n // built for this connection alone, or the app's.\n const path = params.get('path');\n const route = path === null ? undefined : ctx.page?.(path);\n const host = route?.host ?? ctx.shells;\n\n const session = await host?.session(token, principal, { ...(seed === undefined ? {} : { seed }), ...(route === undefined ? {} : { inputs: route.inputs }) });\n if (session !== undefined) {\n session.attach(connection, { delta: wantsDelta });\n connection.onClose(() => session.detach(connection));\n }\n\n // Admitted: the handshake resolved a principal, said hello, and attached a\n // shell. The span measures that, not the connection's life (that is\n // `socket.close`).\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: principal !== null } });\n }\n\n connection.onMessage((text) => {\n const message = parse(text);\n // Reset first, and answered on its own terms: a wedged session is\n // exactly the one whose other paths cannot be trusted to run.\n if (message !== null && message['type'] === 'reset') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.reset();\n return;\n }\n // Resync before the ordinary paths, for the reason reset is: a terminal\n // asking for this has already decided it cannot trust what it is holding.\n if (message !== null && message['type'] === 'resync') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.resync(connection);\n return;\n }\n if (message !== null && message['type'] === 'back') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.back();\n return;\n }\n if (\n message !== null &&\n message['type'] === 'popTo' &&\n typeof message['canvas'] === 'string' &&\n typeof message['instance'] === 'string'\n ) {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.popTo(message['canvas'], message['instance']);\n return;\n }\n if (message !== null && message['type'] === 'publish' && typeof message['channel'] === 'string') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.publish(message['channel'], message['payload']);\n return;\n }\n if (message === null || message['type'] !== 'event' || typeof message['canvas'] !== 'string') {\n send({ type: 'error', code: 'invalid_message', message: 'Messages are JSON { type: \"event\", canvas, event }.' });\n return;\n }\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.', canvas: message['canvas'] });\n return;\n }\n const event = message['event'];\n if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n send({ type: 'error', code: 'invalid_message', message: 'The event field must be a NovaEvent object.', canvas: message['canvas'] });\n return;\n }\n session.dispatch(message['canvas'], event as Record<string, unknown>);\n });\n };\n\n return Object.assign(accept, {\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n });\n};\n","// Frame deltas — send what changed, not the frame.\n//\n// A shell re-sends a whole canvas tree whenever that tree changes. Most changes\n// are small against a large tree (a keystroke filters a list, one badge flips),\n// so the new frame is mostly a rearrangement of bytes the client already holds.\n//\n// This encodes the new frame as COPY runs from the old one plus literal\n// inserts. It is deliberately not a structural diff over the tree: a\n// navigation produces a genuinely different tree, and a path-based diff then\n// costs MORE than the frame it replaces, while a byte matcher still finds the\n// shared vocabulary. It is also not zlib's preset dictionary, which would be\n// two lines here and does not exist in a browser.\n//\n// No dependency, both directions in one file, and small enough to read in\n// full — a delta layer that cannot be audited is a desync you cannot diagnose.\n\n/** A run copied from the base frame: offset, length. */\ntype Copy = [0, number, number];\n/** Bytes that are not in the base at all. */\ntype Insert = [1, string];\nexport type DeltaOp = Copy | Insert;\n\n// Matches shorter than this cost more to describe than to inline. 16 is a\n// compromise: low enough to catch a changed cell inside a row, high enough that\n// the index does not match noise.\nconst BLOCK = 16;\n\n/**\n * Encode `target` as operations against `base`.\n *\n * Greedy and single-pass: at each position look for a block that already exists\n * in the base, extend the match as far as it runs, and emit a copy. Anything\n * unmatched accumulates into a literal. Not optimal — an optimal encoder needs\n * a suffix automaton — but it captures the long shared runs that dominate a\n * render tree, which is where the bytes are.\n */\nexport const encodeDelta = (base: string, target: string): DeltaOp[] => {\n if (base.length < BLOCK) return [[1, target]];\n\n const index = new Map<string, number>();\n for (let i = 0; i + BLOCK <= base.length; i += 1) {\n // First position wins: earlier offsets tend to extend further in a tree\n // whose head is stable chrome.\n const key = base.slice(i, i + BLOCK);\n if (!index.has(key)) index.set(key, i);\n }\n\n const ops: DeltaOp[] = [];\n let literal = '';\n let at = 0;\n\n while (at < target.length) {\n const key = target.slice(at, at + BLOCK);\n const found = key.length === BLOCK ? index.get(key) : undefined;\n if (found === undefined) {\n literal += target[at];\n at += 1;\n continue;\n }\n let length = BLOCK;\n while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {\n length += 1;\n }\n if (literal !== '') {\n ops.push([1, literal]);\n literal = '';\n }\n ops.push([0, found, length]);\n at += length;\n }\n if (literal !== '') ops.push([1, literal]);\n return ops;\n};\n\n/** Rebuild the frame. Throws on a malformed op rather than returning a\n * half-applied string — a silently wrong frame is the failure this whole\n * layer has to not have. */\nexport const applyDelta = (base: string, ops: readonly DeltaOp[]): string => {\n let out = '';\n for (const op of ops) {\n if (op[0] === 1) {\n out += op[1];\n continue;\n }\n const [, offset, length] = op;\n if (offset < 0 || length < 0 || offset + length > base.length) {\n throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);\n }\n out += base.slice(offset, offset + length);\n }\n return out;\n};\n\n/**\n * A cheap, order-sensitive checksum of a frame.\n *\n * Carried on every delta so a client can prove it rebuilt the frame the server\n * meant. A delta protocol without this is one dropped message away from a\n * client that is permanently and silently wrong, with no error anywhere — which\n * is strictly worse than sending whole frames forever.\n */\nexport const frameHash = (text: string): number => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i += 1) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n"]}
|