@niscorp/moss 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { renderDocument, createServer } from './chunk-AUZMT3GL.js';
1
+ import { renderDocument, createServer } from './chunk-R3QMJ3JF.js';
2
2
  import { SUBPROTOCOL } from './chunk-HOZID4EM.js';
3
3
  import { readFile } from 'fs/promises';
4
4
  import { relative, extname, join } from 'path';
@@ -99,5 +99,5 @@ var serve = async (app, runtime) => {
99
99
  };
100
100
 
101
101
  export { MOSS_PATHS, attachSocket, mountSite, serve };
102
- //# sourceMappingURL=chunk-NE2EXMTO.js.map
103
- //# sourceMappingURL=chunk-NE2EXMTO.js.map
102
+ //# sourceMappingURL=chunk-U3UR5AOQ.js.map
103
+ //# sourceMappingURL=chunk-U3UR5AOQ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/node.ts"],"names":["listen"],"mappings":";;;;;;;;AAwCA,IAAM,oBAAoB,GAAA,GAAM,IAAA;AAMzB,IAAM,eAAe,CAC1B,UAAA,EACA,MAAA,EACA,IAAA,GAAO,WACP,OAAA,KACS;AACT,EAAA,MAAM,GAAA,GAAM,IAAI,eAAA,CAAgB;AAAA,IAC9B,QAAA,EAAU,IAAA;AAAA,IACV,iBAAA,EAAmB,SAAS,WAAA,IAAe,IAAA;AAAA,IAC3C,UAAA,EAAY,SAAS,eAAA,IAAmB,iBAAA;AAAA;AAAA;AAAA,IAGxC,iBAAiB,CAAC,OAAA,KAAa,QAAQ,GAAA,CAAI,WAAW,IAAI,WAAA,GAAc;AAAA,GACzE,CAAA;AAED,EAAA,MAAM,OAAA,uBAAc,OAAA,EAA4C;AAChE,EAAA,GAAA,CAAI,EAAA,CAAG,SAAA,EAAW,CAAC,OAAA,EAAS,GAAA,KAAQ;AAClC,IAAA,KAAA,MAAW,MAAA,IAAU,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA,IAAK,EAA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EAAM,CAAA,CAAE,GAAA,CAAI,SAAS,aAAA,GAAgB,GAAA,GAAM,CAAA,CAAE,GAAA,CAAI,IAAA,EAAM,MAAA,EAAQ,EAAE,GAAA,CAAI,MAAA,CAAO,QAAQ,CAAA,IAAK,IAAA,EAAM,IAAA,EAAM,EAAE,GAAA,CAAI,MAAA,CAAO,MAAM,CAAA,IAAK,IAAA;AAAK,KAC9I,CAAA;AACD,IAAA,OAAO,EAAE,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,GAAA,EAAK,KAAK,OAAO,CAAA;AAAA,EAC5C,CAAC,CAAA;AACH;AAEO,IAAM,KAAA,GAAQ,OAAO,GAAA,EAAc,OAAA,KAAkE;AAC1G,EAAA,MAAM,MAAA,GAAS,MAAM,YAAA,CAAa,GAAA,EAAK,OAAO,CAAA;AAC9C,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,IAAQ,IAAA;AAC7B,EAAA,MAAM,aAAaA,OAAA,CAAO,EAAE,OAAO,MAAA,CAAO,KAAA,EAAO,MAAM,CAAA;AACvD,EAAA,YAAA,CAAa,YAAY,MAAA,CAAO,MAAA,EAAQ,SAAA,EAAW,EAAE,GAAI,OAAA,CAAQ,iBAAA,KAAsB,MAAA,GAAY,EAAE,aAAa,OAAA,CAAQ,iBAAA,EAAkB,GAAI,IAAK,CAAA;AACrJ,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,8BAAA,EAAiC,IAAI,CAAA,CAAE,CAAA;AACnD,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,oGAAA,EAA8F,IAAI,CAAA,OAAA,CAAS,CAAA;AACvH,EAAA,OAAO,MAAA;AACT","file":"chunk-NE2EXMTO.js","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { extname, join, relative } from 'node:path';\nimport { serve as listen } from '@hono/node-server';\nimport { serveStatic } from '@hono/node-server/serve-static';\nimport { WebSocketServer } from 'ws';\nimport type { 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"]}
1
+ {"version":3,"sources":["../src/node.ts"],"names":["listen"],"mappings":";;;;;;;;AAwCA,IAAM,oBAAoB,GAAA,GAAM,IAAA;AAMzB,IAAM,eAAe,CAC1B,UAAA,EACA,MAAA,EACA,IAAA,GAAO,WACP,OAAA,KACS;AACT,EAAA,MAAM,GAAA,GAAM,IAAI,eAAA,CAAgB;AAAA,IAC9B,QAAA,EAAU,IAAA;AAAA,IACV,iBAAA,EAAmB,SAAS,WAAA,IAAe,IAAA;AAAA,IAC3C,UAAA,EAAY,SAAS,eAAA,IAAmB,iBAAA;AAAA;AAAA;AAAA,IAGxC,iBAAiB,CAAC,OAAA,KAAa,QAAQ,GAAA,CAAI,WAAW,IAAI,WAAA,GAAc;AAAA,GACzE,CAAA;AAED,EAAA,MAAM,OAAA,uBAAc,OAAA,EAA4C;AAChE,EAAA,G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import { 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"]}
package/dist/index.cjs CHANGED
@@ -7,15 +7,15 @@ var hono = require('hono');
7
7
  var hono$1 = require('@niscorp/vex/hono');
8
8
  var vex = require('@niscorp/vex');
9
9
  var strata = require('@niscorp/strata');
10
- var migrations$1 = require('@niscorp/nova/migrations');
11
- var migrations = require('@niscorp/prism/migrations');
10
+ var migrations = require('@niscorp/nova/migrations');
11
+ var prism = require('@niscorp/prism');
12
+ var migrations$1 = require('@niscorp/prism/migrations');
12
13
  var charter = require('@niscorp/charter');
13
14
  var nova = require('@niscorp/nova');
14
15
  var zod = require('zod');
15
16
  var reflect = require('@niscorp/nova/reflect');
16
17
  var i18n = require('@niscorp/nova/i18n');
17
18
  var tide = require('@niscorp/tide');
18
- var prism = require('@niscorp/prism');
19
19
  var document = require('@niscorp/nova/document');
20
20
 
21
21
  // src/app.ts
@@ -185,11 +185,11 @@ var createWireFollower = (callSignal) => {
185
185
  return { live, onChange, handedOver, end };
186
186
  };
187
187
  var grammarsOf = (app) => [
188
- migrations$1.NOVA_SEQUENCE,
189
- migrations.PRISM_SEQUENCE,
188
+ migrations.NOVA_SEQUENCE,
189
+ migrations$1.PRISM_SEQUENCE,
190
190
  ...app.grammars ?? []
191
191
  ];
192
- var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform: migrations.prismTransform });
192
+ var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform: prism.evaluate });
193
193
  var auditClosure = (definitions, variants = {}) => {
194
194
  return (grantedIds, layoutIds = []) => {
195
195
  const bindings = /* @__PURE__ */ new Map();
@@ -2314,11 +2314,9 @@ var createShellHost = (ctx) => {
2314
2314
  ...shellManifest.fragments !== void 0 ? { fragments: shellManifest.fragments } : {},
2315
2315
  // The same seam the client shell used: prism evaluates endpoint
2316
2316
  // request/response transforms; `$.userId` and `$.today` are ambient,
2317
- // never authorable by a request.
2318
- transform: (config, source) => prism.evaluate(
2319
- config,
2320
- source !== null && typeof source === "object" && !Array.isArray(source) ? { ...source, userId, today: today() } : source
2321
- ),
2317
+ // never authorable by a request. The config is the action's own object
2318
+ // on every call, so evaluate checks it once (the source is new each time).
2319
+ transform: (config, source) => prism.evaluate(config, source !== null && typeof source === "object" && !Array.isArray(source) ? { ...source, userId, today: today() } : source),
2322
2320
  fetch: wire,
2323
2321
  functions,
2324
2322
  ...ctx.runtime.endpointTimeoutMs === void 0 ? {} : { endpointTimeoutMs: ctx.runtime.endpointTimeoutMs },