@niscorp/moss 0.3.3 → 0.5.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 +534 -0
- package/DESIGN.md +265 -49
- package/DOCS.md +1524 -341
- package/README.md +37 -20
- package/dist/app-BoVB0_0j.d.ts +143 -0
- package/dist/app-Cc8VnOz8.d.cts +143 -0
- package/dist/chunk-3RIWTXGI.cjs +174 -0
- package/dist/chunk-3RIWTXGI.cjs.map +1 -0
- package/dist/chunk-4ZGAFZGS.js +152 -0
- package/dist/chunk-4ZGAFZGS.js.map +1 -0
- package/dist/chunk-5U2ZZUI5.cjs +137 -0
- package/dist/chunk-5U2ZZUI5.cjs.map +1 -0
- package/dist/chunk-6QPTMKRE.cjs +53 -0
- package/dist/chunk-6QPTMKRE.cjs.map +1 -0
- package/dist/chunk-BQRPR2F7.js +2704 -0
- package/dist/chunk-BQRPR2F7.js.map +1 -0
- package/dist/chunk-BZK37HR3.cjs +2716 -0
- package/dist/chunk-BZK37HR3.cjs.map +1 -0
- package/dist/chunk-FTFME3HS.cjs +383 -0
- package/dist/chunk-FTFME3HS.cjs.map +1 -0
- package/dist/{chunk-NE2EXMTO.js → chunk-FTZ6NFKZ.js} +43 -16
- package/dist/chunk-FTZ6NFKZ.js.map +1 -0
- package/dist/chunk-IUJ2TRNB.cjs +57 -0
- package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
- package/dist/chunk-IW3A2YIC.js +49 -0
- package/dist/chunk-IW3A2YIC.js.map +1 -0
- package/dist/chunk-JYBHJDT7.cjs +30 -0
- package/dist/chunk-JYBHJDT7.cjs.map +1 -0
- package/dist/chunk-NRZ3Z2FF.js +61 -0
- package/dist/chunk-NRZ3Z2FF.js.map +1 -0
- package/dist/chunk-PCPQMC7A.js +26 -0
- package/dist/chunk-PCPQMC7A.js.map +1 -0
- package/dist/chunk-T5BRTFKP.js +53 -0
- package/dist/chunk-T5BRTFKP.js.map +1 -0
- package/dist/chunk-TGKDS2T7.cjs +330 -0
- package/dist/chunk-TGKDS2T7.cjs.map +1 -0
- package/dist/chunk-TLNRFAQ6.js +326 -0
- package/dist/chunk-TLNRFAQ6.js.map +1 -0
- package/dist/chunk-VKQPOZDJ.cjs +72 -0
- package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
- package/dist/chunk-ZWB6QDGF.js +374 -0
- package/dist/chunk-ZWB6QDGF.js.map +1 -0
- package/dist/client/node.cjs.map +1 -1
- package/dist/client/node.d.cts +3 -1
- package/dist/client/node.d.ts +3 -1
- package/dist/client/node.js.map +1 -1
- package/dist/client.cjs +14 -302
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +9 -33
- package/dist/client.d.ts +9 -33
- package/dist/client.js +2 -2
- package/dist/document-CU3muGbz.d.cts +169 -0
- package/dist/document-UFbAd-Ka.d.ts +169 -0
- package/dist/env-CY8EGWnD.d.cts +24 -0
- package/dist/env-DEPqqHEb.d.ts +24 -0
- package/dist/index-BuDuOSyx.d.cts +130 -0
- package/dist/index-BuDuOSyx.d.ts +130 -0
- package/dist/index.cjs +45 -3918
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +46 -100
- package/dist/index.d.ts +46 -100
- package/dist/index.js +4 -94
- package/dist/index.js.map +1 -1
- package/dist/integrations.cjs +975 -0
- package/dist/integrations.cjs.map +1 -0
- package/dist/integrations.d.cts +63 -0
- package/dist/integrations.d.ts +63 -0
- package/dist/integrations.js +972 -0
- package/dist/integrations.js.map +1 -0
- package/dist/messages-CSwCJgH3.d.cts +51 -0
- package/dist/messages-CSwCJgH3.d.ts +51 -0
- package/dist/node.cjs +17 -3457
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +13 -10
- package/dist/node.d.ts +13 -10
- package/dist/node.js +5 -3
- package/dist/protocol.cjs +24 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +11 -0
- package/dist/protocol.d.ts +11 -0
- package/dist/protocol.js +3 -0
- package/dist/protocol.js.map +1 -0
- package/dist/slots-96gNc9uH.d.cts +12 -0
- package/dist/slots-BX5N0Juv.d.ts +14 -0
- package/dist/slots-CU-AbnJg.d.cts +14 -0
- package/dist/slots-sLXDrlbG.d.ts +12 -0
- package/dist/socket-D90h1xSV.d.cts +24 -0
- package/dist/socket-D90h1xSV.d.ts +24 -0
- package/dist/targets-DInbLzff.d.cts +9 -0
- package/dist/targets-DInbLzff.d.ts +9 -0
- package/dist/terminal/dom/index.cjs +8 -3
- package/dist/terminal/dom/index.cjs.map +1 -1
- package/dist/terminal/dom/index.d.cts +3 -0
- package/dist/terminal/dom/index.d.ts +3 -0
- package/dist/terminal/dom/index.js +8 -3
- package/dist/terminal/dom/index.js.map +1 -1
- package/dist/terminal/dom/server.cjs +2 -7
- package/dist/terminal/dom/server.cjs.map +1 -1
- package/dist/terminal/dom/server.d.cts +3 -5
- package/dist/terminal/dom/server.d.ts +3 -5
- package/dist/terminal/dom/server.js +2 -7
- package/dist/terminal/dom/server.js.map +1 -1
- package/dist/terminal/index.cjs +22 -300
- package/dist/terminal/index.cjs.map +1 -1
- package/dist/terminal/index.d.cts +7 -2
- package/dist/terminal/index.d.ts +7 -2
- package/dist/terminal/index.js +21 -22
- package/dist/terminal/index.js.map +1 -1
- package/dist/terminal/ink/index.d.ts +3 -2
- package/dist/terminal/ink/index.js +149 -106
- package/dist/terminal/ink/index.js.map +1 -1
- package/dist/terminal/react/index.cjs +21 -71
- package/dist/terminal/react/index.cjs.map +1 -1
- package/dist/terminal/react/index.d.cts +5 -2
- package/dist/terminal/react/index.d.ts +5 -2
- package/dist/terminal/react/index.js +17 -20
- package/dist/terminal/react/index.js.map +1 -1
- package/dist/terminal/react/server.cjs +4 -68
- package/dist/terminal/react/server.cjs.map +1 -1
- package/dist/terminal/react/server.d.cts +9 -6
- package/dist/terminal/react/server.d.ts +9 -6
- package/dist/terminal/react/server.js +3 -18
- package/dist/terminal/react/server.js.map +1 -1
- package/dist/terminal/tty/index.cjs +147 -130
- package/dist/terminal/tty/index.cjs.map +1 -1
- package/dist/terminal/tty/index.d.cts +4 -2
- package/dist/terminal/tty/index.d.ts +4 -2
- package/dist/terminal/tty/index.js +147 -130
- package/dist/terminal/tty/index.js.map +1 -1
- package/dist/terminal/vue/index.cjs +20 -72
- package/dist/terminal/vue/index.cjs.map +1 -1
- package/dist/terminal/vue/index.d.cts +8 -12
- package/dist/terminal/vue/index.d.ts +8 -12
- package/dist/terminal/vue/index.js +45 -1
- package/dist/terminal/vue/index.js.map +1 -1
- package/dist/terminal/vue/server.cjs +4 -76
- package/dist/terminal/vue/server.cjs.map +1 -1
- package/dist/terminal/vue/server.d.cts +7 -6
- package/dist/terminal/vue/server.d.ts +7 -6
- package/dist/terminal/vue/server.js +3 -10
- package/dist/terminal/vue/server.js.map +1 -1
- package/dist/tide.cjs +41 -0
- package/dist/tide.cjs.map +1 -0
- package/dist/tide.d.cts +25 -0
- package/dist/tide.d.ts +25 -0
- package/dist/tide.js +39 -0
- package/dist/tide.js.map +1 -0
- package/dist/unverified.cjs +12 -0
- package/dist/unverified.cjs.map +1 -0
- package/dist/unverified.d.cts +7 -0
- package/dist/unverified.d.ts +7 -0
- package/dist/unverified.js +10 -0
- package/dist/unverified.js.map +1 -0
- package/dist/vite.cjs +96 -232
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +6 -8
- package/dist/vite.d.ts +6 -8
- package/dist/vite.js +97 -71
- package/dist/vite.js.map +1 -1
- package/package.json +56 -13
- package/dist/chunk-4T6KAXBP.js +0 -256
- package/dist/chunk-4T6KAXBP.js.map +0 -1
- package/dist/chunk-AUZMT3GL.js +0 -3406
- package/dist/chunk-AUZMT3GL.js.map +0 -1
- package/dist/chunk-EMRDIZLY.js +0 -99
- package/dist/chunk-EMRDIZLY.js.map +0 -1
- package/dist/chunk-HOZID4EM.js +0 -366
- package/dist/chunk-HOZID4EM.js.map +0 -1
- package/dist/chunk-NE2EXMTO.js.map +0 -1
- package/dist/chunk-SK4PDGEE.js +0 -55
- package/dist/chunk-SK4PDGEE.js.map +0 -1
- package/dist/document-DhWxieUc.d.cts +0 -1024
- package/dist/document-DhWxieUc.d.ts +0 -1024
- package/dist/slots-Do9ScG7v.d.cts +0 -37
- package/dist/slots-Do9ScG7v.d.ts +0 -37
package/dist/vite.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/session-cookie.ts","../src/document.ts","../src/socket.ts","../src/node.ts","../src/vite.ts"],"names":["said","headOf","placeHead","WebSocketServer","getRequestListener","path","readFile","resolve"],"mappings":";;;;;;;;;;;;;AA4BO,IAAM,iBAAA,GAAoB,YAAA;AAG1B,IAAM,eAAA,GAAkB,CAAC,MAAA,EAAmC,IAAA,GAAO,iBAAA,KAAqC;AAC7G,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,IAAA,EAAM,OAAO,IAAA;AACpD,EAAA,MAAM,MAAA,GAAS,mBAAmB,IAAI,CAAA;AACtC,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AACpC,IAAA,MAAM,EAAA,GAAK,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAC3B,IAAA,IAAI,EAAA,GAAK,KAAK,IAAA,CAAK,KAAA,CAAM,GAAG,EAAE,CAAA,CAAE,IAAA,EAAK,KAAM,MAAA,EAAQ;AACnD,IAAA,IAAI;AACF,MAAA,MAAM,KAAA,GAAQ,mBAAmB,IAAA,CAAK,KAAA,CAAM,KAAK,CAAC,CAAA,CAAE,MAAM,CAAA;AAC1D,MAAA,OAAO,KAAA,KAAU,KAAK,IAAA,GAAO,KAAA;AAAA,IAC/B,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT,CAAA;AAWA,IAAM,MAAA,GAAS,CAAC,GAAA,EAAa,IAAA,KAAyB,CAAA,EAAG,GAAG,CAA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AAI,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.cjs","sourcesContent":["// ═══════════════════════════════════════════════════════════════\n// A BROWSER'S SESSION, KEPT WHERE ITS PAGE CANNOT READ IT.\n//\n// A terminal served by the app it talks to does not hold its session: the\n// browser does, in a cookie no script can read, and sends it by itself with\n// the two requests that need to know who is asking — the page, and the\n// upgrade that opens the socket. The server writes it in its answer to that\n// upgrade (socket.ts), or to a sign-in the app answers over HTTP\n// (`sessionCookies`, below). Any other terminal — a process, a page served\n// from somewhere else — holds its own token and offers it, as before.\n//\n// THE NAME is the terminal's token key (`nisc.token`, or a seat's own), so\n// several people can be signed in on one origin, each in a seat. It ends with\n// the port when the page is on one: a browser keeps cookies by host and not by\n// port, and two apps on localhost would otherwise sign each other out. Over\n// https it is `__Host-` prefixed and `Secure`, which a browser lets nothing\n// but this host set.\n//\n// BESIDE IT, `<name>.held=1`, which script CAN read and which says nothing but\n// that the browser holds a session — how a terminal knows to let go of a token\n// it was holding, and that a page drawn for somebody was drawn for it.\n//\n// NO ROUTE ANSWERS TO THIS COOKIE. It is read for a page request, which every\n// site may link to and none can read the answer of, and on an upgrade from the\n// app's own page — never from another origin's, which a browser would send it\n// with all the same.\n// ═══════════════════════════════════════════════════════════════\n\nexport const DEFAULT_TOKEN_KEY = 'nisc.token';\n\n// The token under one name in a `Cookie` header.\nexport const tokenFromCookie = (header: string | null | undefined, name = DEFAULT_TOKEN_KEY): string | null => {\n if (header === undefined || header === null) return null;\n const wanted = encodeURIComponent(name);\n for (const part of header.split(';')) {\n const at = part.indexOf('=');\n if (at < 0 || part.slice(0, at).trim() !== wanted) continue;\n try {\n const value = decodeURIComponent(part.slice(at + 1).trim());\n return value === '' ? null : value;\n } catch {\n return null;\n }\n }\n return null;\n};\n\n// Is this the app's own page asking? Its origin's host is the host the request\n// was addressed to — or one the deployment lists, behind a proxy that rewrites\n// `Host`. A sibling subdomain, another port, an opaque origin: not it.\nexport const isOwnOrigin = (origin: string | null | undefined, host: string | null | undefined, listed: readonly string[] = []): origin is string => {\n if (origin === undefined || origin === null || !URL.canParse(origin)) return false;\n const asked = new URL(origin);\n return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);\n};\n\nconst nameOf = (key: string, port: string): string => `${key}${port === '' ? '' : `.${port}`}`;\n\n// The flag's name, as a terminal on `port` reads it out of `document.cookie`.\nexport const heldCookieName = (key = DEFAULT_TOKEN_KEY, port = ''): string => encodeURIComponent(`${nameOf(key, port)}.held`);\n\nconst cookiesAt = (where: { port: string; secure: boolean }, key: string, token: string | null, lastsMs?: number | null): string[] => {\n const name = encodeURIComponent(nameOf(key, where.port));\n const life = token === null ? '; Max-Age=0' : typeof lastsMs === 'number' ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1000))}` : '';\n const kept = `Path=/; SameSite=Lax${where.secure ? '; Secure' : ''}${life}`;\n return [`${where.secure ? '__Host-' : ''}${name}=${encodeURIComponent(token ?? '')}; HttpOnly; ${kept}`, `${name}.held=${token === null ? '' : '1'}; ${kept}`];\n};\n\n// The page's origin as its browser sees it: what the request says, else where\n// it was addressed and how a proxy in front says it arrived.\nconst originOf = (request: Request): string => {\n const said = request.headers.get('origin');\n if (said !== null && URL.canParse(said)) return said;\n const here = new URL(request.url);\n const scheme = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() || here.protocol.slice(0, -1);\n return `${scheme}://${request.headers.get('host') ?? here.host}`;\n};\n\n// THE `Set-Cookie` VALUES that keep `token` in the browser of the page at this\n// origin — or, for `null`, take it back. For a sign-in the app answers over\n// HTTP (a link redeemed, a provider's callback): set these on the response and\n// the page that follows is signed in, having never held the token. `lastsMs`\n// is how long the browser keeps it; left out, until the browser closes.\nexport const sessionCookies = (page: string | Request, token: string | null, options: { key?: string; lastsMs?: number | null } = {}): string[] => {\n const at = new URL(typeof page === 'string' ? page : originOf(page));\n return cookiesAt({ port: at.port, secure: at.protocol === 'https:' }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);\n};\n\n// What the browser holds for this key, out of a request's `Cookie` header.\n// `secure` says which of the two names to read; unknown (a page request does\n// not say how it arrived), the one only this host can have set is read first.\nexport const sessionTokenOf = (\n cookies: string | null | undefined,\n where: { port: string; secure?: boolean },\n key = DEFAULT_TOKEN_KEY,\n): { token: string; clear: string[] } | null => {\n const name = nameOf(key, where.port);\n for (const secure of where.secure === undefined ? [true, false] : [where.secure]) {\n const token = tokenFromCookie(cookies, `${secure ? '__Host-' : ''}${name}`);\n if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };\n }\n return null;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// THE SEAL — how a sign-in made over the socket reaches that cookie.\n//\n// Only an HTTP answer can write a cookie, and a sign-in over the socket is not\n// one: the token has to travel through the page to the next upgrade. It\n// travels SEALED — encrypted with a key the page's browser holds in a second\n// cookie no script can read, set by the answer to its first upgrade. The page\n// can hand it back and cannot open it; neither can anybody it is shown to, on\n// this machine or another. It is good for a minute.\n//\n// The seal rides only the socket's own path: no page request carries it, so a\n// page drawn for nobody is still the same for everybody. It lasts until the\n// browser closes, and is never stored or looked up here — a key, not a name.\n//\n// ITS NAME IS WHAT KEEPS A SCRIPT FROM SUPPLYING IT. A request shows a cookie's\n// name and value and nothing of who set it, so a seal a script planted before\n// the browser's first upgrade would look like one given here — and the script\n// would hold the key. Over https the seal is `__Http-` prefixed: a name a\n// browser lets only an HTTP answer set, never script. A browser that does not\n// know the prefix treats it as any other name, and is where that is still open.\n//\n// WebCrypto, so this is the same on every runtime and nothing here is Node's.\n// ═══════════════════════════════════════════════════════════════\n\nconst SEALED_FOR_MS = 60_000;\nconst sealName = (secure: boolean): string => `${secure ? '__Http-' : ''}nisc.seal`;\nconst toBase64Url = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\nconst fromBase64Url = (text: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), (char) => char.charCodeAt(0));\nconst keyOf = async (seal: string): Promise<CryptoKey> => crypto.subtle.importKey('raw', await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seal)), 'AES-GCM', false, ['encrypt', 'decrypt']);\n\nexport const newSeal = (): string => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));\n\n// The seal a browser sent with an upgrade, and the `Set-Cookie` value that\n// gives it one: for the socket's own `path` only, unreadable to script.\nexport const sealOf = (cookies: string | null | undefined, secure: boolean): string | null => tokenFromCookie(cookies, sealName(secure));\nexport const sealCookie = (seal: string, where: { secure: boolean; path: string }): string => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? '; Secure' : ''}`;\n\nexport const sealSession = async (seal: string, token: string, forMs = SEALED_FOR_MS): Promise<string> => {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));\n return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));\n};\n\n// The token in a sealed sign-in — or null: not sealed with this seal, altered, or too old.\nexport const openSealed = async (seal: string, sealed: string): Promise<string | null> => {\n try {\n const bytes = fromBase64Url(sealed);\n const opened = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));\n const { token, until } = JSON.parse(new TextDecoder().decode(opened)) as { token?: unknown; until?: unknown };\n return typeof token === 'string' && typeof until === 'number' && until > Date.now() ? token : null;\n } catch {\n return null;\n }\n};\n","import { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport type { ShellSnapshot } from './shells';\nimport type { MossServer } from './server';\nimport { DEFAULT_TOKEN_KEY, sessionTokenOf, tokenFromCookie } from './session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The document — what a page request is answered with when the server draws\n// the first screen itself.\n//\n// A page request names a path and carries, at most, a cookie. From those two:\n// WHICH shell (a page's, if the path leads to one; otherwise the app's), for\n// WHOM (the cookie's principal, or nobody), read as it stands\n// (`shells.snapshot`), drawn to a string by a terminal the app hands in\n// (./terminal/react/server and its siblings), and written into the app's own\n// index.html beside the snapshot it was drawn from. The browser's terminal\n// starts from that snapshot (../client's `readDocumentSnapshot`) and adopts the\n// elements already there.\n//\n// Moss holds no opinion about the page around the screen: the template is the\n// app's file, the kit is the app's, and so is the route this is called from.\n//\n// The page's <head> is a node in a layout too (nova's `nova:head`, holding the\n// elements a head holds), so it is in the snapshot's trees like everything\n// else on the screen, and is written into the template's <head> as the screen\n// is written into its root.\n//\n// TWO RULES LIVE HERE, each in one place:\n//\n// WHO MAY KEEP A PAGE follows from who asked, and from nothing else\n// (`documentHeaders`). A page drawn for nobody is the same for everybody; a\n// page drawn for somebody is theirs. No page declares which it is.\n//\n// NOTHING HERE CAN FAIL A PAGE. Whatever goes wrong — a kit component that\n// throws, a shell that will not build — the answer is the template as it is,\n// and the terminal paints it the way it did before any of this existed.\n// ═══════════════════════════════════════════════════════════════\n\n// The element id the terminal looks for — the same constant ../client reads by.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\nconst DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport { tokenFromCookie };\n\n// The snapshot, as an element to put in the page. A tree carries what people\n// typed (a name, a note), and it sits inside a <script>: every `<` is written\n// as its escape, so nothing in a tree can close the element or open another.\n// U+2028/2029 go the same way — legal in JSON, line breaks to an HTML parser.\nexport const embedSnapshot = (snapshot: ShellSnapshot, principal: string | null, path?: string): string => {\n const { frame, trees, seed, live } = snapshot;\n const text = JSON.stringify({ frame, trees, principal: principal !== null, live, ...(seed !== undefined ? { seed } : {}), ...(path !== undefined ? { path } : {}) })\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n return `<script type=\"application/json\" id=\"${SNAPSHOT_ELEMENT_ID}\">${text}</script>`;\n};\n\n// A page drawn for somebody is theirs alone: nothing between here and their\n// browser may keep it. A page drawn for nobody is the same for everybody and\n// may be kept — but it must never be handed to a request that carried a\n// credential, so the two are told apart on the cookie.\nexport const documentHeaders = (principal: string | null): Record<string, string> =>\n principal === null ? { 'cache-control': 'no-cache', vary: 'Cookie' } : { 'cache-control': 'private, no-store', vary: 'Cookie' };\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<');\n\nexport type DocumentConfig = {\n server: MossServer;\n // The app's index.html, as it would be served undrawn. It must hold the empty\n // root (`root`, default `<div id=\"root\"></div>`) exactly once — that is where\n // the screen goes.\n template: string;\n // What the request named and carried. `host` is its `Host` header: the\n // session cookie's name ends with the port a page is on (session-cookie.ts),\n // so without it a page on a port is drawn for nobody.\n request: { path: string; cookie?: string | null; host?: string | null };\n // A terminal that draws to a string: the app's kit, bound to one of moss's\n // server targets (`renderSnapshot` from ./terminal/react/server, /vue/server,\n // /dom/server).\n draw: (snapshot: ShellSnapshot) => string | Promise<string>;\n // Attributes for the page's <html>, read off the screen — what a kit would\n // otherwise set from an effect that never runs here (a palette, a scheme).\n // Names are the app's and are written as given; values are escaped.\n htmlAttributes?: (snapshot: ShellSnapshot) => Record<string, string>;\n // The address the site is served at (\"https://example.com\"). With it, every\n // path's document says its own canonical address. Without it, where a\n // document lives is left as the template says.\n site?: string;\n // The wire's token key, which the session cookie is named by. Default `nisc.token`.\n tokenKey?: string;\n // How long the screen may take to settle before it is drawn as it stands.\n waitMs?: number;\n root?: string;\n};\n\nexport type DrawnDocument = {\n html: string;\n headers: Record<string, string>;\n // whether the screen is in the page (false: the template went out as it is)\n drawn: boolean;\n // who it was drawn for\n principal: string | null;\n // the page the path led to, when it led to one\n page?: string;\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?: ScreenHead;\n // the snapshot's own account of itself (see ShellSnapshot) — present when drawn\n live?: boolean;\n why?: string[];\n drawnWith?: string[];\n settled?: boolean;\n};\n\nexport const renderDocument = async (config: DocumentConfig): Promise<DrawnDocument> => {\n const { server, template, request, draw } = config;\n const tokenKey = config.tokenKey ?? DEFAULT_TOKEN_KEY;\n const root = config.root ?? DEFAULT_ROOT;\n const undrawn: DrawnDocument = { html: template, headers: documentHeaders(null), drawn: false, principal: null };\n if (!template.includes(root)) return undrawn;\n\n try {\n // The session the browser holds (session-cookie.ts). A page request does\n // not say how it arrived, so the name only this host can have set is read\n // before the plain one. Its name ends with the port the page is on: the\n // one the request was addressed to, and — behind a proxy that rewrote\n // `Host` to its own upstream — the one the site says it is served at.\n const ports = [/:(\\d+)$/.exec(request.host ?? '')?.[1] ?? '', ...(config.site !== undefined && URL.canParse(config.site) ? [new URL(config.site).port] : [])];\n const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;\n // A token that no longer resolves is nobody: the page is drawn for nobody.\n // Nothing is written here — the upgrade is where a browser's cookie is set\n // and taken back (socket.ts), and one writer cannot disagree with itself. A\n // verifier that THROWS is a fault, not a sign-out — the page goes out\n // undrawn and the socket, which asks again, is where it is settled.\n const principal = token === null ? null : await server.principalOf(token);\n const route = server.page(request.path);\n const host = route?.host ?? server.shells;\n if (host === undefined) return undrawn;\n\n const snapshot = await host.snapshot(principal === null ? null : token, principal, {\n ...(config.waitMs !== undefined ? { waitMs: config.waitMs } : {}),\n ...(route !== undefined ? { inputs: route.inputs } : {}),\n });\n const screen = await draw(snapshot);\n const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {})\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n const placed = template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => `${root.replace('></div>', () => `>${screen}</div>`)}${embedSnapshot(snapshot, principal, request.path)}`)\n .replace(/<html([^>]*)>/, (whole, existing: string) => (attributes === '' ? whole : `<html${existing}${attributes}>`));\n const head = headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });\n // what a head may not hold was left out: say so, where somebody can see it\n for (const why of head?.refused ?? []) console.error(`[moss/document] \"${request.path}\" — ${why}`);\n const html = placeHead(placed, head?.elements, { ...(config.site !== undefined ? { site: config.site } : {}), path: request.path });\n\n return {\n html,\n ...(head !== undefined ? { head } : {}),\n headers: documentHeaders(principal),\n drawn: true,\n principal,\n ...(route !== undefined ? { page: route.name } : {}),\n live: snapshot.live,\n why: snapshot.why,\n drawnWith: snapshot.drawnWith,\n settled: snapshot.settled,\n };\n } catch (error) {\n console.error(`[moss/document] \"${request.path}\" could not be drawn — serving it undrawn:`, error);\n return undrawn;\n }\n};\n\n// ── pages, as files ──\n//\n// The same draw, for NOBODY, once per path: what a static host serves. There is\n// no credential to pass and no way to pass one — a file is the page as nobody\n// in particular sees it, which is the only page that may be kept.\n//\n// A page that is LIVE is still written, and said so: its file is a true first\n// screen, and its terminal will look for a socket. Whether that is acceptable\n// (a server stands beside the files) or a mistake (there is no server) is the\n// build's to decide, from the report — nothing here guesses.\n\nexport type ExportedDocument = {\n path: string;\n html: string;\n page?: string;\n head?: ScreenHead;\n drawn: boolean;\n live: boolean;\n why: string[];\n // reads whose answers are in the file as they were when it was written\n drawnWith: string[];\n settled: boolean;\n};\n\nexport const exportDocuments = async (config: Omit<DocumentConfig, 'request'> & { paths: readonly string[] }): Promise<ExportedDocument[]> => {\n const { paths, ...rest } = config;\n const out: ExportedDocument[] = [];\n for (const path of paths) {\n const page = await renderDocument({ ...rest, request: { path, cookie: null } });\n out.push({\n path,\n html: page.html,\n ...(page.page !== undefined ? { page: page.page } : {}),\n ...(page.head !== undefined ? { head: page.head } : {}),\n drawn: page.drawn,\n // undrawn is not concluded finished\n live: page.live ?? true,\n why: page.why ?? (page.drawn ? [] : ['the page could not be drawn']),\n drawnWith: page.drawnWith ?? [],\n settled: page.settled ?? false,\n });\n }\n return out;\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';\nimport { DEFAULT_TOKEN_KEY, isOwnOrigin, newSeal, openSealed, sealCookie, sealOf, sealSession, sessionCookies, sessionTokenOf } from './session-cookie';\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, and what the request that opened the connection offered;\n// 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 // The upgrade request, as far as it says who is asking: the subprotocols it\n // offered (`Sec-WebSocket-Protocol`, split), and — for a browser's session\n // (session-cookie.ts) — where the page is, where the request was addressed,\n // and the cookies it carried. A transport that leaves this out serves every\n // terminal as nobody.\n //\n // `answer`: a transport that has NOT answered the request yet says so by\n // giving this, and is told — once who is asking is decided, before the\n // connection is used at all — the `Set-Cookie` values its answer is to\n // carry: the one moment a cookie can be written. It answers when the\n // connection is first used.\n // Without it nothing is written, and a browser's terminal goes on holding\n // its own token.\n upgrade?: {\n offered: readonly string[];\n origin?: string | null;\n host?: string | null;\n cookie?: string | null;\n answer?: (cookies: readonly string[]) => void;\n };\n // Set here, not by a transport: how this connection's terminal is handed a\n // session when its browser holds a seal (session-cookie.ts) — sealed, so the\n // page carries it to the next upgrade and cannot open it. Absent, a session\n // is handed over as its token.\n seal?: (token: string) => Promise<string>;\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 // A sign-in: the terminal comes back as that principal. As the token, for a\n // terminal that keeps its own; SEALED, for one whose browser keeps the\n // session — it offers it on its next upgrade, where its browser's seal opens it.\n | { type: 'session'; token: string }\n | { type: 'session'; sealed: 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` — known\n// before the first frame is sent); one that says nothing speaks 1, which is\n// every terminal built before the question existed. Outside the range the\n// 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.\n//\n// 2: the token left the address. A terminal at 1 put it in `?token=`, and an\n// address is what every proxy on the way writes into its log. A server that\n// went on reading it there would keep that open for as long as anything used\n// it, so 1 is no longer spoken: a terminal built before is told to reload.\nexport const PROTOCOL = 2;\nexport const PROTOCOL_MIN = 2;\n\n// WHO A TERMINAL IS rides the upgrade request, in the one header every host\n// lets a terminal set, a browser included: the subprotocols it offers. It\n// offers `nisc`, and beside it its token when it holds one — base64url,\n// because a subprotocol is an HTTP token and a session token need not be. The\n// server answers `nisc`, never the other. Decided on the request, so no\n// connection is ever open and waiting to be told who it is.\nexport const SUBPROTOCOL = 'nisc';\nconst TOKEN_OFFER = 'nisc.token.';\nconst SEALED_OFFER = 'nisc.sealed.';\n\n// `sealed`: a sign-in the terminal was handed sealed, offered back as it is.\nexport const offerToken = (token: string | null, sealed: string | null = null): string[] => {\n const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];\n if (token === null) return offer;\n const bytes = String.fromCharCode(...new TextEncoder().encode(token));\n return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')}`];\n};\n\nexport const offeredToken = (offered: readonly string[] = []): string | null => {\n const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));\n if (offer === undefined) return null;\n try {\n const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, '+').replace(/_/g, '/'));\n return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;\n } catch {\n return null;\n }\n};\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 // Origins that are this app's own page beside the host a request is\n // addressed to (`runtime.origins`) — a proxy that rewrites `Host`.\n origins?: readonly string[];\n // How much longer a token resolves, when the credential knows — how long a\n // browser is told to keep the cookie that carries it. Unknown: until the\n // browser closes.\n sessionLastsMs?: (token: string) => number | null | Promise<number | null>;\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 let saidNotOwn = false;\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 upgrade = connection.upgrade;\n // THE APP'S OWN PAGE does not hold its session: its browser does, in a\n // cookie the page cannot read (session-cookie.ts), and sent it with this\n // request. From any other origin the cookie is not looked at — a browser\n // sends it with a stranger's page all the same. `key` is which of the\n // browser's sessions this terminal is (a seat); a name, not a secret.\n const key = /^[\\w.-]{1,64}$/.test(params.get('key') ?? '') ? (params.get('key') as string) : DEFAULT_TOKEN_KEY;\n const page = upgrade !== undefined && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : undefined;\n const secure = page?.protocol === 'https:';\n const held = page === undefined ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);\n // A SIGN-IN OVER THE SOCKET REACHES THAT COOKIE SEALED. A terminal whose\n // browser can keep a session says so (`sealed=1`), and its browser is given\n // a seal — a key in a second cookie no script can read — by the answer to\n // its first upgrade. A sign-in is then handed to the page sealed with it;\n // the page offers it back here, and only this browser's seal opens it.\n const sealing = page !== undefined && params.get('sealed') === '1';\n // A browser terminal that is not on the app's own page works as it always\n // did, holding its own token — which is right for a page served from\n // somewhere else, and is what a proxy that rewrites `Host` looks like too.\n // Said once: nothing else would tell a deployment it is in the second case.\n if (page === undefined && params.get('sealed') === '1' && typeof upgrade?.origin === 'string' && !saidNotOwn) {\n saidNotOwn = true;\n console.warn(`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? 'nothing'}, so that is not the app’s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`);\n }\n const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;\n const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;\n // A sealed sign-in that came back with no seal to open it: this browser\n // does not keep the cookie, and is not handed another sign-in that way.\n const sealLost = sealing && sealedOffer !== null && hadSeal === null;\n const seal = !sealing || sealLost ? null : (hadSeal ?? (upgrade?.answer === undefined ? null : newSeal()));\n const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));\n // A token the terminal offers comes first. `leave`: it was signed out, and\n // says so because what its browser holds may be a token that still\n // resolves — an app's own provider's is not moss's to revoke.\n let token = offered ?? (params.get('leave') === '1' ? null : (held?.token ?? null));\n let principal = token === null ? null : await ctx.session(token);\n if (offered !== null && 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 // What the browser held and no longer resolves is nobody — not a refusal:\n // the page cannot read it to drop it, so a 4401 would be one it could\n // never stop getting.\n if (principal === null) token = null;\n // THE ANSWER makes the browser hold who this turned out to be. A token the\n // page offered — left in storage by an earlier build, or just handed to it\n // at sign-in — is moved into the cookie, and that was the last time the\n // page held it; a session that ended is taken back. An offered token is\n // written even when the browser sent the same one: over plain http on the\n // default port the copy an earlier build kept, readable by script, has\n // this cookie's name.\n const answered = [\n ...(page === undefined || (offered === null && (held?.token ?? null) === token) ? [] : token === null ? (held?.clear ?? []) : sessionCookies(page.origin, token, { key, lastsMs: (await ctx.sessionLastsMs?.(token)) ?? null })),\n ...(seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, 'http://nisc.local').pathname })] : []),\n ];\n if (answered.length > 0) upgrade?.answer?.(answered);\n if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);\n // The terminal is told, and stops asking to be handed sign-ins sealed —\n // the next one reaches it as a token, on this connection already.\n if (sealLost) {\n send({ type: 'error', code: 'seal_not_kept', message: 'This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token.' });\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","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 { WebSocket as ServerSocket } 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 { SUBPROTOCOL } from './socket';\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 LARGEST MESSAGE A CONNECTION MAY SEND, in bytes, unless the host says\n// otherwise (`options.maxMessageBytes`). Told nothing, `ws` takes 100 MiB — and\n// what a terminal sends is an event: a press, a typed value, one row handed\n// back. A few KB. Whatever a message carries, the server then keeps (the value\n// in the shell, and again in the last frame it sent) and sends back down in\n// every later frame of that canvas, so this is what ONE connection, signed in\n// or not, can make the process hold and re-send: about 1.5 MB at this limit,\n// 48 MB for a 16 MiB value. Compression is no bound — 64 MB of one letter is\n// 60 KB on the wire — so the count is of the message once inflated. A message\n// over it closes that connection with 1009, and nothing else.\nconst MAX_MESSAGE_BYTES = 256 * 1024;\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>; maxMessageBytes?: number },\n): void => {\n const wss = new WebSocketServer({\n noServer: true,\n perMessageDeflate: options?.compression ?? true,\n maxPayload: options?.maxMessageBytes ?? MAX_MESSAGE_BYTES,\n // Of what a terminal offers, `nisc` is answered and nothing else: the\n // other entry is its token (socket.ts), which is not said back.\n handleProtocols: (offered) => (offered.has(SUBPROTOCOL) ? SUBPROTOCOL : false),\n });\n // The cookies moss answers an upgrade with ride the 101 itself.\n const answers = new WeakMap<IncomingMessage, readonly string[]>();\n wss.on('headers', (headers, req) => {\n for (const cookie of answers.get(req) ?? []) headers.push(`Set-Cookie: ${cookie}`);\n });\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 // THE REQUEST IS ANSWERED ONCE MOSS HAS DECIDED WHO IS ASKING, because the\n // answer is the one thing that can write a browser's session cookie\n // (session-cookie.ts). Until then the raw socket is nobody's to listen to,\n // and a peer that resets it would be an 'error' thrown out of Node — the\n // whole process. Heard here, it is that request's alone.\n socket.on('error', () => {});\n let ws: ServerSocket | undefined;\n let answered = false;\n // The first use of the connection answers the request, with the cookies\n // moss has named by then — which is as soon as it has decided who is\n // asking, or is refusing the terminal outright. A request `ws` will not\n // upgrade (a bad key, a peer already gone) leaves no websocket: nothing is\n // sent to it, and it is closed already.\n let cookies: readonly string[] = [];\n const answer = (): ServerSocket | undefined => {\n if (answered) return ws;\n answered = true;\n answers.set(req, cookies);\n wss.handleUpgrade(req, socket, head, (opened) => {\n ws = opened;\n // `ws` reports what it refuses from a client — a malformed frame, a\n // message over its size limit — as an 'error' on that connection, having\n // already closed it with the status that says why (1002, 1009). An\n // 'error' nobody listens for is thrown by Node, out of the socket's own\n // data handler where nothing can catch it: one bad frame from one\n // client took the process, and every session on it, down. Heard here it\n // is that connection's alone, and the close it already got is the answer.\n opened.on('error', (error) => {\n console.warn(`[moss/node] a connection was closed on what it sent: ${error.message}`);\n });\n });\n return ws;\n };\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) => void answer()?.send(text),\n close: (code, reason) => void answer()?.close(code, reason),\n onMessage: (fn) => void answer()?.on('message', (data) => fn(String(data))),\n onClose: (fn) => {\n const opened = answer();\n if (opened === undefined) queueMicrotask(fn);\n else opened.on('close', () => fn());\n },\n upgrade: {\n offered: String(req.headers['sec-websocket-protocol'] ?? '').split(',').map((entry) => entry.trim()),\n origin: req.headers.origin ?? null,\n host: req.headers.host ?? null,\n cookie: req.headers.cookie ?? null,\n answer: (given) => void (cookies = given),\n },\n }).catch((error: unknown) => {\n console.error('[moss/node] a connection escaped accept:', error);\n try {\n answer()?.close(1011, 'accept failed');\n } catch {\n // already gone\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, host: c.req.header('host') ?? 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","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/node/vite.ts"],"names":["BlockList","isIPv4","isIPv6","path","sessionCookies","readFile","resolve","renderDocument","MOSS_PATHS","getRequestListener","createTransport","listenForUpgrades"],"mappings":";;;;;;;;;;;;AAgCA,IAAM,aAAA,GAAgB,yEAAA;AACtB,IAAM,kBAAA,GAAqB,GAAA;AAE3B,IAAM,WAAW,MAAiB;AAChC,EAAA,MAAM,SAAA,GAAY,IAAIA,aAAA,EAAU;AAChC,EAAA,SAAA,CAAU,SAAA,CAAU,WAAA,EAAa,CAAA,EAAG,MAAM,CAAA;AAC1C,EAAA,SAAA,CAAU,UAAA,CAAW,OAAO,MAAM,CAAA;AAClC,EAAA,OAAO,S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E/E,IAAA,IAAA,CAAK,WAAA,CAAY,IAAI,aAAA,CAAc,IAAA,EAAM,SAAS,KAAA,EAAO,MAAM,OAAO,CAAC,CAAA;AAAA,EACzE;AACF,CAAA","file":"vite.cjs","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { BlockList, isIPv4, isIPv6 } from 'node:net';\nimport { resolve } from 'node:path';\nimport type { Connect, Plugin, ViteDevServer } from 'vite';\nimport { getRequestListener } from '@hono/node-server';\nimport { renderDocument } from '../documents';\nimport type { DocumentConfig } from '../documents';\nimport { sessionCookies } from '../identity';\nimport type { MossServer } from '../server';\nimport { MOSS_PATHS } from './index';\nimport { createTransport, listenForUpgrades } from './transport';\nimport type { Transport } from './transport';\n\nexport type DevApp = {\n server: MossServer;\n close?: () => void | Promise<void>;\n draw?: DocumentConfig['draw'];\n htmlAttributes?: DocumentConfig['htmlAttributes'];\n site?: DocumentConfig['site'];\n tokenKey?: string;\n signIn?: (who: string) => string | null | Promise<string | null>;\n};\n\nexport type MossDevOptions = {\n app: (load: (id: string) => Promise<Record<string, unknown>>) => Promise<DevApp>;\n watch?: RegExp;\n index?: string;\n owned?: RegExp;\n label?: string;\n signInFromNetwork?: boolean;\n};\n\nconst DEFAULT_WATCH = /([\\\\/]src[\\\\/](app|server|db|ui)[\\\\/])|([\\\\/]nisc\\.config\\.[cm]?[jt]s$)/;\nconst REBOOT_DEBOUNCE_MS = 200;\n\nconst loopback = (): BlockList => {\n const addresses = new BlockList();\n addresses.addSubnet('127.0.0.0', 8, 'ipv4');\n addresses.addAddress('::1', 'ipv6');\n return addresses;\n};\nconst LOOPBACK = loopback();\n\n// By the socket's address alone: `X-Forwarded-For` is written by whoever sent\n// the request. `BlockList` holds an IPv4-mapped IPv6 address\n// (`::ffff:127.0.0.1`) to the IPv4 rule.\nconst isFromThisMachine = (address: string | undefined): boolean =>\n address !== undefined && (isIPv4(address) ? LOOPBACK.check(address, 'ipv4') : isIPv6(address) && LOOPBACK.check(address, 'ipv6'));\n\nconst signInRefusal = (req: Connect.IncomingMessage, fromNetwork: boolean): string | undefined => {\n if (!fromNetwork && !isFromThisMachine(req.socket.remoteAddress)) {\n return (\n `The dev sign-in (/dev/as/…) answers requests from this machine only, and this one came from ${req.socket.remoteAddress ?? 'an address the server cannot see'}. ` +\n 'It hands out a session for whoever the address names. To sign in from another device, set `signInFromNetwork: true` on mossDev: anybody who can reach this dev server then signs in as anybody.'\n );\n }\n return undefined;\n};\n\ntype Booted = { app: DevApp; listener: ReturnType<typeof getRequestListener>; transport?: Transport };\n\nconst retire = async (booted: Booted): Promise<void> => {\n booted.transport?.close();\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\nconst devMiddleware =\n (vite: ViteDevServer, options: MossDevOptions, owned: RegExp, current: () => Promise<Booted>): Connect.NextHandleFunction =>\n (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 refusal = signInRefusal(req, options.signInFromNetwork === true);\n if (refusal !== undefined) {\n res.statusCode = 403;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(refusal);\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 = 'encrypted' in req.socket && req.socket.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.\n .catch(() => next());\n };\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 httpServer = vite.httpServer;\n const boot = async (): Promise<Booted> => {\n const app = await options.app(load);\n return { app, listener: getRequestListener(app.server.fetch), ...(httpServer !== null ? { transport: createTransport(app.server.socket) } : {}) };\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 (httpServer !== null) {\n listenForUpgrades(httpServer, '/socket', (req, socket, head) => {\n void current.then(\n ({ transport }) => transport?.upgrade(req, socket, head),\n () => socket.end('HTTP/1.1 503 Service Unavailable\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n'),\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 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(devMiddleware(vite, options, owned, () => current));\n },\n});\n"]}
|
package/dist/vite.d.cts
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import { Plugin } from 'vite';
|
|
2
|
-
import {
|
|
3
|
-
import '
|
|
2
|
+
import { M as MossServer, D as DocumentConfig } from './document-CU3muGbz.cjs';
|
|
3
|
+
import 'hono';
|
|
4
|
+
import '@niscorp/charter';
|
|
4
5
|
import '@niscorp/nova';
|
|
5
6
|
import '@niscorp/vex';
|
|
6
|
-
import '
|
|
7
|
-
import '@niscorp/
|
|
8
|
-
import 'zod';
|
|
9
|
-
import '@niscorp/charter';
|
|
10
|
-
import '@niscorp/nova/i18n';
|
|
11
|
-
import 'hono';
|
|
7
|
+
import './socket-D90h1xSV.cjs';
|
|
8
|
+
import '@niscorp/nova/document';
|
|
12
9
|
|
|
13
10
|
type DevApp = {
|
|
14
11
|
server: MossServer;
|
|
@@ -25,6 +22,7 @@ type MossDevOptions = {
|
|
|
25
22
|
index?: string;
|
|
26
23
|
owned?: RegExp;
|
|
27
24
|
label?: string;
|
|
25
|
+
signInFromNetwork?: boolean;
|
|
28
26
|
};
|
|
29
27
|
declare const mossDev: (options: MossDevOptions) => Plugin;
|
|
30
28
|
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import { Plugin } from 'vite';
|
|
2
|
-
import {
|
|
3
|
-
import '
|
|
2
|
+
import { M as MossServer, D as DocumentConfig } from './document-UFbAd-Ka.js';
|
|
3
|
+
import 'hono';
|
|
4
|
+
import '@niscorp/charter';
|
|
4
5
|
import '@niscorp/nova';
|
|
5
6
|
import '@niscorp/vex';
|
|
6
|
-
import '
|
|
7
|
-
import '@niscorp/
|
|
8
|
-
import 'zod';
|
|
9
|
-
import '@niscorp/charter';
|
|
10
|
-
import '@niscorp/nova/i18n';
|
|
11
|
-
import 'hono';
|
|
7
|
+
import './socket-D90h1xSV.js';
|
|
8
|
+
import '@niscorp/nova/document';
|
|
12
9
|
|
|
13
10
|
type DevApp = {
|
|
14
11
|
server: MossServer;
|
|
@@ -25,6 +22,7 @@ type MossDevOptions = {
|
|
|
25
22
|
index?: string;
|
|
26
23
|
owned?: RegExp;
|
|
27
24
|
label?: string;
|
|
25
|
+
signInFromNetwork?: boolean;
|
|
28
26
|
};
|
|
29
27
|
declare const mossDev: (options: MossDevOptions) => Plugin;
|
|
30
28
|
|
package/dist/vite.js
CHANGED
|
@@ -1,17 +1,101 @@
|
|
|
1
|
-
import { MOSS_PATHS,
|
|
2
|
-
import { renderDocument } from './chunk-
|
|
3
|
-
import
|
|
1
|
+
import { MOSS_PATHS, listenForUpgrades, createTransport } from './chunk-FTZ6NFKZ.js';
|
|
2
|
+
import { sessionCookies, renderDocument } from './chunk-BQRPR2F7.js';
|
|
3
|
+
import './chunk-ZWB6QDGF.js';
|
|
4
|
+
import './chunk-PCPQMC7A.js';
|
|
5
|
+
import './chunk-4ZGAFZGS.js';
|
|
4
6
|
import { readFile } from 'fs/promises';
|
|
7
|
+
import { BlockList, isIPv4, isIPv6 } from 'net';
|
|
5
8
|
import { resolve } from 'path';
|
|
6
9
|
import { getRequestListener } from '@hono/node-server';
|
|
7
10
|
|
|
8
11
|
var DEFAULT_WATCH = /([\\/]src[\\/](app|server|db|ui)[\\/])|([\\/]nisc\.config\.[cm]?[jt]s$)/;
|
|
9
12
|
var REBOOT_DEBOUNCE_MS = 200;
|
|
13
|
+
var loopback = () => {
|
|
14
|
+
const addresses = new BlockList();
|
|
15
|
+
addresses.addSubnet("127.0.0.0", 8, "ipv4");
|
|
16
|
+
addresses.addAddress("::1", "ipv6");
|
|
17
|
+
return addresses;
|
|
18
|
+
};
|
|
19
|
+
var LOOPBACK = loopback();
|
|
20
|
+
var isFromThisMachine = (address) => address !== void 0 && (isIPv4(address) ? LOOPBACK.check(address, "ipv4") : isIPv6(address) && LOOPBACK.check(address, "ipv6"));
|
|
21
|
+
var signInRefusal = (req, fromNetwork) => {
|
|
22
|
+
if (!fromNetwork && !isFromThisMachine(req.socket.remoteAddress)) {
|
|
23
|
+
return `The dev sign-in (/dev/as/\u2026) answers requests from this machine only, and this one came from ${req.socket.remoteAddress ?? "an address the server cannot see"}. It hands out a session for whoever the address names. To sign in from another device, set \`signInFromNetwork: true\` on mossDev: anybody who can reach this dev server then signs in as anybody.`;
|
|
24
|
+
}
|
|
25
|
+
return void 0;
|
|
26
|
+
};
|
|
10
27
|
var retire = async (booted) => {
|
|
28
|
+
booted.transport?.close();
|
|
11
29
|
booted.app.server.socket.stop();
|
|
12
30
|
await (booted.app.close ?? (() => booted.app.server.close()))();
|
|
13
31
|
};
|
|
14
32
|
var said = (error) => error instanceof Error ? error.message : String(error);
|
|
33
|
+
var devMiddleware = (vite, options, owned, current) => (req, res, next) => {
|
|
34
|
+
const url = req.url ?? "/";
|
|
35
|
+
const path = url.split("?")[0] ?? "/";
|
|
36
|
+
const who = /^\/dev\/as\/([\w.@%-]+)$/.exec(path)?.[1];
|
|
37
|
+
if (who !== void 0) {
|
|
38
|
+
void current().then(async ({ app }) => {
|
|
39
|
+
if (app.signIn === void 0) {
|
|
40
|
+
next();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const refusal = signInRefusal(req, options.signInFromNetwork === true);
|
|
44
|
+
if (refusal !== void 0) {
|
|
45
|
+
res.statusCode = 403;
|
|
46
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
47
|
+
res.end(refusal);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const token = await app.signIn(decodeURIComponent(who));
|
|
51
|
+
if (token === null) {
|
|
52
|
+
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
53
|
+
res.end(`<p>nobody called ${who.replace(/[<&"]/g, "")}</p>`);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const scheme = "encrypted" in req.socket && req.socket.encrypted === true ? "https" : "http";
|
|
57
|
+
res.statusCode = 302;
|
|
58
|
+
res.setHeader("set-cookie", sessionCookies(`${scheme}://${req.headers.host ?? "localhost"}`, token, app.tokenKey !== void 0 ? { key: app.tokenKey } : {}));
|
|
59
|
+
res.setHeader("location", "/");
|
|
60
|
+
res.end();
|
|
61
|
+
}).catch(() => {
|
|
62
|
+
res.statusCode = 500;
|
|
63
|
+
res.end("the dev sign-in failed");
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (owned.test(path)) {
|
|
68
|
+
void current().then(({ listener }) => listener(req, res)).catch(() => {
|
|
69
|
+
res.statusCode = 503;
|
|
70
|
+
res.end("the app server did not boot \u2014 see the dev server\u2019s log");
|
|
71
|
+
});
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (req.method !== "GET") {
|
|
75
|
+
next();
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
void current().then(async ({ app }) => {
|
|
79
|
+
if (app.draw === void 0 || path !== "/" && path !== "/index.html" && app.server.page(path) === void 0) {
|
|
80
|
+
next();
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const template = await vite.transformIndexHtml(url, await readFile(resolve(vite.config.root, options.index ?? "index.html"), "utf8"));
|
|
84
|
+
const page = await renderDocument({
|
|
85
|
+
server: app.server,
|
|
86
|
+
template,
|
|
87
|
+
request: { path: path === "/index.html" ? "/" : path, cookie: req.headers.cookie ?? null, host: req.headers.host ?? null },
|
|
88
|
+
draw: app.draw,
|
|
89
|
+
...app.htmlAttributes !== void 0 ? { htmlAttributes: app.htmlAttributes } : {},
|
|
90
|
+
...app.site !== void 0 ? { site: app.site } : {},
|
|
91
|
+
...app.tokenKey !== void 0 ? { tokenKey: app.tokenKey } : {}
|
|
92
|
+
});
|
|
93
|
+
res.statusCode = 200;
|
|
94
|
+
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
95
|
+
for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
|
|
96
|
+
res.end(page.html);
|
|
97
|
+
}).catch(() => next());
|
|
98
|
+
};
|
|
15
99
|
var mossDev = (options) => ({
|
|
16
100
|
name: "moss-dev",
|
|
17
101
|
apply: "serve",
|
|
@@ -20,20 +104,20 @@ var mossDev = (options) => ({
|
|
|
20
104
|
const watch = options.watch ?? DEFAULT_WATCH;
|
|
21
105
|
const owned = options.owned ?? MOSS_PATHS;
|
|
22
106
|
const load = (id) => vite.ssrLoadModule(id);
|
|
107
|
+
const httpServer = vite.httpServer;
|
|
23
108
|
const boot = async () => {
|
|
24
109
|
const app = await options.app(load);
|
|
25
|
-
return { app, listener: getRequestListener(app.server.fetch) };
|
|
110
|
+
return { app, listener: getRequestListener(app.server.fetch), ...httpServer !== null ? { transport: createTransport(app.server.socket) } : {} };
|
|
26
111
|
};
|
|
27
112
|
let current = boot();
|
|
28
113
|
current.catch((error) => vite.config.logger.error(`[${label}] the app did not boot: ${said(error)}`, { timestamp: true }));
|
|
29
|
-
if (
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
);
|
|
114
|
+
if (httpServer !== null) {
|
|
115
|
+
listenForUpgrades(httpServer, "/socket", (req, socket, head) => {
|
|
116
|
+
void current.then(
|
|
117
|
+
({ transport }) => transport?.upgrade(req, socket, head),
|
|
118
|
+
() => socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n")
|
|
119
|
+
);
|
|
120
|
+
});
|
|
37
121
|
}
|
|
38
122
|
let timer;
|
|
39
123
|
const reboot = (file) => {
|
|
@@ -59,65 +143,7 @@ var mossDev = (options) => ({
|
|
|
59
143
|
vite.watcher.on("add", reboot);
|
|
60
144
|
vite.watcher.on("unlink", reboot);
|
|
61
145
|
vite.httpServer?.once("close", () => void current.then(retire, () => void 0));
|
|
62
|
-
vite.middlewares.use((
|
|
63
|
-
const url = req.url ?? "/";
|
|
64
|
-
const path = url.split("?")[0] ?? "/";
|
|
65
|
-
const who = /^\/dev\/as\/([\w.@%-]+)$/.exec(path)?.[1];
|
|
66
|
-
if (who !== void 0) {
|
|
67
|
-
void current.then(async ({ app }) => {
|
|
68
|
-
if (app.signIn === void 0) {
|
|
69
|
-
next();
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
const token = await app.signIn(decodeURIComponent(who));
|
|
73
|
-
if (token === null) {
|
|
74
|
-
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
75
|
-
res.end(`<p>nobody called ${who.replace(/[<&"]/g, "")}</p>`);
|
|
76
|
-
return;
|
|
77
|
-
}
|
|
78
|
-
const scheme = req.socket.encrypted === true ? "https" : "http";
|
|
79
|
-
res.statusCode = 302;
|
|
80
|
-
res.setHeader("set-cookie", sessionCookies(`${scheme}://${req.headers.host ?? "localhost"}`, token, app.tokenKey !== void 0 ? { key: app.tokenKey } : {}));
|
|
81
|
-
res.setHeader("location", "/");
|
|
82
|
-
res.end();
|
|
83
|
-
}).catch(() => {
|
|
84
|
-
res.statusCode = 500;
|
|
85
|
-
res.end("the dev sign-in failed");
|
|
86
|
-
});
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
if (owned.test(path)) {
|
|
90
|
-
void current.then(({ listener }) => listener(req, res)).catch(() => {
|
|
91
|
-
res.statusCode = 503;
|
|
92
|
-
res.end("the app server did not boot \u2014 see the dev server\u2019s log");
|
|
93
|
-
});
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
if (req.method !== "GET") {
|
|
97
|
-
next();
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
void current.then(async ({ app }) => {
|
|
101
|
-
if (app.draw === void 0 || path !== "/" && path !== "/index.html" && app.server.page(path) === void 0) {
|
|
102
|
-
next();
|
|
103
|
-
return;
|
|
104
|
-
}
|
|
105
|
-
const template = await vite.transformIndexHtml(url, await readFile(resolve(vite.config.root, options.index ?? "index.html"), "utf8"));
|
|
106
|
-
const page = await renderDocument({
|
|
107
|
-
server: app.server,
|
|
108
|
-
template,
|
|
109
|
-
request: { path: path === "/index.html" ? "/" : path, cookie: req.headers.cookie ?? null, host: req.headers.host ?? null },
|
|
110
|
-
draw: app.draw,
|
|
111
|
-
...app.htmlAttributes !== void 0 ? { htmlAttributes: app.htmlAttributes } : {},
|
|
112
|
-
...app.site !== void 0 ? { site: app.site } : {},
|
|
113
|
-
...app.tokenKey !== void 0 ? { tokenKey: app.tokenKey } : {}
|
|
114
|
-
});
|
|
115
|
-
res.statusCode = 200;
|
|
116
|
-
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
117
|
-
for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
|
|
118
|
-
res.end(page.html);
|
|
119
|
-
}).catch(() => next());
|
|
120
|
-
});
|
|
146
|
+
vite.middlewares.use(devMiddleware(vite, options, owned, () => current));
|
|
121
147
|
}
|
|
122
148
|
});
|
|
123
149
|
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,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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"]}
|
|
1
|
+
{"version":3,"sources":["../src/node/vite.ts"],"names":[],"mappings":";;;;;;;;;;AAgCA,IAAM,aAAA,GAAgB,yEAAA;AACtB,IAAM,kBAAA,GAAqB,GAAA;AAE3B,IAAM,WAAW,MAAiB;AAChC,EAAA,MAAM,SAAA,GAAY,IAAI,SAAA,EAAU;AAChC,EAAA,SAAA,CAAU,SAAA,CAAU,WAAA,EAAa,CAAA,EAAG,MAAM,CAAA;AAC1C,EAAA,SAAA,CAAU,UAAA,CAAW,OAAO,MAAM,CAAA;AAClC,EAAA,OAAO,SAAA;AACT,CAAA;AACA,IAAM,WAAW,QAAA,EAAS;AAK1B,IAAM,oBAAoB,CAAC,OAAA,KACzB,YAAY,MAAA,KAAc,MAAA,CAAO,OAAO,CAAA,GAAI,QAAA,CAAS,MAAM,OAAA,EAAS,MAAM,IAAI,MAAA,CAAO,OAAO,KAAK,QAAA,CAAS,KAAA,CAAM,SAAS,MAAM,CAAA,CAAA;AAEjI,I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AA,CAAS,IAAA,CAAK,MAAA,EAAQ,MAAM,MAAS,CAAA;AAC1C,YAAA,IAAA,CAAK,MAAA,CAAO,OAAO,IAAA,CAAK,CAAA,CAAA,EAAI,KAAK,CAAA,sBAAA,CAAA,EAA0B,EAAE,SAAA,EAAW,IAAA,EAAM,CAAA;AAC9E,YAAA,IAAA,CAAK,EAAA,CAAG,IAAA,CAAK,EAAE,IAAA,EAAM,eAAe,CAAA;AAAA,UACtC,CAAA;AAAA,UACA,CAAC,KAAA,KAAmB;AAClB,YAAA,OAAA,GAAU,QAAA;AACV,YAAA,IAAA,CAAK,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,CAAA,CAAA,EAAI,KAAK,CAAA,kBAAA,EAAqB,IAAA,CAAK,KAAK,CAAC,CAAA,CAAA,EAAI,EAAE,SAAA,EAAW,MAAM,CAAA;AAAA,UAC3F;AAAA,SACF;AAAA,MACF,GAAG,kBAAkB,CAAA;AAAA,IACvB,CAAA;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,EAAA,CAAG,QAAA,EAAU,MAAM,CAAA;AAChC,IAAA,IAAA,CAAK,OAAA,CAAQ,EAAA,CAAG,KAAA,EAAO,MAAM,CAAA;AAC7B,IAAA,IAAA,CAAK,OAAA,CAAQ,EAAA,CAAG,QAAA,EAAU,MAAM,CAAA;AAChC,IAAA,IAAA,CAAK,UAAA,EAAY,IAAA,CAAK,OAAA,EAAS,MAAM,KAAK,QAAQ,IAAA,CAAK,MAAA,EAAQ,MAAM,MAAS,CAAC,CAAA;AAE/E,IAAA,IAAA,CAAK,WAAA,CAAY,IAAI,aAAA,CAAc,IAAA,EAAM,SAAS,KAAA,EAAO,MAAM,OAAO,CAAC,CAAA;AAAA,EACzE;AACF,CAAA","file":"vite.js","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { BlockList, isIPv4, isIPv6 } from 'node:net';\nimport { resolve } from 'node:path';\nimport type { Connect, Plugin, ViteDevServer } from 'vite';\nimport { getRequestListener } from '@hono/node-server';\nimport { renderDocument } from '../documents';\nimport type { DocumentConfig } from '../documents';\nimport { sessionCookies } from '../identity';\nimport type { MossServer } from '../server';\nimport { MOSS_PATHS } from './index';\nimport { createTransport, listenForUpgrades } from './transport';\nimport type { Transport } from './transport';\n\nexport type DevApp = {\n server: MossServer;\n close?: () => void | Promise<void>;\n draw?: DocumentConfig['draw'];\n htmlAttributes?: DocumentConfig['htmlAttributes'];\n site?: DocumentConfig['site'];\n tokenKey?: string;\n signIn?: (who: string) => string | null | Promise<string | null>;\n};\n\nexport type MossDevOptions = {\n app: (load: (id: string) => Promise<Record<string, unknown>>) => Promise<DevApp>;\n watch?: RegExp;\n index?: string;\n owned?: RegExp;\n label?: string;\n signInFromNetwork?: boolean;\n};\n\nconst DEFAULT_WATCH = /([\\\\/]src[\\\\/](app|server|db|ui)[\\\\/])|([\\\\/]nisc\\.config\\.[cm]?[jt]s$)/;\nconst REBOOT_DEBOUNCE_MS = 200;\n\nconst loopback = (): BlockList => {\n const addresses = new BlockList();\n addresses.addSubnet('127.0.0.0', 8, 'ipv4');\n addresses.addAddress('::1', 'ipv6');\n return addresses;\n};\nconst LOOPBACK = loopback();\n\n// By the socket's address alone: `X-Forwarded-For` is written by whoever sent\n// the request. `BlockList` holds an IPv4-mapped IPv6 address\n// (`::ffff:127.0.0.1`) to the IPv4 rule.\nconst isFromThisMachine = (address: string | undefined): boolean =>\n address !== undefined && (isIPv4(address) ? LOOPBACK.check(address, 'ipv4') : isIPv6(address) && LOOPBACK.check(address, 'ipv6'));\n\nconst signInRefusal = (req: Connect.IncomingMessage, fromNetwork: boolean): string | undefined => {\n if (!fromNetwork && !isFromThisMachine(req.socket.remoteAddress)) {\n return (\n `The dev sign-in (/dev/as/…) answers requests from this machine only, and this one came from ${req.socket.remoteAddress ?? 'an address the server cannot see'}. ` +\n 'It hands out a session for whoever the address names. To sign in from another device, set `signInFromNetwork: true` on mossDev: anybody who can reach this dev server then signs in as anybody.'\n );\n }\n return undefined;\n};\n\ntype Booted = { app: DevApp; listener: ReturnType<typeof getRequestListener>; transport?: Transport };\n\nconst retire = async (booted: Booted): Promise<void> => {\n booted.transport?.close();\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\nconst devMiddleware =\n (vite: ViteDevServer, options: MossDevOptions, owned: RegExp, current: () => Promise<Booted>): Connect.NextHandleFunction =>\n (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 refusal = signInRefusal(req, options.signInFromNetwork === true);\n if (refusal !== undefined) {\n res.statusCode = 403;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(refusal);\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 = 'encrypted' in req.socket && req.socket.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.\n .catch(() => next());\n };\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 httpServer = vite.httpServer;\n const boot = async (): Promise<Booted> => {\n const app = await options.app(load);\n return { app, listener: getRequestListener(app.server.fetch), ...(httpServer !== null ? { transport: createTransport(app.server.socket) } : {}) };\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 (httpServer !== null) {\n listenForUpgrades(httpServer, '/socket', (req, socket, head) => {\n void current.then(\n ({ transport }) => transport?.upgrade(req, socket, head),\n () => socket.end('HTTP/1.1 503 Service Unavailable\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n'),\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 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(devMiddleware(vite, options, owned, () => current));\n },\n});\n"]}
|