@niscorp/nova 0.1.4 → 0.2.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/ADAPTER.md +6 -6
- package/CHANGELOG.md +30 -0
- package/README.md +46 -21
- package/dist/adapters/dom/components/index.d.cts +2 -2
- package/dist/adapters/dom/components/index.d.ts +2 -2
- package/dist/adapters/dom/index.cjs +163 -34
- package/dist/adapters/dom/index.cjs.map +1 -1
- package/dist/adapters/dom/index.d.cts +2 -2
- package/dist/adapters/dom/index.d.ts +2 -2
- package/dist/adapters/dom/index.js +6 -6
- package/dist/adapters/dom/server.cjs +0 -2
- package/dist/adapters/dom/server.cjs.map +1 -1
- package/dist/adapters/dom/server.d.cts +2 -2
- package/dist/adapters/dom/server.d.ts +2 -2
- package/dist/adapters/dom/server.js +6 -6
- package/dist/adapters/react/components/index.cjs +6 -8
- package/dist/adapters/react/components/index.cjs.map +1 -1
- package/dist/adapters/react/components/index.d.cts +4 -4
- package/dist/adapters/react/components/index.d.ts +4 -4
- package/dist/adapters/react/components/index.js +7 -7
- package/dist/adapters/react/index.cjs +181 -51
- package/dist/adapters/react/index.cjs.map +1 -1
- package/dist/adapters/react/index.d.cts +4 -4
- package/dist/adapters/react/index.d.ts +4 -4
- package/dist/adapters/react/index.js +7 -7
- package/dist/adapters/tty/components/index.d.cts +2 -2
- package/dist/adapters/tty/components/index.d.ts +2 -2
- package/dist/adapters/tty/index.cjs +0 -2
- package/dist/adapters/tty/index.cjs.map +1 -1
- package/dist/adapters/tty/index.d.cts +2 -2
- package/dist/adapters/tty/index.d.ts +2 -2
- package/dist/adapters/tty/index.js +4 -4
- package/dist/adapters/tty/index.js.map +1 -1
- package/dist/adapters/vue/components/index.cjs +4 -6
- package/dist/adapters/vue/components/index.cjs.map +1 -1
- package/dist/adapters/vue/components/index.d.cts +9 -9
- package/dist/adapters/vue/components/index.d.ts +9 -9
- package/dist/adapters/vue/components/index.js +7 -7
- package/dist/adapters/vue/index.cjs +175 -46
- package/dist/adapters/vue/index.cjs.map +1 -1
- package/dist/adapters/vue/index.d.cts +4 -4
- package/dist/adapters/vue/index.d.ts +4 -4
- package/dist/adapters/vue/index.js +9 -9
- package/dist/adapters/vue/index.js.map +1 -1
- package/dist/agent/index.d.cts +2 -2
- package/dist/agent/index.d.ts +2 -2
- package/dist/{chunk-7PKS7UYL.js → chunk-3JRTELLC.js} +3 -3
- package/dist/{chunk-7PKS7UYL.js.map → chunk-3JRTELLC.js.map} +1 -1
- package/dist/{chunk-4I2PFMY7.js → chunk-MHW5VEIM.js} +8 -8
- package/dist/chunk-MHW5VEIM.js.map +1 -0
- package/dist/chunk-OE4E6IBD.js +25 -0
- package/dist/chunk-OE4E6IBD.js.map +1 -0
- package/dist/{chunk-KYQ4EAQH.js → chunk-QXQCPH33.js} +17 -17
- package/dist/chunk-QXQCPH33.js.map +1 -0
- package/dist/chunk-RFBIGRCI.js +127 -0
- package/dist/chunk-RFBIGRCI.js.map +1 -0
- package/dist/{chunk-WZVQ5PUB.js → chunk-RYIIIXDX.js} +4 -4
- package/dist/{chunk-WZVQ5PUB.js.map → chunk-RYIIIXDX.js.map} +1 -1
- package/dist/{chunk-4ERQYDF6.js → chunk-UDCXGDLQ.js} +10 -10
- package/dist/chunk-UDCXGDLQ.js.map +1 -0
- package/dist/chunk-V4BPFFFV.js +152 -0
- package/dist/chunk-V4BPFFFV.js.map +1 -0
- package/dist/{chunk-UUYXVOK2.js → chunk-VU6NNCEJ.js} +16 -16
- package/dist/chunk-VU6NNCEJ.js.map +1 -0
- package/dist/{chunk-RXECI7DE.js → chunk-Y6XVPRYH.js} +33 -17
- package/dist/chunk-Y6XVPRYH.js.map +1 -0
- package/dist/devtools/index.d.cts +2 -2
- package/dist/devtools/index.d.ts +2 -2
- package/dist/devtools/index.js +3 -3
- package/dist/document/index.cjs +228 -119
- package/dist/document/index.cjs.map +1 -1
- package/dist/document/index.d.cts +10 -8
- package/dist/document/index.d.ts +10 -8
- package/dist/document/index.js +3 -122
- package/dist/document/index.js.map +1 -1
- package/dist/head-CAzfTnpV.d.cts +25 -0
- package/dist/head-DRpbbj-l.d.ts +25 -0
- package/dist/i18n/index.d.cts +2 -2
- package/dist/i18n/index.d.ts +2 -2
- package/dist/index.cjs +151 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -31
- package/dist/index.d.ts +19 -31
- package/dist/index.js +4 -4
- package/dist/{palette-Mx7XHYC6.d.ts → palette-CIpPH90W.d.ts} +1 -1
- package/dist/{palette-wbJB_svk.d.cts → palette-CvwZZCkx.d.cts} +1 -1
- package/dist/reflect/index.d.cts +2 -2
- package/dist/reflect/index.d.ts +2 -2
- package/dist/reflect/index.js +3 -3
- package/dist/{types-B-rjaUX0.d.ts → types-BSKx5MXW.d.ts} +1 -1
- package/dist/{types-B_nOtkyt.d.ts → types-BWc-olbY.d.ts} +1 -1
- package/dist/{types-mRKXqZPX.d.cts → types-C9734_lJ.d.cts} +1 -1
- package/dist/{types-BB9RXel5.d.ts → types-D23TRvqe.d.ts} +1 -1
- package/dist/{types-uk19d6KC.d.cts → types-DsWNYc7R.d.cts} +1 -1
- package/dist/{types-BLVRduoz.d.cts → types-j290XhCn.d.cts} +1 -1
- package/dist/{types-PDXOkvtK.d.cts → types-qkzTfSye.d.cts} +1 -1
- package/dist/{types-DE77Jl2W.d.ts → types-qnKMx0_V.d.ts} +1 -1
- package/package.json +3 -3
- package/dist/chunk-4ERQYDF6.js.map +0 -1
- package/dist/chunk-4I2PFMY7.js.map +0 -1
- package/dist/chunk-EHHJJLRX.js +0 -16
- package/dist/chunk-EHHJJLRX.js.map +0 -1
- package/dist/chunk-KYQ4EAQH.js.map +0 -1
- package/dist/chunk-RXECI7DE.js.map +0 -1
- package/dist/chunk-UUYXVOK2.js.map +0 -1
- package/dist/chunk-UV5YGBHQ.js +0 -62
- package/dist/chunk-UV5YGBHQ.js.map +0 -1
- package/dist/chunk-X7SSNSQC.js +0 -6
- package/dist/chunk-X7SSNSQC.js.map +0 -1
- package/dist/head-BNj8GwPO.d.cts +0 -20
- package/dist/head-CS6X6ZKr.d.ts +0 -20
- package/dist/{primitive-props-Cl5jiC8g.d.cts → primitive-props-CGoJvmcH.d.cts} +5 -5
- package/dist/{primitive-props-Cl5jiC8g.d.ts → primitive-props-CGoJvmcH.d.ts} +5 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/shared/common.ts","../src/shared/errors.ts","../src/shared/ids.ts","../src/shared/bindings/schemas.ts","../src/shared/bindings/scope.ts","../src/shared/bindings/paths.ts","../src/shared/bindings/resolve.ts","../src/shared/data-store/data-store.ts","../src/shared/event-bus/schemas.ts","../src/shared/event-bus/event-bus.ts","../src/shared/event-bus/scope-dispatch.ts","../src/shared/message-bus/schemas.ts","../src/shared/message-bus/message-bus.ts","../src/layout/schemas.ts","../src/layout/guards.ts","../src/i18n/phrases.ts","../src/i18n/swap.ts","../src/layout/head.ts","../src/layout/renderer.ts","../src/layout/compose.ts","../src/layout/adapter.ts","../src/layout/store.ts","../src/layout/registry.ts","../src/layout/head.schema.ts","../src/agent/palette.ts","../src/action/mutations/ops/set.ts","../src/action/mutations/ops/toggle.ts","../src/action/mutations/ops/increment.ts","../src/action/mutations/ops/decrement.ts","../src/action/mutations/ops/push.ts","../src/action/mutations/ops/pop.ts","../src/action/mutations/ops/remove-at.ts","../src/action/mutations/ops/move.ts","../src/action/mutations/ops/clear.ts","../src/action/mutations/ops/reset.ts","../src/action/mutations/ops/index.ts","../src/action/mutations/registry.ts","../src/action/schemas/endpoints.ts","../src/action/schemas/effects.ts","../src/action/schemas/lifecycle.ts","../src/action/schemas/triggers.ts","../src/action/schemas/index.ts","../src/action/compose.ts","../src/agent/affordances.ts","../src/action/grammar.ts","../src/action/audit.ts","../src/action/runtime/endpoints.ts","../src/action/runtime/cause.ts","../src/action/runtime/next-task.ts","../src/action/runtime/steps.ts","../src/action/runtime/lifecycle.ts","../src/action/runtime/model-bindings.ts","../src/action/runtime/render.ts","../src/action/runtime/triggers.ts","../src/action/runtime/runtime.ts","../src/shell/shell-internals.ts","../src/shell/canvas.ts","../src/shell/slot-names.ts","../src/shell/default-layouts.ts","../src/shell/flatten-render-tree.ts","../src/reflect/grammar.ts","../src/shell/reconcile.ts","../src/shell/journal.ts","../src/shell/lifecycle-ops.ts","../src/shell/navigation.ts","../src/shell/runtime-registry.ts","../src/shell/telemetry.ts","../src/shell/shell.ts","../src/shell/head.ts","../src/shell/view.ts"],"names":["z","segments","evaluateSafe","exceedsDepth","depthRefusal","next","walk","noopOnError","isLayoutNode","render","fragment","isObject","resolve"],"mappings":";;;;;;;AAOO,IAAM,QAAA,GAAW,CAAC,KAAA,KACvB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAQ9D,IAAM,OAAA,GAAU,CAAC,KAAA,KAAuC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAK3E,IAAM,SAAS,CACpB,GAAA,EACA,QAC8B,QAAA,CAAS,GAAG,KAAK,GAAA,IAAO,GAAA;;;AClBjD,IAAM,UAAA,GAAa;AAAA,EACxB,MAAA,EAAQ,cAAA;AAAA,EACR,iBAAA,EAAmB,qBAAA;AAAA,EACnB,iBAAA,EAAmB,sBAAA;AAAA,EACnB,oBAAA,EAAsB,6BAAA;AAAA,EACtB,aAAA,EAAe,gBAAA;AAAA,EACf,eAAA,EAAiB,kBAAA;AAAA,EACjB,eAAA,EAAiB,kBAAA;AAAA,EACjB,aAAA,EAAe,gBAAA;AAAA,EACf,SAAA,EAAW,iBAAA;AAAA,EACX,QAAA,EAAU,gBAAA;AAAA,EACV,OAAA,EAAS;AACX;AAcO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CACE,IAAA,EACA,OAAA,EACA,OAAA,EACA,O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A,WAAS;AACP,MAAA,IAAI,OAAA,CAAQ,OAAA,IAAU,KAAM,IAAA,EAAM,OAAO,KAAA;AACzC,MAAA,IAAI,CAAC,UAAS,EAAG;AACf,QAAA,MAAM,IAAI,OAAA,CAAc,CAACA,aAAY,UAAA,CAAWA,QAAAA,EAAS,CAAC,CAAC,CAAA;AAC3D,QAAA,IAAI,CAAC,QAAA,EAAS,EAAG,OAAO,IAAA;AAAA,MAC1B;AACA,MAAA,MAAM,IAAI,OAAA,CAAc,CAACA,QAAAA,KAAY;AACnC,QAAA,MAAM,GAAA,GAAM,KAAA,CAAM,aAAA,CAAc,MAAM;AACpC,UAAA,GAAA,EAAI;AACJ,UAAAA,QAAAA,EAAQ;AAAA,QACV,CAAC,CAAA;AAED,QAAA,UAAA,CAAW,MAAM;AACf,UAAA,GAAA,EAAI;AACJ,UAAAA,QAAAA,EAAQ;AAAA,QACV,GAAG,EAAE,CAAA;AAAA,MACP,CAAC,CAAA;AAAA,IACH;AAAA,EACF,CAAA,GAAG;AACH,EAAA,MAAM,UAAU,MAAM,OAAA,CAAQ,KAAK,CAAC,KAAA,EAAO,QAAQ,CAAC,CAAA;AACpD,EAAA,YAAA,CAAa,KAAK,CAAA;AAClB,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["// ═══════════════════════════════════════════════════════════\n// Shared primitives — common types + generic guards used to\n// narrow `unknown` across the package.\n// ═══════════════════════════════════════════════════════════\n\nexport type Unsubscribe = () => void;\n\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nexport const isString = (value: unknown): value is string => typeof value === 'string';\n\nexport const isNumber = (value: unknown): value is number => typeof value === 'number';\n\nexport const isBoolean = (value: unknown): value is boolean => typeof value === 'boolean';\n\nexport const isArray = (value: unknown): value is unknown[] => Array.isArray(value);\n\nexport const isNonNull = <T>(value: T | null | undefined): value is T =>\n value !== null && value !== undefined;\n\nexport const hasKey = <K extends string>(\n obj: unknown,\n key: K,\n): obj is Record<K, unknown> => isObject(obj) && key in obj;\n","import type { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════\n// Error codes\n// ═══════════════════════════════════════════════════════════\n\nexport const ErrorCodes = {\n render: 'RENDER_ERROR',\n componentNotFound: 'COMPONENT_NOT_FOUND',\n layoutRefNotFound: 'LAYOUT_REF_NOT_FOUND',\n definitionValidation: 'DEFINITION_VALIDATION_ERROR',\n unknownAction: 'UNKNOWN_ACTION',\n unknownFragment: 'UNKNOWN_FRAGMENT',\n unknownFunction: 'UNKNOWN_FUNCTION',\n shellDisposed: 'SHELL_DISPOSED',\n lifecycle: 'LIFECYCLE_ERROR',\n mutation: 'MUTATION_ERROR',\n runaway: 'RUNAWAY_CHAIN',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\nexport type NovaErrorContext = Record<string, unknown>;\n\n// ═══════════════════════════════════════════════════════════\n// Base error — classes are permitted here because these are\n// the only thrown error types; identity + instanceof are needed.\n//\n// Subclasses are added when there is a real throw site. Do not\n// add dead exports.\n// ═══════════════════════════════════════════════════════════\n\nexport class NovaError extends Error {\n readonly code: ErrorCode;\n readonly context: NovaErrorContext | undefined;\n\n constructor(\n code: ErrorCode,\n message: string,\n context?: NovaErrorContext,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = 'NovaError';\n this.code = code;\n this.context = context;\n }\n}\n\nexport class RenderError extends NovaError {\n constructor(message: string, context?: NovaErrorContext, options?: { cause?: unknown }) {\n super(ErrorCodes.render, message, context, options);\n this.name = 'RenderError';\n }\n}\n\nexport type ComponentNotFoundContext = NovaErrorContext & { name: string };\n\nexport class ComponentNotFoundError extends NovaError {\n constructor(\n message: string,\n context: ComponentNotFoundContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.componentNotFound, message, context, options);\n this.name = 'ComponentNotFoundError';\n }\n}\n\nexport type LayoutRefNotFoundContext = NovaErrorContext & { ref: string };\n\nexport class LayoutRefNotFoundError extends NovaError {\n constructor(\n message: string,\n context: LayoutRefNotFoundContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.layoutRefNotFound, message, context, options);\n this.name = 'LayoutRefNotFoundError';\n }\n}\n\nexport type DefinitionValidationFailure = {\n id: string;\n issues: z.core.$ZodIssue[];\n};\n\nexport type DefinitionValidationContext = NovaErrorContext & {\n failures: DefinitionValidationFailure[];\n};\n\nexport class DefinitionValidationError extends NovaError {\n constructor(\n message: string,\n context: DefinitionValidationContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.definitionValidation, message, context, options);\n this.name = 'DefinitionValidationError';\n }\n}\n\nexport type UnknownActionContext = NovaErrorContext & { actionId: string };\n\nexport class UnknownActionError extends NovaError {\n constructor(\n message: string,\n context: UnknownActionContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.unknownAction, message, context, options);\n this.name = 'UnknownActionError';\n }\n}\n\nexport type UnknownFragmentContext = NovaErrorContext & { fragmentId: string };\n\nexport class UnknownFragmentError extends NovaError {\n constructor(\n message: string,\n context: UnknownFragmentContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.unknownFragment, message, context, options);\n this.name = 'UnknownFragmentError';\n }\n}\n\nexport class ShellDisposedError extends NovaError {\n constructor(message: string, context?: NovaErrorContext, options?: { cause?: unknown }) {\n super(ErrorCodes.shellDisposed, message, context, options);\n this.name = 'ShellDisposedError';\n }\n}\n\nexport type UnknownFunctionContext = NovaErrorContext & { name: string };\n\nexport class UnknownFunctionError extends NovaError {\n constructor(name: string, options?: { cause?: unknown }) {\n super(\n ErrorCodes.unknownFunction,\n `Unknown function: \"${name}\". Is it registered in shell config's \\`functions\\` map?`,\n { name },\n options,\n );\n this.name = 'UnknownFunctionError';\n }\n}\n\nexport type LifecycleHook = 'mount' | 'unmount' | 'suspend' | 'resume';\n\nexport type LifecycleErrorContext = NovaErrorContext & {\n hook?: LifecycleHook;\n instanceId?: string;\n};\n\nexport class LifecycleError extends NovaError {\n constructor(\n message: string,\n context?: LifecycleErrorContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.lifecycle, message, context, options);\n this.name = 'LifecycleError';\n }\n}\n\nexport type MutationErrorContext = NovaErrorContext & {\n op: string;\n path: string;\n reason: 'missing' | 'wrong-type';\n};\n\nexport class MutationError extends NovaError {\n constructor(\n message: string,\n context: MutationErrorContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.mutation, message, context, options);\n this.name = 'MutationError';\n }\n}\n","// ═══════════════════════════════════════════════════════════\n// ID factory — closure-scoped, never module-mutable counters.\n// Uses crypto.randomUUID when available, falls back to a\n// Math.random-based token. Not security-sensitive.\n// ═══════════════════════════════════════════════════════════\n\nexport type IdFactory = () => string;\n\ntype CryptoLike = { randomUUID?: () => string };\n\nconst fallbackToken = (): string =>\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n\nconst getCrypto = (): CryptoLike | undefined => {\n if (typeof globalThis === 'undefined') return undefined;\n const g: { crypto?: CryptoLike } = globalThis;\n return g.crypto;\n};\n\nexport const createIdFactory = (prefix: string): IdFactory => {\n const cryptoObj = getCrypto();\n const randomUUID = cryptoObj?.randomUUID;\n if (typeof randomUUID === 'function') {\n return (): string => `${prefix}-${randomUUID.call(cryptoObj)}`;\n }\n return (): string => `${prefix}-${fallbackToken()}`;\n};\n","import { z } from 'zod';\n\nexport const IfDirectiveSchema = z\n .object({\n $if: z.unknown().describe('Condition — resolved recursively, then checked for truthiness.'),\n $then: z.unknown().describe('Value when condition is truthy — resolved recursively.'),\n $else: z\n .unknown()\n .optional()\n .describe('Value when condition is falsy — resolved recursively.'),\n })\n .strict()\n .describe('Conditional value directive. Resolved at bind time.');\n\nexport type IfDirective = z.infer<typeof IfDirectiveSchema>;\n\nexport const ResolvableSchema = z\n .unknown()\n .describe(\n 'Any value. Strings support {{}} templates and bare $-paths. The data ROOT is '\n + '\"$.\" — a data key is ALWAYS \"$.key\" (\"{{$.rows.length}} found\", \"$.loading\"); '\n + '\"$key\" without the dot is INVALID. Loop variables (a `for` directive\\'s `as`) '\n + 'are \"$<name>.field\" (\"{{$row.title}}\"). Objects may be directives like '\n + '{$if,$then,$else}. Arrays and nested objects are walked recursively. '\n + 'Everything else is literal.',\n );\n","import type { Scope, ScopeChain } from './types';\n\nexport const createScopeChain = (data: Scope): ScopeChain => [data];\n\nexport const pushScope = (chain: ScopeChain, scope: Scope): ScopeChain => [scope, ...chain];\n","import { isArray, isObject } from '../common';\n\n// ═══════════════════════════════════════════════════════════\n// Path helpers — get/set/delete on nested data structures.\n// Dot paths: \"a.b.0.c\". Numeric segments are array indices\n// when the parent is an array.\n// ═══════════════════════════════════════════════════════════\n\nconst splitPath = (path: string): string[] => {\n if (path.length === 0) return [];\n return path.split('.');\n};\n\nconst isIndex = (segment: string): boolean => /^\\d+$/.test(segment);\n\ntype Container = Record<string, unknown> | unknown[];\n\nconst cloneContainer = (value: unknown, nextSegment: string | undefined): Container => {\n if (isArray(value)) return value.slice();\n if (isObject(value)) return { ...value };\n if (nextSegment !== undefined && isIndex(nextSegment)) return [];\n return {};\n};\n\nconst writeSegment = (container: Container, segment: string, value: unknown): void => {\n if (isArray(container)) {\n if (isIndex(segment)) {\n const index = Number.parseInt(segment, 10);\n container[index] = value;\n }\n return;\n }\n container[segment] = value;\n};\n\nconst readSegment = (container: Container, segment: string): unknown => {\n if (isArray(container)) {\n if (!isIndex(segment)) return undefined;\n const index = Number.parseInt(segment, 10);\n return container[index];\n }\n return container[segment];\n};\n\nexport const getPath = (data: unknown, path: string): unknown => {\n const segments = splitPath(path);\n let current: unknown = data;\n for (const segment of segments) {\n if (current === undefined || current === null) return undefined;\n if (isArray(current)) {\n if (isIndex(segment)) {\n const index = Number.parseInt(segment, 10);\n current = current[index];\n continue;\n }\n if (segment === 'length') {\n current = current.length;\n continue;\n }\n return undefined;\n }\n if (isObject(current)) {\n if (segment in current) {\n current = current[segment];\n continue;\n }\n return undefined;\n }\n return undefined;\n }\n return current;\n};\n\nexport const setPath = (data: unknown, path: string, value: unknown): unknown => {\n const segments = splitPath(path);\n if (segments.length === 0) return value;\n\n const root = cloneContainer(data, segments[0]);\n let parent: Container = root;\n\n for (let i = 0; i < segments.length - 1; i += 1) {\n const segment = segments[i];\n const nextSegment = segments[i + 1];\n if (segment === undefined) continue;\n const existing = readSegment(parent, segment);\n const cloned = cloneContainer(existing, nextSegment);\n writeSegment(parent, segment, cloned);\n parent = cloned;\n }\n\n const last = segments[segments.length - 1];\n if (last !== undefined) writeSegment(parent, last, value);\n return root;\n};\n\nexport const deletePath = (data: unknown, path: string): unknown => {\n const segments = splitPath(path);\n if (segments.length === 0) return undefined;\n\n const root = cloneContainer(data, segments[0]);\n let parent: Container = root;\n\n for (let i = 0; i < segments.length - 1; i += 1) {\n const segment = segments[i];\n const nextSegment = segments[i + 1];\n if (segment === undefined) continue;\n const existing = readSegment(parent, segment);\n if (existing === undefined || existing === null) return root;\n const cloned = cloneContainer(existing, nextSegment);\n writeSegment(parent, segment, cloned);\n parent = cloned;\n }\n\n const last = segments[segments.length - 1];\n if (last === undefined) return root;\n if (isArray(parent)) {\n if (isIndex(last)) {\n const index = Number.parseInt(last, 10);\n parent.splice(index, 1);\n }\n } else {\n delete parent[last];\n }\n return root;\n};\n","import { evaluateSafe } from '@niscorp/prism';\nimport { hasKey, isArray, isObject } from '../common';\nimport { getPath } from './paths';\nimport type { ScopeChain } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Unified value resolver.\n//\n// One function — `resolve` — handles every binding site uniformly.\n//\n// String semantics:\n// 1. \"{{ expr }}\" (sole expression) → raw value of expr (type preserved)\n// 2. \"...{{expr}}...\" → interpolated string\n// 3. \"$.x\" or \"$ident...\" → raw value of path (type preserved)\n// 4. anything else → literal string\n//\n// Array → mapped recursively.\n// Object → walked recursively, OR treated as an `$if` directive.\n// Primitives → returned as-is.\n//\n// Path expressions resolve via `resolvePath`, which uses the ScopeChain\n// (innermost first). An optional `extras` map injects keyed scopes for\n// templates (e.g. `{ '@error': errObj }`); longest-prefix match wins.\n// ═══════════════════════════════════════════════════════════\n\nconst TEMPLATE_REGEX = /\\{\\{\\s*([^}]+?)\\s*\\}\\}/g;\nconst SOLE_TEMPLATE_REGEX = /^\\{\\{\\s*([^}]+?)\\s*\\}\\}$/;\nconst BARE_PATH_REGEX = /^\\$(\\.|[A-Za-z_]|$)/;\n\nexport type ExtraScopes = Record<string, unknown>;\n\nconst matchExtra = (expression: string, extras: ExtraScopes): string | undefined => {\n let matched: string | undefined;\n for (const key of Object.keys(extras)) {\n if (expression === key || expression.startsWith(`${key}.`)) {\n if (matched === undefined || key.length > matched.length) matched = key;\n }\n }\n return matched;\n};\n\nconst resolveExtraExpression = (\n expression: string,\n matchedKey: string,\n extras: ExtraScopes,\n): unknown => {\n const root = extras[matchedKey];\n if (expression === matchedKey) return root;\n const rest = expression.slice(matchedKey.length + 1);\n if (rest.length === 0) return root;\n return getPath(root, rest);\n};\n\nconst walkFromScopeHead = (head: unknown, restSegments: readonly string[]): unknown => {\n if (restSegments.length === 0) return head;\n return getPath(head, restSegments.join('.'));\n};\n\nexport const resolvePath = (\n path: string,\n chain: ScopeChain,\n extras: ExtraScopes = {},\n): unknown => {\n const extraKey = matchExtra(path, extras);\n if (extraKey !== undefined) return resolveExtraExpression(path, extraKey, extras);\n\n if (!path.startsWith('$')) return undefined;\n if (path === '$') return chain[0];\n\n const afterDollar = path.slice(1);\n\n if (afterDollar.startsWith('.')) {\n const rest = afterDollar.slice(1);\n if (rest.length === 0) return chain[0];\n const segments = rest.split('.');\n const head = segments[0];\n if (head === undefined) return undefined;\n for (const scope of chain) {\n if (hasKey(scope, head)) {\n return walkFromScopeHead(scope[head], segments.slice(1));\n }\n }\n return undefined;\n }\n\n const segments = afterDollar.split('.');\n const varName = segments[0];\n if (varName === undefined || varName.length === 0) return undefined;\n for (const scope of chain) {\n if (hasKey(scope, varName)) {\n return walkFromScopeHead(scope[varName], segments.slice(1));\n }\n }\n return undefined;\n};\n\nconst stringify = (value: unknown): string => {\n if (value === null || value === undefined) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n};\n\nconst isTruthy = (value: unknown): boolean => {\n if (value === null || value === undefined) return false;\n if (value === false) return false;\n if (value === 0) return false;\n if (value === '') return false;\n if (isArray(value) && value.length === 0) return false;\n return true;\n};\n\n// Directives — evaluated objects keyed by an operator (`$if`, `$eq`, …). Each\n// resolves its operands and returns a value. Add an operator here and it works\n// everywhere bindings are resolved; later operators (`$gte`, `$and`, …) slot in\n// the same way.\ntype Directive = (node: Record<string, unknown>, chain: ScopeChain, extras: ExtraScopes) => unknown;\n\nconst DIRECTIVES: Record<string, Directive> = {\n $if: (node, chain, extras) => {\n if (isTruthy(resolve(node.$if, chain, extras))) return resolve(node.$then, chain, extras);\n if (hasKey(node, '$else')) return resolve(node.$else, chain, extras);\n return undefined;\n },\n $eq: (node, chain, extras) => {\n const args = isArray(node.$eq) ? node.$eq : [];\n return resolve(args[0], chain, extras) === resolve(args[1], chain, extras);\n },\n // True when the operand path resolves to a present value. The structural\n // counterpart to `$eq`: discriminate a union by which key a branch carries\n // (`{ $exists: \"$.shape.component\" }`) rather than a shared tag's value.\n $exists: (node, chain, extras) => resolve(node.$exists, chain, extras) !== undefined,\n // Read an array element by a (dynamic) index: `{ $at: [\"$.results\", \"$.i\"] }`.\n // An optional third arg pulls one field off the element: `[\"$.results\", \"$.i\",\n // \"id\"]`. Returns undefined when the array/index doesn't resolve.\n $at: (node, chain, extras) => {\n const args = isArray(node.$at) ? node.$at : [];\n const arr = resolve(args[0], chain, extras);\n const index = Number(resolve(args[1], chain, extras));\n if (!isArray(arr) || Number.isNaN(index)) return undefined;\n const element = arr[index];\n const field = args[2];\n return field !== undefined && isObject(element) ? element[String(field)] : element;\n },\n // THE WHOLE TRANSFORM GRAMMAR, BEHIND ONE EXPLICIT DOOR. The directives\n // above stay the small binding set; a value that needs a real transformation\n // — a join, a projection, a group — says so out loud: `{ $prism: <node> }`\n // evaluates the node with prism against the action's ROOT data. One grammar,\n // one evaluator, nothing ambient — a prism-shaped object OUTSIDE this\n // wrapper stays what it always was, a plain object walked for strings.\n //\n // The quiet failure this replaces was worse than a crash: an unrecognised\n // op-shaped value passed through `resolve` as structure, landed in data, and\n // rendered as garbage three screens later. Inside the wrapper, a bad node\n // resolves to undefined — absent, not wrong.\n $prism: (node, chain) => {\n const result = evaluateSafe(node.$prism as never, (chain[0] ?? {}) as never);\n return result.ok ? result.data : undefined;\n },\n};\n\nconst directiveOf = (value: Record<string, unknown>): Directive | undefined => {\n for (const key of Object.keys(value)) {\n const directive = DIRECTIVES[key];\n if (directive !== undefined) return directive;\n }\n return undefined;\n};\n\nconst resolveString = (value: string, chain: ScopeChain, extras: ExtraScopes): unknown => {\n const sole = value.match(SOLE_TEMPLATE_REGEX);\n if (sole !== null) {\n const expr = sole[1];\n if (expr === undefined) return value;\n return resolvePath(expr.trim(), chain, extras);\n }\n\n if (value.includes('{{')) {\n return value.replace(TEMPLATE_REGEX, (_match: string, expression: string): string => {\n const resolved = resolvePath(expression.trim(), chain, extras);\n return stringify(resolved);\n });\n }\n\n if (BARE_PATH_REGEX.test(value)) {\n return resolvePath(value, chain, extras);\n }\n\n if (matchExtra(value, extras) !== undefined) {\n return resolvePath(value, chain, extras);\n }\n\n return value;\n};\n\nexport const resolve = (\n value: unknown,\n chain: ScopeChain,\n extras: ExtraScopes = {},\n): unknown => {\n if (typeof value === 'string') return resolveString(value, chain, extras);\n if (isArray(value)) return value.map((entry) => resolve(entry, chain, extras));\n if (isObject(value)) {\n const directive = directiveOf(value);\n if (directive !== undefined) return directive(value, chain, extras);\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n out[key] = resolve(value[key], chain, extras);\n }\n return out;\n }\n return value;\n};\n","import type { Unsubscribe } from '../common';\nimport type { DataStore } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// createDataStore — mutations live outside the store and are\n// applied via `store.update(curr => applyMutations(curr, list))`.\n// ═══════════════════════════════════════════════════════════\n\nexport const createDataStore = <T extends Record<string, unknown> = Record<string, unknown>>(\n initial: T,\n): DataStore<T> => {\n let current: T = { ...initial };\n const subscribers: Array<(data: T) => void> = [];\n\n const get = (): T => current;\n\n const update = (updater: (current: T) => T): void => {\n current = updater(current);\n for (const handler of subscribers.slice()) {\n try {\n handler(current);\n } catch {\n // handler errors must not crash the store\n }\n }\n };\n\n const subscribe = (handler: (data: T) => void): Unsubscribe => {\n subscribers.push(handler);\n return (): void => {\n const idx = subscribers.indexOf(handler);\n if (idx >= 0) subscribers.splice(idx, 1);\n };\n };\n\n return { get, update, subscribe };\n};\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════\n// NovaEvent — the built-in discriminated union of UI events.\n// Consumers may supply their own union to createEventBus<T>.\n//\n// Every UI event shares the same envelope: a `type` discriminator, an optional\n// target `ref`, an optional `payload`, and an optional `origin` — the id of the\n// action instance that dispatched it. `origin` is stamped automatically when an\n// event is dispatched from inside an instance's rendered layout (see ActionSlot),\n// and lets the runtime deliver a UI event to that instance's OWN triggers only,\n// so two instances of the same action (e.g. a list on `main` and on `aside`)\n// don't both react to one click. Events dispatched programmatically\n// (`shell.dispatch`) carry no `origin` and stay global.\n// ═══════════════════════════════════════════════════════════\n\nconst uiEvent = <T extends string, E extends z.ZodRawShape = Record<never, never>>(\n type: T,\n extra: E = {} as E,\n) =>\n z\n .object({\n type: z.literal(type).describe('Event type discriminator.'),\n ref: z.string().optional().describe('Target component ref.'),\n payload: z.unknown().optional().describe('Optional event payload.'),\n origin: z\n .string()\n .optional()\n .describe(\n 'Id of the action instance that dispatched this event. Stamped automatically for events dispatched from within an instance’s layout; used to deliver UI events to that instance’s own triggers only. Absent on programmatic (global) dispatch.',\n ),\n ...extra,\n })\n .strict();\n\nconst UiClickSchema = uiEvent('ui:click').describe('A UI click event.');\nconst UiSubmitSchema = uiEvent('ui:submit').describe('A UI submit event.');\nconst UiInputSchema = uiEvent('ui:input').describe('A UI input event.');\nconst UiFocusSchema = uiEvent('ui:focus').describe('A UI focus event.');\nconst UiBlurSchema = uiEvent('ui:blur').describe('A UI blur event.');\nconst UiModelSchema = uiEvent('ui:model').describe('A two-way-bound model update event.');\nconst UiKeySchema = uiEvent('ui:key', {\n key: z.string().describe('The key pressed, e.g. \"ArrowDown\", \"Enter\", \"Escape\".'),\n}).describe('A keyboard key event. A trigger filters it by `key` (and optionally `ref`).');\nconst UiDropSchema = uiEvent('ui:drop').describe(\n 'A drag-and-drop \"drop\" event — the semantic outcome of a drag gesture, dispatched by a drop zone. The gesture mechanics stay in the component; only the drop reaches Nova.',\n);\n\nexport const NovaEventSchema = z\n .discriminatedUnion('type', [\n UiClickSchema,\n UiSubmitSchema,\n UiInputSchema,\n UiFocusSchema,\n UiBlurSchema,\n UiModelSchema,\n UiKeySchema,\n UiDropSchema,\n ])\n .describe('Discriminated union of the built-in Nova UI events.');\n\nexport type NovaEvent = z.infer<typeof NovaEventSchema>;\n","import type { Unsubscribe } from '../common';\nimport type { EventBus, EventHandler, EventMatcher } from './types';\nimport type { NovaEvent } from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// Typed event bus. Factory function.\n//\n// Generic over TEvent (a discriminated union of events, defaulting\n// to NovaEvent). The bus only ever inspects `event.type` for matching.\n//\n// `scoped()` returns a child bus that forwards every event it emits\n// to its parent. No type mangling, no string prefixing — if you want\n// namespacing, put it in your event payload.\n// ═══════════════════════════════════════════════════════════\n\ntype Subscription<TEvent extends { type: string }> = {\n matcher: EventMatcher;\n handler: EventHandler<TEvent>;\n};\n\nconst typeMatches = (matcher: EventMatcher, type: string): boolean => {\n if (typeof matcher === 'string') return matcher === type;\n return matcher.test(type);\n};\n\nconst createChildBus = <TEvent extends { type: string }>(\n parent: EventBus<TEvent> | undefined,\n): EventBus<TEvent> => {\n const subscriptions: Subscription<TEvent>[] = [];\n\n const emit = (event: TEvent): void => {\n for (const sub of subscriptions.slice()) {\n if (!typeMatches(sub.matcher, event.type)) continue;\n try {\n sub.handler(event);\n } catch {\n // handler failures must not crash the bus\n }\n }\n if (parent !== undefined) parent.emit(event);\n };\n\n const on = (matcher: EventMatcher, handler: EventHandler<TEvent>): Unsubscribe => {\n const sub: Subscription<TEvent> = { matcher, handler };\n subscriptions.push(sub);\n return (): void => {\n const idx = subscriptions.indexOf(sub);\n if (idx >= 0) subscriptions.splice(idx, 1);\n };\n };\n\n const once = (matcher: EventMatcher, handler: EventHandler<TEvent>): Unsubscribe => {\n const off = on(matcher, (event) => {\n off();\n handler(event);\n });\n return off;\n };\n\n const bus: EventBus<TEvent> = {\n emit,\n on,\n once,\n scoped: () => createChildBus<TEvent>(bus),\n };\n\n return bus;\n};\n\nexport const createEventBus = <\n TEvent extends { type: string } = NovaEvent,\n>(): EventBus<TEvent> => createChildBus<TEvent>(undefined);\n","import type { NovaEvent } from './schemas';\n\n// Wraps a dispatch function so every event passing through it gets stamped\n// with `origin` (the dispatching action instance's id) unless it already\n// carries one — a re-dispatch keeps its original origin. Adapters wrap the\n// dispatch they hand to an instance's rendered subtree with this, so the\n// runtime delivers UI events to that instance's own triggers only. This is\n// routing semantics: never reimplement it per adapter.\nexport const scopeDispatch = (\n dispatch: (event: NovaEvent) => void,\n origin: string,\n): ((event: NovaEvent) => void) => {\n return (event) => dispatch(event.origin === undefined ? { ...event, origin } : event);\n};\n","import { z } from 'zod';\n\nexport const MessageEnvelopeSchema = z\n .object({\n channel: z.string().describe('Channel name the message is published on.'),\n from: z.string().optional().describe('Optional sender identifier.'),\n to: z.string().optional().describe('Optional direct recipient identifier.'),\n payload: z.unknown().optional().describe('Optional message payload.'),\n })\n .strict()\n .describe('A message envelope passed through the message bus.');\n\nexport type MessageEnvelope = z.infer<typeof MessageEnvelopeSchema>;\n","import type { Unsubscribe } from '../common';\nimport type { ChannelHandler, MessageBus } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Pure channel-based message bus. Internal subscriber map;\n// does NOT depend on the event bus.\n// ═══════════════════════════════════════════════════════════\n\nexport const createMessageBus = (): MessageBus => {\n const handlers = new Map<string, ChannelHandler[]>();\n\n const dispatch = (channel: string, payload: unknown, from: string | undefined, cause?: unknown): void => {\n const list = handlers.get(channel);\n if (list === undefined) return;\n for (const handler of list.slice()) {\n try {\n handler(payload, from, cause);\n } catch {\n // handler errors must not crash the bus\n }\n }\n };\n\n const publish = (channel: string, payload?: unknown, cause?: unknown): void => {\n dispatch(channel, payload, undefined, cause);\n };\n\n const send = (from: string, to: string, payload?: unknown): void => {\n dispatch(to, payload, from);\n };\n\n const subscribe = (channel: string, handler: ChannelHandler): Unsubscribe => {\n const list = handlers.get(channel) ?? [];\n list.push(handler);\n handlers.set(channel, list);\n return (): void => {\n const current = handlers.get(channel);\n if (current === undefined) return;\n const idx = current.indexOf(handler);\n if (idx >= 0) current.splice(idx, 1);\n };\n };\n\n return { publish, send, subscribe };\n};\n","import { z } from 'zod';\nimport { ResolvableSchema } from '../shared/bindings/schemas';\n\n// ═══════════════════════════════════════════════════════════\n// Layout node schemas\n// ═══════════════════════════════════════════════════════════\n\nexport const LayoutPrimitiveSchema = z\n .union([z.string(), z.number(), z.boolean(), z.null()])\n .describe('A primitive layout value rendered as text.');\n\nexport type LayoutPrimitive = z.infer<typeof LayoutPrimitiveSchema>;\n\nexport type ComponentNode = {\n component: string;\n props?: Record<string, unknown>;\n children?: LayoutNode | LayoutNode[];\n ref?: string;\n model?: string;\n events?: Record<string, unknown>;\n};\n\nexport const ComponentNodeSchema: z.ZodType<ComponentNode> = z.lazy(() =>\n z\n .object({\n component: z.string().describe('The registry name of the component to render.'),\n props: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Component props; values may be bindings to be resolved at render time.'),\n children: z\n .union([LayoutNodeSchema, z.array(LayoutNodeSchema)])\n .optional()\n .describe('Child layout content (a single node or an array of nodes).'),\n ref: z.string().optional().describe('A stable identifier used to target this component from event handlers.'),\n model: z.string().optional().describe('A two-way binding path, e.g. \"$.name\".'),\n events: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Map of event name to event configuration handled by the action runtime.'),\n })\n .strict()\n .describe('A node that instantiates a component from the registry.'),\n);\n\nexport type ConditionalNode = {\n if: unknown;\n then: LayoutNode;\n else?: LayoutNode;\n};\n\nexport const ConditionalNodeSchema: z.ZodType<ConditionalNode> = z.lazy(() =>\n z\n .object({\n if: ResolvableSchema.describe('Resolvable value evaluated for truthiness.'),\n then: LayoutNodeSchema.describe('Layout to render when condition is truthy.'),\n else: LayoutNodeSchema.optional().describe('Layout to render when condition is falsy.'),\n })\n .strict()\n .describe('A node that conditionally renders one of two branches.'),\n);\n\nexport type LoopNode = {\n for: unknown;\n as: string;\n key?: string;\n do: LayoutNode;\n};\n\nexport const LoopNodeSchema: z.ZodType<LoopNode> = z.lazy(() =>\n z\n .object({\n for: ResolvableSchema.describe('Resolvable value that resolves to an iterable array.'),\n as: z.string().describe('Name to bind each iterated item under in the inner scope.'),\n key: z.string().optional().describe('Optional key path on each item used for stable identity.'),\n do: LayoutNodeSchema.describe('Layout rendered once per iterated item.'),\n })\n .strict()\n .describe('A node that iterates an array binding and renders a layout for each item.'),\n);\n\nexport const LayoutRefNodeSchema = z\n .object({\n ref: z.string().describe('Identifier of a layout stored in the layout store to inline at this position.'),\n })\n .strict()\n .describe('A reference to a stored layout, inlined during render.');\n\nexport type LayoutRefNode = z.infer<typeof LayoutRefNodeSchema>;\n\nexport const SlotNodeSchema = z\n .object({\n slot: z\n .string()\n .describe(\n 'Name of a slot placeholder. When an ActionFragment is composed with an action ' +\n '(a push/replace `with`), the fragment\\'s `{ slot: \"body\" }` node is replaced by ' +\n 'the composing action\\'s own layout. An unfilled slot renders nothing.',\n ),\n })\n .strict()\n .describe(\n 'A placeholder that a fragment-merge fills with a composing action\\'s layout. ' +\n 'Only meaningful inside an ActionFragment\\'s layout.',\n );\n\nexport type SlotNode = z.infer<typeof SlotNodeSchema>;\n\nexport type LayoutNode =\n | ComponentNode\n | ConditionalNode\n | LoopNode\n | LayoutRefNode\n | SlotNode\n | LayoutNode[]\n | LayoutPrimitive;\n\nexport const LayoutNodeSchema: z.ZodType<LayoutNode> = z.lazy(() =>\n z\n .union([\n ComponentNodeSchema,\n ConditionalNodeSchema,\n LoopNodeSchema,\n LayoutRefNodeSchema,\n SlotNodeSchema,\n z.array(LayoutNodeSchema),\n LayoutPrimitiveSchema,\n ])\n .describe('Any layout node: component, conditional, loop, layout ref, slot, array of nodes, or a primitive text value.'),\n);\n","import { hasKey, isObject } from '../shared/common';\nimport type {\n ComponentNode,\n ConditionalNode,\n LayoutNode,\n LayoutPrimitive,\n LayoutRefNode,\n LoopNode,\n SlotNode,\n} from './schemas';\n\nexport const isLayoutPrimitive = (value: unknown): value is LayoutPrimitive =>\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean';\n\nexport const isComponentNode = (value: unknown): value is ComponentNode =>\n hasKey(value, 'component') && typeof value['component'] === 'string';\n\nexport const isConditionalNode = (value: unknown): value is ConditionalNode =>\n hasKey(value, 'if') && hasKey(value, 'then') && !hasKey(value, 'for');\n\nexport const isLoopNode = (value: unknown): value is LoopNode =>\n hasKey(value, 'for') && hasKey(value, 'as') && hasKey(value, 'do');\n\nexport const isLayoutRefNode = (value: unknown): value is LayoutRefNode =>\n isObject(value) &&\n hasKey(value, 'ref') &&\n typeof value['ref'] === 'string' &&\n !hasKey(value, 'component') &&\n Object.keys(value).length === 1;\n\nexport const isSlotNode = (value: unknown): value is SlotNode =>\n isObject(value) &&\n hasKey(value, 'slot') &&\n typeof value['slot'] === 'string' &&\n Object.keys(value).length === 1;\n\nexport const isLayoutNode = (value: unknown): value is LayoutNode =>\n isLayoutPrimitive(value) ||\n Array.isArray(value) ||\n isComponentNode(value) ||\n isConditionalNode(value) ||\n isLoopNode(value) ||\n isLayoutRefNode(value) ||\n isSlotNode(value);\n","// ═══════════════════════════════════════════════════════════\n// NOVA IS LANGUAGE-BLIND, the same way it is surface-blind.\n//\n// The core renders a layout into a `RenderNode` tree and knows nothing about\n// what language the words in it are. This area adds one late pass over that\n// tree — swap the words, leave the structure — plus the harvester that tells\n// you which words there are to swap.\n//\n// WHY A LATE PASS AND NOT A `$t` IN THE LAYOUT. Both work; they cost\n// differently. A key-per-string layout (`label: '@t.people.add'`) is precise\n// and makes every layout in the application unreadable — the file stops saying\n// what it draws. A late pass leaves the layouts as the readable English they\n// already are and moves the whole problem to one walk, at the price of keying\n// the dictionary on the source string rather than on an invented id.\n//\n// The price is real and worth naming: English-as-key cannot distinguish two\n// senses of one word. \"Book\" the verb and \"Book\" the noun are one key here and\n// two words in German. When that bites, the answer is not to abandon the pass\n// — it is to disambiguate that one string at its author site, and a `$t`\n// directive is the natural place for it. The two compose; this is the layer\n// that makes the other one optional rather than mandatory.\n//\n// WHAT THIS PASS CANNOT DO, and where the rest of the work goes:\n// - Open-ended formatted values — dates, money, counts. \"Fri 14 Mar\" has\n// unbounded cardinality and no dictionary will ever hold it. Those are\n// formatted at their source with a locale (prism's `$localeDate`,\n// `$localeMoney`, `$localeNumber`).\n// - Anything not in the tree: a server error message, a notification body.\n// ═══════════════════════════════════════════════════════════\n\n/** Source phrase → the words a reader of this locale should see. */\nexport type Phrasebook = Readonly<Record<string, string>>;\n\n// WHICH STRINGS IN A TREE ARE PROSE, declared by the host rather than guessed.\n//\n// A render tree is mostly not prose. It carries person names, ids, css values,\n// tone words, icon names and row data, and a pass that translated every string\n// it found would rename a member called \"Pass\" the first time somebody bought\n// one. So the host names the carriers, and everything else is left alone.\nexport type PhraseKeys = {\n // Prop names whose string values are prose: `label`, `title`, `placeholder`.\n // Matched at ANY depth inside a prop value, which is what makes a spec prop\n // work — a `Table`'s `columns: [{ label }]` and a `Select`'s\n // `options: [{ label }]` are the same rule as a bare `label`.\n props?: readonly string[];\n // Suffixes marking a DATA field as a display string. An app that spells its\n // read-time display fields `status_display`, `term_display` declares\n // `['_display']` once here, and every closed-set word a query manufactures\n // becomes translatable without the app naming them one by one.\n //\n // Only for CLOSED sets. A `_display` field holding a formatted date or an\n // amount will simply miss, every time, and should be formatted with a locale\n // at its source instead.\n suffixes?: readonly string[];\n // Translate bare text nodes (a layout's literal children). Default: true.\n text?: boolean;\n};\n\nexport const DEFAULT_PHRASE_KEYS: Required<Pick<PhraseKeys, 'props' | 'text'>> = {\n // A starting set, not a standard — an app with its own vocabulary passes its\n // own. Deliberately absent: `name`, `value`, `id`, `icon`, `tone`, `variant`,\n // `key`. Those carry data or design tokens, and translating them is how a\n // person called \"Active\" gets renamed.\n props: [\n 'label',\n 'title',\n 'subtitle',\n 'heading',\n 'eyebrow',\n 'lead',\n 'blurb',\n 'placeholder',\n 'hint',\n 'help',\n 'message',\n 'empty',\n 'emptyHint',\n 'emptyLabel',\n 'noMatch',\n 'caption',\n 'description',\n 'confirmLabel',\n 'cancelLabel',\n 'alt',\n 'tooltip',\n ],\n text: true,\n};\n\nexport type PhraseKeyMatcher = {\n isProse: (key: string) => boolean;\n text: boolean;\n};\n\nexport const matcherFor = (keys: PhraseKeys | undefined): PhraseKeyMatcher => {\n const props = new Set(keys?.props ?? DEFAULT_PHRASE_KEYS.props);\n const suffixes = keys?.suffixes ?? [];\n return {\n isProse: (key: string): boolean => props.has(key) || suffixes.some((suffix) => key.endsWith(suffix)),\n text: keys?.text ?? DEFAULT_PHRASE_KEYS.text,\n };\n};\n\n// A string that is a BINDING resolves to data at render time, so it is never a\n// phrase: harvesting `'$.member.person_name'` would put a path in the\n// dictionary and translating it would do nothing.\n//\n// Three forms, matching what the resolver recognises\n// (`shared/bindings/resolve.ts`): a bare `$` path, a `{{ }}` template, and an\n// `@`-prefixed EXTRA scope. The last one is easy to forget and shows up\n// immediately — a trigger's `{ set: 'x', value: '@event.payload.theme_id' }`\n// is a step's plumbing, and a harvester without this rule fills a language\n// file with several dozen of them.\nconst BARE_PATH = /^\\$(\\.|[A-Za-z_]|$)/;\nconst EXTRA_SCOPE = /^@[A-Za-z_]/;\n\nexport const isBinding = (value: string): boolean =>\n BARE_PATH.test(value) || EXTRA_SCOPE.test(value) || value.includes('{{');\n\n// Worth translating at all: a non-empty string that is not a binding and is not\n// obviously machine vocabulary. The last clause is a cheap guard against\n// harvesting css values and tokens that happen to sit at an allowlisted key.\nexport const isPhrase = (value: string): boolean => {\n const trimmed = value.trim();\n if (trimmed === '' || isBinding(trimmed)) return false;\n // A phrase has a letter in it. '—', '18:30', '#fff', '100%' do not.\n return /\\p{L}/u.test(trimmed);\n};\n","import { isArray, isObject } from '../shared/common';\nimport { matcherFor } from './phrases';\nimport { isPhrase } from './phrases';\nimport type { PhraseKeys, Phrasebook } from './phrases';\n\n// ═══════════════════════════════════════════════════════════\n// The swap itself — over VALUES, knowing nothing about trees.\n//\n// Deliberately free of any layout import, because the renderer needs it and\n// the renderer is what layout IS. `translate.ts` (the tree walk) and\n// `layout/renderer.ts` (the mint) are two callers of this one engine, and the\n// whole point of the file is that they can never disagree about what a swap\n// means.\n// ═══════════════════════════════════════════════════════════\n\nexport type Pass = {\n phrases: Phrasebook;\n isProse: (key: string) => boolean;\n text: boolean;\n onMiss: ((phrase: string, where: string) => void) | undefined;\n};\n\nexport type PassOptions = {\n phrases?: Phrasebook;\n keys?: PhraseKeys;\n onMiss?: (phrase: string, where: string) => void;\n};\n\nconst EMPTY: Phrasebook = {};\n\n// ACTIVE OR ABSENT, decided once. A host that named neither a book nor a key\n// set is not doing i18n, and pays nothing: `undefined` here means the renderer\n// skips every branch below, and a `{ phrase, slots }` object passes through as\n// the object it is.\n//\n// A key set WITHOUT a book is the source language, and is NOT nothing: patterns\n// still have to be filled, because a counted phrase reaches the glass as a\n// structure and nobody downstream knows how to read it. That is the one job\n// this pass keeps doing when there is nothing to translate.\nexport const passFor = (options: PassOptions | undefined): Pass | undefined => {\n if (options === undefined) return undefined;\n if (options.phrases === undefined && options.keys === undefined) return undefined;\n const matcher = matcherFor(options.keys);\n return {\n phrases: options.phrases ?? EMPTY,\n isProse: matcher.isProse,\n text: matcher.text,\n onMiss: options.onMiss,\n };\n};\n\nexport const swap = (value: string, where: string, pass: Pass): string => {\n if (!isPhrase(value)) return value;\n const hit = pass.phrases[value];\n if (hit !== undefined) return hit;\n // Trailing/leading whitespace is a layout accident, not part of the phrase.\n // Trying the trimmed form keeps `'Save '` from being a second dictionary\n // entry nobody remembers to fill in.\n const trimmed = value.trim();\n if (trimmed !== value) {\n const onTrimmed = pass.phrases[trimmed];\n if (onTrimmed !== undefined) return value.replace(trimmed, onTrimmed);\n }\n pass.onMiss?.(trimmed, where);\n return value;\n};\n\n// A PATTERN: a counted phrase, translated WHOLE and filled here — the one\n// point that has the book. `{ phrase: '{n} of {total}', slots: { n: 1,\n// total: 12 } }` becomes `'1 von 12'`: the pattern is a dictionary row like\n// any other, so cardinality stays out of the book. A string slot is offered\n// to the book too — a composed sentence's fragments (\"somebody enquires\")\n// are vocabulary in their own right — and everything else interpolates as\n// itself. An empty book fills the holes and translates nothing, which is\n// exactly what a source-language session needs.\nconst isPattern = (value: Record<string, unknown>): value is { phrase: string; slots: Record<string, unknown> } =>\n typeof value['phrase'] === 'string' && isObject(value['slots']);\n\nconst fillPattern = (pattern: { phrase: string; slots: Record<string, unknown> }, where: string, pass: Pass): string =>\n swap(pattern.phrase, where, pass).replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (hole, name: string) => {\n const slot = pattern.slots[name];\n if (slot === undefined || slot === null) return hole;\n return typeof slot === 'string' && isPhrase(slot) ? swap(slot, `${where}.${name}`, pass) : String(slot);\n });\n\n// A book that translates nothing — for filling a pattern outside a render,\n// which is the only thing left to do with one when there are no words to swap.\nconst SOURCE: Pass = { phrases: EMPTY, isProse: () => true, text: true, onMiss: undefined };\n\n// FILL A COUNTED PHRASE THAT NEVER WENT THROUGH A RENDER.\n//\n// The renderer fills patterns on the way to a screen, so nothing downstream of\n// it needs this. What does need it is everything UPSTREAM: a check that reads\n// an entry straight from the engine, a fixture, an exporter — anywhere a\n// `{ phrase, slots }` is held as data rather than shown as words. Nova defines\n// the shape, so nova reads it; a host writing its own copy of this loop is how\n// two spellings of one rule start drifting.\n//\n// Anything that is not a pattern comes back untouched, so it is safe to call\n// on a whole column of mixed values.\nexport const fillPhrase = (value: unknown): unknown => {\n if (!isObject(value) || !isPattern(value)) return value;\n return fillPattern(value, '', SOURCE);\n};\n\n// Walk a prop VALUE. Depth matters: a spec prop is where the repeated structure\n// of a screen lives (`columns: [{ label }]`, `options: [{ label }]`), so the\n// rule cannot be \"top-level props only\" without missing most of a table.\n//\n// Returns the value it was given when nothing under it changed. Identity is\n// load-bearing rather than tidy: a source-language render must produce the\n// props object it produced before this existed, or every untranslated session\n// pays a rebuild for a walk that did nothing.\nexport const walkValue = (value: unknown, prose: boolean, where: string, pass: Pass): unknown => {\n if (typeof value === 'string') return prose ? swap(value, where, pass) : value;\n if (isArray(value)) {\n let changed = false;\n const out = value.map((entry, index) => {\n // An array inherits its key's proseness — `options: ['Yes', 'No']` is as\n // much prose as `options: [{ label: 'Yes' }]`.\n const next = walkValue(entry, prose, `${where}[${String(index)}]`, pass);\n if (next !== entry) changed = true;\n return next;\n });\n return changed ? out : value;\n }\n if (isObject(value)) {\n if (prose && isPattern(value)) return fillPattern(value, where, pass);\n let changed = false;\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const next = walkValue(entry, pass.isProse(key), `${where}.${key}`, pass);\n if (next !== entry) changed = true;\n out[key] = next;\n }\n return changed ? out : value;\n }\n return value;\n};\n","// ═══════════════════════════════════════════════════════════\n// THE HEAD — what a screen says it is, as a node in its layout.\n//\n// A document has a part nobody sees on the screen: its title, the sentence\n// that describes it, the picture shown where a link to it is pasted. Those are\n// facts about what the screen shows, so they come from where everything else\n// on the screen comes from — a layout node, its props bound to the action's\n// data — and travel the way everything else does, in the render tree.\n//\n// The node draws nothing. No adapter builds an element for it and no registry\n// has to hold it. Whoever writes the document reads it off the tree (`headOf`)\n// and says it in the surface's own terms: a browser's <head>, a tab's title.\n//\n// The props say what the screen IS, from a closed set of names\n// (./head.schema). How that is spelled in tags is the writer's business, and\n// where the document lives (its address) is not the screen's to say at all — a\n// layout never holds a URL of its own page.\n//\n// This file holds no schema on purpose: a terminal that only reads a head off\n// the wire needs the name and the shape, and nothing to validate with.\n// ═══════════════════════════════════════════════════════════\n\n// Namespaced as a package's own in-layout components are (`loom:field`), so it\n// can never be a name an app's kit already uses for something else.\nexport const HEAD_NAME = 'nova:head';\n\n// What a head node said, once its bindings are resolved and anything it left\n// empty is gone.\nexport type Head = {\n title?: string;\n description?: string;\n image?: string;\n kind?: 'website' | 'article';\n structured?: Record<string, unknown> | Record<string, unknown>[];\n};\n","import { isArray } from '../shared/common';\nimport {\n ComponentNotFoundError,\n LayoutRefNotFoundError,\n NovaError,\n RenderError,\n} from '../shared/errors';\nimport { createScopeChain, getPath, pushScope, resolve } from '../shared/bindings';\nimport type { ScopeChain } from '../shared/bindings';\nimport { isBinding } from '../i18n/phrases';\nimport { passFor, swap, walkValue } from '../i18n/swap';\nimport type { Pass } from '../i18n/swap';\nimport {\n isComponentNode,\n isConditionalNode,\n isLayoutPrimitive,\n isLayoutRefNode,\n isLoopNode,\n isSlotNode,\n} from './guards';\nimport { HEAD_NAME } from './head';\nimport type { ComponentNode, LayoutNode } from './schemas';\nimport type {\n DataStoreView,\n ModelBindingDescriptor,\n RenderContext,\n RenderErrorNode,\n RenderNode,\n RenderOnError,\n} from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Renderer — converts a LayoutNode tree into a framework-agnostic\n// RenderNode[] tree. Renders children in try/catch boundaries so a\n// single broken subtree does not poison siblings, unless strict mode\n// is enabled. All errors flow through the ctx.onError telemetry hook.\n// ═══════════════════════════════════════════════════════════\n\nconst noopOnError: RenderOnError = (_error: NovaError): void => {\n // default — errors silently dropped if no handler provided\n};\n\ntype InternalRenderContext = {\n store: RenderContext['store'];\n registry: RenderContext['registry'];\n strict: boolean;\n onError: RenderOnError;\n scopePaths: string[];\n // Undefined when the host named no book and no keys — the whole language\n // apparatus is then absent rather than idling, and a `{ phrase, slots }`\n // object passes through as the object it is.\n pass: Pass | undefined;\n // Where a miss was found, coarse: the chain of component names above it.\n // Only maintained while a pass is active, since nothing else reads it.\n where: string;\n};\n\nconst textNode = (value: string): RenderNode => ({ type: 'text', value });\n\nconst fragment = (children: RenderNode[]): RenderNode => ({ type: 'fragment', children });\n\nconst errorNode = (\n error: NovaError,\n nodeRef: string | undefined,\n): RenderErrorNode => ({\n type: 'error',\n code: error.code,\n message: error.message,\n ...(nodeRef === undefined ? {} : { nodeRef }),\n});\n\nconst toRenderError = (err: unknown): NovaError => {\n if (err instanceof NovaError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new RenderError(message, {}, { cause: err });\n};\n\n// Resolve a `$.x.y` or `$loopVar.y` binding to an absolute data path\n// (used to construct stable model binding descriptors inside loops).\nconst resolveDataPath = (\n binding: string,\n scopePaths: string[],\n): string | undefined => {\n if (!binding.startsWith('$')) return undefined;\n const after = binding.slice(1);\n if (after.startsWith('.')) return after.slice(1);\n const segments = after.split('.');\n const head = segments[0];\n if (head === undefined || head.length === 0) return undefined;\n for (let i = scopePaths.length - 1; i >= 0; i -= 1) {\n const entry = scopePaths[i];\n if (entry === undefined) continue;\n const eq = entry.indexOf('=');\n if (eq < 0) continue;\n const key = entry.slice(0, eq);\n if (key !== head) continue;\n const rooted = entry.slice(eq + 1);\n const rest = segments.slice(1).join('.');\n if (rest.length === 0) return rooted;\n return `${rooted}.${rest}`;\n }\n return undefined;\n};\n\nconst makeAutoRef = (componentName: string, path: string): string =>\n `auto-${componentName}-${path}`;\n\nconst renderNode = (\n node: LayoutNode,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode[] => {\n if (node === null) return [textNode('')];\n if (typeof node === 'string') {\n const resolved = resolve(node, chain);\n if (resolved === undefined || resolved === null) return [textNode('')];\n const value = String(resolved);\n // A LITERAL text child is prose; a BOUND one is data wearing a text\n // position, and offering it to the book is how a member called \"Pass\" gets\n // renamed. Nothing but the renderer can tell those apart — by the time a\n // tree exists both are the same plain string — which is why this rule\n // could not be written in `translateRenderTree` and can be written here.\n if (ctx.pass === undefined || !ctx.pass.text || isBinding(node)) return [textNode(value)];\n return [textNode(swap(value, `${ctx.where}#text`, ctx.pass))];\n }\n if (isLayoutPrimitive(node)) {\n return [textNode(String(node))];\n }\n if (isArray(node)) {\n const children = renderChildArray(node, chain, ctx);\n return [fragment(children)];\n }\n if (isLayoutRefNode(node)) {\n const target = ctx.store.get(node.ref);\n if (target === undefined) {\n throw new LayoutRefNotFoundError(`Layout ref not found: ${node.ref}`, { ref: node.ref });\n }\n return renderNode(target, chain, ctx);\n }\n if (isSlotNode(node)) {\n // A slot is filled at fragment-merge time (fillSlots). One that survives to\n // render was never filled — render nothing.\n return [];\n }\n if (isConditionalNode(node)) {\n const condition = resolve(node.if, chain);\n const truthy =\n condition !== undefined &&\n condition !== null &&\n condition !== false &&\n condition !== 0 &&\n condition !== '';\n const branchTruthy = isArray(condition) ? condition.length > 0 : truthy;\n if (branchTruthy) return renderNode(node.then, chain, ctx);\n if (node.else !== undefined) return renderNode(node.else, chain, ctx);\n return [];\n }\n if (isLoopNode(node)) {\n const items = resolve(node.for, chain);\n if (!isArray(items)) return [];\n const loopBasePath = typeof node.for === 'string'\n ? resolveDataPath(node.for, ctx.scopePaths)\n : undefined;\n const out: RenderNode[] = [];\n items.forEach((item, index) => {\n // Each iteration binds three reserved loop vars: the element (`$<as>`),\n // its position (`$index`), and the array itself (`$items`). `$items`\n // lets a control inside the loop edit the whole list — remove or reorder\n // an element — not just its own value. Both `index` and `items` are\n // reserved names; an `as` of `'index'` or `'items'` would shadow them.\n const innerChain = pushScope(chain, { [node.as]: item, index, items });\n // `$items` resolves to a *writable* path (so `model: \"$items\"` works) only\n // when the loop's source is itself a resolvable path; a literal-array loop\n // exposes the value but stays read-only, exactly as `$<as>` does.\n const nextScopePaths =\n loopBasePath === undefined\n ? ctx.scopePaths\n : [...ctx.scopePaths, `${node.as}=${loopBasePath}.${index}`, `items=${loopBasePath}`];\n const innerCtx: InternalRenderContext = { ...ctx, scopePaths: nextScopePaths };\n // Stamp a stable React-identity key on each item's output: the value at\n // `node.key` (e.g. the row id), or the index when no key path is given.\n // This is what lets looped rows share a `ref` (the trigger target) without\n // colliding as React keys. `withKey` (in render-tree) prefers it over ref.\n const idKey = node.key !== undefined ? getPath(item, node.key) : index;\n const rendered = safeRenderSingle(node.do, innerChain, innerCtx, undefined);\n rendered.forEach((rn, sub) => {\n out.push({ ...rn, key: rendered.length === 1 ? String(idKey) : `${String(idKey)}:${sub}` });\n });\n });\n return [fragment(out)];\n }\n if (isComponentNode(node)) {\n return [renderComponent(node, chain, ctx)];\n }\n return [];\n};\n\nconst renderComponent = (\n node: ComponentNode,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode => {\n // The head draws nothing, so no kit has anything to register for it.\n if (node.component !== HEAD_NAME && !ctx.registry.has(node.component)) {\n throw new ComponentNotFoundError(\n `Component not found in registry: ${node.component}`,\n { name: node.component },\n );\n }\n // THE ONE PLACE A PROP BECOMES A WORD ON A SCREEN. The swap belongs here\n // rather than in a later walk over the finished tree: the value is already\n // in hand, so translating it costs one lookup instead of a second traversal\n // of everything that was just built.\n //\n // Unlike a text child, a BOUND prop is translated — that is the whole\n // `_display` mechanism, where a query manufactures a closed-set word and a\n // read puts it on the screen. What protects data here is the KEY: `label` is\n // prose, `name` is not, and no value ever votes on the question.\n const pass = ctx.pass;\n const at = pass === undefined ? '' : `${ctx.where}/${node.component}`;\n const props: Record<string, unknown> = Object.fromEntries(\n Object.entries(node.props ?? {}).map(([k, v]) => {\n const resolved = resolve(v, chain);\n if (pass === undefined) return [k, resolved];\n return [k, walkValue(resolved, pass.isProse(k), `${at}.${k}`, pass)];\n }),\n );\n const children = renderChildren(node.children, chain, pass === undefined ? ctx : { ...ctx, where: at });\n\n let model: ModelBindingDescriptor | undefined;\n if (node.model !== undefined) {\n const resolvedPath = resolveDataPath(node.model, ctx.scopePaths);\n if (resolvedPath !== undefined) {\n const ref = node.ref ?? makeAutoRef(node.component, resolvedPath);\n model = { path: resolvedPath, ref };\n // Two-way binding: if the component doesn't already have an explicit\n // `value` prop, auto-derive it from the model expression so the\n // displayed value tracks the data store. Without this, controlled\n // inputs always show their initial value because nothing updates the\n // `value` prop on re-render.\n if (!('value' in props)) {\n props['value'] = resolve(node.model, chain);\n }\n }\n }\n\n const component: RenderNode = {\n type: 'component',\n name: node.component,\n props,\n children,\n ...(node.ref === undefined ? {} : { ref: node.ref }),\n ...(model === undefined ? {} : { model }),\n };\n return component;\n};\n\nconst safeRenderSingle = (\n node: LayoutNode,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n nodeRef: string | undefined,\n): RenderNode[] => {\n try {\n return renderNode(node, chain, ctx);\n } catch (err) {\n const novaError = toRenderError(err);\n if (ctx.strict) throw novaError;\n ctx.onError(novaError);\n return [errorNode(novaError, nodeRef)];\n }\n};\n\nconst renderChildArray = (\n nodes: LayoutNode[],\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode[] => {\n const out: RenderNode[] = [];\n for (const child of nodes) out.push(...safeRenderSingle(child, chain, ctx, undefined));\n return out;\n};\n\nconst renderChildren = (\n children: LayoutNode | LayoutNode[] | undefined,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode[] => {\n if (children === undefined) return [];\n if (isArray(children)) return renderChildArray(children, chain, ctx);\n return safeRenderSingle(children, chain, ctx, undefined);\n};\n\nconst toInternal = (ctx: RenderContext): InternalRenderContext => ({\n store: ctx.store,\n registry: ctx.registry,\n strict: ctx.strict ?? false,\n onError: ctx.onError ?? noopOnError,\n scopePaths: [],\n // Built once per render call. The matcher compiles a Set and a suffix list,\n // and doing that per node would make the cheapest branch the expensive one.\n pass: passFor({\n ...(ctx.phrases === undefined ? {} : { phrases: ctx.phrases }),\n ...(ctx.phraseKeys === undefined ? {} : { keys: ctx.phraseKeys }),\n ...(ctx.onPhraseMiss === undefined ? {} : { onMiss: ctx.onPhraseMiss }),\n }),\n where: '',\n});\n\nexport const renderLayout = (\n node: LayoutNode,\n data: Record<string, unknown>,\n ctx: RenderContext,\n): RenderNode[] => {\n const internal = toInternal(ctx);\n return safeRenderSingle(node, createScopeChain(data), internal, undefined);\n};\n\n// Object-form alias for renderLayout. Same semantics, named parameters —\n// so the caller doesn't have to remember the positional order of\n// (layout, data, ctx) and so `data` can be omitted when the layout has\n// no resolvables.\nexport type RenderOptions = {\n layout: LayoutNode;\n data?: Record<string, unknown>;\n store: RenderContext['store'];\n registry: RenderContext['registry'];\n strict?: boolean;\n onError?: RenderOnError;\n phrases?: RenderContext['phrases'];\n phraseKeys?: RenderContext['phraseKeys'];\n onPhraseMiss?: RenderContext['onPhraseMiss'];\n};\n\nexport const render = (options: RenderOptions): RenderNode[] =>\n renderLayout(options.layout, options.data ?? {}, {\n store: options.store,\n registry: options.registry,\n ...(options.strict === undefined ? {} : { strict: options.strict }),\n ...(options.onError === undefined ? {} : { onError: options.onError }),\n ...(options.phrases === undefined ? {} : { phrases: options.phrases }),\n ...(options.phraseKeys === undefined ? {} : { phraseKeys: options.phraseKeys }),\n ...(options.onPhraseMiss === undefined ? {} : { onPhraseMiss: options.onPhraseMiss }),\n });\n\n// Render a layout reading its root data from a DataStore view. Used by the\n// action runtime so layout and action share a single data store instance.\nexport const renderLayoutFromStore = (\n node: LayoutNode,\n store: DataStoreView,\n ctx: RenderContext,\n): RenderNode[] => {\n const internal = toInternal(ctx);\n return safeRenderSingle(node, createScopeChain(store.get()), internal, undefined);\n};\n\nexport type { ScopeChain };\n","import { isComponentNode, isConditionalNode, isLoopNode, isSlotNode } from './guards';\nimport type { LayoutNode } from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// fillSlots — replace every `{ slot: name }` placeholder in a layout tree with\n// the layout in `fills[name]`. Used by the ActionFragment merge: a fragment's\n// chrome layout has a `{ slot: 'body' }`, and the composing action's own layout\n// is dropped into it. A slot whose name has no fill is left in place — the\n// renderer renders an unfilled slot as nothing.\n//\n// A pure tree-walk modelled on the layout store's `resolveReferences`: recurse\n// through children / then / else / do / arrays, rebuilding the tree.\n// ═══════════════════════════════════════════════════════════\n\nexport const fillSlots = (layout: LayoutNode, fills: Record<string, LayoutNode>): LayoutNode => {\n if (isSlotNode(layout)) {\n const fill = fills[layout.slot];\n return fill === undefined ? layout : fill;\n }\n if (Array.isArray(layout)) {\n return layout.map((node) => fillSlots(node, fills));\n }\n if (isComponentNode(layout)) {\n const { children } = layout;\n if (children === undefined) return layout;\n const next = Array.isArray(children)\n ? children.map((child) => fillSlots(child, fills))\n : fillSlots(children, fills);\n return { ...layout, children: next };\n }\n if (isConditionalNode(layout)) {\n return {\n ...layout,\n then: fillSlots(layout.then, fills),\n ...(layout.else === undefined ? {} : { else: fillSlots(layout.else, fills) }),\n };\n }\n if (isLoopNode(layout)) {\n return { ...layout, do: fillSlots(layout.do, fills) };\n }\n // primitives, layout refs, slot-less nodes — unchanged\n return layout;\n};\n","import type { RenderNode } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Adapter helpers — framework-agnostic pieces every adapter\n// (React, Vue, …) needs to render a RenderNode tree the same\n// way. See packages/nova/ADAPTER.md for the full contract.\n// ═══════════════════════════════════════════════════════════\n\n// Names of the props an adapter injects on rendered components:\n// `RenderNode.model` → NOVA_MODEL_PROP ({ ref, path }),\n// `RenderNode.ref` → NOVA_REF_PROP (string). Constants so all\n// adapters inject identically and components can rely on them.\nexport const NOVA_MODEL_PROP = 'novaModel';\nexport const NOVA_REF_PROP = 'novaRef';\n\n// Stable identity for a RenderNode within its sibling list.\n// Loop identity (stamped from LoopNode.key/index) wins over ref: a shared\n// `ref` across looped rows is an event-target id, not a list key.\nexport const renderNodeKey = (node: RenderNode, index: number): string => {\n if (node.key !== undefined) return `k:${node.key}`;\n if (node.type === 'component') {\n if (node.ref !== undefined) return `c:${node.ref}`;\n return `c:${node.name}:${index}`;\n }\n if (node.type === 'text') return `t:${index}`;\n if (node.type === 'fragment') return `f:${index}`;\n return `e:${node.code}:${index}`;\n};\n","import { DefinitionValidationError } from '../shared/errors';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport {\n isComponentNode,\n isConditionalNode,\n isLayoutRefNode,\n isLoopNode,\n} from './guards';\nimport { LayoutNodeSchema, type LayoutNode } from './schemas';\nimport type { LayoutStore } from './types';\n\nexport const createLayoutStore = (): LayoutStore => {\n const layouts = new Map<string, LayoutNode>();\n\n const get = (id: string): LayoutNode | undefined => layouts.get(id);\n\n const set = (id: string, layout: LayoutNode): void => {\n // Before the schema: a deep enough layout overflows it (strata depth.ts).\n if (exceedsDepth(layout)) {\n throw new DefinitionValidationError(`Invalid layout for id \"${id}\"`, { failures: [{ id, issues: [{ code: 'custom', path: [], message: depthRefusal(), input: undefined }] }] });\n }\n const result = LayoutNodeSchema.safeParse(layout);\n if (!result.success) {\n throw new DefinitionValidationError(`Invalid layout for id \"${id}\"`, {\n failures: [{ id, issues: result.error.issues }],\n });\n }\n layouts.set(id, layout);\n };\n\n const remove = (id: string): void => {\n layouts.delete(id);\n };\n\n const list = (): string[] => Array.from(layouts.keys());\n\n const resolveReferences = (layout: LayoutNode): LayoutNode => {\n if (isLayoutRefNode(layout)) {\n const target = layouts.get(layout.ref);\n if (target === undefined) return layout;\n return resolveReferences(target);\n }\n if (Array.isArray(layout)) {\n return layout.map(resolveReferences);\n }\n if (isComponentNode(layout)) {\n const children = layout.children;\n let resolvedChildren: LayoutNode | LayoutNode[] | undefined;\n if (children === undefined) {\n resolvedChildren = undefined;\n } else if (Array.isArray(children)) {\n resolvedChildren = children.map(resolveReferences);\n } else {\n resolvedChildren = resolveReferences(children);\n }\n return {\n ...layout,\n ...(resolvedChildren === undefined ? {} : { children: resolvedChildren }),\n };\n }\n if (isConditionalNode(layout)) {\n return {\n ...layout,\n then: resolveReferences(layout.then),\n ...(layout.else === undefined ? {} : { else: resolveReferences(layout.else) }),\n };\n }\n if (isLoopNode(layout)) {\n return {\n ...layout,\n do: resolveReferences(layout.do),\n };\n }\n return layout;\n };\n\n return { get, set, delete: remove, list, resolveReferences };\n};\n","import type {\n ComponentEntry,\n ComponentMeta,\n ComponentRegistry,\n RegistrationInput,\n} from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Component registry\n//\n// Stores `{component, meta}` entries keyed by name. Components\n// can carry a static `.meta` property; `registerAll` picks it up\n// automatically. Explicit meta passed to `register`/`registerAll`\n// wins over a component's static meta.\n// ═══════════════════════════════════════════════════════════\n\nconst hasOwn = (value: object, key: string): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\n\nconst isComponentMeta = (value: unknown): value is ComponentMeta => {\n if (typeof value !== 'object' || value === null) return false;\n // Meta is an open bag with optional fields; any plain object qualifies.\n return true;\n};\n\nconst extractStaticMeta = <TComponent>(component: TComponent): ComponentMeta | undefined => {\n if (typeof component !== 'function' && (typeof component !== 'object' || component === null)) {\n return undefined;\n }\n const host: object = component;\n if (!hasOwn(host, 'meta')) return undefined;\n const candidate = (host as { meta: unknown }).meta;\n if (!isComponentMeta(candidate)) return undefined;\n return candidate;\n};\n\nconst isEntryShape = <TComponent>(\n value: RegistrationInput<TComponent>,\n): value is { component: TComponent; meta?: ComponentMeta } => {\n if (typeof value !== 'object' || value === null) return false;\n return hasOwn(value, 'component');\n};\n\nexport const createComponentRegistry = <TComponent = unknown>(): ComponentRegistry<TComponent> => {\n const entries = new Map<string, ComponentEntry<TComponent>>();\n\n const register = (name: string, component: TComponent, meta?: ComponentMeta): void => {\n const staticMeta = extractStaticMeta(component);\n const merged: ComponentMeta = { ...(staticMeta ?? {}), ...(meta ?? {}) };\n entries.set(name, { component, meta: merged });\n };\n\n const registerAll = (batch: Record<string, RegistrationInput<TComponent>>): void => {\n for (const name of Object.keys(batch)) {\n const input = batch[name];\n if (input === undefined) continue;\n if (isEntryShape<TComponent>(input)) {\n register(name, input.component, input.meta);\n } else {\n register(name, input);\n }\n }\n };\n\n const get = (name: string): ComponentEntry<TComponent> | undefined => entries.get(name);\n\n const has = (name: string): boolean => entries.has(name);\n\n const list = (): string[] => Array.from(entries.keys());\n\n return { register, registerAll, get, has, list };\n};\n","import { z } from 'zod';\n\n// The authoring contract of a head node (./head): what a layout may set on it.\n// Its props are bound and resolved like any other node's.\n\nconst HEAD_DESCRIPTION =\n 'What this screen says it is: its title, description and preview picture. Draws nothing. One per screen, holding everything it says: where several are on a screen the last one is used whole, and they are never merged.';\n\nexport const HeadPropsSchema = z\n .object({\n title: z.string().optional().describe('The name of what this screen shows. Written as given: it becomes the document title and the title of its preview.'),\n description: z.string().optional().describe('One or two sentences saying what this screen shows, as plain text.'),\n image: z\n .string()\n .optional()\n .describe(\n 'Address of a picture that stands for this screen where a link to it is previewed: an absolute URL, or a path. A path is made absolute against the page’s own address when the site’s address is known, and written as given when it is not.',\n ),\n kind: z\n .enum(['website', 'article'])\n .optional()\n .describe('What sort of thing this screen is. `article`: a piece of writing that stands on its own. `website`: anything else. Left out, nothing is written and the document keeps what it already says.'),\n structured: z\n .union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))])\n .optional()\n .describe('Structured data about what this screen shows: a JSON-LD object, or a list of them. Written as given, so each object carries its own `@context` and `@type`.'),\n })\n .strict()\n .describe(HEAD_DESCRIPTION);\n\nexport type HeadProps = z.infer<typeof HeadPropsSchema>;\n\n// What to register the name with, for a palette that should offer it.\nexport const HEAD_META = {\n description: HEAD_DESCRIPTION,\n propsSchema: HeadPropsSchema,\n};\n","import type { ComponentRegistry, ComponentMeta } from '../layout/types';\n\n// ───────────────────────────────────────────────────────────\n// Derive a layout-agent palette from a ComponentRegistry.\n//\n// Reads each component's `meta.description` + `meta.propsSchema` straight off the\n// registry and hands the agent a JSON Schema derived from the same Zod schema the\n// renderer validates against — no drift. Component authors put what the agent\n// needs on the source schema via `.describe()`; fixes go there, not here.\n// ───────────────────────────────────────────────────────────\n\nexport type LayoutPaletteEntry = { name: string; description: string; propsSchema?: object };\n\nexport type PaletteFromRegistryOptions = {\n // Optional allowlist of component names. When omitted, every registered\n // component appears — pass a curated subset to keep the agent's vocabulary\n // tight (e.g. exclude shell slots / nav chrome).\n include?: readonly string[];\n // Prop names to strip from every component's schema. Use it to hide props the\n // agent must not set — e.g. presentational knobs (`bg`, `class`, `pad`) — so the\n // components can only render in their default style.\n omitProps?: readonly string[];\n};\n\n// Drop `omit` keys from a JSON Schema's `properties` (and `required`), so the\n// agent never sees them.\nconst stripProps = (schema: object, omit: readonly string[]): object => {\n const s = schema as { properties?: Record<string, unknown>; required?: string[] };\n if (s.properties === undefined) return schema;\n const properties = { ...s.properties };\n for (const p of omit) delete properties[p];\n const required = s.required?.filter((r) => !omit.includes(r));\n return { ...s, properties, ...(required !== undefined ? { required } : {}) };\n};\n\n// ONE PALETTE ENTRY, from a component's meta — the conversion at the heart of a\n// palette, factored out so a second caller derives an author's props from the\n// SAME Zod schema and the SAME JSON-Schema target, never a fork that drifts.\n// moss's integration contract calls this to answer \"what may I build against\"\n// for a person, which is the same question the layout agent asks of the palette;\n// `omitProps` and binding-awareness stay the caller's concern. A component with\n// no schema yields name + description alone, exactly as a bare registration does.\nexport const paletteEntryOf = (name: string, meta: ComponentMeta, omitProps?: readonly string[]): LayoutPaletteEntry => {\n let propsSchema: object | undefined;\n if (meta.propsSchema !== undefined) {\n // The app's schema converts itself (Standard JSON Schema): it may come from\n // the app's zod copy, and ours would read that copy's metadata through our registry.\n const js = meta.propsSchema['~standard'].jsonSchema.output({ target: 'draft-07' });\n propsSchema = omitProps !== undefined && omitProps.length > 0 ? stripProps(js, omitProps) : js;\n }\n return { name, description: meta.description ?? '', ...(propsSchema === undefined ? {} : { propsSchema }) };\n};\n\nexport const paletteFromRegistry = (\n registry: ComponentRegistry,\n options: PaletteFromRegistryOptions = {},\n): LayoutPaletteEntry[] => {\n const names = options.include ?? registry.list();\n const out: LayoutPaletteEntry[] = [];\n for (const name of names) {\n const entry = registry.get(name);\n if (entry === undefined) continue;\n out.push(paletteEntryOf(name, entry.meta, options.omitProps));\n }\n return out;\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { hasKey, isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const SetByValueSchema = z\n .object({\n set: z.string().describe('Data path to write to, e.g. \"user.name\" or \"items.0.title\".'),\n value: z.unknown().describe('Literal value to write at the path.'),\n })\n .strict()\n .describe('Set a field at a path to a literal value.');\n\nexport type SetByValueMutation = z.infer<typeof SetByValueSchema>;\n\nexport const SetByFromSchema = z\n .object({\n set: z.string().describe('Data path to write to.'),\n from: z.string().describe('Data path (or template path) to read the value from.'),\n })\n .strict()\n .describe('Set a field at a path by copying from another path.');\n\nexport type SetByFromMutation = z.infer<typeof SetByFromSchema>;\n\nexport const setValueOp: MutationOp<SetByValueMutation> = {\n key: 'set',\n schema: SetByValueSchema,\n match: (mutation) => hasKey(mutation, 'set') && hasKey(mutation, 'value'),\n apply: (data, mutation) => {\n const next = setPath(data, mutation.set, mutation.value);\n return isObject(next) ? next : data;\n },\n};\n\nexport const setFromOp: MutationOp<SetByFromMutation> = {\n key: 'set',\n schema: SetByFromSchema,\n match: (mutation) => hasKey(mutation, 'set') && hasKey(mutation, 'from'),\n apply: (data, mutation) => {\n const value = getPath(data, mutation.from);\n const next = setPath(data, mutation.set, value);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const ToggleSchema = z\n .object({\n toggle: z.string().describe('Boolean data path to flip.'),\n })\n .strict()\n .describe('Flip a boolean at the given path.');\n\nexport type ToggleMutation = z.infer<typeof ToggleSchema>;\n\nexport const toggleOp: MutationOp<ToggleMutation> = {\n key: 'toggle',\n schema: ToggleSchema,\n apply: (data, mutation) => {\n const current = getPath(data, mutation.toggle);\n const flipped = !(current === true);\n const next = setPath(data, mutation.toggle, flipped);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const IncrementSchema = z\n .object({\n increment: z.string().describe('Numeric data path to increment.'),\n by: z.number().optional().describe('Amount to increment by; defaults to 1.'),\n })\n .strict()\n .describe('Increment a numeric field.');\n\nexport type IncrementMutation = z.infer<typeof IncrementSchema>;\n\nexport const incrementOp: MutationOp<IncrementMutation> = {\n key: 'increment',\n schema: IncrementSchema,\n apply: (data, mutation) => {\n const current = getPath(data, mutation.increment);\n const base = typeof current === 'number' ? current : 0;\n const by = mutation.by ?? 1;\n const next = setPath(data, mutation.increment, base + by);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const DecrementSchema = z\n .object({\n decrement: z.string().describe('Numeric data path to decrement.'),\n by: z.number().optional().describe('Amount to decrement by; defaults to 1.'),\n })\n .strict()\n .describe('Decrement a numeric field.');\n\nexport type DecrementMutation = z.infer<typeof DecrementSchema>;\n\nexport const decrementOp: MutationOp<DecrementMutation> = {\n key: 'decrement',\n schema: DecrementSchema,\n apply: (data, mutation) => {\n const current = getPath(data, mutation.decrement);\n const base = typeof current === 'number' ? current : 0;\n const by = mutation.by ?? 1;\n const next = setPath(data, mutation.decrement, base - by);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const PushSchema = z\n .object({\n push: z.string().describe('Array data path to append to.'),\n value: z.unknown().optional().describe('Value to append.'),\n })\n .strict()\n .describe('Append a value to an array field.');\n\nexport type PushMutation = z.infer<typeof PushSchema>;\n\nexport const pushOp: MutationOp<PushMutation> = {\n key: 'push',\n schema: PushSchema,\n // Guard against the PushEffect navigation effect whose `push` is an object.\n match: (mutation) => typeof mutation.push === 'string',\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.push);\n // push tolerates missing paths by creating a new array (lax mode only).\n if (current !== undefined && !isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `push: path \"${mutation.push}\" is not an array`,\n { op: 'push', path: mutation.push, reason: 'wrong-type' },\n );\n }\n return data;\n }\n if (current === undefined && ctx.strict) {\n throw new MutationError(\n `push: path \"${mutation.push}\" does not exist`,\n { op: 'push', path: mutation.push, reason: 'missing' },\n );\n }\n const arr = isArray(current) ? current.slice() : [];\n arr.push(mutation.value);\n const next = setPath(data, mutation.push, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const PopSchema = z\n .object({\n pop: z.string().describe('Array data path to remove the last element from.'),\n })\n .strict()\n .describe('Remove the last element from an array field.');\n\nexport type PopMutation = z.infer<typeof PopSchema>;\n\nexport const popOp: MutationOp<PopMutation> = {\n key: 'pop',\n schema: PopSchema,\n // Guard against the PopEffect whose `pop` is the literal `true`.\n match: (mutation) => typeof mutation.pop === 'string',\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.pop);\n if (!isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `pop: path \"${mutation.pop}\" ${current === undefined ? 'does not exist' : 'is not an array'}`,\n { op: 'pop', path: mutation.pop, reason: current === undefined ? 'missing' : 'wrong-type' },\n );\n }\n return data;\n }\n const arr = current.slice();\n arr.pop();\n const next = setPath(data, mutation.pop, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const RemoveAtSchema = z\n .object({\n removeAt: z.string().describe('Array data path to remove an element from.'),\n index: z\n .union([z.number().int(), z.string()])\n .describe('Index to remove. A string is a template (e.g. \"{{@event.payload}}\") resolved before applying.'),\n })\n .strict()\n .describe('Remove an element at a specific index of an array field.');\n\nexport type RemoveAtMutation = z.infer<typeof RemoveAtSchema>;\n\nexport const removeAtOp: MutationOp<RemoveAtMutation> = {\n key: 'removeAt',\n schema: RemoveAtSchema,\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.removeAt);\n if (!isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `removeAt: path \"${mutation.removeAt}\" ${current === undefined ? 'does not exist' : 'is not an array'}`,\n {\n op: 'removeAt',\n path: mutation.removeAt,\n reason: current === undefined ? 'missing' : 'wrong-type',\n },\n );\n }\n return data;\n }\n // Index may be a literal number or a resolved template; coerce and guard.\n const index = Number(mutation.index);\n if (!Number.isInteger(index)) return data;\n const arr = current.slice();\n arr.splice(index, 1);\n const next = setPath(data, mutation.removeAt, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const MoveSchema = z\n .object({\n move: z.string().describe('Array data path to reorder within.'),\n from: z\n .union([z.number().int(), z.string()])\n .describe('Index to move. A string is a template (e.g. \"{{@event.payload}}\") resolved before applying.'),\n to: z\n .union([z.number().int(), z.string()])\n .describe('Destination index. A string is a template resolved before applying.'),\n })\n .strict()\n .describe('Move an array element from one index to another.');\n\nexport type MoveMutation = z.infer<typeof MoveSchema>;\n\nexport const moveOp: MutationOp<MoveMutation> = {\n key: 'move',\n schema: MoveSchema,\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.move);\n if (!isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `move: path \"${mutation.move}\" ${current === undefined ? 'does not exist' : 'is not an array'}`,\n {\n op: 'move',\n path: mutation.move,\n reason: current === undefined ? 'missing' : 'wrong-type',\n },\n );\n }\n return data;\n }\n // from/to may be literal numbers or resolved templates; coerce and guard.\n const from = Number(mutation.from);\n const to = Number(mutation.to);\n if (!Number.isInteger(from) || !Number.isInteger(to)) return data;\n if (from < 0 || from >= current.length) return data;\n const arr = current.slice();\n const [item] = arr.splice(from, 1);\n arr.splice(Math.max(0, Math.min(to, arr.length)), 0, item);\n const next = setPath(data, mutation.move, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { deletePath, getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const ClearSchema = z\n .object({\n clear: z.string().describe('Array or object data path to clear.'),\n })\n .strict()\n .describe('Clear an array or object field.');\n\nexport type ClearMutation = z.infer<typeof ClearSchema>;\n\nexport const clearOp: MutationOp<ClearMutation> = {\n key: 'clear',\n schema: ClearSchema,\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.clear);\n if (isArray(current)) {\n const next = setPath(data, mutation.clear, []);\n return isObject(next) ? next : data;\n }\n if (isObject(current)) {\n const next = setPath(data, mutation.clear, {});\n return isObject(next) ? next : data;\n }\n if (ctx.strict) {\n throw new MutationError(\n `clear: path \"${mutation.clear}\" ${current === undefined ? 'does not exist' : 'is not an array or object'}`,\n {\n op: 'clear',\n path: mutation.clear,\n reason: current === undefined ? 'missing' : 'wrong-type',\n },\n );\n }\n const next = deletePath(data, mutation.clear);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const ResetSchema = z\n .object({\n reset: z.string().describe('Data path to reset to its initial (definition.data) value.'),\n })\n .strict()\n .describe('Reset a field to its initial value from the action definition.');\n\nexport type ResetMutation = z.infer<typeof ResetSchema>;\n\nexport const resetOp: MutationOp<ResetMutation> = {\n key: 'reset',\n schema: ResetSchema,\n apply: (data, mutation, ctx) => {\n const initialValue = getPath(ctx.initial, mutation.reset);\n const next = setPath(data, mutation.reset, initialValue);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { setValueOp, setFromOp } from './set';\nimport { toggleOp } from './toggle';\nimport { incrementOp } from './increment';\nimport { decrementOp } from './decrement';\nimport { pushOp } from './push';\nimport { popOp } from './pop';\nimport { removeAtOp } from './remove-at';\nimport { moveOp } from './move';\nimport { clearOp } from './clear';\nimport { resetOp } from './reset';\nimport type { MutationOp } from '../types';\n\n// The single source of truth for mutation operations. The validation schema,\n// the `Mutation` type, and the runtime dispatch table (see registry.ts) are\n// all derived from this one list — adding an op is a one-line change here.\nexport const OPS = [\n setValueOp,\n setFromOp,\n toggleOp,\n incrementOp,\n decrementOp,\n pushOp,\n popOp,\n removeAtOp,\n moveOp,\n clearOp,\n resetOp,\n] as const;\n\n// Precise mutation type, distributed from each op's own mutation shape.\ntype MutationOf<O> = O extends MutationOp<infer T> ? T : never;\nexport type Mutation = MutationOf<(typeof OPS)[number]>;\n\n// Runtime validator, derived from the ops: a mutation is any one of their\n// schemas. The cast widens each op's schema to `z.ZodType<Mutation>` (sound —\n// every op's mutation is a Mutation) so the union's output type is `Mutation`.\nexport const MutationSchema = z\n .union(\n OPS.map((op) => op.schema) as [z.ZodType<Mutation>, z.ZodType<Mutation>, ...z.ZodType<Mutation>[]],\n )\n .describe('A single immutable mutation applied to the action data.');\n","import { hasKey, isObject } from '@shared/common';\nimport { OPS, type Mutation } from './ops';\nimport type { MutationContext, MutationData, MutationOp } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Pure dispatch over the op list. Each op is generic over its own\n// mutation shape; `toDispatchOp` collapses that into a uniform handler\n// that runs the op's own schema parse before apply. The single `any` is\n// the deliberate type-erasure boundary where the heterogeneous ops meet\n// one dispatch table — each op's schema/apply stay type-checked at their\n// definition. The table is derived from OPS, so it can't drift from it.\n// ═══════════════════════════════════════════════════════════\n\ntype DispatchOp = {\n key: string;\n match: (mutation: Record<string, unknown>) => boolean;\n run: (data: MutationData, mutation: Record<string, unknown>, ctx: MutationContext) => MutationData;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- erasure boundary\nconst toDispatchOp = (op: MutationOp<any>): DispatchOp => ({\n key: op.key,\n match: op.match ?? ((mutation) => hasKey(mutation, op.key)),\n run: (data, mutation, ctx) => op.apply(data, op.schema.parse(mutation), ctx),\n});\n\nconst DISPATCH: readonly DispatchOp[] = OPS.map(toDispatchOp);\n\nconst findOp = (mutation: Record<string, unknown>): DispatchOp | undefined => {\n for (const op of DISPATCH) {\n if (op.match(mutation)) return op;\n }\n return undefined;\n};\n\nexport type ApplyMutationOptions = {\n /** Snapshot used by `reset`. Must be deep-cloned by the caller. */\n initial?: MutationData;\n /** Strict mode — array ops throw MutationError on missing/wrong-type paths. */\n strict?: boolean;\n};\n\nconst buildCtx = (opts: ApplyMutationOptions): MutationContext => ({\n initial: opts.initial ?? {},\n strict: opts.strict ?? false,\n});\n\nexport const applyMutation = (\n data: MutationData,\n mutation: Mutation,\n opts: ApplyMutationOptions = {},\n): MutationData => {\n if (!isObject(mutation)) return data;\n const op = findOp(mutation);\n if (op === undefined) return data;\n return op.run(data, mutation, buildCtx(opts));\n};\n\nexport const applyMutations = (\n data: MutationData,\n mutations: readonly Mutation[],\n opts: ApplyMutationOptions = {},\n): MutationData => {\n if (mutations.length === 0) return data;\n const ctx = buildCtx(opts);\n let current = data;\n for (const mutation of mutations) {\n if (!isObject(mutation)) continue;\n const op = findOp(mutation);\n if (op === undefined) continue;\n current = op.run(current, mutation, ctx);\n }\n return current;\n};\n","import { z } from 'zod';\n\nconst HttpEndpointSchema = z\n .object({\n url: z.string().describe('Template URL, e.g. \"/api/users/{{$.userId}}\".'),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method.'),\n headers: z.record(z.string(), z.string()).optional().describe('Static request headers.'),\n request: z\n .unknown()\n .optional()\n .describe(\n 'Transform config run by the injected evaluator over the ACTION DATA to build the ' +\n 'request body — EVALUATED ON EVERY CALL, so body values can follow screen state. ' +\n 'Static parts are literal JSON; a dynamic part is an evaluator op over the data root, ' +\n 'e.g. { \"q\": { \"$ref\": \"$.search\" } } makes body field q carry the current $.search each call. ' +\n 'Requires an injected transform.',\n ),\n response: z\n .unknown()\n .optional()\n .describe(\n 'Transform config run by the injected evaluator over the reply as received ' +\n '(`$` is the reply — object, array, or scalar) to produce the value stored at `target`. ' +\n 'Requires an injected transform.',\n ),\n target: z.string().optional().describe('Data path to store the result at on success.'),\n errorTarget: z.string().optional().describe('Data path to store the error at on failure.'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('How long to wait for the reply, in ms, before the call fails to onError. Defaults to the shell default (30000). Set it on an endpoint that is slow by nature — a model call that may take minutes.'),\n })\n .strict()\n .describe('A named HTTP call. `request`/`response` shape the body/reply via the injected transform.');\n\nconst FunctionEndpointSchema = z\n .object({\n fn: z\n .string()\n .describe(\n 'Key of a function registered in `ShellConfig.functions`. The host must ' +\n 'register the name before the action runs.',\n ),\n target: z.string().optional().describe('Data path to store the return value at on success.'),\n errorTarget: z.string().optional().describe('Data path to store the error at on failure.'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('How long to wait for the reply, in ms, before the call fails to onError. Defaults to the shell default (30000). Set it on an endpoint that is slow by nature — a model call that may take minutes.'),\n })\n .strict()\n .describe('A named local function call. Handler is provided via `ShellConfig.functions`.');\n\nexport const EndpointConfigSchema = z\n .union([HttpEndpointSchema, FunctionEndpointSchema])\n .describe('An endpoint — either an HTTP call or a local function.');\n\nexport type EndpointConfig = z.infer<typeof EndpointConfigSchema>;\nexport type HttpEndpointConfig = z.infer<typeof HttpEndpointSchema>;\nexport type FunctionEndpointConfig = z.infer<typeof FunctionEndpointSchema>;\n","import { z } from 'zod';\nimport { MutationSchema } from '../mutations';\nimport type { Mutation } from '../mutations';\n\n// ═══════════════════════════════════════════════════════════\n// Effects + Steps (recursive union of Mutation | Effect)\n// ═══════════════════════════════════════════════════════════\n\nexport type Step = Mutation | Effect;\n\nexport type CallEffect = {\n call: string;\n onSuccess?: Step[];\n onError?: Step[];\n};\n\nexport type EmitEffect = {\n emit: { channel: string; payload?: unknown };\n};\n\nexport type PushEffect = {\n push: { action: string; canvas?: string; input?: Record<string, unknown>; with?: string[] };\n};\n\nexport type PopEffect = { pop: true };\n\nexport type ReplaceEffect = {\n replace: { action: string; canvas?: string; input?: Record<string, unknown>; with?: string[] };\n};\n\n// Pop a canvas down to a given instance (everything above it is popped). The\n// stack-nav breadcrumb fires this with the target crumb's instance id.\nexport type PopToEffect = { popTo: { canvas?: string; instance: string } };\n\n// Reset a canvas to a single root action (clear the whole stack, then push). The\n// screen-level nav (sidebar) fires this so drilling into a record doesn't leave\n// a stale stack beneath the new screen.\nexport type ResetToEffect = {\n resetTo: { action: string; canvas?: string; input?: Record<string, unknown>; with?: string[] };\n};\n\n// Remove ONE instance anywhere in a canvas's stack (not just the top). On a\n// list-mode canvas — where every card is live and visible at once — this is how\n// a card's own close button dismisses itself. `pop` removes the top; this\n// removes a named one.\nexport type RemoveInstanceEffect = { removeInstance: { canvas?: string; instance: string } };\n\n// Sugar for `removeInstance` aimed at the firing instance itself: a card's X\n// says \"close me\" without knowing its own id. The runtime desugars it to\n// `removeInstance` with the instance's real id before it escapes.\nexport type RemoveSelfEffect = { removeSelf: true };\n\n// Make a canvas EQUAL a list read from the action's data — the declarative\n// verb (shell/reconcile.ts) as a step. Every other navigation step moves ONE\n// action; a surface whose actions come from rows (a set of tools, a set of\n// cards) has as many as the rows say, and a fixed list of steps cannot.\n// Missing actions are pushed, ones no longer listed are removed, ones already\n// there stay mounted. A row naming an action this shell does not have (not\n// granted) is skipped, as an ungranted `initial` candidate is.\nexport type ReconcileEffect = {\n reconcile: { to: string; action: string; input?: string; canvas?: string; own?: 'pushed' | 'canvas'; with?: string[] };\n};\nexport type ReloadEffect = { reload: true };\n\nexport type Effect =\n | CallEffect\n | EmitEffect\n | PushEffect\n | PopEffect\n | ReplaceEffect\n | PopToEffect\n | ResetToEffect\n | RemoveInstanceEffect\n | RemoveSelfEffect\n | ReconcileEffect\n | ReloadEffect;\n\nexport const StepSchema: z.ZodType<Step> = z.lazy(() =>\n z.union([MutationSchema, EffectSchema]).describe('A step is either a mutation or an effect.'),\n);\n\nconst CallEffectSchema: z.ZodType<CallEffect> = z.lazy(() =>\n z\n .object({\n call: z.string().describe('Name of the endpoint to invoke.'),\n onSuccess: z.array(StepSchema).optional().describe('Steps to run after a successful response.'),\n onError: z\n .array(StepSchema)\n .optional()\n .describe('Steps to run after an error response (with @error scope available).'),\n })\n .strict()\n .describe('Invoke a named endpoint with optional success/error step branches.'),\n);\n\nconst EmitEffectSchema = z\n .object({\n emit: z\n .object({\n channel: z.string().describe('Channel name to publish on.'),\n payload: z\n .unknown()\n .optional()\n .describe('Payload to publish; templates are resolved against the current data.'),\n })\n .strict()\n .describe('Channel + payload to publish.'),\n })\n .strict()\n .describe('Publish a payload to a message channel.');\n\nconst PushEffectSchema = z\n .object({\n push: z\n .object({\n action: z\n .string()\n .describe('Definition id of the action to push onto a canvas — MUST be an id that actually exists (an unknown id fails at click time, invisible to a mount check).'),\n canvas: z.string().optional().describe('Canvas id to push onto; defaults to the current canvas.'),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Initial input merged into the new action data. Keys must belong to the target action\\'s declared input contract — invented keys are silently useless.'),\n with: z\n .array(z.string())\n .optional()\n .describe('Fragment ids to compose the action with before it is instantiated. Each wraps the action (the action fills its `{ slot }`) and contributes its triggers/data; the action wins on conflict. See ActionFragment.'),\n })\n .strict()\n .describe('Push parameters.'),\n })\n .strict()\n .describe('Push a new action onto a canvas (escapes via onNavigate callback).');\n\nconst PopEffectSchema = z\n .object({\n pop: z.literal(true).describe('Sentinel literal — must be true.'),\n })\n .strict()\n .describe('Pop the current action (escapes via onNavigate callback).');\n\nconst ReplaceEffectSchema = z\n .object({\n replace: z\n .object({\n action: z.string().describe('Definition id of the replacement action.'),\n canvas: z\n .string()\n .optional()\n .describe('Canvas id to replace on; defaults to the current canvas.'),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Initial input merged into the new action data.'),\n with: z\n .array(z.string())\n .optional()\n .describe('Fragment ids to compose the action with before it is instantiated. Each wraps the action (the action fills its `{ slot }`) and contributes its triggers/data; the action wins on conflict. See ActionFragment.'),\n })\n .strict()\n .describe('Replace parameters.'),\n })\n .strict()\n .describe('Replace the current action (escapes via onNavigate callback).');\n\nconst PopToEffectSchema = z\n .object({\n popTo: z\n .object({\n canvas: z.string().optional().describe('Canvas id to pop on; defaults to the current canvas.'),\n instance: z.string().describe('Pop the canvas until this instance id is on top (no-op if absent).'),\n })\n .strict()\n .describe('Pop-to-instance parameters.'),\n })\n .strict()\n .describe('Pop a canvas down to a given instance (escapes via onNavigate callback).');\n\nconst ResetToEffectSchema = z\n .object({\n resetTo: z\n .object({\n action: z.string().describe('Definition id of the new root action.'),\n canvas: z.string().optional().describe('Canvas id to reset; defaults to the current canvas.'),\n input: z.record(z.string(), z.unknown()).optional().describe('Initial input merged into the new root action.'),\n with: z.array(z.string()).optional().describe('Fragment ids to compose the action with. See ActionFragment.'),\n })\n .strict()\n .describe('Reset parameters.'),\n })\n .strict()\n .describe('Clear a canvas and push a single new root action (escapes via onNavigate callback).');\n\nconst RemoveInstanceEffectSchema = z\n .object({\n removeInstance: z\n .object({\n canvas: z.string().optional().describe('Canvas id to remove from; defaults to the current canvas.'),\n instance: z.string().describe('Instance id to unmount and drop from the stack (no-op if absent).'),\n })\n .strict()\n .describe('Remove-instance parameters.'),\n })\n .strict()\n .describe('Remove one instance anywhere in a canvas stack (escapes via onNavigate callback).');\n\nconst RemoveSelfEffectSchema = z\n .object({\n removeSelf: z.literal(true).describe('Sentinel literal — must be true. Removes the firing instance (desugars to removeInstance).'),\n })\n .strict()\n .describe('Close the firing instance — the list-card X (escapes via onNavigate callback).');\n\nconst ReconcileEffectSchema = z\n .object({\n reconcile: z\n .object({\n to: z.string().describe('Binding to the desired list, e.g. \"$.tools\" — an array of rows; anything else is an empty list.'),\n action: z.string().describe('The row field naming the action to place, e.g. \"tool_id\". Rows without it are skipped.'),\n input: z.string().optional().describe('The row field holding that action\\'s input (an object), if any.'),\n canvas: z.string().optional().describe('Canvas id to reconcile; defaults to the current canvas.'),\n own: z\n .enum(['pushed', 'canvas'])\n .optional()\n .describe('What this step may remove: \"pushed\" (default) only what this action placed there; \"canvas\" everything on it — for an action that owns the canvas outright.'),\n with: z.array(z.string()).optional().describe('Fragment ids to compose each placed action with. See ActionFragment.'),\n })\n .strict()\n .describe('Reconcile parameters.'),\n })\n .strict()\n .describe('Make a canvas hold exactly the actions a list names: push the missing, remove the unlisted, keep the rest mounted (escapes via onNavigate callback).');\n\n// Re-run the firing instance's `mount` hook — the action re-reads whatever it\n// reads, in place, keeping its identity and its data.\n//\n// The gap this fills: a stacked canvas suspends what it covers and `resume`\n// already re-runs mount, so a revealed action is never stale. A LIST canvas\n// suspends nothing — every card stays active — so a card that loaded at seed\n// time and is opened an hour later would show the hour-old answer. `reload` is\n// what \"opening it\" means there.\nconst ReloadEffectSchema = z\n .object({\n reload: z.literal(true).describe('Sentinel literal — must be true. Re-runs this instance\\'s mount hook.'),\n })\n .strict()\n .describe('Re-read the firing instance in place — the list-card open.');\n\nexport const EffectSchema: z.ZodType<Effect> = z.lazy(() =>\n z\n .union([CallEffectSchema, EmitEffectSchema, PushEffectSchema, PopEffectSchema, ReplaceEffectSchema, PopToEffectSchema, ResetToEffectSchema, RemoveInstanceEffectSchema, RemoveSelfEffectSchema, ReconcileEffectSchema, ReloadEffectSchema])\n .describe('An effect that touches the outside world.'),\n);\n","import { z } from 'zod';\nimport { StepSchema } from './effects';\n\nexport const LifecycleConfigSchema = z\n .object({\n mount: z.array(StepSchema).optional().describe('Steps to run when the action mounts.'),\n unmount: z.array(StepSchema).optional().describe('Steps to run when the action unmounts.'),\n suspend: z.array(StepSchema).optional().describe('Steps to run when the action is suspended.'),\n resume: z.array(StepSchema).optional().describe('Steps to run when the action resumes.'),\n })\n .strict()\n .describe('Lifecycle hooks for the action runtime state machine.');\n\nexport type LifecycleConfig = z.infer<typeof LifecycleConfigSchema>;\n","import { z } from 'zod';\nimport { StepSchema } from './effects';\n\nexport const TriggerConfigSchema = z\n .object({\n event: z\n .string()\n .optional()\n .describe('UI event type to listen for: \"ui:click\" (activations, incl. table rows), \"ui:model\" (an input\\'s value changed), \"ui:key\".'),\n message: z.string().optional().describe('Message bus channel name to listen on (fired by an `emit` step, possibly from another action).'),\n ref: z\n .string()\n .optional()\n .describe('Component ref to filter events by — MUST match a `ref` carried by a node in this action\\'s layout; a trigger on a ref no layout node carries never fires.'),\n key: z.string().optional().describe('Key to filter \"ui:key\" events by, e.g. \"ArrowDown\".'),\n do: z\n .array(StepSchema)\n .describe('Ordered steps to execute when the trigger fires. Steps may reference the firing event as \"@event\" — \"@event.payload\" is the fired value (a table row click: the row\\'s clickKey/rowKey field; an input\\'s ui:model: the typed text).'),\n })\n .strict()\n .refine((trigger) => trigger.event !== undefined || trigger.message !== undefined, {\n message: 'A trigger must specify either \"event\" or \"message\".',\n })\n .describe('Binds an event or message source to an ordered sequence of steps.');\n\nexport type TriggerConfig = z.infer<typeof TriggerConfigSchema>;\n","import { z } from 'zod';\nimport { LayoutNodeSchema } from '@layout/schemas';\nimport { MutationSchema } from '../mutations';\nimport { EndpointConfigSchema } from './endpoints';\nimport { LifecycleConfigSchema } from './lifecycle';\nimport { TriggerConfigSchema } from './triggers';\n\n// ═══════════════════════════════════════════════════════════\n// Action Definition — composes all sibling schemas.\n// ═══════════════════════════════════════════════════════════\n\nexport const ActionDefinitionSchema = z\n .object({\n id: z.string().describe('Stable definition id.'),\n name: z.string().optional().describe('Human-readable name.'),\n description: z.string().optional().describe('Free-form description.'),\n title: z\n .string()\n .optional()\n .describe(\n \"A resolvable label for this instance, evaluated against its own data (e.g. '{{$.view.record.name}}'). Exposed as `instance.title` on a canvas's actionLayout scope so stack-nav chrome can label crumbs/tabs; falls back to `name` then the action id.\",\n ),\n layout: z\n .union([z.string(), LayoutNodeSchema])\n .optional()\n .describe('Either a layout id stored in the layout store, or an inline LayoutNode.'),\n data: z.record(z.string(), z.unknown()).optional().describe('Static default data merged with input on mount.'),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'JSON Schema of the data keys an opener may seed when loading this action — its public, openable-input contract (author in Zod, convert with z.toJSONSchema). Fields must be a subset of `data`. Descriptive only: the runtime does not validate loads against it.',\n ),\n triggers: z.array(TriggerConfigSchema).optional().describe('Event/message triggers.'),\n endpoints: z\n .record(z.string(), EndpointConfigSchema)\n .optional()\n .describe('Named endpoints — HTTP calls or local functions.'),\n lifecycle: LifecycleConfigSchema.optional().describe('Lifecycle hooks.'),\n })\n .strict()\n .describe('Definition of an action: layout + data + behavior.');\n\nexport type ActionDefinition = z.infer<typeof ActionDefinitionSchema>;\n\n// ═══════════════════════════════════════════════════════════\n// Action Fragment — a reusable PARTIAL action (every field optional) that is\n// MERGED into a concrete action at a push/replace `with`, producing the\n// effective ActionDefinition that gets instantiated. This is composition, not\n// inheritance: `Action + ActionFragment ⇒ Action`. A fragment is abstract — it\n// only exists merged, lives in its own registry, and cannot be pushed as an\n// action on its own. Its `layout` is the chrome that WRAPS the action; a\n// `{ slot: 'body' }` node in it is filled with the composing action's layout.\n// On merge: the action's layout fills the slot; data/endpoints deep-merge with\n// the action winning; triggers and per-hook lifecycle steps concatenate\n// (fragment first). See `composeAction`.\n// ═══════════════════════════════════════════════════════════\n\nexport const ActionFragmentSchema = z\n .object({\n kind: z.literal('fragment').describe('Discriminator — marks this as an abstract, merge-only fragment.'),\n id: z.string().describe('Stable fragment id, referenced from a push/replace `with: [...]`.'),\n name: z.string().optional().describe('Human-readable name.'),\n description: z.string().optional().describe('Free-form description.'),\n layout: z\n .union([z.string(), LayoutNodeSchema])\n .optional()\n .describe('The wrapping (chrome) layout, or a layout id. Put a `{ slot: \"body\" }` node where the composing action\\'s own layout is dropped in.'),\n data: z.record(z.string(), z.unknown()).optional().describe('Partial default data; deep-merged under the action (the action wins on conflict).'),\n triggers: z.array(TriggerConfigSchema).optional().describe('Pre-wired triggers (e.g. a modal\\'s close/cancel). Concatenated before the action\\'s triggers.'),\n endpoints: z\n .record(z.string(), EndpointConfigSchema)\n .optional()\n .describe('Named endpoints, merged under the action (the action wins on a name clash).'),\n lifecycle: LifecycleConfigSchema.optional().describe('Lifecycle hooks; per-hook steps run before the action\\'s.'),\n })\n .strict()\n .describe('A reusable partial action — layout + wired behavior — merged into a concrete action at a push `with`. Abstract: only exists merged, never instantiated alone.');\n\nexport type ActionFragment = z.infer<typeof ActionFragmentSchema>;\n\n// Re-export mutations schema (for backwards-compatible imports within action/)\nexport { MutationSchema };\nexport type { Mutation } from '../mutations';\n\n// Re-export sibling schemas + inferred types\nexport { EffectSchema, StepSchema } from './effects';\nexport type { Effect, Step, CallEffect, EmitEffect, PushEffect, PopEffect, ReplaceEffect, PopToEffect, ResetToEffect, RemoveInstanceEffect, RemoveSelfEffect, ReconcileEffect, ReloadEffect } from './effects';\nexport { TriggerConfigSchema } from './triggers';\nexport type { TriggerConfig } from './triggers';\nexport { EndpointConfigSchema } from './endpoints';\nexport type { EndpointConfig, HttpEndpointConfig, FunctionEndpointConfig } from './endpoints';\nexport { LifecycleConfigSchema } from './lifecycle';\nexport type { LifecycleConfig } from './lifecycle';\n","import { fillSlots } from '@layout';\nimport type { LayoutNode } from '@layout';\nimport type {\n ActionDefinition,\n ActionFragment,\n EndpointConfig,\n Step,\n TriggerConfig,\n} from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// composeAction — merge a concrete action with the fragments listed in a\n// push/replace `with`, producing the effective ActionDefinition to instantiate.\n// Composition, not inheritance: the action ALWAYS wins on conflict.\n//\n// - layout: each fragment WRAPS the layout so far — its `{ slot: 'body' }`\n// is filled with the action's own layout (innermost). Fragments\n// fold in array order, so the last listed is the outermost wrap.\n// (Wrapping fragments must use an inline layout, not a store id.)\n// - data: shallow-merge, action wins.\n// - triggers: concat — fragment triggers first, then the action's.\n// - endpoints: merge, action wins on a name clash.\n// - lifecycle: per-hook concat — fragment steps run before the action's.\n// - id/name/description/title/input: the action's (fragments have no say).\n// The result is a plain ActionDefinition.\n// ═══════════════════════════════════════════════════════════\n\nconst HOOKS = ['mount', 'unmount', 'suspend', 'resume'] as const;\n\nexport const composeAction = (\n action: ActionDefinition,\n fragments: ActionFragment[],\n): ActionDefinition => {\n if (fragments.length === 0) return action;\n\n // Layout — wrap the action's layout in each fragment's slot.\n let layout = action.layout;\n for (const frag of fragments) {\n const wrap = frag.layout;\n if (wrap === undefined) continue;\n if (typeof wrap === 'string') {\n layout = wrap; // stored-layout fragment: can't slot-fill, replaces\n continue;\n }\n layout = fillSlots(wrap, layout === undefined ? {} : { body: layout as LayoutNode });\n }\n\n // Data — fragments (in order), then the action on top.\n const data: Record<string, unknown> = {};\n for (const frag of fragments) Object.assign(data, frag.data ?? {});\n Object.assign(data, action.data ?? {});\n\n // Triggers — fragment triggers first, then the action's.\n const triggers: TriggerConfig[] = [\n ...fragments.flatMap((f) => f.triggers ?? []),\n ...(action.triggers ?? []),\n ];\n\n // Endpoints — fragments, then the action (action wins on a name clash).\n const endpoints: Record<string, EndpointConfig> = {};\n for (const frag of fragments) Object.assign(endpoints, frag.endpoints ?? {});\n Object.assign(endpoints, action.endpoints ?? {});\n\n // Lifecycle — per hook, fragment steps before the action's.\n const lifecycle: Record<string, Step[]> = {};\n for (const hook of HOOKS) {\n const steps: Step[] = [\n ...fragments.flatMap((f) => f.lifecycle?.[hook] ?? []),\n ...(action.lifecycle?.[hook] ?? []),\n ];\n if (steps.length > 0) lifecycle[hook] = steps;\n }\n\n return {\n id: action.id,\n ...(action.name === undefined ? {} : { name: action.name }),\n ...(action.description === undefined ? {} : { description: action.description }),\n ...(action.title === undefined ? {} : { title: action.title }),\n ...(action.input === undefined ? {} : { input: action.input }),\n ...(layout === undefined ? {} : { layout }),\n ...(Object.keys(data).length > 0 ? { data } : {}),\n ...(triggers.length > 0 ? { triggers } : {}),\n ...(Object.keys(endpoints).length > 0 ? { endpoints } : {}),\n ...(Object.keys(lifecycle).length > 0 ? { lifecycle } : {}),\n } as ActionDefinition;\n};\n","// ═══════════════════════════════════════════════════════════\n// Affordance collection — the deterministic half of the action/layout seam.\n//\n// A layout's interactive surface is fully present in its tree: `ref` (event\n// sources), `*Ref` props (component-specific event sources, e.g. a Table's\n// sortRef), `model` (two-way input bindings), and every `$.key` binding it\n// reads. A director agent that wires triggers against a layout it never sees\n// needs that surface as data — so it is DERIVED here by walking the tree,\n// never self-reported by the layout model. A receipt computed from the\n// artifact cannot lie about the artifact.\n// ═══════════════════════════════════════════════════════════\n\nexport type InteractiveRef = {\n ref: string;\n component: string;\n // How the ref is attached: the node's own `ref` field, or a `*Ref` prop name.\n via: string;\n};\n\nexport type InteractiveModel = {\n // The bound data path, e.g. '$.search'.\n path: string;\n component: string;\n};\n\nexport type InteractiveSurface = {\n refs: InteractiveRef[];\n models: InteractiveModel[];\n // Distinct top-level data keys the layout reads anywhere ('$.rows' → 'rows').\n boundKeys: string[];\n // Malformed-looking bindings: `$ident.…` where `ident` is neither the data\n // root (`$.`) nor a loop variable declared by an enclosing `for`/`as` —\n // e.g. `{{$kpi.count}}` (missing dot) renders literally and passes every\n // other check. Collected scope-aware so `{{$row.title}}` inside its loop\n // stays legal.\n suspectBindings: string[];\n componentCount: number;\n};\n\nconst KEY_PATTERN = /\\$\\.([A-Za-z_][A-Za-z0-9_]*)/g;\nconst VAR_PATTERN = /\\$([A-Za-z_][A-Za-z0-9_]*)\\./g;\n\nexport const collectInteractive = (layout: unknown): InteractiveSurface => {\n const refs: InteractiveRef[] = [];\n const models: InteractiveModel[] = [];\n const boundKeys = new Set<string>();\n const suspects = new Set<string>();\n let componentCount = 0;\n\n const scanString = (value: string, scope: ReadonlySet<string>): void => {\n for (const match of value.matchAll(KEY_PATTERN)) {\n const key = match[1];\n if (key !== undefined) boundKeys.add(key);\n }\n for (const match of value.matchAll(VAR_PATTERN)) {\n const name = match[1];\n if (name !== undefined && !scope.has(name)) suspects.add(`$${name}.`);\n }\n };\n\n const walk = (node: unknown, scope: ReadonlySet<string>): void => {\n if (typeof node === 'string') return scanString(node, scope);\n if (Array.isArray(node)) {\n for (const child of node) walk(child, scope);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n const record = node as Record<string, unknown>;\n\n // A `for` directive declares its loop variable for everything beneath.\n const loopVar = record['for'] !== undefined && typeof record['as'] === 'string' ? record['as'] : undefined;\n const childScope = loopVar !== undefined ? new Set([...scope, loopVar]) : scope;\n\n const component = typeof record['component'] === 'string' ? record['component'] : undefined;\n if (component !== undefined) {\n componentCount += 1;\n if (typeof record['ref'] === 'string' && record['ref'].length > 0) {\n refs.push({ ref: record['ref'], component, via: 'ref' });\n }\n if (typeof record['model'] === 'string' && record['model'].length > 0) {\n models.push({ path: record['model'], component });\n }\n const props = record['props'];\n if (props !== null && typeof props === 'object' && !Array.isArray(props)) {\n for (const [key, value] of Object.entries(props as Record<string, unknown>)) {\n if (key.endsWith('Ref') && typeof value === 'string' && value.length > 0) {\n refs.push({ ref: value, component, via: key });\n }\n }\n }\n }\n // Generic descent: directives (`if`/`for`), props, children, column cell\n // specs — every nested node and binding is reached without schema-specific\n // cases. Strings are scanned for `$.key` bindings on the way.\n for (const value of Object.values(record)) walk(value, childScope);\n };\n\n walk(layout, new Set());\n return {\n refs,\n models,\n boundKeys: [...boundKeys].sort(),\n suspectBindings: [...suspects].sort(),\n componentCount,\n };\n};\n","import { OPS } from './mutations/ops';\nimport type { Mutation, Step } from './schemas';\n\n// What a step list WRITES, derived from the op registry.\n//\n// Three places needed this and each kept its own copy of the op names: the\n// runtime (which steps are mutations), the audit (which data paths a definition\n// fills), and anything reflecting over a definition. `OPS` is already the single\n// source of truth for operations, so it is the source of truth here too — adding\n// an op stays a one-line change in ops/index.ts.\n\n// Every mutation op's key. Derived, so it cannot drift from the ops themselves.\nexport const MUTATION_KEYS: readonly string[] = [...new Set(OPS.map((op) => op.key))];\n\n// Each op's own discrimination. `push` and `pop` are the interesting ones: as a\n// string they name a data path (a mutation), as anything else they are the\n// navigation effect.\nconst MATCHERS = OPS.map((op) => op.match ?? ((step: Record<string, unknown>) => op.key in step));\n\nexport const isMutationStep = (step: Step): step is Mutation => MATCHERS.some((match) => match(step as unknown as Record<string, unknown>));\n\n// Every data path a step list writes, at any depth. `call` branches nest their\n// own steps, so one trigger can load and then set.\nexport const mutationPaths = (steps: unknown): string[] => {\n const found: string[] = [];\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n const step = node as Record<string, unknown>;\n if (isMutationStep(step as unknown as Step)) {\n for (const key of MUTATION_KEYS) {\n const value = step[key];\n if (typeof value === 'string') found.push(value);\n }\n }\n walk(step['onSuccess']);\n walk(step['onError']);\n };\n walk(steps);\n return found;\n};\n\n// `openIssue.issue_id` and `openIssue` are one key: both point the card at an\n// issue. Every reading below compares at this level.\nexport const rootOf = (path: string): string => path.split('.')[0] ?? path;\n","import { collectInteractive } from '../agent/affordances';\nimport { MUTATION_KEYS } from './grammar';\nimport type { ActionDefinition } from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// auditAction — static analysis of an ActionDefinition's internal wiring.\n//\n// A definition can parse, mount, and render politely while being broken in\n// every way that matters: a table bound to a key no endpoint fills, a search\n// box whose trigger re-calls a load that never reads it, a ref with no\n// trigger (dead chrome), a push into an action that doesn't exist. None of\n// that is visible to a schema parse or a mount probe — it IS visible in the\n// artifact. This audits the definition deterministically: every claim is a\n// cross-reference inside the definition (plus an optional catalog), so there\n// are no heuristics and no false authority.\n//\n// Scope: SELF-CONTAINED definitions with an inline layout — generated\n// actions above all. Hand-authored actions that receive triggers from\n// fragments (`with: [...]`) or bind stored layouts will report issues that\n// composition would resolve; audit the COMPOSED definition instead, or skip.\n// ═══════════════════════════════════════════════════════════\n\nexport type AuditCatalogEntry = {\n id: string;\n // The action's openable-input contract (a JSON Schema). When it carries\n // `properties`, seeded push input keys are checked against them.\n input?: Record<string, unknown>;\n};\n\nexport type AuditOptions = {\n // Known pushable action ids. When given, every push/replace/resetTo\n // target must be one of them (or the definition's own id), with input\n // keys from its contract.\n catalog?: ReadonlyArray<AuditCatalogEntry>;\n // Known message channels (derive them from the registered definitions —\n // see collectChannels). When given, a `message:` listen must name a known\n // channel or one this definition emits itself; an `emit` must name a known\n // channel or one this definition listens on. Catches the silent\n // never-fires class (\"tasks:changed\" vs \"tasks-changed\").\n channels?: ReadonlyArray<string>;\n};\n\nexport type AuditResult = { ok: boolean; issues: string[] };\n\n// The channels a definition talks on — every `message:` trigger (listens)\n// and every `emit` step (emits), nested steps included. Walk a whole\n// registry's definitions to derive the app's live channel vocabulary.\nexport type ChannelUsage = { emits: string[]; listens: string[] };\n\nexport const collectChannels = (definition: ActionDefinition): ChannelUsage => {\n const emits = new Set<string>();\n const listens = new Set<string>();\n\n const walkSteps = (list: unknown): void => {\n if (!Array.isArray(list)) return;\n for (const step of list) {\n if (!isRecord(step)) continue;\n const emit = step['emit'];\n if (isRecord(emit) && typeof emit['channel'] === 'string') emits.add(emit['channel']);\n if (typeof step['call'] === 'string') {\n walkSteps(step['onSuccess']);\n walkSteps(step['onError']);\n }\n }\n };\n for (const trigger of definition.triggers ?? []) {\n if (typeof trigger.message === 'string') listens.add(trigger.message);\n walkSteps(trigger.do);\n }\n for (const hook of Object.values(definition.lifecycle ?? {})) walkSteps(hook);\n\n return { emits: [...emits].sort(), listens: [...listens].sort() };\n};\n\n// Mutation ops whose value is a data PATH (see action/mutations/ops). The\nconst firstSegment = (path: string): string => {\n const segment = path.split('.')[0];\n return segment === undefined || segment.length === 0 ? path : segment;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\ntype NavTarget = { action: string; input?: Record<string, unknown> };\n\nconst navTargetOf = (step: Record<string, unknown>): NavTarget | undefined => {\n for (const key of ['push', 'replace', 'resetTo']) {\n const value = step[key];\n if (isRecord(value) && typeof value['action'] === 'string') {\n const input = value['input'];\n return { action: value['action'], ...(isRecord(input) ? { input } : {}) };\n }\n }\n return undefined;\n};\n\nexport const auditAction = (definition: ActionDefinition, options?: AuditOptions): AuditResult => {\n const issues: string[] = [];\n const dataKeys = new Set(Object.keys(definition.data ?? {}));\n const endpointNames = new Set(Object.keys(definition.endpoints ?? {}));\n\n // ── collect every step (structurally — nested onSuccess/onError included),\n // wherever steps live: triggers and lifecycle hooks ──\n const steps: Record<string, unknown>[] = [];\n const pushSteps = (list: unknown): void => {\n if (!Array.isArray(list)) return;\n for (const step of list) {\n if (!isRecord(step)) continue;\n steps.push(step);\n if (typeof step['call'] === 'string') {\n pushSteps(step['onSuccess']);\n pushSteps(step['onError']);\n }\n }\n };\n for (const trigger of definition.triggers ?? []) pushSteps(trigger.do);\n for (const hook of Object.values(definition.lifecycle ?? {})) pushSteps(hook);\n\n // ── steps: calls name real endpoints; mutations write declared keys;\n // navigation targets exist in the catalog with legal input keys ──\n for (const step of steps) {\n const call = step['call'];\n if (typeof call === 'string' && !endpointNames.has(call)) {\n issues.push(`step calls endpoint \"${call}\" but endpoints has no \"${call}\"`);\n }\n\n for (const key of MUTATION_KEYS) {\n const path = step[key];\n if (typeof path === 'string' && path.length > 0 && !dataKeys.has(firstSegment(path))) {\n issues.push(`step \"${key}: ${path}\" writes a key with no default in data`);\n }\n }\n\n const nav = navTargetOf(step);\n if (nav !== undefined && options?.catalog !== undefined) {\n const entry = options.catalog.find((candidate) => candidate.id === nav.action);\n if (entry === undefined && nav.action !== definition.id) {\n issues.push(`step pushes action \"${nav.action}\" which is not in the catalog`);\n continue;\n }\n const properties = entry?.input?.['properties'];\n if (nav.input !== undefined && isRecord(properties)) {\n for (const key of Object.keys(nav.input)) {\n if (!(key in properties)) {\n issues.push(`push to \"${nav.action}\" seeds input key \"${key}\" which is not in its input contract`);\n }\n }\n }\n }\n }\n\n // ── endpoints: targets land on declared keys ──\n for (const [name, endpoint] of Object.entries(definition.endpoints ?? {})) {\n for (const field of ['target', 'errorTarget'] as const) {\n const target = endpoint[field];\n if (typeof target === 'string' && target.length > 0 && !dataKeys.has(firstSegment(target))) {\n issues.push(`endpoint \"${name}\" ${field} \"${target}\" has no default in data`);\n }\n }\n }\n\n // ── message channels (when the app's vocabulary is provided) ──\n if (options?.channels !== undefined) {\n const known = new Set(options.channels);\n const usage = collectChannels(definition);\n for (const channel of usage.listens) {\n if (!known.has(channel) && !usage.emits.includes(channel)) {\n issues.push(`trigger listens on channel \"${channel}\" which nothing is known to emit`);\n }\n }\n for (const channel of usage.emits) {\n if (!known.has(channel) && !usage.listens.includes(channel)) {\n issues.push(`step emits channel \"${channel}\" which nothing is known to listen on`);\n }\n }\n }\n\n // ── layout ↔ data ↔ triggers (inline layouts only) ──\n if (definition.layout !== undefined && typeof definition.layout !== 'string') {\n const surface = collectInteractive(definition.layout);\n\n for (const key of surface.boundKeys) {\n if (!dataKeys.has(key)) {\n issues.push(`layout binds \"$.${key}\" but data has no \"${key}\" default`);\n }\n }\n\n for (const suspect of surface.suspectBindings) {\n issues.push(\n `layout binding \"${suspect}…\" is malformed — the data root is \"$.\" (\"$.key\"), and \"$name.\" is only legal for a loop variable declared by an enclosing for/as`,\n );\n }\n\n const layoutRefs = new Set(surface.refs.map((entry) => entry.ref));\n const triggerRefs = new Set(\n (definition.triggers ?? [])\n .map((trigger) => trigger.ref)\n .filter((ref): ref is string => typeof ref === 'string'),\n );\n for (const ref of layoutRefs) {\n if (!triggerRefs.has(ref)) {\n issues.push(`layout ref \"${ref}\" has no trigger — dead chrome`);\n }\n }\n for (const ref of triggerRefs) {\n if (!layoutRefs.has(ref)) {\n issues.push(`trigger listens on ref \"${ref}\" but no layout node carries it`);\n }\n }\n }\n\n return { ok: issues.length === 0, issues };\n};\n","import { createScopeChain, resolve } from '@shared/bindings';\nimport { hasKey } from '@shared/common';\nimport type { ScopeChain } from '@shared/bindings';\nimport type { EndpointConfig, FunctionEndpointConfig, HttpEndpointConfig } from '../schemas';\nimport type { FetchFn, FetchResponse, FunctionHandler, TransformFn, Unsubscribe } from '../types';\n\nconst stringifyForBody = (value: unknown): string | undefined => {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return undefined;\n }\n};\n\nconst resolveHeaders = (\n headers: Record<string, string> | undefined,\n chain: ScopeChain,\n): Record<string, string> | undefined => {\n if (headers === undefined) return undefined;\n const out: Record<string, string> = {};\n for (const key of Object.keys(headers)) {\n const value = resolve(headers[key], chain);\n out[key] = typeof value === 'string' ? value : String(value ?? '');\n }\n return out;\n};\n\nexport type EndpointResult =\n // `onChange` — the transport's later bodies, already shaped by the endpoint's\n // `response` (see FetchResponse.onChange). Absent for function endpoints and\n // for any transport that answers once.\n | { ok: true; data: unknown; status: number; onChange?: (handler: (data: unknown) => void) => Unsubscribe }\n | { ok: false; error: { status: number; message: string; data: unknown; aborted?: boolean; timedOut?: boolean } };\n\nconst defaultFetch: FetchFn = () => {\n throw new Error('No fetch implementation provided to action runtime');\n};\n\nconst tryParseJson = async (response: {\n json: () => Promise<unknown>;\n text: () => Promise<string>;\n}): Promise<unknown> => {\n try {\n return await response.json();\n } catch {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n }\n};\n\nexport type CallEndpointOptions = {\n endpoint: EndpointConfig;\n data: Record<string, unknown>;\n fetch?: FetchFn;\n transform?: TransformFn;\n signal?: AbortSignal;\n functions?: Record<string, FunctionHandler>;\n // The shell's default wait for the reply; the endpoint's own `timeoutMs` wins.\n timeoutMs?: number;\n};\n\nexport const DEFAULT_ENDPOINT_TIMEOUT_MS = 30_000;\n\n// A CALL THAT NEVER ANSWERS FAILS. A route that hangs used to leave the action\n// loading for as long as it lived — nothing failed, so nothing said so. Past\n// its wait the call fails to `onError` (not as an abort: an abort is the\n// action going away, and is silent), and the transport is told to stop through\n// the signal it was handed. It bounds the FIRST answer only: a reply that\n// keeps answering (a reactive read under moss) follows on after it.\nexport const callEndpoint = async (\n options: CallEndpointOptions,\n): Promise<EndpointResult> => {\n const wait = options.endpoint.timeoutMs ?? options.timeoutMs ?? DEFAULT_ENDPOINT_TIMEOUT_MS;\n const expiry = new AbortController();\n const signal = options.signal === undefined ? expiry.signal : AbortSignal.any([options.signal, expiry.signal]);\n const called = { ...options, signal };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<EndpointResult>((settle) => {\n timer = setTimeout(() => {\n settle({ ok: false, error: { status: 0, message: `no reply within ${wait}ms`, data: undefined, timedOut: true } });\n expiry.abort();\n }, wait);\n });\n try {\n const call = 'fn' in options.endpoint ? callFunctionEndpoint(options.endpoint, called) : callHttpEndpoint(options.endpoint, called);\n return await Promise.race([call, expired]);\n } finally {\n clearTimeout(timer);\n }\n};\n\nconst callHttpEndpoint = async (\n endpoint: HttpEndpointConfig,\n { data, fetch: fetchFn = defaultFetch, transform, signal }: CallEndpointOptions,\n): Promise<EndpointResult> => {\n const chain = createScopeChain(data);\n const resolvedUrl = resolve(endpoint.url, chain);\n const url = typeof resolvedUrl === 'string' ? resolvedUrl : String(resolvedUrl ?? '');\n const headers = resolveHeaders(endpoint.headers, chain);\n\n // `request` builds the body from the action data via the injected evaluator.\n // Declared without one is a hard error (never a silent empty body).\n let body: string | undefined;\n if (endpoint.request !== undefined) {\n if (transform === undefined) {\n return { ok: false, error: { status: 0, message: 'endpoint declares `request` but no transform was injected into the shell', data: undefined } };\n }\n try {\n body = stringifyForBody(transform(endpoint.request, data));\n } catch (err) {\n const message = err instanceof Error ? err.message : 'request transform failed';\n return { ok: false, error: { status: 0, message, data: undefined } };\n }\n }\n\n let response;\n try {\n response = await fetchFn(url, {\n method: endpoint.method,\n ...(headers === undefined ? {} : { headers }),\n ...(body === undefined ? {} : { body }),\n ...(signal === undefined ? {} : { signal }),\n });\n } catch (err) {\n const isAbort = err instanceof Error && err.name === 'AbortError';\n const message = err instanceof Error ? err.message : 'fetch failed';\n if (isAbort) return { ok: false, error: { status: 0, message, data: undefined, aborted: true } };\n return { ok: false, error: { status: 0, message, data: undefined } };\n }\n\n // A REPLY IS JSON. An endpoint's reply lands in `target`, runs through\n // `response`, and is read by a layout — all of it JSON. A success whose body\n // is not JSON (an HTML page, a proxy's text) used to land as whatever the\n // fallback read, and under a transport that cannot read a body twice that\n // was `undefined`: an empty screen that said it had succeeded. It is an\n // error now, and `onError` hears it. No Content is the one success with no\n // body. A FAILED reply stays tolerant — its text is still worth a message.\n if (!response.ok) {\n const failed = await tryParseJson(response);\n const message =\n hasKey(failed, 'message') && typeof failed['message'] === 'string'\n ? failed['message']\n : `HTTP ${response.status}`;\n return { ok: false, error: { status: response.status, message, data: failed } };\n }\n if (response.status === 204 || response.status === 205) {\n return { ok: true, data: undefined, status: response.status };\n }\n let payload: unknown;\n try {\n payload = await response.json();\n } catch {\n return { ok: false, error: { status: response.status, message: `the reply is not JSON (HTTP ${response.status})`, data: undefined } };\n }\n\n // `response` shapes the reply via the injected evaluator — over the reply\n // exactly as received (`$` is the reply: object, array, or scalar; no wrapping).\n // Declared without an evaluator is a hard error (never silently serve the\n // unshaped reply).\n let result: unknown = payload;\n if (endpoint.response !== undefined) {\n if (transform === undefined) {\n return { ok: false, error: { status: response.status, message: 'endpoint declares `response` but no transform was injected into the shell', data: payload } };\n }\n try {\n result = transform(endpoint.response, payload);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'response transform failed';\n return { ok: false, error: { status: response.status, message, data: payload } };\n }\n }\n\n const onChange = laterBodiesOf(response, endpoint.response, transform);\n return { ok: true, data: result, status: response.status, ...(onChange === undefined ? {} : { onChange }) };\n};\n\n// The transport's later bodies, shaped by the same `response` config as the\n// first. A body the transform rejects is dropped — the screen keeps the last\n// good value rather than showing a half-applied one.\nconst laterBodiesOf = (\n response: FetchResponse,\n config: unknown,\n transform: TransformFn | undefined,\n): ((handler: (data: unknown) => void) => Unsubscribe) | undefined => {\n const subscribe = response.onChange;\n if (subscribe === undefined) return undefined;\n if (config !== undefined && transform === undefined) return undefined;\n return (handler) =>\n subscribe((body) => {\n if (config === undefined || transform === undefined) {\n handler(body);\n return;\n }\n let shaped: unknown;\n try {\n shaped = transform(config, body);\n } catch {\n return;\n }\n handler(shaped);\n });\n};\n\nconst callFunctionEndpoint = async (\n endpoint: FunctionEndpointConfig,\n { data, signal, functions }: CallEndpointOptions,\n): Promise<EndpointResult> => {\n // Callers dispatching to a function endpoint must provide both a signal and\n // a registered handler. `runCall` guarantees both before reaching here.\n if (signal === undefined) {\n throw new Error('callEndpoint: function variant requires an AbortSignal');\n }\n const handler = functions?.[endpoint.fn];\n if (handler === undefined) {\n throw new Error(`callEndpoint: function \"${endpoint.fn}\" is not registered`);\n }\n\n try {\n const result = await handler(data, signal);\n if (signal.aborted) {\n return {\n ok: false,\n error: { status: 0, message: 'aborted', data: undefined, aborted: true },\n };\n }\n return { ok: true, data: result, status: 0 };\n } catch (err) {\n const isAbort = err instanceof Error && err.name === 'AbortError';\n const message = err instanceof Error ? err.message : 'function failed';\n if (isAbort) {\n return { ok: false, error: { status: 0, message, data: undefined, aborted: true } };\n }\n return { ok: false, error: { status: 0, message, data: undefined } };\n }\n};\n","// ═══════════════════════════════════════════════════════════\n// THE CAUSE OF A STEP — how far a chain has run from the gesture that started\n// it. Whether a chain of triggers ends cannot be decided from the definitions\n// in general (it can depend on data), but a budget can always be enforced, so\n// every hop a chain takes is counted and a chain past its budget stops.\n//\n// A ROOT is something from outside the action graph: a UI event, a message\n// published by the host, a mount nothing in a chain caused. A HOP is one\n// step of a chain handing off to more steps:\n//\n// · an `emit` reaching a `message` trigger,\n// · a `reload` re-running the mount hook,\n// · a navigation (`push`, `replace`, …) mounting the action it opens.\n//\n// Two limits, because a runaway chain comes in two shapes. A LOOP is deep:\n// `x` emits `x`, one hop after another. A FAN-OUT is wide: a trigger that\n// emits twice doubles every turn, and 64 doublings is more work than any\n// depth limit alone would stop in time. So depth is counted per branch and\n// hops are counted per root, across every branch the root grew.\n//\n// Tide parks a fact whose cause chain runs away (its maxChainDepth); this is\n// the same idea for actions.\n// ═══════════════════════════════════════════════════════════\n\nexport const CAUSE_DEPTH_LIMIT = 64;\nexport const CAUSE_HOPS_LIMIT = 1024;\n\nexport type Cause = {\n // Hops between this step and its root.\n depth: number;\n // Shared by every branch of one root.\n root: { hops: number };\n};\n\n// Every cause minted here, so one read back off the bus (which carries it\n// opaquely — shared code knows nothing of actions) is the same object, root\n// counter and all, and anything else a publisher passed is no cause at all.\nconst minted = new WeakSet<object>();\nconst mint = (cause: Cause): Cause => {\n minted.add(cause);\n return cause;\n};\nconst isMinted = (value: object): value is Cause => minted.has(value);\n\nexport const rootCause = (): Cause => mint({ depth: 0, root: { hops: 0 } });\n\nexport const asCause = (value: unknown): Cause | undefined =>\n typeof value === 'object' && value !== null && isMinted(value) ? value : undefined;\n\n// The cause one hop on from `parent` — a fresh root when there is no parent.\nexport const nextCause = (parent: Cause | undefined): Cause => {\n if (parent === undefined) return rootCause();\n parent.root.hops += 1;\n return mint({ depth: parent.depth + 1, root: parent.root });\n};\n\nexport const isRunaway = (cause: Cause): boolean =>\n cause.depth > CAUSE_DEPTH_LIMIT || cause.root.hops > CAUSE_HOPS_LIMIT;\n\nexport const runawayMessage = (cause: Cause, what: string): string =>\n `${what} stopped: its chain ran ${cause.depth} hops deep and ${cause.root.hops} hops in total from the gesture that started it ` +\n `(limits ${CAUSE_DEPTH_LIMIT} and ${CAUSE_HOPS_LIMIT}). A trigger that re-emits its own channel, or a mount that reloads itself, never ends.`;\n\n// THE CAUSE A NAVIGATION HANDS TO THE MOUNT IT STARTS. Navigation runs\n// synchronously from a step (step → shell → spawn → mount), and the mount\n// reads its cause before its first await, so the cause rides along for\n// exactly that synchronous stretch instead of being threaded through every\n// shell operation. Restored in `finally`, so a throw cannot leak it.\nlet ambient: Cause | undefined;\n\nexport const withCause = <T>(cause: Cause | undefined, run: () => T): T => {\n const before = ambient;\n ambient = cause;\n try {\n return run();\n } finally {\n ambient = before;\n }\n};\n\nexport const ambientCause = (): Cause | undefined => ambient;\n","// ═══════════════════════════════════════════════════════════\n// RUN ON THE NEXT TASK — after the current turn, with the event loop given a\n// chance to run timers and I/O in between (see the `emit` step for why).\n//\n// Not `setTimeout(…, 0)`: that is a timer, and timers are clamped — to ~1ms\n// in node, 4ms once nested in a browser, and up to the ~15ms system tick on\n// Windows — so every hop of an ordinary chain (write → announce → re-read)\n// would pay it. `setImmediate` (node) and a MessageChannel post (browsers)\n// are tasks with no clamp. A shared channel would hold a node process open\n// forever, which is why node takes `setImmediate` first.\n// ═══════════════════════════════════════════════════════════\n\ntype Task = () => void;\n\nconst viaChannel = (): ((task: Task) => void) => {\n const queue: Task[] = [];\n const channel = new MessageChannel();\n channel.port1.onmessage = (): void => {\n queue.shift()?.();\n };\n return (task) => {\n queue.push(task);\n channel.port2.postMessage(null);\n };\n};\n\nconst pick = (): ((task: Task) => void) => {\n // Read off the global rather than named: nova is surface-blind and carries\n // no node types.\n const host: object = globalThis;\n if ('setImmediate' in host && typeof host.setImmediate === 'function') {\n const immediate = host.setImmediate;\n return (task) => void immediate(task);\n }\n if (typeof MessageChannel === 'function') return viaChannel();\n return (task) => void setTimeout(task, 0);\n};\n\nlet scheduler: ((task: Task) => void) | undefined;\n\nexport const nextTask = (task: Task): void => {\n scheduler ??= pick();\n scheduler(task);\n};\n","import { createScopeChain, resolve } from '@shared/bindings';\nimport type { ExtraScopes, ScopeChain } from '@shared/bindings';\nimport type { DataStore } from '@shared/data-store';\nimport type { EventBus } from '@shared/event-bus';\nimport { isObject } from '@shared/common';\nimport type { MessageBus } from '@shared/message-bus';\nimport { setPath } from '@shared/bindings/paths';\nimport { applyMutations } from '../mutations';\nimport { isMutationStep } from '../grammar';\nimport type { EndpointConfig, Mutation, ReconcileEffect, Step } from '../schemas';\nimport { LifecycleError, UnknownFunctionError, type LifecycleHook, type NovaError } from '@shared/errors';\nimport type {\n EndpointEventInit,\n FetchFn,\n FunctionHandler,\n NavigateHandler,\n NavigationEffect,\n OnErrorHandler,\n TransformFn,\n Unsubscribe,\n} from '../types';\nimport { callEndpoint } from './endpoints';\nimport { withCause, type Cause } from './cause';\nimport { nextTask } from './next-task';\n\n// Wall-clock for endpoint durations. `performance` is present in node, the\n// browser, and jsdom; `Date.now` is the universal fallback.\nconst now = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();\n\n// THE CALLS AN INSTANCE HAS MADE, per endpoint name — held by the runtime,\n// which outlives every step context it builds. Two jobs, one ledger:\n//\n// · A response that lands after a NEWER call to the same endpoint already\n// landed is stale: it must not overwrite what the newer one wrote. (Before\n// this, the slower of two searches won — whichever answered last.)\n// · A response that can change later (`onChange`) is followed until a newer\n// call lands or the instance unmounts — never two at once, or an old\n// search's updates would keep writing over the new one's rows.\n//\n// Absent in a bare step context (a test driving `executeSteps` directly):\n// every response then lands as before and none is followed.\nexport type EndpointCalls = {\n // A ticket for a call that is about to start.\n begin: (endpoint: string) => number;\n // Record that this call's response landed. False when a newer call to the\n // same endpoint landed first — the caller must then leave `target` alone.\n land: (endpoint: string, ticket: number) => boolean;\n // Follow this call's later bodies, replacing whatever the endpoint followed.\n follow: (endpoint: string, ticket: number, stop: Unsubscribe) => void;\n};\n\nexport type StepContext = {\n dataStore: DataStore;\n endpoints: Record<string, EndpointConfig>;\n functions: Record<string, FunctionHandler>;\n // The shell's default wait for a reply; an endpoint's `timeoutMs` wins.\n endpointTimeoutMs?: number;\n eventBus: EventBus;\n messageBus: MessageBus;\n fetch?: FetchFn;\n transform?: TransformFn;\n onNavigate?: NavigateHandler;\n // Re-runs this instance's `mount` hook (the `reload` effect), one hop on\n // from `cause`. Supplied by the runtime, which owns the definition and its\n // lifecycle.\n onReload?: (cause: Cause | undefined) => Promise<void>;\n // How far this chain has run from the gesture that started it (./cause.ts).\n // Absent in a bare step context: the steps are then a root.\n cause?: Cause;\n // Reports a completed `call` step upward (the runtime stamps instance/canvas\n // and forwards to telemetry). Aborted calls are not reported.\n onEndpoint?: (event: EndpointEventInit) => void;\n calls?: EndpointCalls;\n extras: ExtraScopes;\n // The action's data as it was built at spawn — what `reset` restores a path\n // to. Absent in a bare step context: there is then nothing to restore from.\n initial?: Record<string, unknown>;\n strict: boolean;\n onError: OnErrorHandler;\n signal: AbortSignal;\n // True when the owning action is suspended (backgrounded under a stack). Event\n // triggers no-op while suspended — only the active action reacts.\n suspended?: boolean;\n // When set, this step execution is running inside a lifecycle hook.\n // In strict mode, hard failures (unknown endpoint, fetch error without\n // a handler) propagate as LifecycleError instead of being swallowed.\n lifecycleHook?: LifecycleHook;\n};\n\nexport const noopOnError: OnErrorHandler = (_error: NovaError): void => {\n // default no-op; users install their own via config\n};\n\n// Template surfaces that get pre-resolved so the mutation subsystem stays\n// scope-unaware (ops receive already-literal values): `set`/`push` carry a\n// user value (e.g. `{{@error.message}}`); `removeAt`/`move` carry indices\n// that can reference the firing event (e.g. `{{@event.payload}}`). A string\n// index is resolved and coerced to a number; everything else passes through.\nconst resolveMutationValues = (\n list: Mutation[],\n chain: ScopeChain,\n extras: ExtraScopes,\n): Mutation[] => {\n return list.map((m) => {\n if ('set' in m && 'value' in m) {\n return { ...m, value: resolve(m.value, chain, extras) };\n }\n if ('push' in m && typeof m.push === 'string' && 'value' in m) {\n return { ...m, value: resolve(m.value, chain, extras) };\n }\n if ('removeAt' in m && typeof m.index === 'string') {\n return { ...m, index: Number(resolve(m.index, chain, extras)) };\n }\n if ('move' in m) {\n return {\n ...m,\n from: typeof m.from === 'string' ? Number(resolve(m.from, chain, extras)) : m.from,\n to: typeof m.to === 'string' ? Number(resolve(m.to, chain, extras)) : m.to,\n };\n }\n return m;\n });\n};\n\n\nconst writeTarget = (\n dataStore: DataStore,\n target: string | undefined,\n value: unknown,\n): void => {\n if (target === undefined) return;\n dataStore.update((curr) => {\n const next = setPath(curr, target, value);\n return isObject(next) ? next : curr;\n });\n};\n\n// Shared fallback for \"target name not resolvable\" cases (unknown endpoint,\n// unknown function). Runs `onError` with a synthetic @error, else throws a\n// LifecycleError inside a lifecycle hook, else throws the caller-supplied\n// strict error, else silently returns.\nconst raiseUnknown = async (\n message: string,\n onError: Step[] | undefined,\n ctx: StepContext,\n strictError?: NovaError,\n): Promise<void> => {\n if (onError) {\n const errorExtras: ExtraScopes = {\n ...ctx.extras,\n '@error': { message, status: 0 },\n };\n await executeSteps(onError, { ...ctx, extras: errorExtras });\n return;\n }\n if (ctx.lifecycleHook !== undefined) {\n throw new LifecycleError(message, { hook: ctx.lifecycleHook });\n }\n if (ctx.strict && strictError !== undefined) throw strictError;\n};\n\nconst runCall = async (\n callName: string,\n onSuccess: Step[] | undefined,\n onError: Step[] | undefined,\n ctx: StepContext,\n): Promise<void> => {\n const raw = ctx.endpoints[callName];\n if (raw === undefined) {\n await raiseUnknown(`unknown endpoint: ${callName}`, onError, ctx);\n return;\n }\n // Resolve a function endpoint's `fn` through the data scope before dispatch, so\n // `fn: '{{$.saveFn}}'` lets one action pick its handler from data — the same way\n // push/replace already resolve their `action` target (see resolveNavTarget).\n // Literal fn names (no template) pass through resolve() unchanged.\n let endpoint = raw;\n if ('fn' in raw) {\n const chain = createScopeChain(ctx.dataStore.get());\n const fn = String(resolve(raw.fn, chain, ctx.extras) ?? '');\n endpoint = { ...raw, fn };\n if (ctx.functions[fn] === undefined) {\n await raiseUnknown(`unknown function: ${fn}`, onError, ctx, new UnknownFunctionError(fn));\n return;\n }\n }\n const ticket = ctx.calls?.begin(callName);\n const t0 = now();\n const result = await callEndpoint({\n endpoint,\n data: ctx.dataStore.get(),\n fetch: ctx.fetch,\n transform: ctx.transform,\n signal: ctx.signal,\n functions: ctx.functions,\n ...(ctx.endpointTimeoutMs === undefined ? {} : { timeoutMs: ctx.endpointTimeoutMs }),\n });\n if (ctx.signal.aborted) return;\n if (!result.ok && result.error.aborted === true) return;\n // Telemetry: the call completed (ok or error, not aborted) — report it. The\n // endpoint's kind is structural: `fn` in the config means an in-process\n // function endpoint, otherwise an HTTP one.\n ctx.onEndpoint?.({\n name: callName,\n kind: 'fn' in endpoint ? 'fn' : 'http',\n ok: result.ok,\n status: result.ok ? result.status : result.error.status,\n ms: now() - t0,\n });\n if (result.ok) {\n const isCurrent = ticket === undefined || ctx.calls === undefined || ctx.calls.land(callName, ticket);\n if (isCurrent) {\n writeTarget(ctx.dataStore, endpoint.target, result.data);\n const { dataStore } = ctx;\n const { target } = endpoint;\n if (result.onChange !== undefined && ticket !== undefined && ctx.calls !== undefined) {\n ctx.calls.follow(callName, ticket, result.onChange((data) => writeTarget(dataStore, target, data)));\n }\n }\n if (onSuccess) await executeSteps(onSuccess, ctx);\n return;\n }\n writeTarget(ctx.dataStore, endpoint.errorTarget, result.error);\n if (onError) {\n const errorExtras: ExtraScopes = { ...ctx.extras, '@error': result.error };\n await executeSteps(onError, { ...ctx, extras: errorExtras });\n return;\n }\n if (ctx.lifecycleHook !== undefined) {\n throw new LifecycleError(`endpoint '${callName}' failed: ${result.error.message}`, {\n hook: ctx.lifecycleHook,\n });\n }\n};\n\n// The mount a navigation starts is one hop further down this chain: the shell\n// spawns and mounts synchronously, and the mount reads the cause from here.\nconst navigate = (effect: NavigationEffect, ctx: StepContext): void => {\n const { onNavigate } = ctx;\n if (onNavigate === undefined) return;\n withCause(ctx.cause, () => onNavigate(effect));\n};\n\n// Resolve a push/replace effect's `input` against the firing scope (current\n// data + `@event`), so a trigger can pass dynamic data to the action it opens\n// — e.g. `input: { record: '@event.payload' }`. Mirrors how `emit.payload` is\n// resolved; without it, input values reach the new action as raw templates.\nconst resolveInputMap = (\n input: Record<string, unknown>,\n ctx: StepContext,\n): Record<string, unknown> => {\n const chain = createScopeChain(ctx.dataStore.get());\n return Object.fromEntries(\n Object.entries(input).map(([key, value]) => [key, resolve(value, chain, ctx.extras)]),\n );\n};\n\n// Resolve a push/replace target: its `action` (so a trigger can open the action\n// a binding names — e.g. `action: '{{@event.payload}}'` to launch the clicked\n// result; literal ids pass through unchanged) and its `input` map.\nconst resolveNavTarget = <T extends { action: string; input?: Record<string, unknown> }>(\n nav: T,\n ctx: StepContext,\n): T => {\n const chain = createScopeChain(ctx.dataStore.get());\n const out: T = { ...nav, action: String(resolve(nav.action, chain, ctx.extras) ?? '') };\n if (nav.input !== undefined) out.input = resolveInputMap(nav.input, ctx);\n return out;\n};\n\nconst resolveNavInput = (effect: NavigationEffect, ctx: StepContext): NavigationEffect => {\n if ('push' in effect) return { push: resolveNavTarget(effect.push, ctx) };\n if ('replace' in effect) return { replace: resolveNavTarget(effect.replace, ctx) };\n if ('resetTo' in effect) return { resetTo: resolveNavTarget(effect.resetTo, ctx) };\n if ('popTo' in effect) {\n const chain = createScopeChain(ctx.dataStore.get());\n return { popTo: { ...effect.popTo, instance: String(resolve(effect.popTo.instance, chain, ctx.extras) ?? '') } };\n }\n if ('removeInstance' in effect) {\n const chain = createScopeChain(ctx.dataStore.get());\n return { removeInstance: { ...effect.removeInstance, instance: String(resolve(effect.removeInstance.instance, chain, ctx.extras) ?? '') } };\n }\n return effect;\n};\n\n// Resolve a `reconcile` step: read its list and turn each row into the action it\n// names (and that action's input, when the step names a field for it). A value\n// that is not a list is an empty one — the canvas empties, which is what an\n// empty list means.\nconst resolveReconcile = (step: ReconcileEffect, ctx: StepContext): NavigationEffect => {\n const { to, action, input, ...rest } = step.reconcile;\n const rows = resolve(to, createScopeChain(ctx.dataStore.get()), ctx.extras);\n const desired = (Array.isArray(rows) ? rows : []).flatMap((row: unknown) => {\n if (!isObject(row)) return [];\n const actionId = row[action];\n if (typeof actionId !== 'string' || actionId === '') return [];\n const seeded = input === undefined ? undefined : row[input];\n return [isObject(seeded) ? { actionId, input: seeded } : { actionId }];\n });\n return { reconcile: { ...rest, desired } };\n};\n\nexport const executeSteps = async (steps: Step[], ctx: StepContext): Promise<void> => {\n let buffer: Mutation[] = [];\n\n const flush = (): void => {\n if (buffer.length === 0) return;\n const list = buffer;\n buffer = [];\n // Resolve templates against the state at flush entry, matching\n // how `emit` captures data before publishing. The `@error` (and\n // any other) scope lives in ctx.extras.\n const chain = createScopeChain(ctx.dataStore.get());\n const resolved = resolveMutationValues(list, chain, ctx.extras);\n ctx.dataStore.update((curr) =>\n applyMutations(curr, resolved, { ...(ctx.initial === undefined ? {} : { initial: ctx.initial }), strict: ctx.strict }),\n );\n };\n\n for (const step of steps) {\n if (ctx.signal.aborted) {\n buffer = [];\n return;\n }\n if (isMutationStep(step)) {\n buffer.push(step);\n continue;\n }\n flush();\n\n if ('call' in step) {\n await runCall(step.call, step.onSuccess, step.onError, ctx);\n if (ctx.signal.aborted) return;\n continue;\n }\n if ('emit' in step) {\n const data = ctx.dataStore.get();\n const chain = createScopeChain(data);\n const resolvedChannel = resolve(step.emit.channel, chain, ctx.extras);\n const channel =\n typeof resolvedChannel === 'string' ? resolvedChannel : String(resolvedChannel ?? '');\n const payload =\n step.emit.payload === undefined\n ? undefined\n : resolve(step.emit.payload, chain, ctx.extras);\n // PUBLISHED AFTER THE TURN SETTLES, not inside it. The confirm pattern\n // emits then pops: the listener is the action UNDERNEATH, suspended\n // while the confirm sits over it, and a suspended action reacts to\n // nothing. Publishing synchronously delivers to it before the pop\n // reveals it — the message is lost. Deferring lets the same turn's pop\n // resume the listener (its status flips active synchronously) so the\n // message lands on a live subscriber. Resolved values are captured\n // above, so a later data change cannot alter what was announced.\n //\n // A TASK, NOT A MICROTASK. A listener that emits again queues another\n // delivery, and a chain of microtasks never lets the event loop turn:\n // under a server hosting many shells, one action whose trigger re-emits\n // its own channel froze every other principal's shell, the socket and\n // HTTP with it. A task (./next-task.ts) yields between hops, so a chain costs its own\n // shell time and nobody else's; ./cause.ts is what ends it.\n const { messageBus, cause } = ctx;\n nextTask(() => messageBus.publish(channel, payload, cause));\n continue;\n }\n if ('push' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('pop' in step) {\n navigate(step, ctx);\n continue;\n }\n if ('replace' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('popTo' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('resetTo' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('removeInstance' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('reconcile' in step) {\n navigate(resolveReconcile(step, ctx), ctx);\n continue;\n }\n if ('removeSelf' in step) {\n // The runtime desugars this to removeInstance with its own id — the step\n // carries no id to resolve.\n navigate(step, ctx);\n continue;\n }\n if ('reload' in step) {\n // Re-read in place. The runtime supplies the handler (it owns the\n // definition and the lifecycle); an action with no mount hook reloads to\n // nothing, which is correct rather than an error.\n await ctx.onReload?.(ctx.cause);\n if (ctx.signal.aborted) return;\n continue;\n }\n }\n\n flush();\n};\n","import { LifecycleError, type LifecycleHook } from '@shared/errors';\nimport type { ActionDefinition } from '../schemas';\nimport { executeSteps, type StepContext } from './steps';\n\nexport const buildInitialData = (\n definition: ActionDefinition,\n input: Record<string, unknown> | undefined,\n): Record<string, unknown> => {\n const defaults = definition.data ?? {};\n // Deep-clone so the runtime owns an isolated data tree: neither\n // `definition.data` nor the caller's `input` can be mutated by later in-place\n // mutations. Initial data is NOT transformed — the injected `transform` is\n // endpoint-only (request/response), never applied to the data on mount.\n return structuredClone({ ...defaults, ...(input ?? {}) });\n};\n\nexport const runLifecycleHook = async (\n hook: LifecycleHook,\n definition: ActionDefinition,\n buildContext: () => StepContext,\n): Promise<void> => {\n const lifecycle = definition.lifecycle;\n if (lifecycle === undefined) return;\n const steps = lifecycle[hook];\n if (steps === undefined || steps.length === 0) return;\n const ctx: StepContext = { ...buildContext(), lifecycleHook: hook };\n try {\n await executeSteps(steps, ctx);\n } catch (err) {\n if (!ctx.strict) {\n ctx.onError(\n err instanceof LifecycleError\n ? err\n : new LifecycleError(\n err instanceof Error ? err.message : String(err),\n { hook },\n { cause: err },\n ),\n );\n return;\n }\n if (err instanceof LifecycleError) throw err;\n throw new LifecycleError(\n err instanceof Error ? err.message : String(err),\n { hook },\n { cause: err },\n );\n }\n};\n","import type { RenderNode } from '@layout/types';\n\n// ═══════════════════════════════════════════════════════════\n// Walk a RenderNode[] tree and collect every model binding.\n// Used by the action runtime to install listeners on the event bus\n// that write `ui:model` payloads back into the data store.\n// ═══════════════════════════════════════════════════════════\n\nexport type ModelBinding = {\n ref: string;\n path: string;\n};\n\nconst walk = (node: RenderNode, out: ModelBinding[]): void => {\n if (node.type === 'component') {\n if (node.model !== undefined) {\n out.push({ ref: node.model.ref, path: node.model.path });\n }\n for (const child of node.children) walk(child, out);\n return;\n }\n if (node.type === 'fragment') {\n for (const child of node.children) walk(child, out);\n }\n};\n\nexport const collectModelBindings = (nodes: RenderNode[]): ModelBinding[] => {\n const out: ModelBinding[] = [];\n for (const node of nodes) walk(node, out);\n return out;\n};\n","import { renderLayoutFromStore } from '@layout/renderer';\nimport type { LayoutNode } from '@layout/schemas';\nimport type {\n ComponentRegistry,\n DataStoreView,\n LayoutStore,\n RenderContext,\n RenderNode,\n RenderOnError,\n} from '@layout/types';\nimport { isArray, isObject } from '@shared/common';\nimport type { ActionDefinition } from '../schemas';\n\nexport type RenderRuntimeContext = {\n store: LayoutStore;\n registry: ComponentRegistry;\n strict?: boolean;\n onError?: RenderOnError;\n // Passed straight through to the renderer, which is where a language enters.\n phrases?: RenderContext['phrases'];\n phraseKeys?: RenderContext['phraseKeys'];\n onPhraseMiss?: RenderContext['onPhraseMiss'];\n};\n\nconst isLayoutNode = (value: unknown): value is LayoutNode => {\n if (value === null) return true;\n const t = typeof value;\n if (t === 'string' || t === 'number' || t === 'boolean') return true;\n if (isArray(value)) return true;\n if (isObject(value)) return true;\n return false;\n};\n\nexport const renderRuntime = (\n definition: ActionDefinition,\n dataStore: DataStoreView,\n ctx: RenderRuntimeContext,\n): RenderNode[] => {\n const layout = definition.layout;\n if (layout === undefined) return [];\n if (typeof layout === 'string') {\n const target = ctx.store.get(layout);\n if (target === undefined) return [];\n return renderLayoutFromStore(target, dataStore, ctx);\n }\n if (!isLayoutNode(layout)) return [];\n return renderLayoutFromStore(layout, dataStore, ctx);\n};\n","import type { EventBus } from '@shared/event-bus';\nimport { hasKey } from '@shared/common';\nimport { ErrorCodes, NovaError } from '@shared/errors';\nimport type { MessageBus } from '@shared/message-bus';\nimport type { Unsubscribe } from '@shared/common';\nimport type { TriggerConfig } from '../schemas';\nimport { executeSteps, type StepContext } from './steps';\nimport { asCause, isRunaway, nextCause, rootCause, runawayMessage, type Cause } from './cause';\n\n// ═══════════════════════════════════════════════════════════\n// Trigger subscriptions for an action.\n//\n// Event triggers subscribe to the event bus on the declared `type`\n// (e.g. \"ui:click\"). If a `ref` is set, only events whose `ref` field\n// matches fire.\n//\n// Message triggers subscribe to the message bus by channel — no\n// `msg:` prefixing, no bridging through the event bus.\n//\n// Trigger step failures flow to the context's onError hook instead of\n// being silently dropped. If the runtime has been aborted (e.g. mid-\n// unmount), late-arriving events are dropped.\n// ═══════════════════════════════════════════════════════════\n\nexport type TriggerHandle = {\n detach: () => void;\n};\n\nconst eventRef = (event: unknown): string | undefined => {\n if (!hasKey(event, 'ref')) return undefined;\n const candidate = event['ref'];\n return typeof candidate === 'string' ? candidate : undefined;\n};\n\nconst eventKey = (event: unknown): string | undefined => {\n if (!hasKey(event, 'key')) return undefined;\n const candidate = event['key'];\n return typeof candidate === 'string' ? candidate : undefined;\n};\n\nconst toNovaError = (err: unknown): NovaError => {\n if (err instanceof NovaError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new NovaError(ErrorCodes.lifecycle, message, {}, { cause: err });\n};\n\nconst fireTrigger = (\n trigger: TriggerConfig,\n buildContext: () => StepContext,\n event: unknown,\n cause: Cause,\n): void => {\n const built = buildContext();\n if (built.signal.aborted) return;\n // A suspended action (backgrounded under a stack) reacts to nothing — only the\n // active top of a canvas handles events/messages.\n if (built.suspended === true) return;\n // A chain past its budget stops here, and says so (./cause.ts).\n if (isRunaway(cause)) {\n const what = trigger.message === undefined ? 'A trigger' : `The trigger on \"${trigger.message}\"`;\n built.onError(new NovaError(ErrorCodes.runaway, runawayMessage(cause, what), { channel: trigger.message, depth: cause.depth, hops: cause.root.hops }));\n return;\n }\n const base: StepContext = { ...built, cause };\n // Expose the firing event to the trigger's steps as `@event`, mirroring\n // how `@error` is injected on failed calls — so a step can reference\n // `{{@event.payload}}` (e.g. the clicked list index).\n const ctx: StepContext =\n event === undefined ? base : { ...base, extras: { ...base.extras, '@event': event } };\n void executeSteps(trigger.do, ctx).catch((err: unknown) => {\n ctx.onError(toNovaError(err));\n });\n};\n\nconst eventOrigin = (event: unknown): string | undefined => {\n if (!hasKey(event, 'origin')) return undefined;\n const candidate = event['origin'];\n return typeof candidate === 'string' ? candidate : undefined;\n};\n\nexport const attachTriggers = (\n triggers: TriggerConfig[],\n eventBus: EventBus,\n messageBus: MessageBus,\n buildContext: () => StepContext,\n ownInstanceId: string,\n): TriggerHandle => {\n const unsubscribes: Unsubscribe[] = [];\n\n for (const trigger of triggers) {\n if (trigger.event !== undefined) {\n const expectedRef = trigger.ref;\n const expectedKey = trigger.key;\n const triggerType: string = trigger.event;\n const off = eventBus.on(triggerType, (event) => {\n // A UI event stamped with an origin is delivered to that instance only;\n // events with no origin (programmatic `shell.dispatch`) stay global.\n const origin = eventOrigin(event);\n if (origin !== undefined && origin !== ownInstanceId) return;\n if (expectedRef !== undefined && eventRef(event) !== expectedRef) return;\n if (expectedKey !== undefined && eventKey(event) !== expectedKey) return;\n // A gesture starts a chain.\n fireTrigger(trigger, buildContext, event, rootCause());\n });\n unsubscribes.push(off);\n continue;\n }\n if (trigger.message !== undefined) {\n // A MESSAGE CARRIES ITS PAYLOAD THE SAME WAY A UI EVENT DOES. `emit`\n // takes one, steps resolve it, and the bus delivers it — so dropping it\n // here made `{ emit: { channel, payload } }` a declaration with no\n // reader, and an announcement that could only ever say \"something\n // happened\". Wrapped as `{ payload }` so a listener writes\n // `@event.payload` whether it was woken by a click or by an\n // announcement; `@event` is the firing thing in both cases.\n // One hop on from whatever emitted it; a host's publish carries no\n // cause and starts a chain of its own.\n const off = messageBus.subscribe(trigger.message, (payload: unknown, _from?: string, cause?: unknown) => {\n fireTrigger(trigger, buildContext, { payload }, nextCause(asCause(cause)));\n });\n unsubscribes.push(off);\n }\n }\n\n const detach = (): void => {\n for (const off of unsubscribes) off();\n };\n\n return { detach };\n};\n","import { z } from 'zod';\nimport { createDataStore } from '@shared/data-store';\nimport type { DataStore } from '@shared/data-store';\nimport { createIdFactory } from '@shared/ids';\nimport { DefinitionValidationError, ErrorCodes, NovaError } from '@shared/errors';\nimport type { RenderNode } from '@layout/types';\nimport type { Mutation, Step } from '../schemas';\nimport { StepSchema } from '../schemas';\nimport type {\n ActionInstance,\n ActionRuntime,\n ActionRuntimeConfig,\n ActionStatus,\n DataChangeHandler,\n NavigationEffect,\n OnErrorHandler,\n StatusChangeHandler,\n Unsubscribe,\n} from '../types';\nimport { applyMutations } from '../mutations';\nimport { buildInitialData, runLifecycleHook } from './lifecycle';\nimport { collectModelBindings } from './model-bindings';\nimport { renderRuntime } from './render';\nimport { executeSteps, noopOnError, type EndpointCalls, type StepContext } from './steps';\nimport { attachTriggers, type TriggerHandle } from './triggers';\nimport { ambientCause, isRunaway, nextCause, runawayMessage, type Cause } from './cause';\n\nconst defaultInstanceIdFactory = createIdFactory('act');\n\nexport const createActionRuntime = (config: ActionRuntimeConfig): ActionRuntime => {\n const definition = config.definition;\n const initialData = buildInitialData(definition, config.input);\n // Deep-clone so `reset` can restore nested structures without sharing\n // references with the live data store. Fixes correctness bug where\n // mutating nested objects would corrupt the snapshot used by reset.\n const initialSnapshot: Record<string, unknown> = structuredClone(initialData);\n const dataStore: DataStore = createDataStore(initialData);\n\n const abortController = new AbortController();\n const strict = config.strict ?? false;\n const onError: OnErrorHandler = config.onError ?? noopOnError;\n const instanceIdFn = config.instanceIdFn ?? defaultInstanceIdFactory;\n\n const instance: ActionInstance = {\n id: config.instanceId ?? instanceIdFn(),\n definitionId: definition.id,\n canvasId: config.canvasId ?? 'default',\n status: 'initializing',\n data: dataStore.get(),\n };\n\n const statusSubscribers: StatusChangeHandler[] = [];\n let triggerHandle: TriggerHandle | undefined;\n // The single `ui:model` write subscription, made in `attach()` BEFORE any\n // trigger so the model write is always first in the bus's insertion order —\n // a trigger listening to `ui:model` reads the value the event just wrote, not\n // the one the field held before the keystroke. See `attach()`.\n let modelWriteOff: Unsubscribe | undefined;\n // ref → path, the model bindings the current render carries. Reconciled every\n // render; consulted by the ONE subscription above at event time. Keeping this\n // a map (not a subscription per binding) is what lets a binding appear or\n // vanish across renders without ever touching the bus's ordering.\n const modelListeners = new Map<string, string>();\n\n dataStore.subscribe((next) => {\n instance.data = next;\n });\n\n // Per endpoint: the last ticket handed out, the newest that landed, and the\n // later-bodies subscription it holds. See `EndpointCalls` in steps.ts.\n const ledger = new Map<string, { issued: number; landed: number; stop?: Unsubscribe }>();\n const entryOf = (endpoint: string): { issued: number; landed: number; stop?: Unsubscribe } => {\n const existing = ledger.get(endpoint);\n if (existing !== undefined) return existing;\n const created = { issued: 0, landed: 0 };\n ledger.set(endpoint, created);\n return created;\n };\n const calls: EndpointCalls = {\n begin: (endpoint) => {\n const entry = entryOf(endpoint);\n entry.issued += 1;\n return entry.issued;\n },\n land: (endpoint, ticket) => {\n const entry = entryOf(endpoint);\n if (ticket < entry.landed) return false;\n entry.landed = ticket;\n // Whatever the endpoint followed belongs to an older call now.\n entry.stop?.();\n delete entry.stop;\n return true;\n },\n follow: (endpoint, ticket, stop) => {\n const entry = entryOf(endpoint);\n if (ticket !== entry.landed || abortController.signal.aborted) {\n stop();\n return;\n }\n entry.stop?.();\n entry.stop = stop;\n },\n };\n const stopFollowing = (): void => {\n for (const entry of ledger.values()) {\n entry.stop?.();\n delete entry.stop;\n }\n };\n\n // The runtime is the only place that knows THIS instance, so it desugars\n // `{ removeSelf: true }` — a card's \"close me\" — into a `removeInstance`\n // carrying the real id, and stamps a `reconcile` with who is placing things:\n // the firing action's definition id, which outlives any one instance of it\n // (a remounted deck still owns what it placed). Every other effect passes\n // through untouched.\n const stamp = (effect: NavigationEffect): NavigationEffect => {\n if ('removeSelf' in effect) return { removeInstance: { instance: instance.id } };\n if ('reconcile' in effect) return { reconcile: { origin: instance.definitionId, ...effect.reconcile } };\n return effect;\n };\n const onNavigate =\n config.onNavigate === undefined ? undefined : (effect: NavigationEffect): void => config.onNavigate!(stamp(effect));\n\n // RELOADS MERGE. A `reload` asked for while one is running does not start a\n // second mount beside it (a trigger that reloads and re-emits would double\n // them every turn): it marks the running one to go round once more, with\n // the newest cause, and returns. Each round is one hop, so a mount that\n // reloads itself ends where its budget does (./cause.ts).\n let reloading = false;\n let reloadAgain: { cause: Cause | undefined } | undefined;\n const reload = async (cause: Cause | undefined): Promise<void> => {\n if (reloading) {\n reloadAgain = { cause };\n return;\n }\n reloading = true;\n try {\n let next: { cause: Cause | undefined } | undefined = { cause };\n while (next !== undefined) {\n reloadAgain = undefined;\n const hop = nextCause(next.cause);\n if (isRunaway(hop)) {\n onError(new NovaError(ErrorCodes.runaway, runawayMessage(hop, `Reloading \"${definition.id}\"`), { depth: hop.depth, hops: hop.root.hops }));\n return;\n }\n await runLifecycleHook('mount', definition, () => buildContext(abortController.signal, hop));\n next = reloadAgain;\n }\n } finally {\n reloading = false;\n reloadAgain = undefined;\n }\n };\n\n const buildContext = (signal: AbortSignal = abortController.signal, cause?: Cause): StepContext => ({\n dataStore,\n endpoints: definition.endpoints ?? {},\n functions: config.functions ?? {},\n ...(config.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: config.endpointTimeoutMs }),\n eventBus: config.eventBus,\n messageBus: config.messageBus,\n ...(config.fetch === undefined ? {} : { fetch: config.fetch }),\n ...(config.transform === undefined ? {} : { transform: config.transform }),\n ...(onNavigate === undefined ? {} : { onNavigate }),\n // Stamp the call event with this instance's identity before it flows up to\n // the shell's telemetry — `runCall` only knows the endpoint, the runtime\n // knows who made it.\n ...(config.onEndpoint === undefined\n ? {}\n : { onEndpoint: (event) => config.onEndpoint!({ ...event, instanceId: instance.id, canvasId: instance.canvasId }) }),\n calls,\n extras: {},\n initial: initialSnapshot,\n strict,\n onError,\n signal,\n suspended: instance.status === 'suspended',\n // `reload` — re-run this instance's own mount hook. The same refresh\n // `resume` performs, made available as a step for canvases that never\n // suspend (a list keeps every card active, so nothing else would ever\n // re-read one).\n onReload: reload,\n ...(cause === undefined ? {} : { cause }),\n });\n\n const setStatus = (next: ActionStatus): void => {\n if (instance.status === next) return;\n instance.status = next;\n for (const handler of statusSubscribers.slice()) {\n try {\n handler(next);\n } catch {\n // ignore\n }\n }\n };\n\n const attach = (): void => {\n // FIRST, and unconditionally — before the trigger subscriptions below and\n // before either early return, so it wins the bus's insertion order even for\n // an action that has model bindings but no triggers (an inspector field\n // that only previews). The handler resolves the ref against the render-time\n // map at event time and applies the same origin/suspension checks and the\n // same write the per-binding listener used to.\n if (modelWriteOff === undefined) {\n modelWriteOff = config.eventBus.on('ui:model', (event) => {\n if (event.type !== 'ui:model' || instance.status === 'suspended') return;\n // A stamped model event reaches its own instance only; an unstamped\n // (global) one reaches every instance holding the ref.\n if (event.origin !== undefined && event.origin !== instance.id) return;\n if (event.ref === undefined) return;\n const path = modelListeners.get(event.ref);\n if (path === undefined) return;\n dataStore.update((curr) =>\n applyMutations(curr, [{ set: path, value: event.payload }], { initial: initialSnapshot, strict }),\n );\n });\n }\n if (triggerHandle !== undefined) return;\n const triggers = definition.triggers;\n if (triggers === undefined || triggers.length === 0) return;\n triggerHandle = attachTriggers(triggers, config.eventBus, config.messageBus, buildContext, instance.id);\n };\n\n const detach = (): void => {\n if (modelWriteOff !== undefined) {\n modelWriteOff();\n modelWriteOff = undefined;\n }\n if (triggerHandle === undefined) return;\n triggerHandle.detach();\n triggerHandle = undefined;\n };\n\n const getData = (): Record<string, unknown> => dataStore.get();\n\n const updateData = (updates: Record<string, unknown>): void => {\n dataStore.update((curr) => ({ ...curr, ...updates }));\n };\n\n const setData = (next: Record<string, unknown>): void => {\n dataStore.update(() => next);\n };\n\n const applyMutationList = (mutations: Mutation[]): void => {\n if (mutations.length === 0) return;\n dataStore.update((curr) =>\n applyMutations(curr, mutations, { initial: initialSnapshot, strict }),\n );\n };\n\n const StepArraySchema = z.array(StepSchema);\n\n const runSteps = async (steps: Step[]): Promise<void> => {\n const parsed = StepArraySchema.safeParse(steps);\n if (!parsed.success) {\n const error = new DefinitionValidationError(\n 'Invalid steps passed to runtime.executeSteps',\n { failures: [{ id: definition.id, issues: parsed.error.issues }] },\n );\n if (strict) throw error;\n onError(error);\n return;\n }\n await executeSteps(parsed.data, buildContext());\n };\n\n const mount = async (input?: Record<string, unknown>): Promise<void> => {\n if (input !== undefined) {\n const next = buildInitialData(definition, input);\n dataStore.update(() => next);\n }\n attach();\n // A mount a chain caused (a trigger's push) is one hop further down it;\n // one nothing caused starts its own. Read before the first await — the\n // navigation that set it is still on the stack (./cause.ts).\n const parent = ambientCause();\n const cause = nextCause(parent);\n if (isRunaway(cause)) {\n onError(new NovaError(ErrorCodes.runaway, runawayMessage(cause, `Mounting \"${definition.id}\"`), { depth: cause.depth, hops: cause.root.hops }));\n } else {\n await runLifecycleHook('mount', definition, () => buildContext(abortController.signal, cause));\n }\n // Only if nothing moved it meanwhile: an instance covered (or removed)\n // while its mount hook was still running stays suspended (or unmounted).\n if (instance.status === 'initializing') setStatus('active');\n };\n\n const unmount = async (): Promise<void> => {\n // Cancel any in-flight step execution before running unmount hooks, and\n // stop following every endpoint whose answer could still change.\n abortController.abort();\n stopFollowing();\n detach();\n teardownModelListeners();\n // Unmount hooks run on a fresh (non-aborted) signal so they can\n // perform their own async work (e.g. final telemetry calls).\n const unmountController = new AbortController();\n await runLifecycleHook('unmount', definition, () =>\n buildContext(unmountController.signal),\n );\n setStatus('unmounted');\n };\n\n const suspend = async (): Promise<void> => {\n await runLifecycleHook('suspend', definition, buildContext);\n setStatus('suspended');\n };\n\n const resume = async (): Promise<void> => {\n // Becoming active again re-runs `mount` to refresh the action's data — so a\n // backgrounded action (which ignored everything while suspended) is current\n // when it's revealed, with no need to keep it live underneath — then the\n // `resume` hook, if the action defines one.\n setStatus('active');\n await runLifecycleHook('mount', definition, buildContext);\n await runLifecycleHook('resume', definition, buildContext);\n };\n\n // The map the ONE `ui:model` subscription (see `attach()`) consults at event\n // time. Rebuilt from the render tree every render — a binding inside a loop\n // depends on the data, so the set is not knowable before a render. This only\n // ever touches the map, never the bus, so the write's position ahead of the\n // triggers is unaffected by a binding appearing or vanishing across renders.\n const reconcileModelBindings = (nodes: RenderNode[]): void => {\n modelListeners.clear();\n for (const b of collectModelBindings(nodes)) modelListeners.set(b.ref, b.path);\n };\n\n const teardownModelListeners = (): void => {\n modelListeners.clear();\n };\n\n const render = (): RenderNode[] => {\n // Asked per render, not held: `shell.setPhrases` has to reach the screens\n // that are already open, and a book captured at spawn could not.\n const language = config.i18n?.();\n const out = renderRuntime(definition, dataStore, {\n store: config.layoutStore,\n registry: config.registry,\n strict,\n onError,\n ...(language?.phrases === undefined ? {} : { phrases: language.phrases }),\n ...(language?.phraseKeys === undefined ? {} : { phraseKeys: language.phraseKeys }),\n ...(language?.onPhraseMiss === undefined ? {} : { onPhraseMiss: language.onPhraseMiss }),\n });\n reconcileModelBindings(out);\n return out;\n };\n\n const onDataChange = (handler: DataChangeHandler): Unsubscribe => dataStore.subscribe(handler);\n\n const onStatusChange = (handler: StatusChangeHandler): Unsubscribe => {\n statusSubscribers.push(handler);\n return (): void => {\n const idx = statusSubscribers.indexOf(handler);\n if (idx >= 0) statusSubscribers.splice(idx, 1);\n };\n };\n\n const dispose = (): void => {\n stopFollowing();\n detach();\n teardownModelListeners();\n statusSubscribers.length = 0;\n };\n\n return {\n get instance() {\n return instance;\n },\n get definition() {\n return definition;\n },\n get dataStore() {\n return dataStore;\n },\n getData,\n setData,\n updateData,\n applyMutations: applyMutationList,\n executeSteps: runSteps,\n mount,\n unmount,\n suspend,\n resume,\n render,\n onDataChange,\n onStatusChange,\n dispose,\n };\n};\n","import type {\n ActionDefinition,\n ActionFragment,\n ActionRuntime,\n EndpointHandler,\n FunctionHandler,\n LanguageOptions,\n NavigationEffect,\n OnErrorHandler,\n} from '../action';\nimport { ActionDefinitionSchema, ActionFragmentSchema } from '../action';\nimport { createActionRuntime } from '../action/runtime/runtime';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport type { RuntimeRegistry } from './runtime-registry';\nimport type { Shell } from './types';\nimport type { ComponentRegistry, LayoutStore } from '../layout';\nimport type { EventBus } from '../shared/event-bus';\nimport type { MessageBus } from '../shared/message-bus';\nimport {\n DefinitionValidationError,\n type DefinitionValidationFailure,\n} from '../shared/errors';\nimport type { IdFactory } from '../shared/ids';\nimport type { FetchFn, TransformFn } from '../action';\nimport type { Canvas } from './canvas';\nimport type { CanvasState } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Internal helpers for shell.ts — kept here to keep that file's\n// public-facing assembly short and scannable.\n// ═══════════════════════════════════════════════════════════\n\nexport const validateActions = (actions: Record<string, ActionDefinition>): void => {\n const failures: DefinitionValidationFailure[] = [];\n for (const [actionId, def] of Object.entries(actions)) {\n // Asked before the schema reads it: a recursive schema overflows the\n // stack on a deep enough document instead of refusing it (strata depth.ts).\n if (exceedsDepth(def)) {\n failures.push({ id: actionId, issues: [{ code: 'custom', path: [], message: depthRefusal(), input: undefined }] });\n continue;\n }\n const result = ActionDefinitionSchema.safeParse(def);\n if (!result.success) failures.push({ id: actionId, issues: result.error.issues });\n }\n if (failures.length > 0) {\n throw new DefinitionValidationError(\n `${failures.length} action definition(s) failed validation`,\n { failures },\n );\n }\n};\n\nexport const validateFragments = (fragments: Record<string, ActionFragment>): void => {\n const failures: DefinitionValidationFailure[] = [];\n for (const [fragmentId, frag] of Object.entries(fragments)) {\n if (exceedsDepth(frag)) {\n failures.push({ id: fragmentId, issues: [{ code: 'custom', path: [], message: depthRefusal(), input: undefined }] });\n continue;\n }\n const result = ActionFragmentSchema.safeParse(frag);\n if (!result.success) failures.push({ id: fragmentId, issues: result.error.issues });\n }\n if (failures.length > 0) {\n throw new DefinitionValidationError(\n `${failures.length} action fragment(s) failed validation`,\n { failures },\n );\n }\n};\n\nexport const snapshotCanvas = (canvas: Canvas): CanvasState => {\n const stack = canvas.stack.slice();\n return {\n id: canvas.id,\n stack,\n active: stack.length === 0 ? undefined : stack[stack.length - 1],\n };\n};\n\nexport type RuntimeFactoryDeps = {\n eventBus: EventBus;\n messageBus: MessageBus;\n layoutStore: LayoutStore;\n registry: ComponentRegistry;\n transform?: TransformFn;\n fetch?: FetchFn;\n functions?: Record<string, FunctionHandler>;\n endpointTimeoutMs?: number;\n strict: boolean;\n onError?: OnErrorHandler;\n instanceIdFn: IdFactory;\n onNavigate: (canvasId: string, effect: NavigationEffect) => void;\n onEndpoint?: EndpointHandler;\n // The shell's language cell, read per render. See ActionRuntimeConfig.i18n.\n i18n?: () => LanguageOptions | undefined;\n};\n\nexport const createRuntimeFactory = (deps: RuntimeFactoryDeps) => (\n canvasId: string,\n definition: ActionDefinition,\n input: Record<string, unknown> | undefined,\n): ActionRuntime =>\n createActionRuntime({\n definition,\n canvasId,\n ...(input === undefined ? {} : { input }),\n eventBus: deps.eventBus,\n messageBus: deps.messageBus,\n layoutStore: deps.layoutStore,\n registry: deps.registry,\n ...(deps.transform === undefined ? {} : { transform: deps.transform }),\n ...(deps.fetch === undefined ? {} : { fetch: deps.fetch }),\n ...(deps.functions === undefined ? {} : { functions: deps.functions }),\n ...(deps.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: deps.endpointTimeoutMs }),\n onNavigate: (effect) => deps.onNavigate(canvasId, effect),\n ...(deps.onEndpoint === undefined ? {} : { onEndpoint: deps.onEndpoint }),\n strict: deps.strict,\n ...(deps.onError === undefined ? {} : { onError: deps.onError }),\n ...(deps.i18n === undefined ? {} : { i18n: deps.i18n }),\n instanceIdFn: deps.instanceIdFn,\n });\n\n// ═══════════════════════════════════════════════════════════\n// Internal escape hatch for tests that need the full ActionRuntime\n// (executeSteps, applyMutations, etc.) — NOT re-exported from the\n// package root. Tests reach this via `@shell/shell-internals`.\n// ═══════════════════════════════════════════════════════════\n\nconst shellRegistries = new WeakMap<Shell, RuntimeRegistry>();\n\nexport const rememberShellRegistry = (shell: Shell, registry: RuntimeRegistry): void => {\n shellRegistries.set(shell, registry);\n};\n\nexport const getInternalRuntime = (\n shell: Shell,\n instanceId: string,\n): ActionRuntime | undefined => {\n const registry = shellRegistries.get(shell);\n if (registry === undefined) return undefined;\n return registry.get(instanceId);\n};\n","import type { ActionInstance } from '../action';\n\nexport type Canvas = {\n readonly id: string;\n readonly stack: ActionInstance[];\n peek: () => ActionInstance | undefined;\n pushInstance: (inst: ActionInstance) => void;\n popInstance: () => ActionInstance | undefined;\n replaceTop: (inst: ActionInstance) => ActionInstance | undefined;\n clearStack: () => ActionInstance[];\n};\n\nexport const createCanvas = (id: string): Canvas => {\n const stack: ActionInstance[] = [];\n\n const peek = (): ActionInstance | undefined => {\n if (stack.length === 0) return undefined;\n return stack[stack.length - 1];\n };\n\n const pushInstance = (inst: ActionInstance): void => {\n stack.push(inst);\n };\n\n const popInstance = (): ActionInstance | undefined => {\n return stack.pop();\n };\n\n const replaceTop = (inst: ActionInstance): ActionInstance | undefined => {\n const prev = stack.pop();\n stack.push(inst);\n return prev;\n };\n\n const clearStack = (): ActionInstance[] => {\n const removed = stack.slice();\n stack.length = 0;\n return removed;\n };\n\n return { id, stack, peek, pushInstance, popInstance, replaceTop, clearStack };\n};\n","// ═══════════════════════════════════════════════════════════\n// Slot component name constants.\n//\n// Every framework adapter (React, future Vue/Svelte/etc.) must\n// register components under these names in its ComponentRegistry\n// to participate in shell/canvas layout rendering:\n//\n// CANVAS_SLOT_NAME — renders a canvas by id (props: canvasId?)\n// ACTION_SLOT_NAME — renders an action instance by id (props: instanceId?)\n//\n// The shell uses these names in its default layouts and when\n// flattening a render tree for non-React consumers (evaluators,\n// export, testing), so they are part of the package's public\n// contract — not React-only.\n// ═══════════════════════════════════════════════════════════\n\nexport const CANVAS_SLOT_NAME = 'CanvasSlot';\nexport const ACTION_SLOT_NAME = 'ActionSlot';\n","import type { LayoutNode } from '../layout';\nimport { ACTION_SLOT_NAME, CANVAS_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// Default layouts used when a shell or canvas does not declare\n// its own. Preserves pre-layout-aware behaviour:\n// - shell: flex row over canvases, one CanvasSlot per canvas\n// - canvas: render only the top-of-stack instance\n// ═══════════════════════════════════════════════════════════\n\nexport const DEFAULT_SHELL_LAYOUT: LayoutNode = {\n component: 'Stack',\n props: { direction: 'row' },\n children: [\n {\n for: '$.canvases',\n as: 'c',\n key: 'id',\n do: {\n component: CANVAS_SLOT_NAME,\n props: { canvasId: '$.c.id' },\n },\n },\n ],\n};\n\nexport const DEFAULT_ACTION_LAYOUT: LayoutNode = {\n component: ACTION_SLOT_NAME,\n props: { instanceId: '$.active.id' },\n};\n","import type { RenderNode } from '../layout';\nimport type { Shell } from './types';\nimport { ACTION_SLOT_NAME, CANVAS_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// flattenRenderTree — expand slot markers into their resolved\n// content. A shell render tree contains CanvasSlot / ActionSlot\n// component nodes that only recurse at React render time; tests\n// and framework-agnostic consumers need a fully materialised tree.\n//\n// CanvasSlot → inline getCanvasRenderTree(canvasId), flattened.\n// ActionSlot → the marker SURVIVES, carrying identity (instanceId /\n// canvasId / definitionId) with runtime.render() as its children —\n// the per-instance boundary is part of the tree, so a remote\n// renderer can key reconciliation by instance and an app-supplied\n// slotWrapper can wrap each instance (animation, gating, chips).\n// A target with no wrapper renders the children straight through.\n// Unknown / missing ids resolve to an empty fragment (an empty slot\n// is NOT a marker — an empty canvas must stay visibly empty).\n// ═══════════════════════════════════════════════════════════\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === 'string' && value.length > 0 ? value : undefined;\n\nconst emptyFragment = (): RenderNode => ({ type: 'fragment', children: [] });\n\nexport const flattenRenderTree = (tree: RenderNode[], shell: Shell): RenderNode[] =>\n tree.map((node) => flattenNode(node, shell));\n\nconst flattenNode = (node: RenderNode, shell: Shell): RenderNode => {\n if (node.type !== 'component') {\n if (node.type === 'fragment') {\n return { type: 'fragment', children: flattenRenderTree(node.children, shell) };\n }\n return node;\n }\n\n if (node.name === CANVAS_SLOT_NAME) {\n const canvasId = asString(node.props['canvasId']);\n if (canvasId === undefined) return emptyFragment();\n return { type: 'fragment', children: flattenRenderTree(shell.getCanvasRenderTree(canvasId), shell) };\n }\n\n if (node.name === ACTION_SLOT_NAME) {\n const instanceId = asString(node.props['instanceId']);\n if (instanceId === undefined) return emptyFragment();\n const runtime = shell.getRuntime(instanceId);\n if (runtime === undefined) return emptyFragment();\n return {\n type: 'component',\n name: ACTION_SLOT_NAME,\n // identity only — never the definition itself (wire weight)\n props: { instanceId, canvasId: runtime.instance.canvasId, definitionId: runtime.instance.definitionId },\n children: runtime.render(),\n // keyed by instance so a renderer remounts when the instance changes\n // (no stale DOM state across instance swaps, enter animations fire)\n key: instanceId,\n };\n }\n\n return { ...node, children: flattenRenderTree(node.children, shell) };\n};\n","import type { ActionDefinition } from '@action';\nimport { mutationPaths, rootOf } from '@action/grammar';\n\n// What an action does with its DATA KEYS, read off its own definition.\n//\n// Four questions, each a pure function of the artifact and each with more than\n// one consumer: an audit asking whether declared state is reachable, an agent\n// asking whether a change was a person or a re-read, a devtools pane asking what\n// fills a field. Every one of them was being re-derived outside nova, which is\n// how a hand-copied list of mutation ops ended up in an application.\n\n// What a FINGER can write: every data path a `ui:` trigger sets.\nexport const gesturedKeys = (definition: ActionDefinition): readonly string[] => [\n ...new Set(\n (definition.triggers ?? [])\n .filter((trigger) => typeof trigger.event === 'string' && trigger.event.startsWith('ui:'))\n .flatMap((trigger) => mutationPaths(trigger.do))\n .map(rootOf),\n ),\n];\n\n// What an OPENER may set: the declared input contract.\nexport const declaredKeys = (definition: ActionDefinition): readonly string[] =>\n Object.keys((definition.input as { properties?: Record<string, unknown> } | undefined)?.properties ?? {});\n\n// What the DATABASE writes: every endpoint's landing place.\nexport const loadedKeys = (definition: ActionDefinition): readonly string[] => {\n const loaded = new Set<string>();\n for (const endpoint of Object.values(definition.endpoints ?? {})) {\n const spec = endpoint as { target?: string; errorTarget?: string };\n if (spec.target !== undefined) loaded.add(rootOf(spec.target));\n if (spec.errorTarget !== undefined) loaded.add(rootOf(spec.errorTarget));\n }\n return [...loaded];\n};\n\n// What a surface writes to ITSELF when it opens or resumes: a loading flag\n// clearing, a working flag resetting.\nexport const lifecycleKeys = (definition: ActionDefinition): readonly string[] => [\n ...new Set(\n Object.values((definition.lifecycle ?? {}) as Record<string, unknown>)\n .flatMap(mutationPaths)\n .map(rootOf),\n ),\n];\n\n// Endpoint names a `mount` step calls, at any depth.\nconst mountCalls = (definition: ActionDefinition): Set<string> => {\n const names = new Set<string>();\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n const step = node as Record<string, unknown>;\n if (typeof step['call'] === 'string') names.add(step['call']);\n walk(step['onSuccess']);\n walk(step['onError']);\n };\n walk((definition.lifecycle as { mount?: unknown } | undefined)?.mount);\n return names;\n};\n\n// Every `$.<key>` an endpoint's request reads. `{ id: { $ref: '$.issueId' } }`\n// and the bare form `'$.issueId'` both count.\nconst requestKeys = (request: unknown): string[] => {\n const found: string[] = [];\n const walk = (node: unknown): void => {\n if (typeof node === 'string') {\n if (node.startsWith('$.')) found.push(rootOf(node.slice(2)));\n return;\n }\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n for (const value of Object.values(node as Record<string, unknown>)) walk(value);\n };\n walk(request);\n return found.filter((key) => key !== '');\n};\n\nconst mountInputCache = new WeakMap<ActionDefinition, ReadonlySet<string>>();\n\n// Input keys the surface consumes WHEN IT OPENS: an id its own mount-time load\n// sends. Writing one into a live instance leaves the previous record's data on\n// screen, so a caller that wants to re-aim must re-mount instead.\n//\n// Cached per definition object: definitions are read on every telemetry event,\n// and a bundle sync replaces them wholesale, so identity is the right key.\nexport const mountInputKeys = (definition: ActionDefinition): ReadonlySet<string> => {\n const cached = mountInputCache.get(definition);\n if (cached !== undefined) return cached;\n const called = mountCalls(definition);\n const declared = new Set(declaredKeys(definition));\n const keys = new Set<string>();\n for (const [name, endpoint] of Object.entries(definition.endpoints ?? {})) {\n if (!called.has(name)) continue;\n for (const key of requestKeys((endpoint as { request?: unknown }).request)) if (declared.has(key)) keys.add(key);\n }\n mountInputCache.set(definition, keys);\n return keys;\n};\n","import type { ActionDefinition } from '../action';\nimport { mountInputKeys } from '../reflect/grammar';\nimport type { Shell } from './types';\n\n// Make a canvas equal a desired list.\n//\n// nova's other navigation verbs are imperative — push, pop, replace,\n// removeInstance — and describe a screen as a sequence of edits to one nobody\n// holds a picture of. Every caller that produces a whole desired state (a\n// server-driven layout, a restored workspace, an agent's answer) then has to\n// diff it by hand, and each of them writes the same four bugs: duplicates,\n// forgetting to close, closing what somebody else opened, and re-aiming a card\n// whose data no longer matches its id.\n//\n// This is the declarative verb. The caller says what should be there; nova works\n// out push, write or replace.\n//\n// OWNERSHIP `own` decides what the caller may move — see below.\n// RE-AIM writing an input key that the surface's own mount-time load reads\n// would leave the previous record's data on screen under a new id,\n// so those re-mount instead of being written.\n\nexport type Desired = {\n actionId: string;\n input?: Record<string, unknown>;\n // Fragments to compose, as `push` takes them.\n with?: string[];\n};\n\nexport type ReconcileOptions = {\n // Stamped on everything this call pushes. Required whichever `own` is in\n // force: it is how a later call, a telemetry reader or an audit answers \"who\n // put this here\".\n origin: string;\n // Resolves an action id to its definition, for the re-aim rule. Without it,\n // every change to a live card is written in place.\n definitionOf?: (actionId: string) => ActionDefinition | undefined;\n // WHAT THIS CALL MAY MOVE.\n //\n // 'pushed' (default) — only instances carrying `origin`. Anything else on\n // the canvas is left exactly as it is: the safe reading\n // for a caller that SHARES a canvas with a person.\n // 'canvas' — every instance on the canvas, whoever pushed it. For\n // a caller that OWNS the canvas outright.\n //\n // \"Only what I pushed\" is authorship, not ownership, and the two come apart\n // wherever a person and an agent work the same column: an agent granted a\n // canvas cannot write into or take down a record the person opened onto it,\n // while its complete-state answer says it has.\n own?: 'pushed' | 'canvas';\n};\n\nexport type ReconcileResult = {\n changed: boolean;\n // What moved, in order, for a caller that wants to log or trace it.\n notes: string[];\n};\n\nconst differs = (before: Record<string, unknown>, input: Record<string, unknown>): boolean =>\n Object.entries(input).some(([key, value]) => JSON.stringify(before[key]) !== JSON.stringify(value));\n\nexport const reconcileCanvas = (shell: Shell, canvasId: string, desired: readonly Desired[], options: ReconcileOptions): ReconcileResult => {\n const { origin, definitionOf } = options;\n // Asked once, so the close scope and the write scope cannot drift apart: a\n // caller allowed to take a card down is allowed to write into it.\n const ownsCanvas = options.own === 'canvas';\n const notes: string[] = [];\n let changed = false;\n\n if (shell.getState().canvases[canvasId] === undefined) return { changed: false, notes: [`no canvas \"${canvasId}\"`] };\n\n // A canvas is a set, not a bag: one instance per action id.\n const wanted: Desired[] = [];\n for (const entry of desired) if (!wanted.some((other) => other.actionId === entry.actionId)) wanted.push(entry);\n\n const mine = (shell.getState().canvases[canvasId]?.stack ?? []).filter((item) => ownsCanvas || shell.originOf(item.id) === origin);\n for (const item of mine) {\n if (wanted.some((entry) => entry.actionId === item.definitionId)) continue;\n shell.removeInstance(canvasId, item.id);\n changed = true;\n notes.push(`closed ${item.definitionId}`);\n }\n\n for (const entry of wanted) {\n const input = entry.input ?? {};\n const existing = (shell.getState().canvases[canvasId]?.stack ?? []).find((item) => item.definitionId === entry.actionId);\n\n if (existing !== undefined && !ownsCanvas && shell.originOf(existing.id) !== origin) {\n notes.push(`left ${entry.actionId}: not mine`);\n continue;\n }\n\n if (existing !== undefined) {\n const runtime = shell.getRuntime(existing.id);\n const before = runtime?.getData() ?? {};\n if (runtime === undefined || Object.keys(input).length === 0 || !differs(before, input)) continue;\n\n const definition = definitionOf?.(entry.actionId);\n const reAims = definition !== undefined && Object.keys(input).some((key) => mountInputKeys(definition).has(key));\n if (!reAims) {\n runtime.setData({ ...before, ...input });\n changed = true;\n notes.push(`set ${Object.keys(input).join(', ')} on ${entry.actionId}`);\n continue;\n }\n shell.removeInstance(canvasId, existing.id);\n notes.push(`re-opened ${entry.actionId}`);\n }\n\n shell.push(canvasId, entry.actionId, input, entry.with, { origin });\n changed = true;\n notes.push(`placed ${entry.actionId}`);\n }\n\n return { changed, notes };\n};\n","// ═══════════════════════════════════════════════════════════\n// The navigation journal — what BACK undoes.\n//\n// A canvas stack remembers where you ARE; nothing remembered where you WERE.\n// Every navigation destroys some of that: a push buries the top, a replace\n// unmounts it, a resetTo takes the whole deck. So the journal writes the canvas\n// down just BEFORE each of those. One entry is one position somebody can be\n// returned to, and `shell.back()` is \"put the newest one back\".\n//\n// GLOBAL AND ORDERED — one list across every canvas, each entry naming the one\n// canvas it describes. Global because back is a single gesture: somebody who\n// opened a card on `aside` after a screen on `main` expects it to walk back\n// through both, in the order they happened. One canvas per entry because back\n// must undo THEIR last move and not revert a canvas that changed underneath\n// them — a delivered notice, an agent's card — while they were elsewhere.\n//\n// A frame records the instance id it described AND the birth details behind it,\n// because those answer two different questions on the way back: is this the\n// very instance I recorded (keep it, with everything it holds), or is it gone\n// (build a new one from what made it).\n// ═══════════════════════════════════════════════════════════\n\n// One position in a recorded stack.\nexport type HistoryFrame = {\n // The live instance this frame described when it was recorded. Meaningless\n // on its own — its whole job is to be compared against what is standing now.\n instance: string;\n action: string;\n input?: Record<string, unknown>;\n with?: string[];\n};\n\n// One restorable position: a canvas, and the stack it held before the\n// navigation that displaced it.\nexport type HistoryEntry = {\n canvas: string;\n stack: readonly HistoryFrame[];\n};\n\nexport type Journal = {\n record: (canvas: string, stack: readonly HistoryFrame[]) => void;\n // The person went back by hand — spend the entry that gesture satisfied.\n consume: (canvas: string) => void;\n // The newest entry, removed. The restore itself is the shell's business.\n take: () => HistoryEntry | undefined;\n // Drop every entry that would bring a revoked action back.\n forgetAction: (actionId: string) => void;\n // Drop every entry for a canvas that no longer exists.\n forgetCanvas: (canvas: string) => void;\n // Run `fn` with recording off — for the movements that are not navigation\n // (seeding a canvas, restoring one).\n mute: <T>(fn: () => T) => T;\n depth: () => number;\n};\n\n// Deep enough that nobody walks off the end of a session's worth of moving\n// about, shallow enough to be a rounding error beside the instances themselves.\nexport const DEFAULT_HISTORY_DEPTH = 50;\n\nexport const createJournal = (limit: number): Journal => {\n const entries: HistoryEntry[] = [];\n // A counter, not a flag: seeding a canvas from inside a restore is one mute\n // nested in another, and the inner one must not un-mute the outer.\n let mutes = 0;\n\n const off = (): boolean => limit <= 0 || mutes > 0;\n\n return {\n record: (canvas, stack) => {\n if (off()) return;\n entries.push({ canvas, stack });\n // BOUNDED, because a durable shell can stand for hours. The oldest\n // position is the one nobody is walking back to.\n if (entries.length > limit) entries.shift();\n },\n\n // A pop somebody performed themselves IS a back. Without this the journal\n // would still hold the entry that pop just satisfied, and the next press of\n // the back button would spend itself restoring a position already on screen\n // — the double-tap that makes a back button feel broken.\n consume: (canvas) => {\n if (off()) return;\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n if (entries[i]?.canvas !== canvas) continue;\n entries.splice(i, 1);\n return;\n }\n },\n\n take: () => entries.pop(),\n\n // REVOCATION REACHES THE JOURNAL OR IT IS NOT REVOCATION. An entry naming\n // an action this shell no longer serves would hand it back on the way out —\n // a grant dropped at the front door and returned through the back one.\n forgetAction: (actionId) => {\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n if (entries[i]?.stack.some((frame) => frame.action === actionId) === true) entries.splice(i, 1);\n }\n },\n\n forgetCanvas: (canvas) => {\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n if (entries[i]?.canvas === canvas) entries.splice(i, 1);\n }\n },\n\n mute: (fn) => {\n mutes += 1;\n try {\n return fn();\n } finally {\n mutes -= 1;\n }\n },\n\n depth: () => entries.length,\n };\n};\n","import type { Canvas } from './canvas';\nimport type { RuntimeRegistry } from './runtime-registry';\nimport type { Telemetry } from './telemetry';\n\n// ═══════════════════════════════════════════════════════════\n// Shell lifecycle ops — small helpers that the shell public API\n// composes with its own guards. Factored out to keep `shell.ts`\n// focused on assembly and navigation wiring.\n// ═══════════════════════════════════════════════════════════\n\nexport type LifecycleOpsDeps = {\n registry: RuntimeRegistry;\n telemetry: Telemetry;\n onLifecycleError: (err: unknown) => void;\n // Called as an instance is torn down, so per-instance bookkeeping the shell\n // holds beside the registry (push origins) never outlives what it describes.\n onUnmount?: (instanceId: string) => void;\n};\n\nexport type LifecycleOps = {\n unmountInstance: (instanceId: string) => void;\n suspendTop: (canvas: Canvas) => void;\n resumeTop: (canvas: Canvas) => void;\n};\n\nexport const createLifecycleOps = (deps: LifecycleOpsDeps): LifecycleOps => {\n const { registry, onLifecycleError, onUnmount } = deps;\n\n // Track instances we've already unmounted so a redundant unmount is a\n // no-op (idempotency) — never re-fires hooks, never re-disposes.\n const unmounted = new Set<string>();\n\n const unmountInstance = (instanceId: string): void => {\n if (unmounted.has(instanceId)) return;\n const runtime = registry.get(instanceId);\n if (runtime === undefined) return;\n unmounted.add(instanceId);\n runtime.unmount().catch(onLifecycleError);\n runtime.dispose();\n registry.unregister(instanceId);\n onUnmount?.(instanceId);\n // BOUNDED, not forever. Once the registry no longer holds the instance,\n // the `registry.get` guard above returns early on its own — the set only\n // has to cover re-entry inside THIS call. Keeping the id would grow this\n // set by one string per navigation for the life of a durable shell: the\n // one genuinely unbounded structure the memory hunt found.\n unmounted.delete(instanceId);\n };\n\n const suspendTop = (canvas: Canvas): void => {\n const top = canvas.peek();\n if (top === undefined) return;\n // Already suspended is already done. A push onto a fresh stack always finds\n // an active top, so this changes nothing there; `back` restoring a position\n // ABOVE the one on screen finds a top that was suspended when the screen it\n // is undoing went up, and re-firing that action's suspend hook would be a\n // lifecycle event nothing happened to cause.\n if (top.status === 'suspended') return;\n const runtime = registry.get(top.id);\n if (runtime !== undefined) runtime.suspend().catch(onLifecycleError);\n };\n\n const resumeTop = (canvas: Canvas): void => {\n const top = canvas.peek();\n if (top === undefined) return;\n const runtime = registry.get(top.id);\n if (runtime !== undefined) runtime.resume().catch(onLifecycleError);\n };\n\n return { unmountInstance, suspendTop, resumeTop };\n};\n","import type { NavigationEffect } from '../action';\n\n// ═══════════════════════════════════════════════════════════\n// WHERE A CANVAS IS, ANNOUNCED.\n//\n// A canvas knows what is standing on it; nothing else did. Chrome around a\n// canvas — a sidebar highlight, a tab strip, a breadcrumb — used to learn where\n// somebody went from the CLICK that sent them, which is a copy of the fact\n// rather than the fact. It agreed with the canvas right up until something\n// moved the canvas without a click: `back`, an agent opening a screen, a\n// delivered card, a deep link later. Then the sidebar lit one screen while the\n// canvas showed another.\n//\n// So the canvas says where it is. One message per canvas whenever its ACTIVE\n// screen changes, whatever caused the change, on a channel named for the\n// canvas — triggers carry no guard clause, so a listener that wants `main`\n// should not have to hear about `sheet` to ignore it. The payload names the\n// canvas anyway, so nothing has to parse a channel to know what it was told.\n// ═══════════════════════════════════════════════════════════\n\nexport const navigatedChannel = (canvasId: string): string => `nova:navigated:${canvasId}`;\n\n// What lands on that channel. `action`/`instance` are absent when the canvas\n// went empty — which is a position too, and a listener that renders chrome for\n// \"nothing is open\" needs to hear it.\nexport type NavigatedMessage = {\n canvas: string;\n action?: string;\n instance?: string;\n};\n\nexport type ShellNavOps = {\n push: (canvasId: string, actionId: string, input?: Record<string, unknown>, fragments?: string[]) => string;\n pop: (canvasId: string) => void;\n replace: (canvasId: string, actionId: string, input?: Record<string, unknown>, fragments?: string[]) => string;\n clear: (canvasId: string) => void;\n // Clear and push in one movement. Its own op rather than the two calls it\n // used to decompose into, because the journal has to see ONE navigation here:\n // as `clear` then `push` it recorded two positions, and back walked somebody\n // through a blank canvas on the way to the screen they wanted.\n resetTo: (canvasId: string, actionId: string, input?: Record<string, unknown>, fragments?: string[]) => void;\n popTo: (canvasId: string, instanceId: string) => void;\n removeInstance: (canvasId: string, instanceId: string) => void;\n // Make a canvas hold exactly `desired` (shell/reconcile.ts), as one movement.\n reconcile: (\n canvasId: string,\n desired: readonly { actionId: string; input?: Record<string, unknown> }[],\n options: { origin: string; own?: 'pushed' | 'canvas'; with?: string[] },\n ) => void;\n};\n\nexport type NavigationHandler = (currentCanvasId: string, effect: NavigationEffect) => void;\n\nexport const createNavigationHandler = (ops: ShellNavOps): NavigationHandler => {\n return (currentCanvasId, effect): void => {\n if ('push' in effect) {\n const target = effect.push.canvas ?? currentCanvasId;\n ops.push(target, effect.push.action, effect.push.input, effect.push.with);\n return;\n }\n if ('pop' in effect) {\n ops.pop(currentCanvasId);\n return;\n }\n if ('replace' in effect) {\n const target = effect.replace.canvas ?? currentCanvasId;\n ops.replace(target, effect.replace.action, effect.replace.input, effect.replace.with);\n return;\n }\n if ('popTo' in effect) {\n ops.popTo(effect.popTo.canvas ?? currentCanvasId, effect.popTo.instance);\n return;\n }\n if ('resetTo' in effect) {\n const target = effect.resetTo.canvas ?? currentCanvasId;\n ops.resetTo(target, effect.resetTo.action, effect.resetTo.input, effect.resetTo.with);\n return;\n }\n if ('removeInstance' in effect) {\n ops.removeInstance(effect.removeInstance.canvas ?? currentCanvasId, effect.removeInstance.instance);\n return;\n }\n if ('reconcile' in effect) {\n const { canvas, desired, origin, own, with: fragments } = effect.reconcile;\n ops.reconcile(canvas ?? currentCanvasId, desired, {\n origin: origin ?? 'reconcile',\n ...(own === undefined ? {} : { own }),\n ...(fragments === undefined ? {} : { with: fragments }),\n });\n }\n };\n};\n","import type { ActionRuntime } from '../action';\nimport type { Unsubscribe } from '../shared/common';\n\nexport type RuntimeRegistry = {\n register: (runtime: ActionRuntime, onData: (data: Record<string, unknown>) => void) => void;\n unregister: (instanceId: string) => void;\n get: (instanceId: string) => ActionRuntime | undefined;\n disposeAll: () => void;\n};\n\nexport const createRuntimeRegistry = (): RuntimeRegistry => {\n const runtimes = new Map<string, ActionRuntime>();\n const unsubs = new Map<string, Unsubscribe>();\n\n const register = (\n runtime: ActionRuntime,\n onData: (data: Record<string, unknown>) => void,\n ): void => {\n const id = runtime.instance.id;\n runtimes.set(id, runtime);\n unsubs.set(id, runtime.onDataChange(onData));\n };\n\n const unregister = (instanceId: string): void => {\n const off = unsubs.get(instanceId);\n if (off !== undefined) off();\n unsubs.delete(instanceId);\n runtimes.delete(instanceId);\n };\n\n const get = (instanceId: string): ActionRuntime | undefined => runtimes.get(instanceId);\n\n const disposeAll = (): void => {\n for (const off of unsubs.values()) off();\n unsubs.clear();\n runtimes.clear();\n };\n\n return { register, unregister, get, disposeAll };\n};\n","import type { EndpointEvent, EndpointHandler } from '../action';\nimport type { Unsubscribe } from '../shared/common';\nimport type {\n DataChangeEvent,\n DataChangeHandler,\n ShellTelemetry,\n StateChangeHandler,\n StateSnapshot,\n} from './types';\n\nexport type Telemetry = {\n fireStateChange: (snapshot: StateSnapshot) => void;\n fireDataChange: (change: DataChangeEvent) => void;\n fireEndpoint: (event: EndpointEvent) => void;\n onStateChange: (handler: StateChangeHandler) => Unsubscribe;\n onDataChange: (handler: DataChangeHandler) => Unsubscribe;\n onEndpoint: (handler: EndpointHandler) => Unsubscribe;\n clear: () => void;\n};\n\nconst safeCall = <T>(fn: ((arg: T) => void) | undefined, arg: T): void => {\n if (fn === undefined) return;\n try {\n fn(arg);\n } catch {\n // telemetry handlers must not crash the shell\n }\n};\n\nexport const createTelemetry = (config: ShellTelemetry | undefined): Telemetry => {\n const stateSubscribers: StateChangeHandler[] = [];\n const dataSubscribers: DataChangeHandler[] = [];\n const endpointSubscribers: EndpointHandler[] = [];\n\n const fireStateChange = (snapshot: StateSnapshot): void => {\n safeCall(config?.onStateChange, snapshot);\n for (const handler of stateSubscribers.slice()) safeCall(handler, snapshot);\n };\n\n const fireDataChange = (change: DataChangeEvent): void => {\n safeCall(config?.onDataChange, change);\n for (const handler of dataSubscribers.slice()) safeCall(handler, change);\n };\n\n const fireEndpoint = (event: EndpointEvent): void => {\n safeCall(config?.onEndpoint, event);\n for (const handler of endpointSubscribers.slice()) safeCall(handler, event);\n };\n\n const onStateChange = (handler: StateChangeHandler): Unsubscribe => {\n stateSubscribers.push(handler);\n return (): void => {\n const idx = stateSubscribers.indexOf(handler);\n if (idx >= 0) stateSubscribers.splice(idx, 1);\n };\n };\n\n const onDataChange = (handler: DataChangeHandler): Unsubscribe => {\n dataSubscribers.push(handler);\n return (): void => {\n const idx = dataSubscribers.indexOf(handler);\n if (idx >= 0) dataSubscribers.splice(idx, 1);\n };\n };\n\n const onEndpoint = (handler: EndpointHandler): Unsubscribe => {\n endpointSubscribers.push(handler);\n return (): void => {\n const idx = endpointSubscribers.indexOf(handler);\n if (idx >= 0) endpointSubscribers.splice(idx, 1);\n };\n };\n\n const clear = (): void => {\n stateSubscribers.length = 0;\n dataSubscribers.length = 0;\n endpointSubscribers.length = 0;\n };\n\n return { fireStateChange, fireDataChange, fireEndpoint, onStateChange, onDataChange, onEndpoint, clear };\n};\n","import type { ActionDefinition, ActionFragment, ActionInstance, ActionRuntime, EndpointHandler, LanguageOptions, PublicActionRuntime } from '../action';\n// Note: ActionRuntime is used as the internal runtime type returned by spawn/registry.\nimport { composeAction } from '../action';\nimport { createScopeChain, resolve } from '../shared/bindings';\nimport type { LayoutNode, RenderNode } from '../layout';\nimport type { Phrasebook } from '../i18n/phrases';\nimport { createComponentRegistry, createLayoutStore, renderLayoutFromStore } from '../layout';\nimport { createEventBus } from '../shared/event-bus';\nimport { createMessageBus } from '../shared/message-bus';\nimport type { Unsubscribe } from '../shared/common';\nimport {\n LifecycleError,\n NovaError,\n ShellDisposedError,\n UnknownActionError,\n UnknownFragmentError,\n} from '../shared/errors';\nimport { createIdFactory } from '../shared/ids';\nimport { rememberShellRegistry } from './shell-internals';\nimport { createCanvas, type Canvas } from './canvas';\nimport { DEFAULT_ACTION_LAYOUT, DEFAULT_SHELL_LAYOUT } from './default-layouts';\nimport { flattenRenderTree } from './flatten-render-tree';\nimport { reconcileCanvas } from './reconcile';\nimport { createJournal, DEFAULT_HISTORY_DEPTH } from './journal';\nimport type { HistoryEntry, HistoryFrame } from './journal';\nimport { createLifecycleOps } from './lifecycle-ops';\nimport { createNavigationHandler, navigatedChannel } from './navigation';\nimport type { NavigatedMessage } from './navigation';\nimport { createRuntimeRegistry } from './runtime-registry';\nimport { createRuntimeFactory, snapshotCanvas, validateActions, validateFragments } from './shell-internals';\nimport { createTelemetry } from './telemetry';\nimport type {\n CanvasChangeHandler,\n CanvasConfig,\n CanvasState,\n DataChangeHandler,\n PushOptions,\n Shell,\n ShellConfig,\n StateChangeHandler,\n StateSnapshot,\n} from './types';\n\nconst defaultShellIdFactory = createIdFactory('shell');\n\nexport const createShell = (config: ShellConfig): Shell => {\n validateActions(config.actions);\n\n const id = (config.shellIdFn ?? defaultShellIdFactory)();\n const instanceIdFn = config.instanceIdFn ?? createIdFactory('act');\n const strict = config.strict ?? false;\n const eventBus = config.eventBus ?? createEventBus();\n const messageBus = config.messageBus ?? createMessageBus();\n const registry = createRuntimeRegistry();\n const telemetry = createTelemetry(config.telemetry);\n\n // Resolve component registry + layout store: use caller-provided ones when\n // present, otherwise fabricate empty defaults. `components` (if provided) is\n // merged into whichever registry we end up using.\n const componentRegistry = config.registry ?? createComponentRegistry();\n if (config.components !== undefined) componentRegistry.registerAll(config.components);\n const layoutStore = config.layoutStore ?? createLayoutStore();\n\n // In strict mode, the next public shell call rethrows this error.\n // Lifecycle hooks are async fire-and-forget, so failures cannot\n // propagate synchronously to the original push/pop caller; instead\n // we surface them at the boundary of the next operation.\n let pendingStrictError: LifecycleError | undefined;\n\n const toLifecycleError = (err: unknown): LifecycleError => {\n if (err instanceof LifecycleError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new LifecycleError(message, {}, { cause: err });\n };\n\n const handleLifecycleRejection = (err: unknown): void => {\n const lifecycleErr = toLifecycleError(err);\n if (strict && pendingStrictError === undefined) {\n pendingStrictError = lifecycleErr;\n }\n if (config.onError === undefined) return;\n if (err instanceof NovaError) {\n config.onError(err);\n return;\n }\n config.onError(lifecycleErr);\n };\n\n // WHO PUT THIS HERE. A caller that pushes with an `origin` can ask later\n // whether an instance is still one of its own — the question any server-driven\n // or agent-driven layout must answer before it closes something, and one\n // nobody can answer by inspecting the screen. Dropped with the instance.\n const origins = new Map<string, string>();\n\n // WHAT MADE THIS INSTANCE. The stack holds instances; an instance holds its\n // data and no memory of the call that spawned it, so a canvas can say what is\n // standing on it but not how to stand it up again. `back` needs the second\n // question answered for anything a navigation destroyed — hence the birth\n // details, kept beside the instance and dropped with it.\n //\n // `input` is held by REFERENCE, exactly as push already hands it to the\n // runtime: cloning would quietly break an input carrying anything a structured\n // clone cannot take, and would be a copy nobody asked for.\n const births = new Map<string, { action: string; input?: Record<string, unknown>; with?: string[] }>();\n\n const journal = createJournal(config.historyDepth ?? DEFAULT_HISTORY_DEPTH);\n\n const ops = createLifecycleOps({\n registry,\n telemetry,\n onLifecycleError: handleLifecycleRejection,\n onUnmount: (instanceId) => {\n origins.delete(instanceId);\n births.delete(instanceId);\n },\n });\n\n const canvases = new Map<string, Canvas>();\n const actionLayouts = new Map<string, LayoutNode | string>();\n // Canvases declared `mode: 'list'` keep EVERY instance live and visible at\n // once (a tray of cards), instead of the default stack where only the top is\n // active and the rest are suspended. Two behaviours follow: push does not\n // suspend the previous top, and removing a card does not resume another.\n const listCanvases = new Set<string>();\n for (const cfg of config.canvases) {\n canvases.set(cfg.id, createCanvas(cfg.id));\n if (cfg.actionLayout !== undefined) actionLayouts.set(cfg.id, cfg.actionLayout);\n if (cfg.mode === 'list') listCanvases.add(cfg.id);\n }\n\n // Mutable so addCanvas / removeCanvas / setCanvasLayout can change the rendered\n // canvas set and arrangement after creation. Seeded from config; the canvas\n // ids keep declaration order (getShellRenderTree renders them in this order).\n const canvasOrder: string[] = config.canvases.map((cfg) => cfg.id);\n let canvasLayout = config.canvasLayout;\n\n // Mutable so registerAction can add definitions at runtime (push/seed resolve\n // through this, not config.actions).\n const actions: Record<string, ActionDefinition> = { ...config.actions };\n\n // ONE CELL FOR THE LANGUAGE, read at every render by everything that renders.\n // Mutable so `setPhrases` reaches instances that are already mounted; the key\n // set and the miss handler are fixed at build, because they describe the\n // application rather than the reader.\n let phrases = config.phrases;\n\n // WITHDRAWING A BOOK IS THE SOURCE LANGUAGE, NOT SWITCHING i18n OFF — and the\n // difference is not cosmetic. A shell that has stopped doing i18n leaves a\n // counted phrase as the `{ phrase, slots }` object it travels as, and the\n // renderer below has nobody left to close its holes; the object reaches the\n // adapter, which is handed a structure where a word should be and throws.\n //\n // So the question \"is this shell language-bearing\" is answered ONCE, by\n // whether it was ever given a book or a key set, and `setPhrases(undefined)`\n // cannot un-answer it. Only a shell that never mentioned language at all pays\n // nothing — which is still the common case, and still free.\n let bearing = config.phrases !== undefined || config.phraseKeys !== undefined;\n const SOURCE: Phrasebook = {};\n\n const language = (): LanguageOptions | undefined => {\n if (!bearing) return undefined;\n return {\n // An empty book translates nothing and still fills patterns, which is\n // exactly what the source language needs.\n phrases: phrases ?? SOURCE,\n ...(config.phraseKeys === undefined ? {} : { phraseKeys: config.phraseKeys }),\n ...(config.onPhraseMiss === undefined ? {} : { onPhraseMiss: config.onPhraseMiss }),\n };\n };\n\n // Reusable partial actions, composed into a concrete action at push/replace\n // time via the effect's `with: [...]`. Abstract — never instantiated alone.\n const fragments: Record<string, ActionFragment> = { ...(config.fragments ?? {}) };\n\n let disposed = false;\n\n const guardNotDisposed = (): void => {\n if (disposed) throw new ShellDisposedError('Shell disposed');\n };\n\n const guardNoPendingStrictError = (): void => {\n if (pendingStrictError === undefined) return;\n const err = pendingStrictError;\n pendingStrictError = undefined;\n throw err;\n };\n\n const guard = (): void => {\n guardNotDisposed();\n guardNoPendingStrictError();\n };\n\n const getCanvas = (canvasId: string): Canvas => {\n const existing = canvases.get(canvasId);\n if (existing !== undefined) return existing;\n const created = createCanvas(canvasId);\n canvases.set(canvasId, created);\n return created;\n };\n\n const getDefinition = (actionId: string): ActionDefinition => {\n const def = actions[actionId];\n if (def === undefined) throw new UnknownActionError(`Unknown action: ${actionId}`, { actionId });\n return def;\n };\n\n const registerAction = (definition: ActionDefinition): void => {\n guard();\n validateActions({ [definition.id]: definition });\n actions[definition.id] = definition;\n };\n\n // Remove a definition and unmount its live instances (revocation: a\n // removed action is gone, not zombie-running). Other instances keep their\n // stack positions; when a canvas's top was removed, the new top resumes.\n // Unknown ids are a no-op; fragments are untouched.\n const removeAction = (actionId: string): void => {\n guard();\n if (actions[actionId] === undefined) return;\n delete actions[actionId];\n // Revocation reaches the journal too, or back would hand the action back.\n journal.forgetAction(actionId);\n let changed = false;\n for (const [, canvas] of canvases) {\n if (!canvas.stack.some((inst) => inst.definitionId === actionId)) continue;\n const previousTop = canvas.peek();\n for (const inst of canvas.clearStack()) {\n if (inst.definitionId === actionId) ops.unmountInstance(inst.id);\n else canvas.pushInstance(inst);\n }\n if (canvas.peek() !== previousTop) ops.resumeTop(canvas);\n changed = true;\n }\n if (changed) fireState();\n };\n\n const getFragment = (fragmentId: string): ActionFragment => {\n const frag = fragments[fragmentId];\n if (frag === undefined) throw new UnknownFragmentError(`Unknown fragment: ${fragmentId}`, { fragmentId });\n return frag;\n };\n\n const registerFragment = (fragment: ActionFragment): void => {\n guard();\n if (fragment.id === undefined) throw new UnknownFragmentError('Fragment is missing an id', { fragmentId: '' });\n validateFragments({ [fragment.id]: fragment });\n fragments[fragment.id] = fragment;\n };\n\n // Resolve an action id to its (optionally fragment-composed) definition. The\n // effect's `with: [...]` names fragments to merge in; the action wins on\n // conflict. See composeAction.\n const resolveDefinition = (actionId: string, fragmentIds?: string[]): ActionDefinition => {\n const def = getDefinition(actionId);\n if (fragmentIds === undefined || fragmentIds.length === 0) return def;\n return composeAction(def, fragmentIds.map(getFragment));\n };\n\n // The active screen last announced per canvas — see navigatedChannel. Absent\n // and `undefined` mean the same thing (nothing was open), which is why an\n // empty canvas at build announces nothing: there is no move to report.\n const announced = new Map<string, string | undefined>();\n let announcing = false;\n\n // DEFERRED AND COALESCED, for two reasons. A listener woken mid-mutation runs\n // steps against a half-moved shell, which is the re-entrancy `emit` already\n // defers to avoid. And a burst — a resetTo is a clear and a push — should say\n // where the canvas ENDED, once, not narrate every position it passed through.\n // The message is state, not history.\n const announceNavigation = (): void => {\n if (announcing || disposed) return;\n announcing = true;\n queueMicrotask(() => {\n announcing = false;\n if (disposed) return;\n for (const [canvasId, canvas] of canvases) {\n const active = canvas.peek();\n if (announced.get(canvasId) === active?.id) continue;\n announced.set(canvasId, active?.id);\n const message: NavigatedMessage =\n active === undefined\n ? { canvas: canvasId }\n : { canvas: canvasId, action: active.definitionId, instance: active.id };\n messageBus.publish(navigatedChannel(canvasId), message);\n }\n });\n };\n\n const fireState = (): void => {\n if (disposed) return;\n const out: Record<string, CanvasState> = {};\n for (const [cid, c] of canvases) out[cid] = snapshotCanvas(c);\n const snapshot: StateSnapshot = { canvases: out };\n telemetry.fireStateChange(snapshot);\n announceNavigation();\n };\n\n // The canvas as the journal has to remember it: every instance standing on it\n // paired with what would build it again. Taken BEFORE the navigation that\n // displaces it — a position recorded afterwards is the place you already are.\n const positionOf = (canvasId: string): readonly HistoryFrame[] => {\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return [];\n return canvas.stack.map((inst) => {\n const birth = births.get(inst.id);\n return {\n instance: inst.id,\n action: birth?.action ?? inst.definitionId,\n ...(birth?.input === undefined ? {} : { input: birth.input }),\n ...(birth?.with === undefined ? {} : { with: birth.with }),\n };\n });\n };\n\n const record = (canvasId: string): void => journal.record(canvasId, positionOf(canvasId));\n\n const navigationHandler = createNavigationHandler({\n push: (cid, aid, input, frags) => push(cid, aid, input, frags),\n pop: (cid) => pop(cid),\n replace: (cid, aid, input, frags) => replace(cid, aid, input, frags),\n clear: (cid) => clear(cid),\n // ONE position, then both halves — see ShellNavOps.resetTo. The record is\n // taken outside the mute so the deck being thrown away is what back returns\n // to; the calls inside it record nothing of their own.\n resetTo: (cid, aid, input, frags) => {\n record(cid);\n journal.mute(() => {\n clear(cid);\n push(cid, aid, input, frags);\n });\n },\n popTo: (cid, iid) => popTo(cid, iid),\n removeInstance: (cid, iid) => removeInstance(cid, iid),\n // ONE movement, like resetTo: the position before it is what back returns\n // to — recorded only when something actually moved, so a reconcile that\n // found the canvas already right leaves no empty step in history. Rows\n // naming an action this shell does not have are skipped: ungranted is\n // absent, as an ungranted `initial` candidate is.\n reconcile: (cid, desired, options) => {\n const before = positionOf(cid);\n const known = desired\n .filter((entry) => actions[entry.actionId] !== undefined)\n .map((entry) => (options.with === undefined ? entry : { ...entry, with: options.with }));\n const result = journal.mute(() =>\n reconcileCanvas(shell, cid, known, {\n origin: options.origin,\n ...(options.own === undefined ? {} : { own: options.own }),\n definitionOf: (actionId) => actions[actionId],\n }),\n );\n if (result.changed) journal.record(cid, before);\n },\n });\n\n const buildRuntime = createRuntimeFactory({\n eventBus,\n messageBus,\n layoutStore,\n registry: componentRegistry,\n ...(config.transform === undefined ? {} : { transform: config.transform }),\n ...(config.fetch === undefined ? {} : { fetch: config.fetch }),\n ...(config.functions === undefined ? {} : { functions: config.functions }),\n ...(config.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: config.endpointTimeoutMs }),\n strict,\n ...(config.onError === undefined ? {} : { onError: config.onError }),\n i18n: language,\n instanceIdFn,\n onNavigate: (cid, effect) => navigationHandler(cid, effect),\n // Every endpoint call an action makes flows to telemetry — the shell's one\n // observability surface (state, data, and now endpoints all land here).\n onEndpoint: (event) => telemetry.fireEndpoint(event),\n });\n\n const spawn = (\n canvasId: string,\n definition: ActionDefinition,\n input: Record<string, unknown> | undefined,\n ): ActionRuntime => {\n const runtime = buildRuntime(canvasId, definition, input);\n const instId = runtime.instance.id;\n registry.register(runtime, (data) => {\n if (disposed) return;\n telemetry.fireDataChange({ instanceId: instId, canvasId: runtime.instance.canvasId, data });\n });\n runtime.mount(input).catch(handleLifecycleRejection);\n return runtime;\n };\n\n const push = (\n canvasId: string,\n actionId: string,\n input?: Record<string, unknown>,\n fragmentIds?: string[],\n options?: PushOptions,\n ): string => {\n guard();\n if (options?.history !== false) record(canvasId);\n const canvas = getCanvas(canvasId);\n const definition = resolveDefinition(actionId, fragmentIds);\n // A list canvas keeps its existing cards live; only a stack suspends the top.\n if (!listCanvases.has(canvasId)) ops.suspendTop(canvas);\n const runtime = spawn(canvasId, definition, input);\n canvas.pushInstance(runtime.instance);\n births.set(runtime.instance.id, {\n action: actionId,\n ...(input === undefined ? {} : { input }),\n ...(fragmentIds === undefined ? {} : { with: fragmentIds }),\n });\n if (options?.origin !== undefined) origins.set(runtime.instance.id, options.origin);\n fireState();\n return runtime.instance.id;\n };\n\n // Remove ONE instance anywhere in a canvas's stack. On a list canvas this is\n // a card dismissing itself (its X fires `removeSelf`); on a stack, removing\n // the top resumes the one beneath, like `pop`. A no-op if the instance is not\n // in the canvas (a stale close can't clear the wrong card).\n const removeInstance = (canvasId: string, instanceId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n if (!canvas.stack.some((i) => i.id === instanceId)) return;\n const previousTop = canvas.peek();\n for (const inst of canvas.clearStack()) {\n if (inst.id === instanceId) ops.unmountInstance(inst.id);\n else canvas.pushInstance(inst);\n }\n journal.consume(canvasId);\n // Stack canvases resume a newly-exposed top; list canvases never suspended,\n // so there is nothing to resume.\n if (!listCanvases.has(canvasId) && canvas.peek() !== previousTop) ops.resumeTop(canvas);\n fireState();\n };\n\n const pop = (canvasId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n const top = canvas.popInstance();\n if (top === undefined) return;\n ops.unmountInstance(top.id);\n // Going back by hand spends a journal entry — see Journal.consume.\n journal.consume(canvasId);\n ops.resumeTop(canvas);\n fireState();\n };\n\n // Pop a canvas down to a given instance — unmount everything above it, then\n // resume the target once. A no-op if the instance isn't in this canvas's stack\n // (so a stale breadcrumb can't clear the canvas). Powers the breadcrumb jump.\n const popTo = (canvasId: string, instanceId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n if (!snapshotCanvas(canvas).stack.some((i) => i.id === instanceId)) return;\n let changed = false;\n for (;;) {\n const active = snapshotCanvas(canvas).active;\n if (active === undefined || active.id === instanceId) break;\n const top = canvas.popInstance();\n if (top === undefined) break;\n ops.unmountInstance(top.id);\n changed = true;\n }\n if (changed) {\n journal.consume(canvasId);\n ops.resumeTop(canvas);\n fireState();\n }\n };\n\n const replace = (\n canvasId: string,\n actionId: string,\n input?: Record<string, unknown>,\n fragmentIds?: string[],\n ): string => {\n guard();\n record(canvasId);\n const canvas = getCanvas(canvasId);\n const definition = resolveDefinition(actionId, fragmentIds);\n const old = canvas.popInstance();\n if (old !== undefined) ops.unmountInstance(old.id);\n const runtime = spawn(canvasId, definition, input);\n canvas.pushInstance(runtime.instance);\n births.set(runtime.instance.id, {\n action: actionId,\n ...(input === undefined ? {} : { input }),\n ...(fragmentIds === undefined ? {} : { with: fragmentIds }),\n });\n fireState();\n return runtime.instance.id;\n };\n\n const clear = (canvasId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n // RECORDED, not consumed: emptying a canvas is somewhere you went, not a\n // step you retraced, and back should put the deck back.\n if (canvas.stack.length > 0) record(canvasId);\n for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);\n fireState();\n };\n\n // ── BACK ────────────────────────────────────────────────────\n // Put one recorded position back. `false` means this entry had nothing left\n // to undo — the canvas is gone, or somebody already popped their own way to\n // exactly this — and `back` should walk on to the next one.\n const restore = (entry: HistoryEntry): boolean => {\n const canvas = canvases.get(entry.canvas);\n if (canvas === undefined) return false;\n\n // How far up the recorded position the LIVE instances still agree with it.\n // Matched by instance id and nothing else: an instance is either the very\n // one recorded — kept, with everything it holds — or it is not, and comes\n // back derived. There is no third case worth guessing at, because two\n // instances of one action with equal input are not interchangeable, as any\n // half-filled form proves.\n let common = 0;\n while (\n common < canvas.stack.length &&\n common < entry.stack.length &&\n canvas.stack[common]?.id === entry.stack[common]?.instance\n ) {\n common += 1;\n }\n if (common === canvas.stack.length && common === entry.stack.length) return false;\n\n // Anything re-derived has to name an action this shell still serves. It\n // normally does — a revoked action takes its entries with it — and when it\n // does not, the whole entry is refused: a position half put back is a screen\n // nobody authored.\n for (let i = common; i < entry.stack.length; i += 1) {\n const frame = entry.stack[i];\n if (frame !== undefined && actions[frame.action] === undefined) return false;\n }\n\n journal.mute(() => {\n const standing = canvas.clearStack();\n for (let i = 0; i < standing.length; i += 1) {\n const inst = standing[i];\n if (inst === undefined) continue;\n if (i < common) canvas.pushInstance(inst);\n else ops.unmountInstance(inst.id);\n }\n if (common === entry.stack.length) {\n // Nothing to build — the newly exposed top resumes, exactly as on a pop.\n if (!listCanvases.has(entry.canvas)) ops.resumeTop(canvas);\n return;\n }\n for (let i = common; i < entry.stack.length; i += 1) {\n const frame = entry.stack[i];\n if (frame === undefined) continue;\n push(entry.canvas, frame.action, frame.input, frame.with);\n }\n });\n fireState();\n return true;\n };\n\n const back = (): boolean => {\n if (disposed) return false;\n guardNoPendingStrictError();\n // Newest first, past the entries that have nothing to say. Terminates\n // because every pass removes one — an empty journal is a shell standing on\n // its landing screen, and the honest answer there is `false`.\n for (;;) {\n const entry = journal.take();\n if (entry === undefined) return false;\n if (restore(entry)) return true;\n }\n };\n\n // Push a canvas's `initial` action(s), if any. Shared by createShell's seeding\n // loop and addCanvas, so both seed identically.\n const seedCanvas = (cfg: CanvasConfig): void => {\n if (cfg.initial === undefined) return;\n const seeds = Array.isArray(cfg.initial) ? cfg.initial : [cfg.initial];\n // MUTED: a seed is the floor, not a place somebody navigated to. Recorded,\n // it would make `back` able to empty the landing screen — the one move a\n // back button must never have.\n journal.mute(() => {\n for (const seed of seeds) {\n if (typeof seed === 'string') push(cfg.id, seed);\n else push(cfg.id, seed.action, seed.input, seed.with);\n }\n });\n };\n\n const addCanvas = (cfg: CanvasConfig): void => {\n guard();\n if (canvases.has(cfg.id)) return;\n canvases.set(cfg.id, createCanvas(cfg.id));\n if (cfg.actionLayout !== undefined) actionLayouts.set(cfg.id, cfg.actionLayout);\n if (cfg.mode === 'list') listCanvases.add(cfg.id);\n canvasOrder.push(cfg.id);\n seedCanvas(cfg);\n fireState();\n };\n\n const removeCanvas = (canvasId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);\n canvases.delete(canvasId);\n journal.forgetCanvas(canvasId);\n // Or a canvas re-added under the same id would be silently held to the\n // position its predecessor last announced.\n announced.delete(canvasId);\n actionLayouts.delete(canvasId);\n listCanvases.delete(canvasId);\n const index = canvasOrder.indexOf(canvasId);\n if (index >= 0) canvasOrder.splice(index, 1);\n fireState();\n };\n\n const setCanvasLayout = (layout: LayoutNode | string): void => {\n guard();\n canvasLayout = layout;\n fireState();\n };\n\n // Swap the target of a LayoutRef. The frame (canvasLayout) embeds\n // `{ ref: id }` placeholders for dynamic regions; this replaces what one\n // resolves to and re-renders. The frame/chrome itself is never touched, so\n // a swap can't remove the sidebar/topbar — they live in the frame, not the\n // ref. This is the hook an LLM/agent uses to hot-swap a region's layout.\n const setLayout = (refId: string, layout: LayoutNode): void => {\n guard();\n layoutStore.set(refId, layout);\n fireState();\n };\n\n // Swap the book. Every tree this shell renders from here on wears the new\n // words, including the instances already mounted — they ask for the book at\n // render rather than holding one from spawn, which is the whole reason\n // `i18n` is a function and not a value.\n //\n // A state change, not a rebuild: the words are the only thing that moved, so\n // canvases keep their stacks and instances keep their data. An application\n // whose SERVER-derived text was composed in the old language (a greeting, a\n // seeded label) still needs its own rebuild — this reaches what nova renders,\n // and nova does not know what a host built before handing it over.\n const setPhrases = (next: Phrasebook | undefined): void => {\n guard();\n phrases = next;\n // A host may build first and find its book later. Handing one over is the\n // same declaration as naming one at build.\n if (next !== undefined) bearing = true;\n fireState();\n };\n\n const getPhrases = (): Phrasebook | undefined => phrases;\n\n const getCanvasState = (canvasId: string): CanvasState => {\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return { id: canvasId, stack: [], active: undefined };\n return snapshotCanvas(canvas);\n };\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n for (const [, canvas] of canvases) {\n for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);\n }\n registry.disposeAll();\n canvases.clear();\n telemetry.clear();\n };\n\n const getRuntime = (iid: string): PublicActionRuntime | undefined => registry.get(iid);\n const onStateChange = (h: StateChangeHandler): Unsubscribe => telemetry.onStateChange(h);\n const onDataChange = (h: DataChangeHandler): Unsubscribe => telemetry.onDataChange(h);\n const onEndpoint = (h: EndpointHandler): Unsubscribe => telemetry.onEndpoint(h);\n\n // The shell's definition of \"this canvas changed\": stack length, item\n // ids/statuses, or the active instance. Snapshot objects are rebuilt on\n // every state change, so identity can't be used.\n const sameCanvasState = (a: CanvasState, b: CanvasState): boolean => {\n if (a.stack.length !== b.stack.length) return false;\n if (a.active?.id !== b.active?.id) return false;\n for (let i = 0; i < a.stack.length; i += 1) {\n const aItem = a.stack[i];\n const bItem = b.stack[i];\n if (aItem === undefined || bItem === undefined) return false;\n if (aItem.id !== bItem.id || aItem.status !== bItem.status) return false;\n }\n return true;\n };\n\n const onCanvasChange = (canvasId: string, handler: CanvasChangeHandler): Unsubscribe => {\n let prev = getCanvasState(canvasId);\n return telemetry.onStateChange(() => {\n const next = getCanvasState(canvasId);\n if (sameCanvasState(prev, next)) return;\n prev = next;\n handler(next);\n });\n };\n\n const getState = (): StateSnapshot => {\n const out: Record<string, CanvasState> = {};\n for (const [cid, c] of canvases) out[cid] = snapshotCanvas(c);\n return { canvases: out };\n };\n\n const renderLayoutOrRef = (\n layout: LayoutNode | string,\n data: Record<string, unknown>,\n ): RenderNode[] => {\n const resolved = typeof layout === 'string' ? layoutStore.get(layout) : layout;\n if (resolved === undefined) return [];\n const current = language();\n return renderLayoutFromStore(\n resolved,\n { get: () => data },\n {\n store: layoutStore,\n registry: componentRegistry,\n strict,\n ...(config.onError === undefined ? {} : { onError: config.onError }),\n ...(current?.phrases === undefined ? {} : { phrases: current.phrases }),\n ...(current?.phraseKeys === undefined ? {} : { phraseKeys: current.phraseKeys }),\n ...(current?.onPhraseMiss === undefined ? {} : { onPhraseMiss: current.onPhraseMiss }),\n },\n );\n };\n\n const getShellRenderTree = (): RenderNode[] => {\n const canvasList: CanvasState[] = [];\n for (const cid of canvasOrder) {\n const c = canvases.get(cid);\n canvasList.push(c === undefined ? { id: cid, stack: [], active: undefined } : snapshotCanvas(c));\n }\n return renderLayoutOrRef(canvasLayout ?? DEFAULT_SHELL_LAYOUT, { canvases: canvasList });\n };\n\n // An instance's display label: the (composed) definition's `title` resolvable\n // evaluated against the instance's own live data, falling back to `name` then\n // the action id. Surfaced as `instance.title` on the actionLayout scope so\n // stack-nav chrome (crumbs, tabs) can label without reaching into raw data.\n const titleOf = (instance: ActionInstance): string => {\n const def = registry.get(instance.id)?.definition ?? actions[instance.definitionId];\n if (def?.title !== undefined) {\n const resolved = resolve(def.title, createScopeChain(instance.data));\n if (resolved !== undefined && resolved !== null && resolved !== '') return String(resolved);\n }\n return def?.name ?? instance.definitionId;\n };\n\n const getCanvasRenderTree = (canvasId: string): RenderNode[] => {\n const canvas = canvases.get(canvasId);\n const state: CanvasState =\n canvas === undefined ? { id: canvasId, stack: [], active: undefined } : snapshotCanvas(canvas);\n const instances = state.stack.map((i) => ({ ...i, title: titleOf(i) }));\n const scope = {\n instances,\n active: instances.length === 0 ? undefined : instances[instances.length - 1],\n count: instances.length,\n };\n return renderLayoutOrRef(actionLayouts.get(canvasId) ?? DEFAULT_ACTION_LAYOUT, scope);\n };\n\n const dispatch = (event: Parameters<typeof eventBus.emit>[0]): void => {\n eventBus.emit(event);\n };\n\n const publish = (channel: string, payload?: unknown): void => {\n messageBus.publish(channel, payload);\n };\n\n const shell: Shell = {\n id,\n registry: componentRegistry,\n layoutStore,\n push,\n originOf: (instanceId) => origins.get(instanceId),\n pop,\n popTo,\n removeInstance,\n replace,\n clear,\n back,\n registerAction,\n removeAction,\n registerFragment,\n addCanvas,\n removeCanvas,\n setCanvasLayout,\n setPhrases,\n getPhrases,\n setLayout,\n getCanvasState,\n getRuntime,\n getState,\n getShellRenderTree,\n getCanvasRenderTree,\n flattenRenderTree: (tree) => flattenRenderTree(tree, shell),\n dispatch,\n publish,\n onStateChange,\n onDataChange,\n onEndpoint,\n onCanvasChange,\n dispose,\n };\n rememberShellRegistry(shell, registry);\n\n // Seed canvases whose config declares an `initial` action (or list). Done\n // after the shell object is assembled so `push` works exactly as it would\n // for a consumer calling push themselves.\n for (const cfg of config.canvases) seedCanvas(cfg);\n\n return shell;\n};\n","import { HEAD_NAME } from '../layout/head';\nimport type { Head } from '../layout/head';\nimport type { RenderNode } from '../layout';\nimport type { RenderApi } from './types';\nimport { ACTION_SLOT_NAME, CANVAS_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// The head a screen has, read off its render tree.\n//\n// The frame is walked in the order it is drawn, into each canvas where its\n// slot stands and into each instance on it. A screen can hold more than one\n// head node — a dialog opened over a page — and then THE LAST ONE SPEAKS, whole:\n// two heads are two things, and a title from one beside a description from the\n// other describes neither.\n//\n// A node that says nothing (its bindings are not answered yet) is still the\n// one that speaks: the document keeps what it had rather than borrow from a\n// screen underneath.\n// ═══════════════════════════════════════════════════════════\n\nexport type ScreenHead = {\n head: Head;\n // the action whose instance the node stands in; absent for a node in the\n // frame or in a canvas's own layout\n action?: string;\n};\n\ntype Found = { props: Record<string, unknown>; action: string | undefined };\n\nconst said = (value: unknown): string | undefined => (typeof value === 'string' && value.trim() !== '' ? value : undefined);\n\nconst isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst structuredOf = (value: unknown): Head['structured'] => {\n if (isObject(value)) return value;\n if (Array.isArray(value) && value.length > 0 && value.every(isObject)) return value;\n return undefined;\n};\n\n// A prop that is not one of the names, or holds something other than what its\n// name takes, is left out — the document keeps what it had there.\nconst headFrom = (props: Record<string, unknown>): Head => {\n const [title, description, image] = [said(props['title']), said(props['description']), said(props['image'])];\n const kind = props['kind'] === 'website' || props['kind'] === 'article' ? props['kind'] : undefined;\n const structured = structuredOf(props['structured']);\n return {\n ...(title !== undefined ? { title } : {}),\n ...(description !== undefined ? { description } : {}),\n ...(image !== undefined ? { image } : {}),\n ...(kind !== undefined ? { kind } : {}),\n ...(structured !== undefined ? { structured } : {}),\n };\n};\n\nexport const isHeadNode = (node: RenderNode): boolean => node.type === 'component' && node.name === HEAD_NAME;\n\nexport const headOf = (api: Pick<RenderApi, 'frame' | 'canvasTree'>): ScreenHead | undefined => {\n const found: Found[] = [];\n // a canvas whose own tree names it again would never end\n const open = new Set<string>();\n\n const walk = (nodes: readonly RenderNode[], action: string | undefined): void => {\n for (const node of nodes) {\n if (node.type === 'fragment') {\n walk(node.children, action);\n continue;\n }\n if (node.type !== 'component') continue;\n if (node.name === HEAD_NAME) {\n found.push({ props: node.props, action });\n continue;\n }\n if (node.name === CANVAS_SLOT_NAME) {\n const canvasId = node.props['canvasId'];\n if (typeof canvasId !== 'string' || canvasId === '' || open.has(canvasId)) continue;\n open.add(canvasId);\n walk(api.canvasTree(canvasId), undefined);\n open.delete(canvasId);\n continue;\n }\n const definitionId = node.name === ACTION_SLOT_NAME ? node.props['definitionId'] : undefined;\n walk(node.children, typeof definitionId === 'string' ? definitionId : action);\n }\n };\n\n walk(api.frame(), undefined);\n const last = found[found.length - 1];\n if (last === undefined) return undefined;\n return { head: headFrom(last.props), ...(last.action !== undefined ? { action: last.action } : {}) };\n};\n","import type { RenderNode } from '../layout';\nimport type { RenderApi, Shell } from './types';\nimport { isHeadNode } from './head';\nimport { ACTION_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// A shell, as something an adapter draws.\n//\n// Every adapter that draws a SERVED screen draws it through `RenderApi` — the\n// frame, a tree per canvas, events up, messages across — and has always been\n// handed one by a transport (moss's socket wire). A shell that lives in the\n// same process as its adapter is the other case that type was written for, and\n// this is it: the shell's own trees, read as they stand, and its own dispatch.\n// The DOM and TTY adapters draw a local shell through this exactly as they draw\n// a remote one; nothing about them knows the difference.\n//\n// It is also what makes a shell DRAWABLE AHEAD OF TIME. A build runs the app's\n// own boot, waits for the screen to be whole (`shellSettled`), and has an\n// adapter draw this view to markup; the browser runs the same boot and draws\n// the same view over that markup. Where the shell lives was never the\n// adapter's business.\n// ═══════════════════════════════════════════════════════════\n\nexport type ShellView = {\n api: RenderApi;\n // Called after the shell changed — coalesced, so a burst of changes (a press\n // that sets three keys) is one call. Returns the unsubscribe.\n subscribe: (listener: () => void) => () => void;\n};\n\n// NO VISIBLE CONTENT IS AN EMPTY TREE. A canvas whose layout renders nothing but\n// empty text and empty wrappers is handed to an adapter as `[]`, so an adapter\n// collapses the chrome around it on `length` alone, knowing nothing about node\n// shapes. An ActionSlot marker is a boundary, not content — what is inside it\n// decides — and a head is something the screen says, not something it shows.\n// One rule for a canvas that is served and one that is local, so a frame looks\n// the same over both.\nexport const hasVisibleContent = (nodes: readonly RenderNode[]): boolean =>\n nodes.some((node) => {\n if (node.type === 'text') return node.value !== '';\n if (node.type === 'fragment') return hasVisibleContent(node.children);\n if (node.type === 'component' && node.name === ACTION_SLOT_NAME) return hasVisibleContent(node.children);\n if (isHeadNode(node)) return false;\n return true;\n });\n\n// One canvas, as an adapter is handed it.\nexport const canvasTreeOf = (shell: Shell, canvasId: string): RenderNode[] => {\n const tree = shell.flattenRenderTree(shell.getCanvasRenderTree(canvasId));\n return hasVisibleContent(tree) ? tree : [];\n};\n\nexport const shellView = (shell: Shell): ShellView => ({\n api: {\n frame: () => shell.getShellRenderTree(),\n canvasTree: (canvasId) => canvasTreeOf(shell, canvasId),\n // An event that names no origin belongs to the canvas's ACTIVE instance — on\n // a card deck that is the only one drawn. One that names its own (an\n // adapter stamps it at the instance boundary, `scopeDispatch`) keeps it. A\n // canvas with nothing mounted dispatches unstamped.\n dispatch: (canvasId, event) => {\n const active = shell.getState().canvases[canvasId]?.active;\n shell.dispatch(event.origin === undefined && active !== undefined ? { ...event, origin: active.id } : event);\n },\n publish: (channel, payload) => shell.publish(channel, payload),\n },\n subscribe: (listener) => {\n let pending = false;\n let stopped = false;\n const changed = (): void => {\n if (pending || stopped) return;\n pending = true;\n queueMicrotask(() => {\n pending = false;\n if (!stopped) listener();\n });\n };\n const offState = shell.onStateChange(changed);\n const offData = shell.onDataChange(changed);\n return () => {\n stopped = true;\n offState();\n offData();\n };\n },\n});\n\n// THE FIRST SCREEN IS WHOLE. An instance is `initializing` until its mount hook\n// — the loads, and whatever they chain to — has been awaited, so \"nothing is\n// initializing\" is the shell saying its opening screen is complete. A mount can\n// open another action, which starts initializing in turn, so the question is\n// asked again on every change and answered true only when it still holds a\n// macrotask later.\n//\n// Resolves `false` when `waitMs` runs out first: the screen is then drawn as it\n// stands, with whatever is still loading drawn as loading. Default 300ms — a\n// page should not hang on one slow endpoint.\nexport const DEFAULT_SETTLE_WAIT_MS = 300;\n\nexport const shellSettled = async (shell: Shell, options: { waitMs?: number; stopped?: () => boolean } = {}): Promise<boolean> => {\n const waitMs = options.waitMs ?? DEFAULT_SETTLE_WAIT_MS;\n const mounting = (): boolean =>\n Object.values(shell.getState().canvases).some((canvas) => canvas.stack.some((instance) => instance.status === 'initializing'));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), waitMs);\n });\n const quiet = (async (): Promise<boolean> => {\n for (;;) {\n if (options.stopped?.() === true) return false;\n if (!mounting()) {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n if (!mounting()) return true;\n }\n await new Promise<void>((resolve) => {\n const off = shell.onStateChange(() => {\n off();\n resolve();\n });\n // a change that lands with no notification must not leave this waiting\n setTimeout(() => {\n off();\n resolve();\n }, 10);\n });\n }\n })();\n const settled = await Promise.race([quiet, deadline]);\n clearTimeout(timer);\n return settled;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/shared/common.ts","../src/shared/errors.ts","../src/shared/ids.ts","../src/shared/bindings/schemas.ts","../src/shared/bindings/scope.ts","../src/shared/bindings/paths.ts","../src/shared/bindings/resolve.ts","../src/shared/data-store/data-store.ts","../src/shared/event-bus/schemas.ts","../src/shared/event-bus/event-bus.ts","../src/shared/event-bus/scope-dispatch.ts","../src/shared/message-bus/schemas.ts","../src/shared/message-bus/message-bus.ts","../src/layout/schemas.ts","../src/layout/guards.ts","../src/i18n/phrases.ts","../src/i18n/swap.ts","../src/layout/head.ts","../src/layout/renderer.ts","../src/layout/compose.ts","../src/layout/adapter.ts","../src/layout/store.ts","../src/layout/registry.ts","../src/layout/head.schema.ts","../src/agent/palette.ts","../src/action/mutations/ops/set.ts","../src/action/mutations/ops/toggle.ts","../src/action/mutations/ops/increment.ts","../src/action/mutations/ops/decrement.ts","../src/action/mutations/ops/push.ts","../src/action/mutations/ops/pop.ts","../src/action/mutations/ops/remove-at.ts","../src/action/mutations/ops/move.ts","../src/action/mutations/ops/clear.ts","../src/action/mutations/ops/reset.ts","../src/action/mutations/ops/index.ts","../src/action/mutations/registry.ts","../src/action/schemas/endpoints.ts","../src/action/schemas/effects.ts","../src/action/schemas/lifecycle.ts","../src/action/schemas/triggers.ts","../src/action/schemas/index.ts","../src/action/compose.ts","../src/agent/affordances.ts","../src/action/grammar.ts","../src/action/audit.ts","../src/action/runtime/endpoints.ts","../src/action/runtime/cause.ts","../src/action/runtime/next-task.ts","../src/action/runtime/steps.ts","../src/action/runtime/lifecycle.ts","../src/action/runtime/model-bindings.ts","../src/action/runtime/render.ts","../src/action/runtime/triggers.ts","../src/action/runtime/runtime.ts","../src/shell/shell-internals.ts","../src/shell/canvas.ts","../src/shell/slot-names.ts","../src/shell/default-layouts.ts","../src/shell/flatten-render-tree.ts","../src/reflect/grammar.ts","../src/shell/reconcile.ts","../src/shell/journal.ts","../src/shell/lifecycle-ops.ts","../src/shell/navigation.ts","../src/shell/runtime-registry.ts","../src/shell/telemetry.ts","../src/shell/shell.ts","../src/shell/head.ts","../src/shell/view.ts"],"names":["z","segments","evaluateSafe","exceedsDepth","depthRefusal","has","next","walk","noopOnError","isLayoutNode","render","fragment","titleOf","resolve"],"mappings":";;;;;;;AAOO,IAAM,QAAA,GAAW,CAAC,KAAA,KACvB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAQ9D,IAAM,OAAA,GAAU,CAAC,KAAA,KAAuC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAK3E,IAAM,SAAS,CACpB,GAAA,EACA,QAC8B,QAAA,CAAS,GAAG,KAAK,GAAA,IAAO,GAAA;;;AClBjD,IAAM,UAAA,GAAa;AAAA,EACxB,MAAA,EAAQ,cAAA;AAAA,EACR,iBAAA,EAAmB,qBAAA;AAAA,EACnB,iBAAA,EAAmB,sBAAA;AAAA,EACnB,oBAAA,EAAsB,6BAAA;AAAA,EACtB,aAAA,EAAe,gBAAA;AAAA,EACf,eAAA,EAAiB,kBAAA;AAAA,EACjB,eAAA,EAAiB,kBAAA;AAAA,EACjB,aAAA,EAAe,gBAAA;AAAA,EACf,SAAA,EAAW,iBAAA;AAAA,EACX,QAAA,EAAU,gBAAA;AAAA,EACV,OAAA,EAAS;AACX;AAcO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CACE,IAAA,EACA,OAAA,EACA,OAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF;AAEO,IAAM,WAAA,GAAN,cAA0B,SAAA,CAAU;AAAA,EACzC,WAAA,CAA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AAA,CAAW,MAAM;AACf,UAAA,GAAA,EAAI;AACJ,UAAAA,QAAAA,EAAQ;AAAA,QACV,GAAG,EAAE,CAAA;AAAA,MACP,CAAC,CAAA;AAAA,IACH;AAAA,EACF,CAAA,GAAG;AACH,EAAA,MAAM,UAAU,MAAM,OAAA,CAAQ,KAAK,CAAC,KAAA,EAAO,QAAQ,CAAC,CAAA;AACpD,EAAA,YAAA,CAAa,KAAK,CAAA;AAClB,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["// ═══════════════════════════════════════════════════════════\n// Shared primitives — common types + generic guards used to\n// narrow `unknown` across the package.\n// ═══════════════════════════════════════════════════════════\n\nexport type Unsubscribe = () => void;\n\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nexport const isString = (value: unknown): value is string => typeof value === 'string';\n\nexport const isNumber = (value: unknown): value is number => typeof value === 'number';\n\nexport const isBoolean = (value: unknown): value is boolean => typeof value === 'boolean';\n\nexport const isArray = (value: unknown): value is unknown[] => Array.isArray(value);\n\nexport const isNonNull = <T>(value: T | null | undefined): value is T =>\n value !== null && value !== undefined;\n\nexport const hasKey = <K extends string>(\n obj: unknown,\n key: K,\n): obj is Record<K, unknown> => isObject(obj) && key in obj;\n","import type { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════\n// Error codes\n// ═══════════════════════════════════════════════════════════\n\nexport const ErrorCodes = {\n render: 'RENDER_ERROR',\n componentNotFound: 'COMPONENT_NOT_FOUND',\n layoutRefNotFound: 'LAYOUT_REF_NOT_FOUND',\n definitionValidation: 'DEFINITION_VALIDATION_ERROR',\n unknownAction: 'UNKNOWN_ACTION',\n unknownFragment: 'UNKNOWN_FRAGMENT',\n unknownFunction: 'UNKNOWN_FUNCTION',\n shellDisposed: 'SHELL_DISPOSED',\n lifecycle: 'LIFECYCLE_ERROR',\n mutation: 'MUTATION_ERROR',\n runaway: 'RUNAWAY_CHAIN',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\nexport type NovaErrorContext = Record<string, unknown>;\n\n// ═══════════════════════════════════════════════════════════\n// Base error — classes are permitted here because these are\n// the only thrown error types; identity + instanceof are needed.\n//\n// Subclasses are added when there is a real throw site. Do not\n// add dead exports.\n// ═══════════════════════════════════════════════════════════\n\nexport class NovaError extends Error {\n readonly code: ErrorCode;\n readonly context: NovaErrorContext | undefined;\n\n constructor(\n code: ErrorCode,\n message: string,\n context?: NovaErrorContext,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = 'NovaError';\n this.code = code;\n this.context = context;\n }\n}\n\nexport class RenderError extends NovaError {\n constructor(message: string, context?: NovaErrorContext, options?: { cause?: unknown }) {\n super(ErrorCodes.render, message, context, options);\n this.name = 'RenderError';\n }\n}\n\nexport type ComponentNotFoundContext = NovaErrorContext & { name: string };\n\nexport class ComponentNotFoundError extends NovaError {\n constructor(\n message: string,\n context: ComponentNotFoundContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.componentNotFound, message, context, options);\n this.name = 'ComponentNotFoundError';\n }\n}\n\nexport type LayoutRefNotFoundContext = NovaErrorContext & { ref: string };\n\nexport class LayoutRefNotFoundError extends NovaError {\n constructor(\n message: string,\n context: LayoutRefNotFoundContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.layoutRefNotFound, message, context, options);\n this.name = 'LayoutRefNotFoundError';\n }\n}\n\nexport type DefinitionValidationFailure = {\n id: string;\n issues: z.core.$ZodIssue[];\n};\n\nexport type DefinitionValidationContext = NovaErrorContext & {\n failures: DefinitionValidationFailure[];\n};\n\nexport class DefinitionValidationError extends NovaError {\n constructor(\n message: string,\n context: DefinitionValidationContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.definitionValidation, message, context, options);\n this.name = 'DefinitionValidationError';\n }\n}\n\nexport type UnknownActionContext = NovaErrorContext & { actionId: string };\n\nexport class UnknownActionError extends NovaError {\n constructor(\n message: string,\n context: UnknownActionContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.unknownAction, message, context, options);\n this.name = 'UnknownActionError';\n }\n}\n\nexport type UnknownFragmentContext = NovaErrorContext & { fragmentId: string };\n\nexport class UnknownFragmentError extends NovaError {\n constructor(\n message: string,\n context: UnknownFragmentContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.unknownFragment, message, context, options);\n this.name = 'UnknownFragmentError';\n }\n}\n\nexport class ShellDisposedError extends NovaError {\n constructor(message: string, context?: NovaErrorContext, options?: { cause?: unknown }) {\n super(ErrorCodes.shellDisposed, message, context, options);\n this.name = 'ShellDisposedError';\n }\n}\n\nexport type UnknownFunctionContext = NovaErrorContext & { name: string };\n\nexport class UnknownFunctionError extends NovaError {\n constructor(name: string, options?: { cause?: unknown }) {\n super(\n ErrorCodes.unknownFunction,\n `Unknown function: \"${name}\". Is it registered in shell config's \\`functions\\` map?`,\n { name },\n options,\n );\n this.name = 'UnknownFunctionError';\n }\n}\n\nexport type LifecycleHook = 'mount' | 'unmount' | 'suspend' | 'resume';\n\nexport type LifecycleErrorContext = NovaErrorContext & {\n hook?: LifecycleHook;\n instanceId?: string;\n};\n\nexport class LifecycleError extends NovaError {\n constructor(\n message: string,\n context?: LifecycleErrorContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.lifecycle, message, context, options);\n this.name = 'LifecycleError';\n }\n}\n\nexport type MutationErrorContext = NovaErrorContext & {\n op: string;\n path: string;\n reason: 'missing' | 'wrong-type';\n};\n\nexport class MutationError extends NovaError {\n constructor(\n message: string,\n context: MutationErrorContext,\n options?: { cause?: unknown },\n ) {\n super(ErrorCodes.mutation, message, context, options);\n this.name = 'MutationError';\n }\n}\n","// ═══════════════════════════════════════════════════════════\n// ID factory — closure-scoped, never module-mutable counters.\n// Uses crypto.randomUUID when available, falls back to a\n// Math.random-based token. Not security-sensitive.\n// ═══════════════════════════════════════════════════════════\n\nexport type IdFactory = () => string;\n\ntype CryptoLike = { randomUUID?: () => string };\n\nconst fallbackToken = (): string =>\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n\nconst getCrypto = (): CryptoLike | undefined => {\n if (typeof globalThis === 'undefined') return undefined;\n const g: { crypto?: CryptoLike } = globalThis;\n return g.crypto;\n};\n\nexport const createIdFactory = (prefix: string): IdFactory => {\n const cryptoObj = getCrypto();\n const randomUUID = cryptoObj?.randomUUID;\n if (typeof randomUUID === 'function') {\n return (): string => `${prefix}-${randomUUID.call(cryptoObj)}`;\n }\n return (): string => `${prefix}-${fallbackToken()}`;\n};\n","import { z } from 'zod';\n\nexport const IfDirectiveSchema = z\n .object({\n $if: z.unknown().describe('Condition — resolved recursively, then checked for truthiness.'),\n $then: z.unknown().describe('Value when condition is truthy — resolved recursively.'),\n $else: z\n .unknown()\n .optional()\n .describe('Value when condition is falsy — resolved recursively.'),\n })\n .strict()\n .describe('Conditional value directive. Resolved at bind time.');\n\nexport type IfDirective = z.infer<typeof IfDirectiveSchema>;\n\nexport const ResolvableSchema = z\n .unknown()\n .describe(\n 'Any value. Strings support {{}} templates and bare $-paths. The data ROOT is '\n + '\"$.\" — a data key is ALWAYS \"$.key\" (\"{{$.rows.length}} found\", \"$.loading\"); '\n + '\"$key\" without the dot is INVALID. Loop variables (a `for` directive\\'s `as`) '\n + 'are \"$<name>.field\" (\"{{$row.title}}\"). Objects may be directives like '\n + '{$if,$then,$else}. Arrays and nested objects are walked recursively. '\n + 'Everything else is literal.',\n );\n","import type { Scope, ScopeChain } from './types';\n\nexport const createScopeChain = (data: Scope): ScopeChain => [data];\n\nexport const pushScope = (chain: ScopeChain, scope: Scope): ScopeChain => [scope, ...chain];\n","import { isArray, isObject } from '../common';\n\n// ═══════════════════════════════════════════════════════════\n// Path helpers — get/set/delete on nested data structures.\n// Dot paths: \"a.b.0.c\". Numeric segments are array indices\n// when the parent is an array.\n// ═══════════════════════════════════════════════════════════\n\nconst splitPath = (path: string): string[] => {\n if (path.length === 0) return [];\n return path.split('.');\n};\n\nconst isIndex = (segment: string): boolean => /^\\d+$/.test(segment);\n\ntype Container = Record<string, unknown> | unknown[];\n\nconst cloneContainer = (value: unknown, nextSegment: string | undefined): Container => {\n if (isArray(value)) return value.slice();\n if (isObject(value)) return { ...value };\n if (nextSegment !== undefined && isIndex(nextSegment)) return [];\n return {};\n};\n\nconst writeSegment = (container: Container, segment: string, value: unknown): void => {\n if (isArray(container)) {\n if (isIndex(segment)) {\n const index = Number.parseInt(segment, 10);\n container[index] = value;\n }\n return;\n }\n container[segment] = value;\n};\n\nconst readSegment = (container: Container, segment: string): unknown => {\n if (isArray(container)) {\n if (!isIndex(segment)) return undefined;\n const index = Number.parseInt(segment, 10);\n return container[index];\n }\n return container[segment];\n};\n\nexport const getPath = (data: unknown, path: string): unknown => {\n const segments = splitPath(path);\n let current: unknown = data;\n for (const segment of segments) {\n if (current === undefined || current === null) return undefined;\n if (isArray(current)) {\n if (isIndex(segment)) {\n const index = Number.parseInt(segment, 10);\n current = current[index];\n continue;\n }\n if (segment === 'length') {\n current = current.length;\n continue;\n }\n return undefined;\n }\n if (isObject(current)) {\n if (segment in current) {\n current = current[segment];\n continue;\n }\n return undefined;\n }\n return undefined;\n }\n return current;\n};\n\nexport const setPath = (data: unknown, path: string, value: unknown): unknown => {\n const segments = splitPath(path);\n if (segments.length === 0) return value;\n\n const root = cloneContainer(data, segments[0]);\n let parent: Container = root;\n\n for (let i = 0; i < segments.length - 1; i += 1) {\n const segment = segments[i];\n const nextSegment = segments[i + 1];\n if (segment === undefined) continue;\n const existing = readSegment(parent, segment);\n const cloned = cloneContainer(existing, nextSegment);\n writeSegment(parent, segment, cloned);\n parent = cloned;\n }\n\n const last = segments[segments.length - 1];\n if (last !== undefined) writeSegment(parent, last, value);\n return root;\n};\n\nexport const deletePath = (data: unknown, path: string): unknown => {\n const segments = splitPath(path);\n if (segments.length === 0) return undefined;\n\n const root = cloneContainer(data, segments[0]);\n let parent: Container = root;\n\n for (let i = 0; i < segments.length - 1; i += 1) {\n const segment = segments[i];\n const nextSegment = segments[i + 1];\n if (segment === undefined) continue;\n const existing = readSegment(parent, segment);\n if (existing === undefined || existing === null) return root;\n const cloned = cloneContainer(existing, nextSegment);\n writeSegment(parent, segment, cloned);\n parent = cloned;\n }\n\n const last = segments[segments.length - 1];\n if (last === undefined) return root;\n if (isArray(parent)) {\n if (isIndex(last)) {\n const index = Number.parseInt(last, 10);\n parent.splice(index, 1);\n }\n } else {\n delete parent[last];\n }\n return root;\n};\n","import { evaluateSafe } from '@niscorp/prism';\nimport { hasKey, isArray, isObject } from '../common';\nimport { getPath } from './paths';\nimport type { ScopeChain } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Unified value resolver.\n//\n// One function — `resolve` — handles every binding site uniformly.\n//\n// String semantics:\n// 1. \"{{ expr }}\" (sole expression) → raw value of expr (type preserved)\n// 2. \"...{{expr}}...\" → interpolated string\n// 3. \"$.x\" or \"$ident...\" → raw value of path (type preserved)\n// 4. anything else → literal string\n//\n// Array → mapped recursively.\n// Object → walked recursively, OR treated as an `$if` directive.\n// Primitives → returned as-is.\n//\n// Path expressions resolve via `resolvePath`, which uses the ScopeChain\n// (innermost first). An optional `extras` map injects keyed scopes for\n// templates (e.g. `{ '@error': errObj }`); longest-prefix match wins.\n// ═══════════════════════════════════════════════════════════\n\nconst TEMPLATE_REGEX = /\\{\\{\\s*([^}]+?)\\s*\\}\\}/g;\nconst SOLE_TEMPLATE_REGEX = /^\\{\\{\\s*([^}]+?)\\s*\\}\\}$/;\nconst BARE_PATH_REGEX = /^\\$(\\.|[A-Za-z_]|$)/;\n\nexport type ExtraScopes = Record<string, unknown>;\n\nconst matchExtra = (expression: string, extras: ExtraScopes): string | undefined => {\n let matched: string | undefined;\n for (const key of Object.keys(extras)) {\n if (expression === key || expression.startsWith(`${key}.`)) {\n if (matched === undefined || key.length > matched.length) matched = key;\n }\n }\n return matched;\n};\n\nconst resolveExtraExpression = (\n expression: string,\n matchedKey: string,\n extras: ExtraScopes,\n): unknown => {\n const root = extras[matchedKey];\n if (expression === matchedKey) return root;\n const rest = expression.slice(matchedKey.length + 1);\n if (rest.length === 0) return root;\n return getPath(root, rest);\n};\n\nconst walkFromScopeHead = (head: unknown, restSegments: readonly string[]): unknown => {\n if (restSegments.length === 0) return head;\n return getPath(head, restSegments.join('.'));\n};\n\nexport const resolvePath = (\n path: string,\n chain: ScopeChain,\n extras: ExtraScopes = {},\n): unknown => {\n const extraKey = matchExtra(path, extras);\n if (extraKey !== undefined) return resolveExtraExpression(path, extraKey, extras);\n\n if (!path.startsWith('$')) return undefined;\n if (path === '$') return chain[0];\n\n const afterDollar = path.slice(1);\n\n if (afterDollar.startsWith('.')) {\n const rest = afterDollar.slice(1);\n if (rest.length === 0) return chain[0];\n const segments = rest.split('.');\n const head = segments[0];\n if (head === undefined) return undefined;\n for (const scope of chain) {\n if (hasKey(scope, head)) {\n return walkFromScopeHead(scope[head], segments.slice(1));\n }\n }\n return undefined;\n }\n\n const segments = afterDollar.split('.');\n const varName = segments[0];\n if (varName === undefined || varName.length === 0) return undefined;\n for (const scope of chain) {\n if (hasKey(scope, varName)) {\n return walkFromScopeHead(scope[varName], segments.slice(1));\n }\n }\n return undefined;\n};\n\nconst stringify = (value: unknown): string => {\n if (value === null || value === undefined) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n};\n\nconst isTruthy = (value: unknown): boolean => {\n if (value === null || value === undefined) return false;\n if (value === false) return false;\n if (value === 0) return false;\n if (value === '') return false;\n if (isArray(value) && value.length === 0) return false;\n return true;\n};\n\n// Directives — evaluated objects keyed by an operator (`$if`, `$eq`, …). Each\n// resolves its operands and returns a value. Add an operator here and it works\n// everywhere bindings are resolved; later operators (`$gte`, `$and`, …) slot in\n// the same way.\ntype Directive = (node: Record<string, unknown>, chain: ScopeChain, extras: ExtraScopes) => unknown;\n\nconst DIRECTIVES: Record<string, Directive> = {\n $if: (node, chain, extras) => {\n if (isTruthy(resolve(node.$if, chain, extras))) return resolve(node.$then, chain, extras);\n if (hasKey(node, '$else')) return resolve(node.$else, chain, extras);\n return undefined;\n },\n $eq: (node, chain, extras) => {\n const args = isArray(node.$eq) ? node.$eq : [];\n return resolve(args[0], chain, extras) === resolve(args[1], chain, extras);\n },\n // True when the operand path resolves to a present value. The structural\n // counterpart to `$eq`: discriminate a union by which key a branch carries\n // (`{ $exists: \"$.shape.component\" }`) rather than a shared tag's value.\n $exists: (node, chain, extras) => resolve(node.$exists, chain, extras) !== undefined,\n // Read an array element by a (dynamic) index: `{ $at: [\"$.results\", \"$.i\"] }`.\n // An optional third arg pulls one field off the element: `[\"$.results\", \"$.i\",\n // \"id\"]`. Returns undefined when the array/index doesn't resolve.\n $at: (node, chain, extras) => {\n const args = isArray(node.$at) ? node.$at : [];\n const arr = resolve(args[0], chain, extras);\n const index = Number(resolve(args[1], chain, extras));\n if (!isArray(arr) || Number.isNaN(index)) return undefined;\n const element = arr[index];\n const field = args[2];\n return field !== undefined && isObject(element) ? element[String(field)] : element;\n },\n // THE WHOLE TRANSFORM GRAMMAR, BEHIND ONE EXPLICIT DOOR. The directives\n // above stay the small binding set; a value that needs a real transformation\n // — a join, a projection, a group — says so out loud: `{ $prism: <node> }`\n // evaluates the node with prism against the action's ROOT data. One grammar,\n // one evaluator, nothing ambient — a prism-shaped object OUTSIDE this\n // wrapper stays what it always was, a plain object walked for strings.\n //\n // The quiet failure this replaces was worse than a crash: an unrecognised\n // op-shaped value passed through `resolve` as structure, landed in data, and\n // rendered as garbage three screens later. Inside the wrapper, a bad node\n // resolves to undefined — absent, not wrong.\n $prism: (node, chain) => {\n const result = evaluateSafe(node.$prism as never, (chain[0] ?? {}) as never);\n return result.ok ? result.data : undefined;\n },\n};\n\nconst directiveOf = (value: Record<string, unknown>): Directive | undefined => {\n for (const key of Object.keys(value)) {\n const directive = DIRECTIVES[key];\n if (directive !== undefined) return directive;\n }\n return undefined;\n};\n\nconst resolveString = (value: string, chain: ScopeChain, extras: ExtraScopes): unknown => {\n const sole = value.match(SOLE_TEMPLATE_REGEX);\n if (sole !== null) {\n const expr = sole[1];\n if (expr === undefined) return value;\n return resolvePath(expr.trim(), chain, extras);\n }\n\n if (value.includes('{{')) {\n return value.replace(TEMPLATE_REGEX, (_match: string, expression: string): string => {\n const resolved = resolvePath(expression.trim(), chain, extras);\n return stringify(resolved);\n });\n }\n\n if (BARE_PATH_REGEX.test(value)) {\n return resolvePath(value, chain, extras);\n }\n\n if (matchExtra(value, extras) !== undefined) {\n return resolvePath(value, chain, extras);\n }\n\n return value;\n};\n\nexport const resolve = (\n value: unknown,\n chain: ScopeChain,\n extras: ExtraScopes = {},\n): unknown => {\n if (typeof value === 'string') return resolveString(value, chain, extras);\n if (isArray(value)) return value.map((entry) => resolve(entry, chain, extras));\n if (isObject(value)) {\n const directive = directiveOf(value);\n if (directive !== undefined) return directive(value, chain, extras);\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n out[key] = resolve(value[key], chain, extras);\n }\n return out;\n }\n return value;\n};\n","import type { Unsubscribe } from '../common';\nimport type { DataStore } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// createDataStore — mutations live outside the store and are\n// applied via `store.update(curr => applyMutations(curr, list))`.\n// ═══════════════════════════════════════════════════════════\n\nexport const createDataStore = <T extends Record<string, unknown> = Record<string, unknown>>(\n initial: T,\n): DataStore<T> => {\n let current: T = { ...initial };\n const subscribers: Array<(data: T) => void> = [];\n\n const get = (): T => current;\n\n const update = (updater: (current: T) => T): void => {\n current = updater(current);\n for (const handler of subscribers.slice()) {\n try {\n handler(current);\n } catch {\n // handler errors must not crash the store\n }\n }\n };\n\n const subscribe = (handler: (data: T) => void): Unsubscribe => {\n subscribers.push(handler);\n return (): void => {\n const idx = subscribers.indexOf(handler);\n if (idx >= 0) subscribers.splice(idx, 1);\n };\n };\n\n return { get, update, subscribe };\n};\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════\n// NovaEvent — the built-in discriminated union of UI events.\n// Consumers may supply their own union to createEventBus<T>.\n//\n// Every UI event shares the same envelope: a `type` discriminator, an optional\n// target `ref`, an optional `payload`, and an optional `origin` — the id of the\n// action instance that dispatched it. `origin` is stamped automatically when an\n// event is dispatched from inside an instance's rendered layout (see ActionSlot),\n// and lets the runtime deliver a UI event to that instance's OWN triggers only,\n// so two instances of the same action (e.g. a list on `main` and on `aside`)\n// don't both react to one click. Events dispatched programmatically\n// (`shell.dispatch`) carry no `origin` and stay global.\n// ═══════════════════════════════════════════════════════════\n\nconst uiEvent = <T extends string, E extends z.ZodRawShape = Record<never, never>>(\n type: T,\n extra: E = {} as E,\n) =>\n z\n .object({\n type: z.literal(type).describe('Event type discriminator.'),\n ref: z.string().optional().describe('Target component ref.'),\n payload: z.unknown().optional().describe('Optional event payload.'),\n origin: z\n .string()\n .optional()\n .describe(\n 'Id of the action instance that dispatched this event. Stamped automatically for events dispatched from within an instance’s layout; used to deliver UI events to that instance’s own triggers only. Absent on programmatic (global) dispatch.',\n ),\n ...extra,\n })\n .strict();\n\nconst UiClickSchema = uiEvent('ui:click').describe('A UI click event.');\nconst UiSubmitSchema = uiEvent('ui:submit').describe('A UI submit event.');\nconst UiInputSchema = uiEvent('ui:input').describe('A UI input event.');\nconst UiFocusSchema = uiEvent('ui:focus').describe('A UI focus event.');\nconst UiBlurSchema = uiEvent('ui:blur').describe('A UI blur event.');\nconst UiModelSchema = uiEvent('ui:model').describe('A two-way-bound model update event.');\nconst UiKeySchema = uiEvent('ui:key', {\n key: z.string().describe('The key pressed, e.g. \"ArrowDown\", \"Enter\", \"Escape\".'),\n}).describe('A keyboard key event. A trigger filters it by `key` (and optionally `ref`).');\nconst UiDropSchema = uiEvent('ui:drop').describe(\n 'A drag-and-drop \"drop\" event — the semantic outcome of a drag gesture, dispatched by a drop zone. The gesture mechanics stay in the component; only the drop reaches Nova.',\n);\n\nexport const NovaEventSchema = z\n .discriminatedUnion('type', [\n UiClickSchema,\n UiSubmitSchema,\n UiInputSchema,\n UiFocusSchema,\n UiBlurSchema,\n UiModelSchema,\n UiKeySchema,\n UiDropSchema,\n ])\n .describe('Discriminated union of the built-in Nova UI events.');\n\nexport type NovaEvent = z.infer<typeof NovaEventSchema>;\n","import type { Unsubscribe } from '../common';\nimport type { EventBus, EventHandler, EventMatcher } from './types';\nimport type { NovaEvent } from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// Typed event bus. Factory function.\n//\n// Generic over TEvent (a discriminated union of events, defaulting\n// to NovaEvent). The bus only ever inspects `event.type` for matching.\n//\n// `scoped()` returns a child bus that forwards every event it emits\n// to its parent. No type mangling, no string prefixing — if you want\n// namespacing, put it in your event payload.\n// ═══════════════════════════════════════════════════════════\n\ntype Subscription<TEvent extends { type: string }> = {\n matcher: EventMatcher;\n handler: EventHandler<TEvent>;\n};\n\nconst typeMatches = (matcher: EventMatcher, type: string): boolean => {\n if (typeof matcher === 'string') return matcher === type;\n return matcher.test(type);\n};\n\nconst createChildBus = <TEvent extends { type: string }>(\n parent: EventBus<TEvent> | undefined,\n): EventBus<TEvent> => {\n const subscriptions: Subscription<TEvent>[] = [];\n\n const emit = (event: TEvent): void => {\n for (const sub of subscriptions.slice()) {\n if (!typeMatches(sub.matcher, event.type)) continue;\n try {\n sub.handler(event);\n } catch {\n // handler failures must not crash the bus\n }\n }\n if (parent !== undefined) parent.emit(event);\n };\n\n const on = (matcher: EventMatcher, handler: EventHandler<TEvent>): Unsubscribe => {\n const sub: Subscription<TEvent> = { matcher, handler };\n subscriptions.push(sub);\n return (): void => {\n const idx = subscriptions.indexOf(sub);\n if (idx >= 0) subscriptions.splice(idx, 1);\n };\n };\n\n const once = (matcher: EventMatcher, handler: EventHandler<TEvent>): Unsubscribe => {\n const off = on(matcher, (event) => {\n off();\n handler(event);\n });\n return off;\n };\n\n const bus: EventBus<TEvent> = {\n emit,\n on,\n once,\n scoped: () => createChildBus<TEvent>(bus),\n };\n\n return bus;\n};\n\nexport const createEventBus = <\n TEvent extends { type: string } = NovaEvent,\n>(): EventBus<TEvent> => createChildBus<TEvent>(undefined);\n","import type { NovaEvent } from './schemas';\n\n// Wraps a dispatch function so every event passing through it gets stamped\n// with `origin` (the dispatching action instance's id) unless it already\n// carries one — a re-dispatch keeps its original origin. Adapters wrap the\n// dispatch they hand to an instance's rendered subtree with this, so the\n// runtime delivers UI events to that instance's own triggers only. This is\n// routing semantics: never reimplement it per adapter.\nexport const scopeDispatch = (\n dispatch: (event: NovaEvent) => void,\n origin: string,\n): ((event: NovaEvent) => void) => {\n return (event) => dispatch(event.origin === undefined ? { ...event, origin } : event);\n};\n","import { z } from 'zod';\n\nexport const MessageEnvelopeSchema = z\n .object({\n channel: z.string().describe('Channel name the message is published on.'),\n from: z.string().optional().describe('Optional sender identifier.'),\n to: z.string().optional().describe('Optional direct recipient identifier.'),\n payload: z.unknown().optional().describe('Optional message payload.'),\n })\n .strict()\n .describe('A message envelope passed through the message bus.');\n\nexport type MessageEnvelope = z.infer<typeof MessageEnvelopeSchema>;\n","import type { Unsubscribe } from '../common';\nimport type { ChannelHandler, MessageBus } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Pure channel-based message bus. Internal subscriber map;\n// does NOT depend on the event bus.\n// ═══════════════════════════════════════════════════════════\n\nexport const createMessageBus = (): MessageBus => {\n const handlers = new Map<string, ChannelHandler[]>();\n\n const dispatch = (channel: string, payload: unknown, from: string | undefined, cause?: unknown): void => {\n const list = handlers.get(channel);\n if (list === undefined) return;\n for (const handler of list.slice()) {\n try {\n handler(payload, from, cause);\n } catch {\n // handler errors must not crash the bus\n }\n }\n };\n\n const publish = (channel: string, payload?: unknown, cause?: unknown): void => {\n dispatch(channel, payload, undefined, cause);\n };\n\n const send = (from: string, to: string, payload?: unknown): void => {\n dispatch(to, payload, from);\n };\n\n const subscribe = (channel: string, handler: ChannelHandler): Unsubscribe => {\n const list = handlers.get(channel) ?? [];\n list.push(handler);\n handlers.set(channel, list);\n return (): void => {\n const current = handlers.get(channel);\n if (current === undefined) return;\n const idx = current.indexOf(handler);\n if (idx >= 0) current.splice(idx, 1);\n };\n };\n\n return { publish, send, subscribe };\n};\n","import { z } from 'zod';\nimport { ResolvableSchema } from '../shared/bindings/schemas';\n\n// ═══════════════════════════════════════════════════════════\n// Layout node schemas\n// ═══════════════════════════════════════════════════════════\n\nexport const LayoutPrimitiveSchema = z\n .union([z.string(), z.number(), z.boolean(), z.null()])\n .describe('A primitive layout value rendered as text.');\n\nexport type LayoutPrimitive = z.infer<typeof LayoutPrimitiveSchema>;\n\nexport type ComponentNode = {\n component: string;\n props?: Record<string, unknown>;\n children?: LayoutNode | LayoutNode[];\n ref?: string;\n model?: string;\n events?: Record<string, unknown>;\n};\n\nexport const ComponentNodeSchema: z.ZodType<ComponentNode> = z.lazy(() =>\n z\n .object({\n component: z.string().describe('The registry name of the component to render.'),\n props: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Component props; values may be bindings to be resolved at render time.'),\n children: z\n .union([LayoutNodeSchema, z.array(LayoutNodeSchema)])\n .optional()\n .describe('Child layout content (a single node or an array of nodes).'),\n ref: z.string().optional().describe('A stable identifier used to target this component from event handlers.'),\n model: z.string().optional().describe('A two-way binding path, e.g. \"$.name\".'),\n events: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Map of event name to event configuration handled by the action runtime.'),\n })\n .strict()\n .describe('A node that instantiates a component from the registry.'),\n);\n\nexport type ConditionalNode = {\n if: unknown;\n then: LayoutNode;\n else?: LayoutNode;\n};\n\nexport const ConditionalNodeSchema: z.ZodType<ConditionalNode> = z.lazy(() =>\n z\n .object({\n if: ResolvableSchema.describe('Resolvable value evaluated for truthiness.'),\n then: LayoutNodeSchema.describe('Layout to render when condition is truthy.'),\n else: LayoutNodeSchema.optional().describe('Layout to render when condition is falsy.'),\n })\n .strict()\n .describe('A node that conditionally renders one of two branches.'),\n);\n\nexport type LoopNode = {\n for: unknown;\n as: string;\n key?: string;\n do: LayoutNode;\n};\n\nexport const LoopNodeSchema: z.ZodType<LoopNode> = z.lazy(() =>\n z\n .object({\n for: ResolvableSchema.describe('Resolvable value that resolves to an iterable array.'),\n as: z.string().describe('Name to bind each iterated item under in the inner scope.'),\n key: z.string().optional().describe('Optional key path on each item used for stable identity.'),\n do: LayoutNodeSchema.describe('Layout rendered once per iterated item.'),\n })\n .strict()\n .describe('A node that iterates an array binding and renders a layout for each item.'),\n);\n\nexport const LayoutRefNodeSchema = z\n .object({\n ref: z.string().describe('Identifier of a layout stored in the layout store to inline at this position.'),\n })\n .strict()\n .describe('A reference to a stored layout, inlined during render.');\n\nexport type LayoutRefNode = z.infer<typeof LayoutRefNodeSchema>;\n\nexport const SlotNodeSchema = z\n .object({\n slot: z\n .string()\n .describe(\n 'Name of a slot placeholder. When an ActionFragment is composed with an action ' +\n '(a push/replace `with`), the fragment\\'s `{ slot: \"body\" }` node is replaced by ' +\n 'the composing action\\'s own layout. An unfilled slot renders nothing.',\n ),\n })\n .strict()\n .describe(\n 'A placeholder that a fragment-merge fills with a composing action\\'s layout. ' +\n 'Only meaningful inside an ActionFragment\\'s layout.',\n );\n\nexport type SlotNode = z.infer<typeof SlotNodeSchema>;\n\nexport type LayoutNode =\n | ComponentNode\n | ConditionalNode\n | LoopNode\n | LayoutRefNode\n | SlotNode\n | LayoutNode[]\n | LayoutPrimitive;\n\nexport const LayoutNodeSchema: z.ZodType<LayoutNode> = z.lazy(() =>\n z\n .union([\n ComponentNodeSchema,\n ConditionalNodeSchema,\n LoopNodeSchema,\n LayoutRefNodeSchema,\n SlotNodeSchema,\n z.array(LayoutNodeSchema),\n LayoutPrimitiveSchema,\n ])\n .describe('Any layout node: component, conditional, loop, layout ref, slot, array of nodes, or a primitive text value.'),\n);\n","import { hasKey, isObject } from '../shared/common';\nimport type {\n ComponentNode,\n ConditionalNode,\n LayoutNode,\n LayoutPrimitive,\n LayoutRefNode,\n LoopNode,\n SlotNode,\n} from './schemas';\n\nexport const isLayoutPrimitive = (value: unknown): value is LayoutPrimitive =>\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean';\n\nexport const isComponentNode = (value: unknown): value is ComponentNode =>\n hasKey(value, 'component') && typeof value['component'] === 'string';\n\nexport const isConditionalNode = (value: unknown): value is ConditionalNode =>\n hasKey(value, 'if') && hasKey(value, 'then') && !hasKey(value, 'for');\n\nexport const isLoopNode = (value: unknown): value is LoopNode =>\n hasKey(value, 'for') && hasKey(value, 'as') && hasKey(value, 'do');\n\nexport const isLayoutRefNode = (value: unknown): value is LayoutRefNode =>\n isObject(value) &&\n hasKey(value, 'ref') &&\n typeof value['ref'] === 'string' &&\n !hasKey(value, 'component') &&\n Object.keys(value).length === 1;\n\nexport const isSlotNode = (value: unknown): value is SlotNode =>\n isObject(value) &&\n hasKey(value, 'slot') &&\n typeof value['slot'] === 'string' &&\n Object.keys(value).length === 1;\n\nexport const isLayoutNode = (value: unknown): value is LayoutNode =>\n isLayoutPrimitive(value) ||\n Array.isArray(value) ||\n isComponentNode(value) ||\n isConditionalNode(value) ||\n isLoopNode(value) ||\n isLayoutRefNode(value) ||\n isSlotNode(value);\n","// ═══════════════════════════════════════════════════════════\n// NOVA IS LANGUAGE-BLIND, the same way it is surface-blind.\n//\n// The core renders a layout into a `RenderNode` tree and knows nothing about\n// what language the words in it are. This area adds one late pass over that\n// tree — swap the words, leave the structure — plus the harvester that tells\n// you which words there are to swap.\n//\n// WHY A LATE PASS AND NOT A `$t` IN THE LAYOUT. Both work; they cost\n// differently. A key-per-string layout (`label: '@t.people.add'`) is precise\n// and makes every layout in the application unreadable — the file stops saying\n// what it draws. A late pass leaves the layouts as the readable English they\n// already are and moves the whole problem to one walk, at the price of keying\n// the dictionary on the source string rather than on an invented id.\n//\n// The price is real and worth naming: English-as-key cannot distinguish two\n// senses of one word. \"Book\" the verb and \"Book\" the noun are one key here and\n// two words in German. When that bites, the answer is not to abandon the pass\n// — it is to disambiguate that one string at its author site, and a `$t`\n// directive is the natural place for it. The two compose; this is the layer\n// that makes the other one optional rather than mandatory.\n//\n// WHAT THIS PASS CANNOT DO, and where the rest of the work goes:\n// - Open-ended formatted values — dates, money, counts. \"Fri 14 Mar\" has\n// unbounded cardinality and no dictionary will ever hold it. Those are\n// formatted at their source with a locale (prism's `$localeDate`,\n// `$localeMoney`, `$localeNumber`).\n// - Anything not in the tree: a server error message, a notification body.\n// ═══════════════════════════════════════════════════════════\n\n/** Source phrase → the words a reader of this locale should see. */\nexport type Phrasebook = Readonly<Record<string, string>>;\n\n// WHICH STRINGS IN A TREE ARE PROSE, declared by the host rather than guessed.\n//\n// A render tree is mostly not prose. It carries person names, ids, css values,\n// tone words, icon names and row data, and a pass that translated every string\n// it found would rename a member called \"Pass\" the first time somebody bought\n// one. So the host names the carriers, and everything else is left alone.\nexport type PhraseKeys = {\n // Prop names whose string values are prose: `label`, `title`, `placeholder`.\n // Matched at ANY depth inside a prop value, which is what makes a spec prop\n // work — a `Table`'s `columns: [{ label }]` and a `Select`'s\n // `options: [{ label }]` are the same rule as a bare `label`.\n props?: readonly string[];\n // Suffixes marking a DATA field as a display string. An app that spells its\n // read-time display fields `status_display`, `term_display` declares\n // `['_display']` once here, and every closed-set word a query manufactures\n // becomes translatable without the app naming them one by one.\n //\n // Only for CLOSED sets. A `_display` field holding a formatted date or an\n // amount will simply miss, every time, and should be formatted with a locale\n // at its source instead.\n suffixes?: readonly string[];\n // Translate bare text nodes (a layout's literal children). Default: true.\n text?: boolean;\n};\n\nexport const DEFAULT_PHRASE_KEYS: Required<Pick<PhraseKeys, 'props' | 'text'>> = {\n // A starting set, not a standard — an app with its own vocabulary passes its\n // own. Deliberately absent: `name`, `value`, `id`, `icon`, `tone`, `variant`,\n // `key`. Those carry data or design tokens, and translating them is how a\n // person called \"Active\" gets renamed.\n props: [\n 'label',\n 'title',\n 'subtitle',\n 'heading',\n 'eyebrow',\n 'lead',\n 'blurb',\n 'placeholder',\n 'hint',\n 'help',\n 'message',\n 'empty',\n 'emptyHint',\n 'emptyLabel',\n 'noMatch',\n 'caption',\n 'description',\n 'confirmLabel',\n 'cancelLabel',\n 'alt',\n 'tooltip',\n ],\n text: true,\n};\n\nexport type PhraseKeyMatcher = {\n isProse: (key: string) => boolean;\n text: boolean;\n};\n\nexport const matcherFor = (keys: PhraseKeys | undefined): PhraseKeyMatcher => {\n const props = new Set(keys?.props ?? DEFAULT_PHRASE_KEYS.props);\n const suffixes = keys?.suffixes ?? [];\n return {\n isProse: (key: string): boolean => props.has(key) || suffixes.some((suffix) => key.endsWith(suffix)),\n text: keys?.text ?? DEFAULT_PHRASE_KEYS.text,\n };\n};\n\n// A string that is a BINDING resolves to data at render time, so it is never a\n// phrase: harvesting `'$.member.person_name'` would put a path in the\n// dictionary and translating it would do nothing.\n//\n// Three forms, matching what the resolver recognises\n// (`shared/bindings/resolve.ts`): a bare `$` path, a `{{ }}` template, and an\n// `@`-prefixed EXTRA scope. The last one is easy to forget and shows up\n// immediately — a trigger's `{ set: 'x', value: '@event.payload.theme_id' }`\n// is a step's plumbing, and a harvester without this rule fills a language\n// file with several dozen of them.\nconst BARE_PATH = /^\\$(\\.|[A-Za-z_]|$)/;\nconst EXTRA_SCOPE = /^@[A-Za-z_]/;\n\nexport const isBinding = (value: string): boolean =>\n BARE_PATH.test(value) || EXTRA_SCOPE.test(value) || value.includes('{{');\n\n// Worth translating at all: a non-empty string that is not a binding and is not\n// obviously machine vocabulary. The last clause is a cheap guard against\n// harvesting css values and tokens that happen to sit at an allowlisted key.\nexport const isPhrase = (value: string): boolean => {\n const trimmed = value.trim();\n if (trimmed === '' || isBinding(trimmed)) return false;\n // A phrase has a letter in it. '—', '18:30', '#fff', '100%' do not.\n return /\\p{L}/u.test(trimmed);\n};\n","import { isArray, isObject } from '../shared/common';\nimport { matcherFor } from './phrases';\nimport { isPhrase } from './phrases';\nimport type { PhraseKeys, Phrasebook } from './phrases';\n\n// ═══════════════════════════════════════════════════════════\n// The swap itself — over VALUES, knowing nothing about trees.\n//\n// Deliberately free of any layout import, because the renderer needs it and\n// the renderer is what layout IS. `translate.ts` (the tree walk) and\n// `layout/renderer.ts` (the mint) are two callers of this one engine, and the\n// whole point of the file is that they can never disagree about what a swap\n// means.\n// ═══════════════════════════════════════════════════════════\n\nexport type Pass = {\n phrases: Phrasebook;\n isProse: (key: string) => boolean;\n text: boolean;\n onMiss: ((phrase: string, where: string) => void) | undefined;\n};\n\nexport type PassOptions = {\n phrases?: Phrasebook;\n keys?: PhraseKeys;\n onMiss?: (phrase: string, where: string) => void;\n};\n\nconst EMPTY: Phrasebook = {};\n\n// ACTIVE OR ABSENT, decided once. A host that named neither a book nor a key\n// set is not doing i18n, and pays nothing: `undefined` here means the renderer\n// skips every branch below, and a `{ phrase, slots }` object passes through as\n// the object it is.\n//\n// A key set WITHOUT a book is the source language, and is NOT nothing: patterns\n// still have to be filled, because a counted phrase reaches the glass as a\n// structure and nobody downstream knows how to read it. That is the one job\n// this pass keeps doing when there is nothing to translate.\nexport const passFor = (options: PassOptions | undefined): Pass | undefined => {\n if (options === undefined) return undefined;\n if (options.phrases === undefined && options.keys === undefined) return undefined;\n const matcher = matcherFor(options.keys);\n return {\n phrases: options.phrases ?? EMPTY,\n isProse: matcher.isProse,\n text: matcher.text,\n onMiss: options.onMiss,\n };\n};\n\nexport const swap = (value: string, where: string, pass: Pass): string => {\n if (!isPhrase(value)) return value;\n const hit = pass.phrases[value];\n if (hit !== undefined) return hit;\n // Trailing/leading whitespace is a layout accident, not part of the phrase.\n // Trying the trimmed form keeps `'Save '` from being a second dictionary\n // entry nobody remembers to fill in.\n const trimmed = value.trim();\n if (trimmed !== value) {\n const onTrimmed = pass.phrases[trimmed];\n if (onTrimmed !== undefined) return value.replace(trimmed, onTrimmed);\n }\n pass.onMiss?.(trimmed, where);\n return value;\n};\n\n// A PATTERN: a counted phrase, translated WHOLE and filled here — the one\n// point that has the book. `{ phrase: '{n} of {total}', slots: { n: 1,\n// total: 12 } }` becomes `'1 von 12'`: the pattern is a dictionary row like\n// any other, so cardinality stays out of the book. A string slot is offered\n// to the book too — a composed sentence's fragments (\"somebody enquires\")\n// are vocabulary in their own right — and everything else interpolates as\n// itself. An empty book fills the holes and translates nothing, which is\n// exactly what a source-language session needs.\nconst isPattern = (value: Record<string, unknown>): value is { phrase: string; slots: Record<string, unknown> } =>\n typeof value['phrase'] === 'string' && isObject(value['slots']);\n\nconst fillPattern = (pattern: { phrase: string; slots: Record<string, unknown> }, where: string, pass: Pass): string =>\n swap(pattern.phrase, where, pass).replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (hole, name: string) => {\n const slot = pattern.slots[name];\n if (slot === undefined || slot === null) return hole;\n return typeof slot === 'string' && isPhrase(slot) ? swap(slot, `${where}.${name}`, pass) : String(slot);\n });\n\n// A book that translates nothing — for filling a pattern outside a render,\n// which is the only thing left to do with one when there are no words to swap.\nconst SOURCE: Pass = { phrases: EMPTY, isProse: () => true, text: true, onMiss: undefined };\n\n// FILL A COUNTED PHRASE THAT NEVER WENT THROUGH A RENDER.\n//\n// The renderer fills patterns on the way to a screen, so nothing downstream of\n// it needs this. What does need it is everything UPSTREAM: a check that reads\n// an entry straight from the engine, a fixture, an exporter — anywhere a\n// `{ phrase, slots }` is held as data rather than shown as words. Nova defines\n// the shape, so nova reads it; a host writing its own copy of this loop is how\n// two spellings of one rule start drifting.\n//\n// Anything that is not a pattern comes back untouched, so it is safe to call\n// on a whole column of mixed values.\nexport const fillPhrase = (value: unknown): unknown => {\n if (!isObject(value) || !isPattern(value)) return value;\n return fillPattern(value, '', SOURCE);\n};\n\n// Walk a prop VALUE. Depth matters: a spec prop is where the repeated structure\n// of a screen lives (`columns: [{ label }]`, `options: [{ label }]`), so the\n// rule cannot be \"top-level props only\" without missing most of a table.\n//\n// Returns the value it was given when nothing under it changed. Identity is\n// load-bearing rather than tidy: a source-language render must produce the\n// props object it produced before this existed, or every untranslated session\n// pays a rebuild for a walk that did nothing.\nexport const walkValue = (value: unknown, prose: boolean, where: string, pass: Pass): unknown => {\n if (typeof value === 'string') return prose ? swap(value, where, pass) : value;\n if (isArray(value)) {\n let changed = false;\n const out = value.map((entry, index) => {\n // An array inherits its key's proseness — `options: ['Yes', 'No']` is as\n // much prose as `options: [{ label: 'Yes' }]`.\n const next = walkValue(entry, prose, `${where}[${String(index)}]`, pass);\n if (next !== entry) changed = true;\n return next;\n });\n return changed ? out : value;\n }\n if (isObject(value)) {\n if (prose && isPattern(value)) return fillPattern(value, where, pass);\n let changed = false;\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const next = walkValue(entry, pass.isProse(key), `${where}.${key}`, pass);\n if (next !== entry) changed = true;\n out[key] = next;\n }\n return changed ? out : value;\n }\n return value;\n};\n","// ═══════════════════════════════════════════════════════════\n// THE HEAD — `nova:head` is the document's <head>, as a node in a layout.\n//\n// A document has a part nobody sees on the screen: its title, the sentence\n// that describes it, the card shown where a link to it is pasted. That part\n// is written the way the rest of the screen is — a layout node, its children\n// bound to the action's data — and travels the way the rest does, in the\n// render tree.\n//\n// Its children are the elements a head holds, named as HTML names them:\n// `nova:title`, `nova:meta`, `nova:link`, `nova:script`. A child's props are\n// that element's ATTRIBUTES, written as given. Nova keeps no list of them, so\n// any `name`, `property` or `rel` there is — or will be — can be said without\n// nova learning it.\n//\n// Nothing here is drawn on the screen. No adapter builds an element for a head\n// or for anything in it, and no registry has to hold the names. Whoever writes\n// the document reads the elements off the tree (`headOf`) and writes them into\n// its <head>.\n//\n// WHAT A HEAD DOES NOT HOLD is what runs or styles: a script that executes, a\n// stylesheet, a <base>, an instruction to the browser (`http-equiv`), a handler\n// attribute. A layout is data, and data that reaches every page must not be\n// able to run. Those stay in the app's own index.html, which holds anything.\n//\n// This file holds no schema on purpose: a terminal that only reads a head off\n// the wire needs the names and the shape, and nothing to validate with.\n// ═══════════════════════════════════════════════════════════\n\n// Namespaced as a package's own in-layout components are (`loom:field`), so\n// none can be a name an app's kit already uses for something else.\nexport const HEAD_NAME = 'nova:head';\nexport const HEAD_TITLE_NAME = 'nova:title';\nexport const HEAD_META_NAME = 'nova:meta';\nexport const HEAD_LINK_NAME = 'nova:link';\nexport const HEAD_SCRIPT_NAME = 'nova:script';\n\n// The head and what it holds: the names a layout may use with no registry\n// entry behind them.\nexport const HEAD_NAMES: readonly string[] = [HEAD_NAME, HEAD_TITLE_NAME, HEAD_META_NAME, HEAD_LINK_NAME, HEAD_SCRIPT_NAME];\n\n// One element of a head, as data: what to write, wherever a head is written.\nexport type HeadElement = {\n tag: 'title' | 'meta' | 'link' | 'script';\n // as the layout gave them, in the order it gave them\n attributes: Record<string, string>;\n // a title's words; a script's data, as JSON\n text?: string;\n};\n\n// What two elements both say, when they say the same thing — the later one\n// then takes the earlier one's place. A document has one title, one <meta> of\n// a given name or property, one canonical address. Anything else stands beside\n// its like: two alternates, two data blocks.\nexport const headKeyOf = (element: Pick<HeadElement, 'tag' | 'attributes'>): string | undefined => {\n const said = (name: string): string | undefined => {\n const found = Object.entries(element.attributes).find(([key]) => key.toLowerCase() === name)?.[1].trim().toLowerCase();\n return found === undefined || found === '' ? undefined : found;\n };\n if (element.tag === 'title') return 'title';\n if (element.tag === 'meta') {\n const [name, property] = [said('name'), said('property')];\n if (name !== undefined) return `meta name ${name}`;\n return property === undefined ? undefined : `meta property ${property}`;\n }\n if (element.tag === 'link') return (said('rel') ?? '').split(/\\s+/).includes('canonical') ? 'link canonical' : undefined;\n return undefined;\n};\n","import { isArray } from '../shared/common';\nimport {\n ComponentNotFoundError,\n LayoutRefNotFoundError,\n NovaError,\n RenderError,\n} from '../shared/errors';\nimport { createScopeChain, getPath, pushScope, resolve } from '../shared/bindings';\nimport type { ScopeChain } from '../shared/bindings';\nimport { isBinding } from '../i18n/phrases';\nimport { passFor, swap, walkValue } from '../i18n/swap';\nimport type { Pass } from '../i18n/swap';\nimport {\n isComponentNode,\n isConditionalNode,\n isLayoutPrimitive,\n isLayoutRefNode,\n isLoopNode,\n isSlotNode,\n} from './guards';\nimport { HEAD_NAMES } from './head';\nimport type { ComponentNode, LayoutNode } from './schemas';\nimport type {\n DataStoreView,\n ModelBindingDescriptor,\n RenderContext,\n RenderErrorNode,\n RenderNode,\n RenderOnError,\n} from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Renderer — converts a LayoutNode tree into a framework-agnostic\n// RenderNode[] tree. Renders children in try/catch boundaries so a\n// single broken subtree does not poison siblings, unless strict mode\n// is enabled. All errors flow through the ctx.onError telemetry hook.\n// ═══════════════════════════════════════════════════════════\n\nconst noopOnError: RenderOnError = (_error: NovaError): void => {\n // default — errors silently dropped if no handler provided\n};\n\ntype InternalRenderContext = {\n store: RenderContext['store'];\n registry: RenderContext['registry'];\n strict: boolean;\n onError: RenderOnError;\n scopePaths: string[];\n // Undefined when the host named no book and no keys — the whole language\n // apparatus is then absent rather than idling, and a `{ phrase, slots }`\n // object passes through as the object it is.\n pass: Pass | undefined;\n // Where a miss was found, coarse: the chain of component names above it.\n // Only maintained while a pass is active, since nothing else reads it.\n where: string;\n};\n\nconst textNode = (value: string): RenderNode => ({ type: 'text', value });\n\nconst fragment = (children: RenderNode[]): RenderNode => ({ type: 'fragment', children });\n\nconst errorNode = (\n error: NovaError,\n nodeRef: string | undefined,\n): RenderErrorNode => ({\n type: 'error',\n code: error.code,\n message: error.message,\n ...(nodeRef === undefined ? {} : { nodeRef }),\n});\n\nconst toRenderError = (err: unknown): NovaError => {\n if (err instanceof NovaError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new RenderError(message, {}, { cause: err });\n};\n\n// Resolve a `$.x.y` or `$loopVar.y` binding to an absolute data path\n// (used to construct stable model binding descriptors inside loops).\nconst resolveDataPath = (\n binding: string,\n scopePaths: string[],\n): string | undefined => {\n if (!binding.startsWith('$')) return undefined;\n const after = binding.slice(1);\n if (after.startsWith('.')) return after.slice(1);\n const segments = after.split('.');\n const head = segments[0];\n if (head === undefined || head.length === 0) return undefined;\n for (let i = scopePaths.length - 1; i >= 0; i -= 1) {\n const entry = scopePaths[i];\n if (entry === undefined) continue;\n const eq = entry.indexOf('=');\n if (eq < 0) continue;\n const key = entry.slice(0, eq);\n if (key !== head) continue;\n const rooted = entry.slice(eq + 1);\n const rest = segments.slice(1).join('.');\n if (rest.length === 0) return rooted;\n return `${rooted}.${rest}`;\n }\n return undefined;\n};\n\nconst makeAutoRef = (componentName: string, path: string): string =>\n `auto-${componentName}-${path}`;\n\nconst renderNode = (\n node: LayoutNode,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode[] => {\n if (node === null) return [textNode('')];\n if (typeof node === 'string') {\n const resolved = resolve(node, chain);\n if (resolved === undefined || resolved === null) return [textNode('')];\n const value = String(resolved);\n // A LITERAL text child is prose; a BOUND one is data wearing a text\n // position, and offering it to the book is how a member called \"Pass\" gets\n // renamed. Nothing but the renderer can tell those apart — by the time a\n // tree exists both are the same plain string — which is why this rule\n // could not be written in `translateRenderTree` and can be written here.\n if (ctx.pass === undefined || !ctx.pass.text || isBinding(node)) return [textNode(value)];\n return [textNode(swap(value, `${ctx.where}#text`, ctx.pass))];\n }\n if (isLayoutPrimitive(node)) {\n return [textNode(String(node))];\n }\n if (isArray(node)) {\n const children = renderChildArray(node, chain, ctx);\n return [fragment(children)];\n }\n if (isLayoutRefNode(node)) {\n const target = ctx.store.get(node.ref);\n if (target === undefined) {\n throw new LayoutRefNotFoundError(`Layout ref not found: ${node.ref}`, { ref: node.ref });\n }\n return renderNode(target, chain, ctx);\n }\n if (isSlotNode(node)) {\n // A slot is filled at fragment-merge time (fillSlots). One that survives to\n // render was never filled — render nothing.\n return [];\n }\n if (isConditionalNode(node)) {\n const condition = resolve(node.if, chain);\n const truthy =\n condition !== undefined &&\n condition !== null &&\n condition !== false &&\n condition !== 0 &&\n condition !== '';\n const branchTruthy = isArray(condition) ? condition.length > 0 : truthy;\n if (branchTruthy) return renderNode(node.then, chain, ctx);\n if (node.else !== undefined) return renderNode(node.else, chain, ctx);\n return [];\n }\n if (isLoopNode(node)) {\n const items = resolve(node.for, chain);\n if (!isArray(items)) return [];\n const loopBasePath = typeof node.for === 'string'\n ? resolveDataPath(node.for, ctx.scopePaths)\n : undefined;\n const out: RenderNode[] = [];\n items.forEach((item, index) => {\n // Each iteration binds three reserved loop vars: the element (`$<as>`),\n // its position (`$index`), and the array itself (`$items`). `$items`\n // lets a control inside the loop edit the whole list — remove or reorder\n // an element — not just its own value. Both `index` and `items` are\n // reserved names; an `as` of `'index'` or `'items'` would shadow them.\n const innerChain = pushScope(chain, { [node.as]: item, index, items });\n // `$items` resolves to a *writable* path (so `model: \"$items\"` works) only\n // when the loop's source is itself a resolvable path; a literal-array loop\n // exposes the value but stays read-only, exactly as `$<as>` does.\n const nextScopePaths =\n loopBasePath === undefined\n ? ctx.scopePaths\n : [...ctx.scopePaths, `${node.as}=${loopBasePath}.${index}`, `items=${loopBasePath}`];\n const innerCtx: InternalRenderContext = { ...ctx, scopePaths: nextScopePaths };\n // Stamp a stable React-identity key on each item's output: the value at\n // `node.key` (e.g. the row id), or the index when no key path is given.\n // This is what lets looped rows share a `ref` (the trigger target) without\n // colliding as React keys. `withKey` (in render-tree) prefers it over ref.\n const idKey = node.key !== undefined ? getPath(item, node.key) : index;\n const rendered = safeRenderSingle(node.do, innerChain, innerCtx, undefined);\n rendered.forEach((rn, sub) => {\n out.push({ ...rn, key: rendered.length === 1 ? String(idKey) : `${String(idKey)}:${sub}` });\n });\n });\n return [fragment(out)];\n }\n if (isComponentNode(node)) {\n return [renderComponent(node, chain, ctx)];\n }\n return [];\n};\n\nconst renderComponent = (\n node: ComponentNode,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode => {\n // A head and what it holds are drawn by nobody, so no kit has anything to\n // register for them.\n if (!HEAD_NAMES.includes(node.component) && !ctx.registry.has(node.component)) {\n throw new ComponentNotFoundError(\n `Component not found in registry: ${node.component}`,\n { name: node.component },\n );\n }\n // THE ONE PLACE A PROP BECOMES A WORD ON A SCREEN. The swap belongs here\n // rather than in a later walk over the finished tree: the value is already\n // in hand, so translating it costs one lookup instead of a second traversal\n // of everything that was just built.\n //\n // Unlike a text child, a BOUND prop is translated — that is the whole\n // `_display` mechanism, where a query manufactures a closed-set word and a\n // read puts it on the screen. What protects data here is the KEY: `label` is\n // prose, `name` is not, and no value ever votes on the question.\n const pass = ctx.pass;\n const at = pass === undefined ? '' : `${ctx.where}/${node.component}`;\n const props: Record<string, unknown> = Object.fromEntries(\n Object.entries(node.props ?? {}).map(([k, v]) => {\n const resolved = resolve(v, chain);\n if (pass === undefined) return [k, resolved];\n return [k, walkValue(resolved, pass.isProse(k), `${at}.${k}`, pass)];\n }),\n );\n const children = renderChildren(node.children, chain, pass === undefined ? ctx : { ...ctx, where: at });\n\n let model: ModelBindingDescriptor | undefined;\n if (node.model !== undefined) {\n const resolvedPath = resolveDataPath(node.model, ctx.scopePaths);\n if (resolvedPath !== undefined) {\n const ref = node.ref ?? makeAutoRef(node.component, resolvedPath);\n model = { path: resolvedPath, ref };\n // Two-way binding: if the component doesn't already have an explicit\n // `value` prop, auto-derive it from the model expression so the\n // displayed value tracks the data store. Without this, controlled\n // inputs always show their initial value because nothing updates the\n // `value` prop on re-render.\n if (!('value' in props)) {\n props['value'] = resolve(node.model, chain);\n }\n }\n }\n\n const component: RenderNode = {\n type: 'component',\n name: node.component,\n props,\n children,\n ...(node.ref === undefined ? {} : { ref: node.ref }),\n ...(model === undefined ? {} : { model }),\n };\n return component;\n};\n\nconst safeRenderSingle = (\n node: LayoutNode,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n nodeRef: string | undefined,\n): RenderNode[] => {\n try {\n return renderNode(node, chain, ctx);\n } catch (err) {\n const novaError = toRenderError(err);\n if (ctx.strict) throw novaError;\n ctx.onError(novaError);\n return [errorNode(novaError, nodeRef)];\n }\n};\n\nconst renderChildArray = (\n nodes: LayoutNode[],\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode[] => {\n const out: RenderNode[] = [];\n for (const child of nodes) out.push(...safeRenderSingle(child, chain, ctx, undefined));\n return out;\n};\n\nconst renderChildren = (\n children: LayoutNode | LayoutNode[] | undefined,\n chain: ScopeChain,\n ctx: InternalRenderContext,\n): RenderNode[] => {\n if (children === undefined) return [];\n if (isArray(children)) return renderChildArray(children, chain, ctx);\n return safeRenderSingle(children, chain, ctx, undefined);\n};\n\nconst toInternal = (ctx: RenderContext): InternalRenderContext => ({\n store: ctx.store,\n registry: ctx.registry,\n strict: ctx.strict ?? false,\n onError: ctx.onError ?? noopOnError,\n scopePaths: [],\n // Built once per render call. The matcher compiles a Set and a suffix list,\n // and doing that per node would make the cheapest branch the expensive one.\n pass: passFor({\n ...(ctx.phrases === undefined ? {} : { phrases: ctx.phrases }),\n ...(ctx.phraseKeys === undefined ? {} : { keys: ctx.phraseKeys }),\n ...(ctx.onPhraseMiss === undefined ? {} : { onMiss: ctx.onPhraseMiss }),\n }),\n where: '',\n});\n\nexport const renderLayout = (\n node: LayoutNode,\n data: Record<string, unknown>,\n ctx: RenderContext,\n): RenderNode[] => {\n const internal = toInternal(ctx);\n return safeRenderSingle(node, createScopeChain(data), internal, undefined);\n};\n\n// Object-form alias for renderLayout. Same semantics, named parameters —\n// so the caller doesn't have to remember the positional order of\n// (layout, data, ctx) and so `data` can be omitted when the layout has\n// no resolvables.\nexport type RenderOptions = {\n layout: LayoutNode;\n data?: Record<string, unknown>;\n store: RenderContext['store'];\n registry: RenderContext['registry'];\n strict?: boolean;\n onError?: RenderOnError;\n phrases?: RenderContext['phrases'];\n phraseKeys?: RenderContext['phraseKeys'];\n onPhraseMiss?: RenderContext['onPhraseMiss'];\n};\n\nexport const render = (options: RenderOptions): RenderNode[] =>\n renderLayout(options.layout, options.data ?? {}, {\n store: options.store,\n registry: options.registry,\n ...(options.strict === undefined ? {} : { strict: options.strict }),\n ...(options.onError === undefined ? {} : { onError: options.onError }),\n ...(options.phrases === undefined ? {} : { phrases: options.phrases }),\n ...(options.phraseKeys === undefined ? {} : { phraseKeys: options.phraseKeys }),\n ...(options.onPhraseMiss === undefined ? {} : { onPhraseMiss: options.onPhraseMiss }),\n });\n\n// Render a layout reading its root data from a DataStore view. Used by the\n// action runtime so layout and action share a single data store instance.\nexport const renderLayoutFromStore = (\n node: LayoutNode,\n store: DataStoreView,\n ctx: RenderContext,\n): RenderNode[] => {\n const internal = toInternal(ctx);\n return safeRenderSingle(node, createScopeChain(store.get()), internal, undefined);\n};\n\nexport type { ScopeChain };\n","import { isComponentNode, isConditionalNode, isLoopNode, isSlotNode } from './guards';\nimport type { LayoutNode } from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// fillSlots — replace every `{ slot: name }` placeholder in a layout tree with\n// the layout in `fills[name]`. Used by the ActionFragment merge: a fragment's\n// chrome layout has a `{ slot: 'body' }`, and the composing action's own layout\n// is dropped into it. A slot whose name has no fill is left in place — the\n// renderer renders an unfilled slot as nothing.\n//\n// A pure tree-walk modelled on the layout store's `resolveReferences`: recurse\n// through children / then / else / do / arrays, rebuilding the tree.\n// ═══════════════════════════════════════════════════════════\n\nexport const fillSlots = (layout: LayoutNode, fills: Record<string, LayoutNode>): LayoutNode => {\n if (isSlotNode(layout)) {\n const fill = fills[layout.slot];\n return fill === undefined ? layout : fill;\n }\n if (Array.isArray(layout)) {\n return layout.map((node) => fillSlots(node, fills));\n }\n if (isComponentNode(layout)) {\n const { children } = layout;\n if (children === undefined) return layout;\n const next = Array.isArray(children)\n ? children.map((child) => fillSlots(child, fills))\n : fillSlots(children, fills);\n return { ...layout, children: next };\n }\n if (isConditionalNode(layout)) {\n return {\n ...layout,\n then: fillSlots(layout.then, fills),\n ...(layout.else === undefined ? {} : { else: fillSlots(layout.else, fills) }),\n };\n }\n if (isLoopNode(layout)) {\n return { ...layout, do: fillSlots(layout.do, fills) };\n }\n // primitives, layout refs, slot-less nodes — unchanged\n return layout;\n};\n","import type { RenderNode } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Adapter helpers — framework-agnostic pieces every adapter\n// (React, Vue, …) needs to render a RenderNode tree the same\n// way. See packages/nova/ADAPTER.md for the full contract.\n// ═══════════════════════════════════════════════════════════\n\n// Names of the props an adapter injects on rendered components:\n// `RenderNode.model` → NOVA_MODEL_PROP ({ ref, path }),\n// `RenderNode.ref` → NOVA_REF_PROP (string). Constants so all\n// adapters inject identically and components can rely on them.\nexport const NOVA_MODEL_PROP = 'novaModel';\nexport const NOVA_REF_PROP = 'novaRef';\n\n// Stable identity for a RenderNode within its sibling list.\n// Loop identity (stamped from LoopNode.key/index) wins over ref: a shared\n// `ref` across looped rows is an event-target id, not a list key.\nexport const renderNodeKey = (node: RenderNode, index: number): string => {\n if (node.key !== undefined) return `k:${node.key}`;\n if (node.type === 'component') {\n if (node.ref !== undefined) return `c:${node.ref}`;\n return `c:${node.name}:${index}`;\n }\n if (node.type === 'text') return `t:${index}`;\n if (node.type === 'fragment') return `f:${index}`;\n return `e:${node.code}:${index}`;\n};\n","import { DefinitionValidationError } from '../shared/errors';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport {\n isComponentNode,\n isConditionalNode,\n isLayoutRefNode,\n isLoopNode,\n} from './guards';\nimport { LayoutNodeSchema, type LayoutNode } from './schemas';\nimport type { LayoutStore } from './types';\n\nexport const createLayoutStore = (): LayoutStore => {\n const layouts = new Map<string, LayoutNode>();\n\n const get = (id: string): LayoutNode | undefined => layouts.get(id);\n\n const set = (id: string, layout: LayoutNode): void => {\n // Before the schema: a deep enough layout overflows it (strata depth.ts).\n if (exceedsDepth(layout)) {\n throw new DefinitionValidationError(`Invalid layout for id \"${id}\"`, { failures: [{ id, issues: [{ code: 'custom', path: [], message: depthRefusal(), input: undefined }] }] });\n }\n const result = LayoutNodeSchema.safeParse(layout);\n if (!result.success) {\n throw new DefinitionValidationError(`Invalid layout for id \"${id}\"`, {\n failures: [{ id, issues: result.error.issues }],\n });\n }\n layouts.set(id, layout);\n };\n\n const remove = (id: string): void => {\n layouts.delete(id);\n };\n\n const list = (): string[] => Array.from(layouts.keys());\n\n const resolveReferences = (layout: LayoutNode): LayoutNode => {\n if (isLayoutRefNode(layout)) {\n const target = layouts.get(layout.ref);\n if (target === undefined) return layout;\n return resolveReferences(target);\n }\n if (Array.isArray(layout)) {\n return layout.map(resolveReferences);\n }\n if (isComponentNode(layout)) {\n const children = layout.children;\n let resolvedChildren: LayoutNode | LayoutNode[] | undefined;\n if (children === undefined) {\n resolvedChildren = undefined;\n } else if (Array.isArray(children)) {\n resolvedChildren = children.map(resolveReferences);\n } else {\n resolvedChildren = resolveReferences(children);\n }\n return {\n ...layout,\n ...(resolvedChildren === undefined ? {} : { children: resolvedChildren }),\n };\n }\n if (isConditionalNode(layout)) {\n return {\n ...layout,\n then: resolveReferences(layout.then),\n ...(layout.else === undefined ? {} : { else: resolveReferences(layout.else) }),\n };\n }\n if (isLoopNode(layout)) {\n return {\n ...layout,\n do: resolveReferences(layout.do),\n };\n }\n return layout;\n };\n\n return { get, set, delete: remove, list, resolveReferences };\n};\n","import type {\n ComponentEntry,\n ComponentMeta,\n ComponentRegistry,\n RegistrationInput,\n} from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Component registry\n//\n// Stores `{component, meta}` entries keyed by name. Components\n// can carry a static `.meta` property; `registerAll` picks it up\n// automatically. Explicit meta passed to `register`/`registerAll`\n// wins over a component's static meta.\n// ═══════════════════════════════════════════════════════════\n\nconst hasOwn = (value: object, key: string): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\n\nconst isComponentMeta = (value: unknown): value is ComponentMeta => {\n if (typeof value !== 'object' || value === null) return false;\n // Meta is an open bag with optional fields; any plain object qualifies.\n return true;\n};\n\nconst extractStaticMeta = <TComponent>(component: TComponent): ComponentMeta | undefined => {\n if (typeof component !== 'function' && (typeof component !== 'object' || component === null)) {\n return undefined;\n }\n const host: object = component;\n if (!hasOwn(host, 'meta')) return undefined;\n const candidate = (host as { meta: unknown }).meta;\n if (!isComponentMeta(candidate)) return undefined;\n return candidate;\n};\n\nconst isEntryShape = <TComponent>(\n value: RegistrationInput<TComponent>,\n): value is { component: TComponent; meta?: ComponentMeta } => {\n if (typeof value !== 'object' || value === null) return false;\n return hasOwn(value, 'component');\n};\n\nexport const createComponentRegistry = <TComponent = unknown>(): ComponentRegistry<TComponent> => {\n const entries = new Map<string, ComponentEntry<TComponent>>();\n\n const register = (name: string, component: TComponent, meta?: ComponentMeta): void => {\n const staticMeta = extractStaticMeta(component);\n const merged: ComponentMeta = { ...(staticMeta ?? {}), ...(meta ?? {}) };\n entries.set(name, { component, meta: merged });\n };\n\n const registerAll = (batch: Record<string, RegistrationInput<TComponent>>): void => {\n for (const name of Object.keys(batch)) {\n const input = batch[name];\n if (input === undefined) continue;\n if (isEntryShape<TComponent>(input)) {\n register(name, input.component, input.meta);\n } else {\n register(name, input);\n }\n }\n };\n\n const get = (name: string): ComponentEntry<TComponent> | undefined => entries.get(name);\n\n const has = (name: string): boolean => entries.has(name);\n\n const list = (): string[] => Array.from(entries.keys());\n\n return { register, registerAll, get, has, list };\n};\n","import { z } from 'zod';\nimport { HEAD_LINK_NAME, HEAD_META_NAME, HEAD_NAME, HEAD_SCRIPT_NAME, HEAD_TITLE_NAME } from './head';\nimport type { ComponentMeta } from './types';\n\n// The authoring contracts of a head and the elements it holds (./head): what a\n// layout may set on each. Props are bound and resolved like any other node's.\n//\n// An element's props are its attributes, so these are open records: any\n// attribute HTML gives the element may be written. What each refuses is said\n// in its description, and held by the reader (`headOf`), not by a list here.\n\n// What every element refuses, whatever else it is.\nconst REFUSED_ATTRIBUTES = 'an attribute whose name starts with `on`, or a prop whose name is not an attribute’s name';\n\nconst AttributeSchema = z\n .union([z.string(), z.number(), z.boolean()])\n .describe(\n 'An attribute’s value. Text is written as given, a number as text. `true` writes the attribute with no value. `false`, an empty or blank string, and anything that is none of these (a binding not answered yet, an object, a list) leave the attribute out.',\n );\n\nexport const HeadPropsSchema = z\n .object({})\n .strict()\n .describe(\n 'The document’s <head>. Takes no props. Its children are the elements the head holds — `nova:title`, `nova:meta`, `nova:link`, `nova:script` — placed directly or through loops and conditions; any other component among them is refused and left out, and the rest stand. Draws nothing on the screen. Elements are read in the order written, and where a screen holds several heads, in the order the screen is drawn. A later element takes an earlier one’s place when both are the title, both are a `nova:meta` of the same `name` or `property`, or both are a `nova:link` whose `rel` includes `canonical`. Any other two stand side by side.',\n );\n\nexport const HeadTitlePropsSchema = z\n .object({})\n .strict()\n .describe(\n 'The document’s <title>, inside `nova:head`. Takes no props. Its text is given as its children: a text string, which may hold bindings — not components. A title with no text is left out.',\n );\n\nexport const HeadMetaPropsSchema = z\n .record(z.string(), AttributeSchema)\n .describe(\n `A <meta> element, inside \\`nova:head\\`. Its props are the element’s attributes, written as given: \\`name\\` or \\`property\\` to say what it is, \\`content\\` for its value. Left out while it has no \\`content\\`. A later one with the same \\`name\\` or \\`property\\` takes an earlier one’s place (compared without regard to case; \\`name\\` decides when both are set), and one with neither stands beside the rest. The whole element is refused and left out if it has \\`http-equiv\\`, which instructs the browser rather than describing the document, ${REFUSED_ATTRIBUTES}.`,\n );\n\nexport const HeadLinkPropsSchema = z\n .record(z.string(), AttributeSchema)\n .describe(\n `A <link> element, inside \\`nova:head\\`. Its props are the element’s attributes, written as given: \\`rel\\` to say what the link is, \\`href\\` for its address, and any other the element takes (\\`type\\`, \\`hreflang\\`, \\`sizes\\`, \\`media\\`). Left out while it has no \\`href\\`. A later one whose \\`rel\\` includes \\`canonical\\` takes an earlier canonical’s place; all other links stand side by side. The whole element is refused and left out if its \\`rel\\` includes \\`stylesheet\\`, which styles the page, or it has ${REFUSED_ATTRIBUTES}.`,\n );\n\nexport const HeadScriptPropsSchema = z\n .object({\n type: z\n .string()\n .describe('The kind of data the block holds. Only a JSON type is accepted: `application/json`, or one ending in `+json` such as `application/ld+json`. Any other type, or none, is refused.'),\n data: z\n .unknown()\n .describe('What the block holds: the value itself — an object, a list, a number, text — which is serialised as JSON. Not JSON already written as text. Nothing, `null` or an empty string counts as no data.'),\n })\n .catchall(AttributeSchema)\n .describe(\n `A <script> element that holds data, inside \\`nova:head\\`: \\`type\\`, \\`data\\`, and any other attribute the element takes. Left out while it has no \\`data\\`. Data blocks never take one another’s place. It never runs: the whole element is refused and left out unless its \\`type\\` is a JSON type, and if it has a \\`src\\` or ${REFUSED_ATTRIBUTES}.`,\n );\n\nexport type HeadMetaProps = z.infer<typeof HeadMetaPropsSchema>;\nexport type HeadLinkProps = z.infer<typeof HeadLinkPropsSchema>;\nexport type HeadScriptProps = z.infer<typeof HeadScriptPropsSchema>;\n\nconst described = (schema: z.ZodTypeAny): ComponentMeta => ({ description: schema.description ?? '', propsSchema: schema });\n\n// What to register each name with, for a palette that should offer them.\nexport const HEAD_META: Record<string, ComponentMeta> = {\n [HEAD_NAME]: described(HeadPropsSchema),\n [HEAD_TITLE_NAME]: described(HeadTitlePropsSchema),\n [HEAD_META_NAME]: described(HeadMetaPropsSchema),\n [HEAD_LINK_NAME]: described(HeadLinkPropsSchema),\n [HEAD_SCRIPT_NAME]: described(HeadScriptPropsSchema),\n};\n","import type { ComponentRegistry, ComponentMeta } from '../layout/types';\n\n// ───────────────────────────────────────────────────────────\n// Derive a layout-agent palette from a ComponentRegistry.\n//\n// Reads each component's `meta.description` + `meta.propsSchema` straight off the\n// registry and hands the agent a JSON Schema derived from the same Zod schema the\n// renderer validates against — no drift. Component authors put what the agent\n// needs on the source schema via `.describe()`; fixes go there, not here.\n// ───────────────────────────────────────────────────────────\n\nexport type LayoutPaletteEntry = { name: string; description: string; propsSchema?: object };\n\nexport type PaletteFromRegistryOptions = {\n // Optional allowlist of component names. When omitted, every registered\n // component appears — pass a curated subset to keep the agent's vocabulary\n // tight (e.g. exclude shell slots / nav chrome).\n include?: readonly string[];\n // Prop names to strip from every component's schema. Use it to hide props the\n // agent must not set — e.g. presentational knobs (`bg`, `class`, `pad`) — so the\n // components can only render in their default style.\n omitProps?: readonly string[];\n};\n\n// Drop `omit` keys from a JSON Schema's `properties` (and `required`), so the\n// agent never sees them.\nconst stripProps = (schema: object, omit: readonly string[]): object => {\n const s = schema as { properties?: Record<string, unknown>; required?: string[] };\n if (s.properties === undefined) return schema;\n const properties = { ...s.properties };\n for (const p of omit) delete properties[p];\n const required = s.required?.filter((r) => !omit.includes(r));\n return { ...s, properties, ...(required !== undefined ? { required } : {}) };\n};\n\n// ONE PALETTE ENTRY, from a component's meta — the conversion at the heart of a\n// palette, factored out so a second caller derives an author's props from the\n// SAME Zod schema and the SAME JSON-Schema target, never a fork that drifts.\n// moss's integration contract calls this to answer \"what may I build against\"\n// for a person, which is the same question the layout agent asks of the palette;\n// `omitProps` and binding-awareness stay the caller's concern. A component with\n// no schema yields name + description alone, exactly as a bare registration does.\nexport const paletteEntryOf = (name: string, meta: ComponentMeta, omitProps?: readonly string[]): LayoutPaletteEntry => {\n let propsSchema: object | undefined;\n if (meta.propsSchema !== undefined) {\n // The app's schema converts itself (Standard JSON Schema): it may come from\n // the app's zod copy, and ours would read that copy's metadata through our registry.\n const js = meta.propsSchema['~standard'].jsonSchema.output({ target: 'draft-07' });\n propsSchema = omitProps !== undefined && omitProps.length > 0 ? stripProps(js, omitProps) : js;\n }\n return { name, description: meta.description ?? '', ...(propsSchema === undefined ? {} : { propsSchema }) };\n};\n\nexport const paletteFromRegistry = (\n registry: ComponentRegistry,\n options: PaletteFromRegistryOptions = {},\n): LayoutPaletteEntry[] => {\n const names = options.include ?? registry.list();\n const out: LayoutPaletteEntry[] = [];\n for (const name of names) {\n const entry = registry.get(name);\n if (entry === undefined) continue;\n out.push(paletteEntryOf(name, entry.meta, options.omitProps));\n }\n return out;\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { hasKey, isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const SetByValueSchema = z\n .object({\n set: z.string().describe('Data path to write to, e.g. \"user.name\" or \"items.0.title\".'),\n value: z.unknown().describe('Literal value to write at the path.'),\n })\n .strict()\n .describe('Set a field at a path to a literal value.');\n\nexport type SetByValueMutation = z.infer<typeof SetByValueSchema>;\n\nexport const SetByFromSchema = z\n .object({\n set: z.string().describe('Data path to write to.'),\n from: z.string().describe('Data path (or template path) to read the value from.'),\n })\n .strict()\n .describe('Set a field at a path by copying from another path.');\n\nexport type SetByFromMutation = z.infer<typeof SetByFromSchema>;\n\nexport const setValueOp: MutationOp<SetByValueMutation> = {\n key: 'set',\n schema: SetByValueSchema,\n match: (mutation) => hasKey(mutation, 'set') && hasKey(mutation, 'value'),\n apply: (data, mutation) => {\n const next = setPath(data, mutation.set, mutation.value);\n return isObject(next) ? next : data;\n },\n};\n\nexport const setFromOp: MutationOp<SetByFromMutation> = {\n key: 'set',\n schema: SetByFromSchema,\n match: (mutation) => hasKey(mutation, 'set') && hasKey(mutation, 'from'),\n apply: (data, mutation) => {\n const value = getPath(data, mutation.from);\n const next = setPath(data, mutation.set, value);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const ToggleSchema = z\n .object({\n toggle: z.string().describe('Boolean data path to flip.'),\n })\n .strict()\n .describe('Flip a boolean at the given path.');\n\nexport type ToggleMutation = z.infer<typeof ToggleSchema>;\n\nexport const toggleOp: MutationOp<ToggleMutation> = {\n key: 'toggle',\n schema: ToggleSchema,\n apply: (data, mutation) => {\n const current = getPath(data, mutation.toggle);\n const flipped = !(current === true);\n const next = setPath(data, mutation.toggle, flipped);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const IncrementSchema = z\n .object({\n increment: z.string().describe('Numeric data path to increment.'),\n by: z.number().optional().describe('Amount to increment by; defaults to 1.'),\n })\n .strict()\n .describe('Increment a numeric field.');\n\nexport type IncrementMutation = z.infer<typeof IncrementSchema>;\n\nexport const incrementOp: MutationOp<IncrementMutation> = {\n key: 'increment',\n schema: IncrementSchema,\n apply: (data, mutation) => {\n const current = getPath(data, mutation.increment);\n const base = typeof current === 'number' ? current : 0;\n const by = mutation.by ?? 1;\n const next = setPath(data, mutation.increment, base + by);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const DecrementSchema = z\n .object({\n decrement: z.string().describe('Numeric data path to decrement.'),\n by: z.number().optional().describe('Amount to decrement by; defaults to 1.'),\n })\n .strict()\n .describe('Decrement a numeric field.');\n\nexport type DecrementMutation = z.infer<typeof DecrementSchema>;\n\nexport const decrementOp: MutationOp<DecrementMutation> = {\n key: 'decrement',\n schema: DecrementSchema,\n apply: (data, mutation) => {\n const current = getPath(data, mutation.decrement);\n const base = typeof current === 'number' ? current : 0;\n const by = mutation.by ?? 1;\n const next = setPath(data, mutation.decrement, base - by);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const PushSchema = z\n .object({\n push: z.string().describe('Array data path to append to.'),\n value: z.unknown().optional().describe('Value to append.'),\n })\n .strict()\n .describe('Append a value to an array field.');\n\nexport type PushMutation = z.infer<typeof PushSchema>;\n\nexport const pushOp: MutationOp<PushMutation> = {\n key: 'push',\n schema: PushSchema,\n // Guard against the PushEffect navigation effect whose `push` is an object.\n match: (mutation) => typeof mutation.push === 'string',\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.push);\n // push tolerates missing paths by creating a new array (lax mode only).\n if (current !== undefined && !isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `push: path \"${mutation.push}\" is not an array`,\n { op: 'push', path: mutation.push, reason: 'wrong-type' },\n );\n }\n return data;\n }\n if (current === undefined && ctx.strict) {\n throw new MutationError(\n `push: path \"${mutation.push}\" does not exist`,\n { op: 'push', path: mutation.push, reason: 'missing' },\n );\n }\n const arr = isArray(current) ? current.slice() : [];\n arr.push(mutation.value);\n const next = setPath(data, mutation.push, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const PopSchema = z\n .object({\n pop: z.string().describe('Array data path to remove the last element from.'),\n })\n .strict()\n .describe('Remove the last element from an array field.');\n\nexport type PopMutation = z.infer<typeof PopSchema>;\n\nexport const popOp: MutationOp<PopMutation> = {\n key: 'pop',\n schema: PopSchema,\n // Guard against the PopEffect whose `pop` is the literal `true`.\n match: (mutation) => typeof mutation.pop === 'string',\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.pop);\n if (!isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `pop: path \"${mutation.pop}\" ${current === undefined ? 'does not exist' : 'is not an array'}`,\n { op: 'pop', path: mutation.pop, reason: current === undefined ? 'missing' : 'wrong-type' },\n );\n }\n return data;\n }\n const arr = current.slice();\n arr.pop();\n const next = setPath(data, mutation.pop, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const RemoveAtSchema = z\n .object({\n removeAt: z.string().describe('Array data path to remove an element from.'),\n index: z\n .union([z.number().int(), z.string()])\n .describe('Index to remove. A string is a template (e.g. \"{{@event.payload}}\") resolved before applying.'),\n })\n .strict()\n .describe('Remove an element at a specific index of an array field.');\n\nexport type RemoveAtMutation = z.infer<typeof RemoveAtSchema>;\n\nexport const removeAtOp: MutationOp<RemoveAtMutation> = {\n key: 'removeAt',\n schema: RemoveAtSchema,\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.removeAt);\n if (!isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `removeAt: path \"${mutation.removeAt}\" ${current === undefined ? 'does not exist' : 'is not an array'}`,\n {\n op: 'removeAt',\n path: mutation.removeAt,\n reason: current === undefined ? 'missing' : 'wrong-type',\n },\n );\n }\n return data;\n }\n // Index may be a literal number or a resolved template; coerce and guard.\n const index = Number(mutation.index);\n if (!Number.isInteger(index)) return data;\n const arr = current.slice();\n arr.splice(index, 1);\n const next = setPath(data, mutation.removeAt, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const MoveSchema = z\n .object({\n move: z.string().describe('Array data path to reorder within.'),\n from: z\n .union([z.number().int(), z.string()])\n .describe('Index to move. A string is a template (e.g. \"{{@event.payload}}\") resolved before applying.'),\n to: z\n .union([z.number().int(), z.string()])\n .describe('Destination index. A string is a template resolved before applying.'),\n })\n .strict()\n .describe('Move an array element from one index to another.');\n\nexport type MoveMutation = z.infer<typeof MoveSchema>;\n\nexport const moveOp: MutationOp<MoveMutation> = {\n key: 'move',\n schema: MoveSchema,\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.move);\n if (!isArray(current)) {\n if (ctx.strict) {\n throw new MutationError(\n `move: path \"${mutation.move}\" ${current === undefined ? 'does not exist' : 'is not an array'}`,\n {\n op: 'move',\n path: mutation.move,\n reason: current === undefined ? 'missing' : 'wrong-type',\n },\n );\n }\n return data;\n }\n // from/to may be literal numbers or resolved templates; coerce and guard.\n const from = Number(mutation.from);\n const to = Number(mutation.to);\n if (!Number.isInteger(from) || !Number.isInteger(to)) return data;\n if (from < 0 || from >= current.length) return data;\n const arr = current.slice();\n const [item] = arr.splice(from, 1);\n arr.splice(Math.max(0, Math.min(to, arr.length)), 0, item);\n const next = setPath(data, mutation.move, arr);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { deletePath, getPath, setPath } from '@shared/bindings/paths';\nimport { isArray, isObject } from '@shared/common';\nimport { MutationError } from '@shared/errors';\nimport type { MutationOp } from '../types';\n\nexport const ClearSchema = z\n .object({\n clear: z.string().describe('Array or object data path to clear.'),\n })\n .strict()\n .describe('Clear an array or object field.');\n\nexport type ClearMutation = z.infer<typeof ClearSchema>;\n\nexport const clearOp: MutationOp<ClearMutation> = {\n key: 'clear',\n schema: ClearSchema,\n apply: (data, mutation, ctx) => {\n const current = getPath(data, mutation.clear);\n if (isArray(current)) {\n const next = setPath(data, mutation.clear, []);\n return isObject(next) ? next : data;\n }\n if (isObject(current)) {\n const next = setPath(data, mutation.clear, {});\n return isObject(next) ? next : data;\n }\n if (ctx.strict) {\n throw new MutationError(\n `clear: path \"${mutation.clear}\" ${current === undefined ? 'does not exist' : 'is not an array or object'}`,\n {\n op: 'clear',\n path: mutation.clear,\n reason: current === undefined ? 'missing' : 'wrong-type',\n },\n );\n }\n const next = deletePath(data, mutation.clear);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { getPath, setPath } from '@shared/bindings/paths';\nimport { isObject } from '@shared/common';\nimport type { MutationOp } from '../types';\n\nexport const ResetSchema = z\n .object({\n reset: z.string().describe('Data path to reset to its initial (definition.data) value.'),\n })\n .strict()\n .describe('Reset a field to its initial value from the action definition.');\n\nexport type ResetMutation = z.infer<typeof ResetSchema>;\n\nexport const resetOp: MutationOp<ResetMutation> = {\n key: 'reset',\n schema: ResetSchema,\n apply: (data, mutation, ctx) => {\n const initialValue = getPath(ctx.initial, mutation.reset);\n const next = setPath(data, mutation.reset, initialValue);\n return isObject(next) ? next : data;\n },\n};\n","import { z } from 'zod';\nimport { setValueOp, setFromOp } from './set';\nimport { toggleOp } from './toggle';\nimport { incrementOp } from './increment';\nimport { decrementOp } from './decrement';\nimport { pushOp } from './push';\nimport { popOp } from './pop';\nimport { removeAtOp } from './remove-at';\nimport { moveOp } from './move';\nimport { clearOp } from './clear';\nimport { resetOp } from './reset';\nimport type { MutationOp } from '../types';\n\n// The single source of truth for mutation operations. The validation schema,\n// the `Mutation` type, and the runtime dispatch table (see registry.ts) are\n// all derived from this one list — adding an op is a one-line change here.\nexport const OPS = [\n setValueOp,\n setFromOp,\n toggleOp,\n incrementOp,\n decrementOp,\n pushOp,\n popOp,\n removeAtOp,\n moveOp,\n clearOp,\n resetOp,\n] as const;\n\n// Precise mutation type, distributed from each op's own mutation shape.\ntype MutationOf<O> = O extends MutationOp<infer T> ? T : never;\nexport type Mutation = MutationOf<(typeof OPS)[number]>;\n\n// Runtime validator, derived from the ops: a mutation is any one of their\n// schemas. The cast widens each op's schema to `z.ZodType<Mutation>` (sound —\n// every op's mutation is a Mutation) so the union's output type is `Mutation`.\nexport const MutationSchema = z\n .union(\n OPS.map((op) => op.schema) as [z.ZodType<Mutation>, z.ZodType<Mutation>, ...z.ZodType<Mutation>[]],\n )\n .describe('A single immutable mutation applied to the action data.');\n","import { hasKey, isObject } from '@shared/common';\nimport { OPS, type Mutation } from './ops';\nimport type { MutationContext, MutationData, MutationOp } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Pure dispatch over the op list. Each op is generic over its own\n// mutation shape; `toDispatchOp` collapses that into a uniform handler\n// that runs the op's own schema parse before apply. The single `any` is\n// the deliberate type-erasure boundary where the heterogeneous ops meet\n// one dispatch table — each op's schema/apply stay type-checked at their\n// definition. The table is derived from OPS, so it can't drift from it.\n// ═══════════════════════════════════════════════════════════\n\ntype DispatchOp = {\n key: string;\n match: (mutation: Record<string, unknown>) => boolean;\n run: (data: MutationData, mutation: Record<string, unknown>, ctx: MutationContext) => MutationData;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- erasure boundary\nconst toDispatchOp = (op: MutationOp<any>): DispatchOp => ({\n key: op.key,\n match: op.match ?? ((mutation) => hasKey(mutation, op.key)),\n run: (data, mutation, ctx) => op.apply(data, op.schema.parse(mutation), ctx),\n});\n\nconst DISPATCH: readonly DispatchOp[] = OPS.map(toDispatchOp);\n\nconst findOp = (mutation: Record<string, unknown>): DispatchOp | undefined => {\n for (const op of DISPATCH) {\n if (op.match(mutation)) return op;\n }\n return undefined;\n};\n\nexport type ApplyMutationOptions = {\n /** Snapshot used by `reset`. Must be deep-cloned by the caller. */\n initial?: MutationData;\n /** Strict mode — array ops throw MutationError on missing/wrong-type paths. */\n strict?: boolean;\n};\n\nconst buildCtx = (opts: ApplyMutationOptions): MutationContext => ({\n initial: opts.initial ?? {},\n strict: opts.strict ?? false,\n});\n\nexport const applyMutation = (\n data: MutationData,\n mutation: Mutation,\n opts: ApplyMutationOptions = {},\n): MutationData => {\n if (!isObject(mutation)) return data;\n const op = findOp(mutation);\n if (op === undefined) return data;\n return op.run(data, mutation, buildCtx(opts));\n};\n\nexport const applyMutations = (\n data: MutationData,\n mutations: readonly Mutation[],\n opts: ApplyMutationOptions = {},\n): MutationData => {\n if (mutations.length === 0) return data;\n const ctx = buildCtx(opts);\n let current = data;\n for (const mutation of mutations) {\n if (!isObject(mutation)) continue;\n const op = findOp(mutation);\n if (op === undefined) continue;\n current = op.run(current, mutation, ctx);\n }\n return current;\n};\n","import { z } from 'zod';\n\nconst HttpEndpointSchema = z\n .object({\n url: z.string().describe('Template URL, e.g. \"/api/users/{{$.userId}}\".'),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method.'),\n headers: z.record(z.string(), z.string()).optional().describe('Static request headers.'),\n request: z\n .unknown()\n .optional()\n .describe(\n 'Transform config run by the injected evaluator over the ACTION DATA to build the ' +\n 'request body — EVALUATED ON EVERY CALL, so body values can follow screen state. ' +\n 'Static parts are literal JSON; a dynamic part is an evaluator op over the data root, ' +\n 'e.g. { \"q\": { \"$ref\": \"$.search\" } } makes body field q carry the current $.search each call. ' +\n 'Requires an injected transform.',\n ),\n response: z\n .unknown()\n .optional()\n .describe(\n 'Transform config run by the injected evaluator over the reply as received ' +\n '(`$` is the reply — object, array, or scalar) to produce the value stored at `target`. ' +\n 'Requires an injected transform.',\n ),\n target: z.string().optional().describe('Data path to store the result at on success.'),\n errorTarget: z.string().optional().describe('Data path to store the error at on failure.'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('How long to wait for the reply, in ms, before the call fails to onError. Defaults to the shell default (30000). Set it on an endpoint that is slow by nature — a model call that may take minutes.'),\n })\n .strict()\n .describe('A named HTTP call. `request`/`response` shape the body/reply via the injected transform.');\n\nconst FunctionEndpointSchema = z\n .object({\n fn: z\n .string()\n .describe(\n 'Key of a function registered in `ShellConfig.functions`. The host must ' +\n 'register the name before the action runs.',\n ),\n target: z.string().optional().describe('Data path to store the return value at on success.'),\n errorTarget: z.string().optional().describe('Data path to store the error at on failure.'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('How long to wait for the reply, in ms, before the call fails to onError. Defaults to the shell default (30000). Set it on an endpoint that is slow by nature — a model call that may take minutes.'),\n })\n .strict()\n .describe('A named local function call. Handler is provided via `ShellConfig.functions`.');\n\nexport const EndpointConfigSchema = z\n .union([HttpEndpointSchema, FunctionEndpointSchema])\n .describe('An endpoint — either an HTTP call or a local function.');\n\nexport type EndpointConfig = z.infer<typeof EndpointConfigSchema>;\nexport type HttpEndpointConfig = z.infer<typeof HttpEndpointSchema>;\nexport type FunctionEndpointConfig = z.infer<typeof FunctionEndpointSchema>;\n","import { z } from 'zod';\nimport { MutationSchema } from '../mutations';\nimport type { Mutation } from '../mutations';\n\n// ═══════════════════════════════════════════════════════════\n// Effects + Steps (recursive union of Mutation | Effect)\n// ═══════════════════════════════════════════════════════════\n\nexport type Step = Mutation | Effect;\n\nexport type CallEffect = {\n call: string;\n onSuccess?: Step[];\n onError?: Step[];\n};\n\nexport type EmitEffect = {\n emit: { channel: string; payload?: unknown };\n};\n\nexport type PushEffect = {\n push: { action: string; canvas?: string; input?: Record<string, unknown>; with?: string[] };\n};\n\nexport type PopEffect = { pop: true };\n\nexport type ReplaceEffect = {\n replace: { action: string; canvas?: string; input?: Record<string, unknown>; with?: string[] };\n};\n\n// Pop a canvas down to a given instance (everything above it is popped). The\n// stack-nav breadcrumb fires this with the target crumb's instance id.\nexport type PopToEffect = { popTo: { canvas?: string; instance: string } };\n\n// Reset a canvas to a single root action (clear the whole stack, then push). The\n// screen-level nav (sidebar) fires this so drilling into a record doesn't leave\n// a stale stack beneath the new screen.\nexport type ResetToEffect = {\n resetTo: { action: string; canvas?: string; input?: Record<string, unknown>; with?: string[] };\n};\n\n// Remove ONE instance anywhere in a canvas's stack (not just the top). On a\n// list-mode canvas — where every card is live and visible at once — this is how\n// a card's own close button dismisses itself. `pop` removes the top; this\n// removes a named one.\nexport type RemoveInstanceEffect = { removeInstance: { canvas?: string; instance: string } };\n\n// Sugar for `removeInstance` aimed at the firing instance itself: a card's X\n// says \"close me\" without knowing its own id. The runtime desugars it to\n// `removeInstance` with the instance's real id before it escapes.\nexport type RemoveSelfEffect = { removeSelf: true };\n\n// Make a canvas EQUAL a list read from the action's data — the declarative\n// verb (shell/reconcile.ts) as a step. Every other navigation step moves ONE\n// action; a surface whose actions come from rows (a set of tools, a set of\n// cards) has as many as the rows say, and a fixed list of steps cannot.\n// Missing actions are pushed, ones no longer listed are removed, ones already\n// there stay mounted. A row naming an action this shell does not have (not\n// granted) is skipped, as an ungranted `initial` candidate is.\nexport type ReconcileEffect = {\n reconcile: { to: string; action: string; input?: string; canvas?: string; own?: 'pushed' | 'canvas'; with?: string[] };\n};\nexport type ReloadEffect = { reload: true };\n\nexport type Effect =\n | CallEffect\n | EmitEffect\n | PushEffect\n | PopEffect\n | ReplaceEffect\n | PopToEffect\n | ResetToEffect\n | RemoveInstanceEffect\n | RemoveSelfEffect\n | ReconcileEffect\n | ReloadEffect;\n\nexport const StepSchema: z.ZodType<Step> = z.lazy(() =>\n z.union([MutationSchema, EffectSchema]).describe('A step is either a mutation or an effect.'),\n);\n\nconst CallEffectSchema: z.ZodType<CallEffect> = z.lazy(() =>\n z\n .object({\n call: z.string().describe('Name of the endpoint to invoke.'),\n onSuccess: z.array(StepSchema).optional().describe('Steps to run after a successful response.'),\n onError: z\n .array(StepSchema)\n .optional()\n .describe('Steps to run after an error response (with @error scope available).'),\n })\n .strict()\n .describe('Invoke a named endpoint with optional success/error step branches.'),\n);\n\nconst EmitEffectSchema = z\n .object({\n emit: z\n .object({\n channel: z.string().describe('Channel name to publish on.'),\n payload: z\n .unknown()\n .optional()\n .describe('Payload to publish; templates are resolved against the current data.'),\n })\n .strict()\n .describe('Channel + payload to publish.'),\n })\n .strict()\n .describe('Publish a payload to a message channel.');\n\nconst PushEffectSchema = z\n .object({\n push: z\n .object({\n action: z\n .string()\n .describe('Definition id of the action to push onto a canvas — MUST be an id that actually exists (an unknown id fails at click time, invisible to a mount check).'),\n canvas: z.string().optional().describe('Canvas id to push onto; defaults to the current canvas.'),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Initial input merged into the new action data. Keys must belong to the target action\\'s declared input contract — invented keys are silently useless.'),\n with: z\n .array(z.string())\n .optional()\n .describe('Fragment ids to compose the action with before it is instantiated. Each wraps the action (the action fills its `{ slot }`) and contributes its triggers/data; the action wins on conflict. See ActionFragment.'),\n })\n .strict()\n .describe('Push parameters.'),\n })\n .strict()\n .describe('Push a new action onto a canvas (escapes via onNavigate callback).');\n\nconst PopEffectSchema = z\n .object({\n pop: z.literal(true).describe('Sentinel literal — must be true.'),\n })\n .strict()\n .describe('Pop the current action (escapes via onNavigate callback).');\n\nconst ReplaceEffectSchema = z\n .object({\n replace: z\n .object({\n action: z.string().describe('Definition id of the replacement action.'),\n canvas: z\n .string()\n .optional()\n .describe('Canvas id to replace on; defaults to the current canvas.'),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Initial input merged into the new action data.'),\n with: z\n .array(z.string())\n .optional()\n .describe('Fragment ids to compose the action with before it is instantiated. Each wraps the action (the action fills its `{ slot }`) and contributes its triggers/data; the action wins on conflict. See ActionFragment.'),\n })\n .strict()\n .describe('Replace parameters.'),\n })\n .strict()\n .describe('Replace the current action (escapes via onNavigate callback).');\n\nconst PopToEffectSchema = z\n .object({\n popTo: z\n .object({\n canvas: z.string().optional().describe('Canvas id to pop on; defaults to the current canvas.'),\n instance: z.string().describe('Pop the canvas until this instance id is on top (no-op if absent).'),\n })\n .strict()\n .describe('Pop-to-instance parameters.'),\n })\n .strict()\n .describe('Pop a canvas down to a given instance (escapes via onNavigate callback).');\n\nconst ResetToEffectSchema = z\n .object({\n resetTo: z\n .object({\n action: z.string().describe('Definition id of the new root action.'),\n canvas: z.string().optional().describe('Canvas id to reset; defaults to the current canvas.'),\n input: z.record(z.string(), z.unknown()).optional().describe('Initial input merged into the new root action.'),\n with: z.array(z.string()).optional().describe('Fragment ids to compose the action with. See ActionFragment.'),\n })\n .strict()\n .describe('Reset parameters.'),\n })\n .strict()\n .describe('Clear a canvas and push a single new root action (escapes via onNavigate callback).');\n\nconst RemoveInstanceEffectSchema = z\n .object({\n removeInstance: z\n .object({\n canvas: z.string().optional().describe('Canvas id to remove from; defaults to the current canvas.'),\n instance: z.string().describe('Instance id to unmount and drop from the stack (no-op if absent).'),\n })\n .strict()\n .describe('Remove-instance parameters.'),\n })\n .strict()\n .describe('Remove one instance anywhere in a canvas stack (escapes via onNavigate callback).');\n\nconst RemoveSelfEffectSchema = z\n .object({\n removeSelf: z.literal(true).describe('Sentinel literal — must be true. Removes the firing instance (desugars to removeInstance).'),\n })\n .strict()\n .describe('Close the firing instance — the list-card X (escapes via onNavigate callback).');\n\nconst ReconcileEffectSchema = z\n .object({\n reconcile: z\n .object({\n to: z.string().describe('Binding to the desired list, e.g. \"$.tools\" — an array of rows; anything else is an empty list.'),\n action: z.string().describe('The row field naming the action to place, e.g. \"tool_id\". Rows without it are skipped.'),\n input: z.string().optional().describe('The row field holding that action\\'s input (an object), if any.'),\n canvas: z.string().optional().describe('Canvas id to reconcile; defaults to the current canvas.'),\n own: z\n .enum(['pushed', 'canvas'])\n .optional()\n .describe('What this step may remove: \"pushed\" (default) only what this action placed there; \"canvas\" everything on it — for an action that owns the canvas outright.'),\n with: z.array(z.string()).optional().describe('Fragment ids to compose each placed action with. See ActionFragment.'),\n })\n .strict()\n .describe('Reconcile parameters.'),\n })\n .strict()\n .describe('Make a canvas hold exactly the actions a list names: push the missing, remove the unlisted, keep the rest mounted (escapes via onNavigate callback).');\n\n// Re-run the firing instance's `mount` hook — the action re-reads whatever it\n// reads, in place, keeping its identity and its data.\n//\n// The gap this fills: a stacked canvas suspends what it covers and `resume`\n// already re-runs mount, so a revealed action is never stale. A LIST canvas\n// suspends nothing — every card stays active — so a card that loaded at seed\n// time and is opened an hour later would show the hour-old answer. `reload` is\n// what \"opening it\" means there.\nconst ReloadEffectSchema = z\n .object({\n reload: z.literal(true).describe('Sentinel literal — must be true. Re-runs this instance\\'s mount hook.'),\n })\n .strict()\n .describe('Re-read the firing instance in place — the list-card open.');\n\nexport const EffectSchema: z.ZodType<Effect> = z.lazy(() =>\n z\n .union([CallEffectSchema, EmitEffectSchema, PushEffectSchema, PopEffectSchema, ReplaceEffectSchema, PopToEffectSchema, ResetToEffectSchema, RemoveInstanceEffectSchema, RemoveSelfEffectSchema, ReconcileEffectSchema, ReloadEffectSchema])\n .describe('An effect that touches the outside world.'),\n);\n","import { z } from 'zod';\nimport { StepSchema } from './effects';\n\nexport const LifecycleConfigSchema = z\n .object({\n mount: z.array(StepSchema).optional().describe('Steps to run when the action mounts.'),\n unmount: z.array(StepSchema).optional().describe('Steps to run when the action unmounts.'),\n suspend: z.array(StepSchema).optional().describe('Steps to run when the action is suspended.'),\n resume: z.array(StepSchema).optional().describe('Steps to run when the action resumes.'),\n })\n .strict()\n .describe('Lifecycle hooks for the action runtime state machine.');\n\nexport type LifecycleConfig = z.infer<typeof LifecycleConfigSchema>;\n","import { z } from 'zod';\nimport { StepSchema } from './effects';\n\nexport const TriggerConfigSchema = z\n .object({\n event: z\n .string()\n .optional()\n .describe('UI event type to listen for: \"ui:click\" (activations, incl. table rows), \"ui:model\" (an input\\'s value changed), \"ui:key\".'),\n message: z.string().optional().describe('Message bus channel name to listen on (fired by an `emit` step, possibly from another action).'),\n ref: z\n .string()\n .optional()\n .describe('Component ref to filter events by — MUST match a `ref` carried by a node in this action\\'s layout; a trigger on a ref no layout node carries never fires.'),\n key: z.string().optional().describe('Key to filter \"ui:key\" events by, e.g. \"ArrowDown\".'),\n do: z\n .array(StepSchema)\n .describe('Ordered steps to execute when the trigger fires. Steps may reference the firing event as \"@event\" — \"@event.payload\" is the fired value (a table row click: the row\\'s clickKey/rowKey field; an input\\'s ui:model: the typed text).'),\n })\n .strict()\n .refine((trigger) => trigger.event !== undefined || trigger.message !== undefined, {\n message: 'A trigger must specify either \"event\" or \"message\".',\n })\n .describe('Binds an event or message source to an ordered sequence of steps.');\n\nexport type TriggerConfig = z.infer<typeof TriggerConfigSchema>;\n","import { z } from 'zod';\nimport { LayoutNodeSchema } from '@layout/schemas';\nimport { MutationSchema } from '../mutations';\nimport { EndpointConfigSchema } from './endpoints';\nimport { LifecycleConfigSchema } from './lifecycle';\nimport { TriggerConfigSchema } from './triggers';\n\n// ═══════════════════════════════════════════════════════════\n// Action Definition — composes all sibling schemas.\n// ═══════════════════════════════════════════════════════════\n\nexport const ActionDefinitionSchema = z\n .object({\n id: z.string().describe('Stable definition id.'),\n name: z.string().optional().describe('Human-readable name.'),\n description: z.string().optional().describe('Free-form description.'),\n title: z\n .string()\n .optional()\n .describe(\n \"A resolvable label for this instance, evaluated against its own data (e.g. '{{$.view.record.name}}'). Exposed as `instance.title` on a canvas's actionLayout scope so stack-nav chrome can label crumbs/tabs; falls back to `name` then the action id.\",\n ),\n layout: z\n .union([z.string(), LayoutNodeSchema])\n .optional()\n .describe('Either a layout id stored in the layout store, or an inline LayoutNode.'),\n data: z.record(z.string(), z.unknown()).optional().describe('Static default data merged with input on mount.'),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'JSON Schema of the data keys an opener may seed when loading this action — its public, openable-input contract (author in Zod, convert with z.toJSONSchema). Fields must be a subset of `data`. Descriptive only: the runtime does not validate loads against it.',\n ),\n triggers: z.array(TriggerConfigSchema).optional().describe('Event/message triggers.'),\n endpoints: z\n .record(z.string(), EndpointConfigSchema)\n .optional()\n .describe('Named endpoints — HTTP calls or local functions.'),\n lifecycle: LifecycleConfigSchema.optional().describe('Lifecycle hooks.'),\n })\n .strict()\n .describe('Definition of an action: layout + data + behavior.');\n\nexport type ActionDefinition = z.infer<typeof ActionDefinitionSchema>;\n\n// ═══════════════════════════════════════════════════════════\n// Action Fragment — a reusable PARTIAL action (every field optional) that is\n// MERGED into a concrete action at a push/replace `with`, producing the\n// effective ActionDefinition that gets instantiated. This is composition, not\n// inheritance: `Action + ActionFragment ⇒ Action`. A fragment is abstract — it\n// only exists merged, lives in its own registry, and cannot be pushed as an\n// action on its own. Its `layout` is the chrome that WRAPS the action; a\n// `{ slot: 'body' }` node in it is filled with the composing action's layout.\n// On merge: the action's layout fills the slot; data/endpoints deep-merge with\n// the action winning; triggers and per-hook lifecycle steps concatenate\n// (fragment first). See `composeAction`.\n// ═══════════════════════════════════════════════════════════\n\nexport const ActionFragmentSchema = z\n .object({\n kind: z.literal('fragment').describe('Discriminator — marks this as an abstract, merge-only fragment.'),\n id: z.string().describe('Stable fragment id, referenced from a push/replace `with: [...]`.'),\n name: z.string().optional().describe('Human-readable name.'),\n description: z.string().optional().describe('Free-form description.'),\n layout: z\n .union([z.string(), LayoutNodeSchema])\n .optional()\n .describe('The wrapping (chrome) layout, or a layout id. Put a `{ slot: \"body\" }` node where the composing action\\'s own layout is dropped in.'),\n data: z.record(z.string(), z.unknown()).optional().describe('Partial default data; deep-merged under the action (the action wins on conflict).'),\n triggers: z.array(TriggerConfigSchema).optional().describe('Pre-wired triggers (e.g. a modal\\'s close/cancel). Concatenated before the action\\'s triggers.'),\n endpoints: z\n .record(z.string(), EndpointConfigSchema)\n .optional()\n .describe('Named endpoints, merged under the action (the action wins on a name clash).'),\n lifecycle: LifecycleConfigSchema.optional().describe('Lifecycle hooks; per-hook steps run before the action\\'s.'),\n })\n .strict()\n .describe('A reusable partial action — layout + wired behavior — merged into a concrete action at a push `with`. Abstract: only exists merged, never instantiated alone.');\n\nexport type ActionFragment = z.infer<typeof ActionFragmentSchema>;\n\n// Re-export mutations schema (for backwards-compatible imports within action/)\nexport { MutationSchema };\nexport type { Mutation } from '../mutations';\n\n// Re-export sibling schemas + inferred types\nexport { EffectSchema, StepSchema } from './effects';\nexport type { Effect, Step, CallEffect, EmitEffect, PushEffect, PopEffect, ReplaceEffect, PopToEffect, ResetToEffect, RemoveInstanceEffect, RemoveSelfEffect, ReconcileEffect, ReloadEffect } from './effects';\nexport { TriggerConfigSchema } from './triggers';\nexport type { TriggerConfig } from './triggers';\nexport { EndpointConfigSchema } from './endpoints';\nexport type { EndpointConfig, HttpEndpointConfig, FunctionEndpointConfig } from './endpoints';\nexport { LifecycleConfigSchema } from './lifecycle';\nexport type { LifecycleConfig } from './lifecycle';\n","import { fillSlots } from '@layout';\nimport type { LayoutNode } from '@layout';\nimport type {\n ActionDefinition,\n ActionFragment,\n EndpointConfig,\n Step,\n TriggerConfig,\n} from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// composeAction — merge a concrete action with the fragments listed in a\n// push/replace `with`, producing the effective ActionDefinition to instantiate.\n// Composition, not inheritance: the action ALWAYS wins on conflict.\n//\n// - layout: each fragment WRAPS the layout so far — its `{ slot: 'body' }`\n// is filled with the action's own layout (innermost). Fragments\n// fold in array order, so the last listed is the outermost wrap.\n// (Wrapping fragments must use an inline layout, not a store id.)\n// - data: shallow-merge, action wins.\n// - triggers: concat — fragment triggers first, then the action's.\n// - endpoints: merge, action wins on a name clash.\n// - lifecycle: per-hook concat — fragment steps run before the action's.\n// - id/name/description/title/input: the action's (fragments have no say).\n// The result is a plain ActionDefinition.\n// ═══════════════════════════════════════════════════════════\n\nconst HOOKS = ['mount', 'unmount', 'suspend', 'resume'] as const;\n\nexport const composeAction = (\n action: ActionDefinition,\n fragments: ActionFragment[],\n): ActionDefinition => {\n if (fragments.length === 0) return action;\n\n // Layout — wrap the action's layout in each fragment's slot.\n let layout = action.layout;\n for (const frag of fragments) {\n const wrap = frag.layout;\n if (wrap === undefined) continue;\n if (typeof wrap === 'string') {\n layout = wrap; // stored-layout fragment: can't slot-fill, replaces\n continue;\n }\n layout = fillSlots(wrap, layout === undefined ? {} : { body: layout as LayoutNode });\n }\n\n // Data — fragments (in order), then the action on top.\n const data: Record<string, unknown> = {};\n for (const frag of fragments) Object.assign(data, frag.data ?? {});\n Object.assign(data, action.data ?? {});\n\n // Triggers — fragment triggers first, then the action's.\n const triggers: TriggerConfig[] = [\n ...fragments.flatMap((f) => f.triggers ?? []),\n ...(action.triggers ?? []),\n ];\n\n // Endpoints — fragments, then the action (action wins on a name clash).\n const endpoints: Record<string, EndpointConfig> = {};\n for (const frag of fragments) Object.assign(endpoints, frag.endpoints ?? {});\n Object.assign(endpoints, action.endpoints ?? {});\n\n // Lifecycle — per hook, fragment steps before the action's.\n const lifecycle: Record<string, Step[]> = {};\n for (const hook of HOOKS) {\n const steps: Step[] = [\n ...fragments.flatMap((f) => f.lifecycle?.[hook] ?? []),\n ...(action.lifecycle?.[hook] ?? []),\n ];\n if (steps.length > 0) lifecycle[hook] = steps;\n }\n\n return {\n id: action.id,\n ...(action.name === undefined ? {} : { name: action.name }),\n ...(action.description === undefined ? {} : { description: action.description }),\n ...(action.title === undefined ? {} : { title: action.title }),\n ...(action.input === undefined ? {} : { input: action.input }),\n ...(layout === undefined ? {} : { layout }),\n ...(Object.keys(data).length > 0 ? { data } : {}),\n ...(triggers.length > 0 ? { triggers } : {}),\n ...(Object.keys(endpoints).length > 0 ? { endpoints } : {}),\n ...(Object.keys(lifecycle).length > 0 ? { lifecycle } : {}),\n } as ActionDefinition;\n};\n","// ═══════════════════════════════════════════════════════════\n// Affordance collection — the deterministic half of the action/layout seam.\n//\n// A layout's interactive surface is fully present in its tree: `ref` (event\n// sources), `*Ref` props (component-specific event sources, e.g. a Table's\n// sortRef), `model` (two-way input bindings), and every `$.key` binding it\n// reads. A director agent that wires triggers against a layout it never sees\n// needs that surface as data — so it is DERIVED here by walking the tree,\n// never self-reported by the layout model. A receipt computed from the\n// artifact cannot lie about the artifact.\n// ═══════════════════════════════════════════════════════════\n\nexport type InteractiveRef = {\n ref: string;\n component: string;\n // How the ref is attached: the node's own `ref` field, or a `*Ref` prop name.\n via: string;\n};\n\nexport type InteractiveModel = {\n // The bound data path, e.g. '$.search'.\n path: string;\n component: string;\n};\n\nexport type InteractiveSurface = {\n refs: InteractiveRef[];\n models: InteractiveModel[];\n // Distinct top-level data keys the layout reads anywhere ('$.rows' → 'rows').\n boundKeys: string[];\n // Malformed-looking bindings: `$ident.…` where `ident` is neither the data\n // root (`$.`) nor a loop variable declared by an enclosing `for`/`as` —\n // e.g. `{{$kpi.count}}` (missing dot) renders literally and passes every\n // other check. Collected scope-aware so `{{$row.title}}` inside its loop\n // stays legal.\n suspectBindings: string[];\n componentCount: number;\n};\n\nconst KEY_PATTERN = /\\$\\.([A-Za-z_][A-Za-z0-9_]*)/g;\nconst VAR_PATTERN = /\\$([A-Za-z_][A-Za-z0-9_]*)\\./g;\n\nexport const collectInteractive = (layout: unknown): InteractiveSurface => {\n const refs: InteractiveRef[] = [];\n const models: InteractiveModel[] = [];\n const boundKeys = new Set<string>();\n const suspects = new Set<string>();\n let componentCount = 0;\n\n const scanString = (value: string, scope: ReadonlySet<string>): void => {\n for (const match of value.matchAll(KEY_PATTERN)) {\n const key = match[1];\n if (key !== undefined) boundKeys.add(key);\n }\n for (const match of value.matchAll(VAR_PATTERN)) {\n const name = match[1];\n if (name !== undefined && !scope.has(name)) suspects.add(`$${name}.`);\n }\n };\n\n const walk = (node: unknown, scope: ReadonlySet<string>): void => {\n if (typeof node === 'string') return scanString(node, scope);\n if (Array.isArray(node)) {\n for (const child of node) walk(child, scope);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n const record = node as Record<string, unknown>;\n\n // A `for` directive declares its loop variable for everything beneath.\n const loopVar = record['for'] !== undefined && typeof record['as'] === 'string' ? record['as'] : undefined;\n const childScope = loopVar !== undefined ? new Set([...scope, loopVar]) : scope;\n\n const component = typeof record['component'] === 'string' ? record['component'] : undefined;\n if (component !== undefined) {\n componentCount += 1;\n if (typeof record['ref'] === 'string' && record['ref'].length > 0) {\n refs.push({ ref: record['ref'], component, via: 'ref' });\n }\n if (typeof record['model'] === 'string' && record['model'].length > 0) {\n models.push({ path: record['model'], component });\n }\n const props = record['props'];\n if (props !== null && typeof props === 'object' && !Array.isArray(props)) {\n for (const [key, value] of Object.entries(props as Record<string, unknown>)) {\n if (key.endsWith('Ref') && typeof value === 'string' && value.length > 0) {\n refs.push({ ref: value, component, via: key });\n }\n }\n }\n }\n // Generic descent: directives (`if`/`for`), props, children, column cell\n // specs — every nested node and binding is reached without schema-specific\n // cases. Strings are scanned for `$.key` bindings on the way.\n for (const value of Object.values(record)) walk(value, childScope);\n };\n\n walk(layout, new Set());\n return {\n refs,\n models,\n boundKeys: [...boundKeys].sort(),\n suspectBindings: [...suspects].sort(),\n componentCount,\n };\n};\n","import { OPS } from './mutations/ops';\nimport type { Mutation, Step } from './schemas';\n\n// What a step list WRITES, derived from the op registry.\n//\n// Three places needed this and each kept its own copy of the op names: the\n// runtime (which steps are mutations), the audit (which data paths a definition\n// fills), and anything reflecting over a definition. `OPS` is already the single\n// source of truth for operations, so it is the source of truth here too — adding\n// an op stays a one-line change in ops/index.ts.\n\n// Every mutation op's key. Derived, so it cannot drift from the ops themselves.\nexport const MUTATION_KEYS: readonly string[] = [...new Set(OPS.map((op) => op.key))];\n\n// Each op's own discrimination. `push` and `pop` are the interesting ones: as a\n// string they name a data path (a mutation), as anything else they are the\n// navigation effect.\nconst MATCHERS = OPS.map((op) => op.match ?? ((step: Record<string, unknown>) => op.key in step));\n\nexport const isMutationStep = (step: Step): step is Mutation => MATCHERS.some((match) => match(step as unknown as Record<string, unknown>));\n\n// Every data path a step list writes, at any depth. `call` branches nest their\n// own steps, so one trigger can load and then set.\nexport const mutationPaths = (steps: unknown): string[] => {\n const found: string[] = [];\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n const step = node as Record<string, unknown>;\n if (isMutationStep(step as unknown as Step)) {\n for (const key of MUTATION_KEYS) {\n const value = step[key];\n if (typeof value === 'string') found.push(value);\n }\n }\n walk(step['onSuccess']);\n walk(step['onError']);\n };\n walk(steps);\n return found;\n};\n\n// `openIssue.issue_id` and `openIssue` are one key: both point the card at an\n// issue. Every reading below compares at this level.\nexport const rootOf = (path: string): string => path.split('.')[0] ?? path;\n","import { collectInteractive } from '../agent/affordances';\nimport { MUTATION_KEYS } from './grammar';\nimport type { ActionDefinition } from './schemas';\n\n// ═══════════════════════════════════════════════════════════\n// auditAction — static analysis of an ActionDefinition's internal wiring.\n//\n// A definition can parse, mount, and render politely while being broken in\n// every way that matters: a table bound to a key no endpoint fills, a search\n// box whose trigger re-calls a load that never reads it, a ref with no\n// trigger (dead chrome), a push into an action that doesn't exist. None of\n// that is visible to a schema parse or a mount probe — it IS visible in the\n// artifact. This audits the definition deterministically: every claim is a\n// cross-reference inside the definition (plus an optional catalog), so there\n// are no heuristics and no false authority.\n//\n// Scope: SELF-CONTAINED definitions with an inline layout — generated\n// actions above all. Hand-authored actions that receive triggers from\n// fragments (`with: [...]`) or bind stored layouts will report issues that\n// composition would resolve; audit the COMPOSED definition instead, or skip.\n// ═══════════════════════════════════════════════════════════\n\nexport type AuditCatalogEntry = {\n id: string;\n // The action's openable-input contract (a JSON Schema). When it carries\n // `properties`, seeded push input keys are checked against them.\n input?: Record<string, unknown>;\n};\n\nexport type AuditOptions = {\n // Known pushable action ids. When given, every push/replace/resetTo\n // target must be one of them (or the definition's own id), with input\n // keys from its contract.\n catalog?: ReadonlyArray<AuditCatalogEntry>;\n // Known message channels (derive them from the registered definitions —\n // see collectChannels). When given, a `message:` listen must name a known\n // channel or one this definition emits itself; an `emit` must name a known\n // channel or one this definition listens on. Catches the silent\n // never-fires class (\"tasks:changed\" vs \"tasks-changed\").\n channels?: ReadonlyArray<string>;\n};\n\nexport type AuditResult = { ok: boolean; issues: string[] };\n\n// The channels a definition talks on — every `message:` trigger (listens)\n// and every `emit` step (emits), nested steps included. Walk a whole\n// registry's definitions to derive the app's live channel vocabulary.\nexport type ChannelUsage = { emits: string[]; listens: string[] };\n\nexport const collectChannels = (definition: ActionDefinition): ChannelUsage => {\n const emits = new Set<string>();\n const listens = new Set<string>();\n\n const walkSteps = (list: unknown): void => {\n if (!Array.isArray(list)) return;\n for (const step of list) {\n if (!isRecord(step)) continue;\n const emit = step['emit'];\n if (isRecord(emit) && typeof emit['channel'] === 'string') emits.add(emit['channel']);\n if (typeof step['call'] === 'string') {\n walkSteps(step['onSuccess']);\n walkSteps(step['onError']);\n }\n }\n };\n for (const trigger of definition.triggers ?? []) {\n if (typeof trigger.message === 'string') listens.add(trigger.message);\n walkSteps(trigger.do);\n }\n for (const hook of Object.values(definition.lifecycle ?? {})) walkSteps(hook);\n\n return { emits: [...emits].sort(), listens: [...listens].sort() };\n};\n\n// Mutation ops whose value is a data PATH (see action/mutations/ops). The\nconst firstSegment = (path: string): string => {\n const segment = path.split('.')[0];\n return segment === undefined || segment.length === 0 ? path : segment;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\ntype NavTarget = { action: string; input?: Record<string, unknown> };\n\nconst navTargetOf = (step: Record<string, unknown>): NavTarget | undefined => {\n for (const key of ['push', 'replace', 'resetTo']) {\n const value = step[key];\n if (isRecord(value) && typeof value['action'] === 'string') {\n const input = value['input'];\n return { action: value['action'], ...(isRecord(input) ? { input } : {}) };\n }\n }\n return undefined;\n};\n\nexport const auditAction = (definition: ActionDefinition, options?: AuditOptions): AuditResult => {\n const issues: string[] = [];\n const dataKeys = new Set(Object.keys(definition.data ?? {}));\n const endpointNames = new Set(Object.keys(definition.endpoints ?? {}));\n\n // ── collect every step (structurally — nested onSuccess/onError included),\n // wherever steps live: triggers and lifecycle hooks ──\n const steps: Record<string, unknown>[] = [];\n const pushSteps = (list: unknown): void => {\n if (!Array.isArray(list)) return;\n for (const step of list) {\n if (!isRecord(step)) continue;\n steps.push(step);\n if (typeof step['call'] === 'string') {\n pushSteps(step['onSuccess']);\n pushSteps(step['onError']);\n }\n }\n };\n for (const trigger of definition.triggers ?? []) pushSteps(trigger.do);\n for (const hook of Object.values(definition.lifecycle ?? {})) pushSteps(hook);\n\n // ── steps: calls name real endpoints; mutations write declared keys;\n // navigation targets exist in the catalog with legal input keys ──\n for (const step of steps) {\n const call = step['call'];\n if (typeof call === 'string' && !endpointNames.has(call)) {\n issues.push(`step calls endpoint \"${call}\" but endpoints has no \"${call}\"`);\n }\n\n for (const key of MUTATION_KEYS) {\n const path = step[key];\n if (typeof path === 'string' && path.length > 0 && !dataKeys.has(firstSegment(path))) {\n issues.push(`step \"${key}: ${path}\" writes a key with no default in data`);\n }\n }\n\n const nav = navTargetOf(step);\n if (nav !== undefined && options?.catalog !== undefined) {\n const entry = options.catalog.find((candidate) => candidate.id === nav.action);\n if (entry === undefined && nav.action !== definition.id) {\n issues.push(`step pushes action \"${nav.action}\" which is not in the catalog`);\n continue;\n }\n const properties = entry?.input?.['properties'];\n if (nav.input !== undefined && isRecord(properties)) {\n for (const key of Object.keys(nav.input)) {\n if (!(key in properties)) {\n issues.push(`push to \"${nav.action}\" seeds input key \"${key}\" which is not in its input contract`);\n }\n }\n }\n }\n }\n\n // ── endpoints: targets land on declared keys ──\n for (const [name, endpoint] of Object.entries(definition.endpoints ?? {})) {\n for (const field of ['target', 'errorTarget'] as const) {\n const target = endpoint[field];\n if (typeof target === 'string' && target.length > 0 && !dataKeys.has(firstSegment(target))) {\n issues.push(`endpoint \"${name}\" ${field} \"${target}\" has no default in data`);\n }\n }\n }\n\n // ── message channels (when the app's vocabulary is provided) ──\n if (options?.channels !== undefined) {\n const known = new Set(options.channels);\n const usage = collectChannels(definition);\n for (const channel of usage.listens) {\n if (!known.has(channel) && !usage.emits.includes(channel)) {\n issues.push(`trigger listens on channel \"${channel}\" which nothing is known to emit`);\n }\n }\n for (const channel of usage.emits) {\n if (!known.has(channel) && !usage.listens.includes(channel)) {\n issues.push(`step emits channel \"${channel}\" which nothing is known to listen on`);\n }\n }\n }\n\n // ── layout ↔ data ↔ triggers (inline layouts only) ──\n if (definition.layout !== undefined && typeof definition.layout !== 'string') {\n const surface = collectInteractive(definition.layout);\n\n for (const key of surface.boundKeys) {\n if (!dataKeys.has(key)) {\n issues.push(`layout binds \"$.${key}\" but data has no \"${key}\" default`);\n }\n }\n\n for (const suspect of surface.suspectBindings) {\n issues.push(\n `layout binding \"${suspect}…\" is malformed — the data root is \"$.\" (\"$.key\"), and \"$name.\" is only legal for a loop variable declared by an enclosing for/as`,\n );\n }\n\n const layoutRefs = new Set(surface.refs.map((entry) => entry.ref));\n const triggerRefs = new Set(\n (definition.triggers ?? [])\n .map((trigger) => trigger.ref)\n .filter((ref): ref is string => typeof ref === 'string'),\n );\n for (const ref of layoutRefs) {\n if (!triggerRefs.has(ref)) {\n issues.push(`layout ref \"${ref}\" has no trigger — dead chrome`);\n }\n }\n for (const ref of triggerRefs) {\n if (!layoutRefs.has(ref)) {\n issues.push(`trigger listens on ref \"${ref}\" but no layout node carries it`);\n }\n }\n }\n\n return { ok: issues.length === 0, issues };\n};\n","import { createScopeChain, resolve } from '@shared/bindings';\nimport { hasKey } from '@shared/common';\nimport type { ScopeChain } from '@shared/bindings';\nimport type { EndpointConfig, FunctionEndpointConfig, HttpEndpointConfig } from '../schemas';\nimport type { FetchFn, FetchResponse, FunctionHandler, TransformFn, Unsubscribe } from '../types';\n\nconst stringifyForBody = (value: unknown): string | undefined => {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return undefined;\n }\n};\n\nconst resolveHeaders = (\n headers: Record<string, string> | undefined,\n chain: ScopeChain,\n): Record<string, string> | undefined => {\n if (headers === undefined) return undefined;\n const out: Record<string, string> = {};\n for (const key of Object.keys(headers)) {\n const value = resolve(headers[key], chain);\n out[key] = typeof value === 'string' ? value : String(value ?? '');\n }\n return out;\n};\n\nexport type EndpointResult =\n // `onChange` — the transport's later bodies, already shaped by the endpoint's\n // `response` (see FetchResponse.onChange). Absent for function endpoints and\n // for any transport that answers once.\n | { ok: true; data: unknown; status: number; onChange?: (handler: (data: unknown) => void) => Unsubscribe }\n | { ok: false; error: { status: number; message: string; data: unknown; aborted?: boolean; timedOut?: boolean } };\n\nconst defaultFetch: FetchFn = () => {\n throw new Error('No fetch implementation provided to action runtime');\n};\n\nconst tryParseJson = async (response: {\n json: () => Promise<unknown>;\n text: () => Promise<string>;\n}): Promise<unknown> => {\n try {\n return await response.json();\n } catch {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n }\n};\n\nexport type CallEndpointOptions = {\n endpoint: EndpointConfig;\n data: Record<string, unknown>;\n fetch?: FetchFn;\n transform?: TransformFn;\n signal?: AbortSignal;\n functions?: Record<string, FunctionHandler>;\n // The shell's default wait for the reply; the endpoint's own `timeoutMs` wins.\n timeoutMs?: number;\n};\n\nexport const DEFAULT_ENDPOINT_TIMEOUT_MS = 30_000;\n\n// A CALL THAT NEVER ANSWERS FAILS. A route that hangs used to leave the action\n// loading for as long as it lived — nothing failed, so nothing said so. Past\n// its wait the call fails to `onError` (not as an abort: an abort is the\n// action going away, and is silent), and the transport is told to stop through\n// the signal it was handed. It bounds the FIRST answer only: a reply that\n// keeps answering (a reactive read under moss) follows on after it.\nexport const callEndpoint = async (\n options: CallEndpointOptions,\n): Promise<EndpointResult> => {\n const wait = options.endpoint.timeoutMs ?? options.timeoutMs ?? DEFAULT_ENDPOINT_TIMEOUT_MS;\n const expiry = new AbortController();\n const signal = options.signal === undefined ? expiry.signal : AbortSignal.any([options.signal, expiry.signal]);\n const called = { ...options, signal };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<EndpointResult>((settle) => {\n timer = setTimeout(() => {\n settle({ ok: false, error: { status: 0, message: `no reply within ${wait}ms`, data: undefined, timedOut: true } });\n expiry.abort();\n }, wait);\n });\n try {\n const call = 'fn' in options.endpoint ? callFunctionEndpoint(options.endpoint, called) : callHttpEndpoint(options.endpoint, called);\n return await Promise.race([call, expired]);\n } finally {\n clearTimeout(timer);\n }\n};\n\nconst callHttpEndpoint = async (\n endpoint: HttpEndpointConfig,\n { data, fetch: fetchFn = defaultFetch, transform, signal }: CallEndpointOptions,\n): Promise<EndpointResult> => {\n const chain = createScopeChain(data);\n const resolvedUrl = resolve(endpoint.url, chain);\n const url = typeof resolvedUrl === 'string' ? resolvedUrl : String(resolvedUrl ?? '');\n const headers = resolveHeaders(endpoint.headers, chain);\n\n // `request` builds the body from the action data via the injected evaluator.\n // Declared without one is a hard error (never a silent empty body).\n let body: string | undefined;\n if (endpoint.request !== undefined) {\n if (transform === undefined) {\n return { ok: false, error: { status: 0, message: 'endpoint declares `request` but no transform was injected into the shell', data: undefined } };\n }\n try {\n body = stringifyForBody(transform(endpoint.request, data));\n } catch (err) {\n const message = err instanceof Error ? err.message : 'request transform failed';\n return { ok: false, error: { status: 0, message, data: undefined } };\n }\n }\n\n let response;\n try {\n response = await fetchFn(url, {\n method: endpoint.method,\n ...(headers === undefined ? {} : { headers }),\n ...(body === undefined ? {} : { body }),\n ...(signal === undefined ? {} : { signal }),\n });\n } catch (err) {\n const isAbort = err instanceof Error && err.name === 'AbortError';\n const message = err instanceof Error ? err.message : 'fetch failed';\n if (isAbort) return { ok: false, error: { status: 0, message, data: undefined, aborted: true } };\n return { ok: false, error: { status: 0, message, data: undefined } };\n }\n\n // A REPLY IS JSON. An endpoint's reply lands in `target`, runs through\n // `response`, and is read by a layout — all of it JSON. A success whose body\n // is not JSON (an HTML page, a proxy's text) used to land as whatever the\n // fallback read, and under a transport that cannot read a body twice that\n // was `undefined`: an empty screen that said it had succeeded. It is an\n // error now, and `onError` hears it. No Content is the one success with no\n // body. A FAILED reply stays tolerant — its text is still worth a message.\n if (!response.ok) {\n const failed = await tryParseJson(response);\n const message =\n hasKey(failed, 'message') && typeof failed['message'] === 'string'\n ? failed['message']\n : `HTTP ${response.status}`;\n return { ok: false, error: { status: response.status, message, data: failed } };\n }\n if (response.status === 204 || response.status === 205) {\n return { ok: true, data: undefined, status: response.status };\n }\n let payload: unknown;\n try {\n payload = await response.json();\n } catch {\n return { ok: false, error: { status: response.status, message: `the reply is not JSON (HTTP ${response.status})`, data: undefined } };\n }\n\n // `response` shapes the reply via the injected evaluator — over the reply\n // exactly as received (`$` is the reply: object, array, or scalar; no wrapping).\n // Declared without an evaluator is a hard error (never silently serve the\n // unshaped reply).\n let result: unknown = payload;\n if (endpoint.response !== undefined) {\n if (transform === undefined) {\n return { ok: false, error: { status: response.status, message: 'endpoint declares `response` but no transform was injected into the shell', data: payload } };\n }\n try {\n result = transform(endpoint.response, payload);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'response transform failed';\n return { ok: false, error: { status: response.status, message, data: payload } };\n }\n }\n\n const onChange = laterBodiesOf(response, endpoint.response, transform);\n return { ok: true, data: result, status: response.status, ...(onChange === undefined ? {} : { onChange }) };\n};\n\n// The transport's later bodies, shaped by the same `response` config as the\n// first. A body the transform rejects is dropped — the screen keeps the last\n// good value rather than showing a half-applied one.\nconst laterBodiesOf = (\n response: FetchResponse,\n config: unknown,\n transform: TransformFn | undefined,\n): ((handler: (data: unknown) => void) => Unsubscribe) | undefined => {\n const subscribe = response.onChange;\n if (subscribe === undefined) return undefined;\n if (config !== undefined && transform === undefined) return undefined;\n return (handler) =>\n subscribe((body) => {\n if (config === undefined || transform === undefined) {\n handler(body);\n return;\n }\n let shaped: unknown;\n try {\n shaped = transform(config, body);\n } catch {\n return;\n }\n handler(shaped);\n });\n};\n\nconst callFunctionEndpoint = async (\n endpoint: FunctionEndpointConfig,\n { data, signal, functions }: CallEndpointOptions,\n): Promise<EndpointResult> => {\n // Callers dispatching to a function endpoint must provide both a signal and\n // a registered handler. `runCall` guarantees both before reaching here.\n if (signal === undefined) {\n throw new Error('callEndpoint: function variant requires an AbortSignal');\n }\n const handler = functions?.[endpoint.fn];\n if (handler === undefined) {\n throw new Error(`callEndpoint: function \"${endpoint.fn}\" is not registered`);\n }\n\n try {\n const result = await handler(data, signal);\n if (signal.aborted) {\n return {\n ok: false,\n error: { status: 0, message: 'aborted', data: undefined, aborted: true },\n };\n }\n return { ok: true, data: result, status: 0 };\n } catch (err) {\n const isAbort = err instanceof Error && err.name === 'AbortError';\n const message = err instanceof Error ? err.message : 'function failed';\n if (isAbort) {\n return { ok: false, error: { status: 0, message, data: undefined, aborted: true } };\n }\n return { ok: false, error: { status: 0, message, data: undefined } };\n }\n};\n","// ═══════════════════════════════════════════════════════════\n// THE CAUSE OF A STEP — how far a chain has run from the gesture that started\n// it. Whether a chain of triggers ends cannot be decided from the definitions\n// in general (it can depend on data), but a budget can always be enforced, so\n// every hop a chain takes is counted and a chain past its budget stops.\n//\n// A ROOT is something from outside the action graph: a UI event, a message\n// published by the host, a mount nothing in a chain caused. A HOP is one\n// step of a chain handing off to more steps:\n//\n// · an `emit` reaching a `message` trigger,\n// · a `reload` re-running the mount hook,\n// · a navigation (`push`, `replace`, …) mounting the action it opens.\n//\n// Two limits, because a runaway chain comes in two shapes. A LOOP is deep:\n// `x` emits `x`, one hop after another. A FAN-OUT is wide: a trigger that\n// emits twice doubles every turn, and 64 doublings is more work than any\n// depth limit alone would stop in time. So depth is counted per branch and\n// hops are counted per root, across every branch the root grew.\n//\n// Tide parks a fact whose cause chain runs away (its maxChainDepth); this is\n// the same idea for actions.\n// ═══════════════════════════════════════════════════════════\n\nexport const CAUSE_DEPTH_LIMIT = 64;\nexport const CAUSE_HOPS_LIMIT = 1024;\n\nexport type Cause = {\n // Hops between this step and its root.\n depth: number;\n // Shared by every branch of one root.\n root: { hops: number };\n};\n\n// Every cause minted here, so one read back off the bus (which carries it\n// opaquely — shared code knows nothing of actions) is the same object, root\n// counter and all, and anything else a publisher passed is no cause at all.\nconst minted = new WeakSet<object>();\nconst mint = (cause: Cause): Cause => {\n minted.add(cause);\n return cause;\n};\nconst isMinted = (value: object): value is Cause => minted.has(value);\n\nexport const rootCause = (): Cause => mint({ depth: 0, root: { hops: 0 } });\n\nexport const asCause = (value: unknown): Cause | undefined =>\n typeof value === 'object' && value !== null && isMinted(value) ? value : undefined;\n\n// The cause one hop on from `parent` — a fresh root when there is no parent.\nexport const nextCause = (parent: Cause | undefined): Cause => {\n if (parent === undefined) return rootCause();\n parent.root.hops += 1;\n return mint({ depth: parent.depth + 1, root: parent.root });\n};\n\nexport const isRunaway = (cause: Cause): boolean =>\n cause.depth > CAUSE_DEPTH_LIMIT || cause.root.hops > CAUSE_HOPS_LIMIT;\n\nexport const runawayMessage = (cause: Cause, what: string): string =>\n `${what} stopped: its chain ran ${cause.depth} hops deep and ${cause.root.hops} hops in total from the gesture that started it ` +\n `(limits ${CAUSE_DEPTH_LIMIT} and ${CAUSE_HOPS_LIMIT}). A trigger that re-emits its own channel, or a mount that reloads itself, never ends.`;\n\n// THE CAUSE A NAVIGATION HANDS TO THE MOUNT IT STARTS. Navigation runs\n// synchronously from a step (step → shell → spawn → mount), and the mount\n// reads its cause before its first await, so the cause rides along for\n// exactly that synchronous stretch instead of being threaded through every\n// shell operation. Restored in `finally`, so a throw cannot leak it.\nlet ambient: Cause | undefined;\n\nexport const withCause = <T>(cause: Cause | undefined, run: () => T): T => {\n const before = ambient;\n ambient = cause;\n try {\n return run();\n } finally {\n ambient = before;\n }\n};\n\nexport const ambientCause = (): Cause | undefined => ambient;\n","// ═══════════════════════════════════════════════════════════\n// RUN ON THE NEXT TASK — after the current turn, with the event loop given a\n// chance to run timers and I/O in between (see the `emit` step for why).\n//\n// Not `setTimeout(…, 0)`: that is a timer, and timers are clamped — to ~1ms\n// in node, 4ms once nested in a browser, and up to the ~15ms system tick on\n// Windows — so every hop of an ordinary chain (write → announce → re-read)\n// would pay it. `setImmediate` (node) and a MessageChannel post (browsers)\n// are tasks with no clamp. A shared channel would hold a node process open\n// forever, which is why node takes `setImmediate` first.\n// ═══════════════════════════════════════════════════════════\n\ntype Task = () => void;\n\nconst viaChannel = (): ((task: Task) => void) => {\n const queue: Task[] = [];\n const channel = new MessageChannel();\n channel.port1.onmessage = (): void => {\n queue.shift()?.();\n };\n return (task) => {\n queue.push(task);\n channel.port2.postMessage(null);\n };\n};\n\nconst pick = (): ((task: Task) => void) => {\n // Read off the global rather than named: nova is surface-blind and carries\n // no node types.\n const host: object = globalThis;\n if ('setImmediate' in host && typeof host.setImmediate === 'function') {\n const immediate = host.setImmediate;\n return (task) => void immediate(task);\n }\n if (typeof MessageChannel === 'function') return viaChannel();\n return (task) => void setTimeout(task, 0);\n};\n\nlet scheduler: ((task: Task) => void) | undefined;\n\nexport const nextTask = (task: Task): void => {\n scheduler ??= pick();\n scheduler(task);\n};\n","import { createScopeChain, resolve } from '@shared/bindings';\nimport type { ExtraScopes, ScopeChain } from '@shared/bindings';\nimport type { DataStore } from '@shared/data-store';\nimport type { EventBus } from '@shared/event-bus';\nimport { isObject } from '@shared/common';\nimport type { MessageBus } from '@shared/message-bus';\nimport { setPath } from '@shared/bindings/paths';\nimport { applyMutations } from '../mutations';\nimport { isMutationStep } from '../grammar';\nimport type { EndpointConfig, Mutation, ReconcileEffect, Step } from '../schemas';\nimport { LifecycleError, UnknownFunctionError, type LifecycleHook, type NovaError } from '@shared/errors';\nimport type {\n EndpointEventInit,\n FetchFn,\n FunctionHandler,\n NavigateHandler,\n NavigationEffect,\n OnErrorHandler,\n TransformFn,\n Unsubscribe,\n} from '../types';\nimport { callEndpoint } from './endpoints';\nimport { withCause, type Cause } from './cause';\nimport { nextTask } from './next-task';\n\n// Wall-clock for endpoint durations. `performance` is present in node, the\n// browser, and jsdom; `Date.now` is the universal fallback.\nconst now = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();\n\n// THE CALLS AN INSTANCE HAS MADE, per endpoint name — held by the runtime,\n// which outlives every step context it builds. Two jobs, one ledger:\n//\n// · A response that lands after a NEWER call to the same endpoint already\n// landed is stale: it must not overwrite what the newer one wrote. (Before\n// this, the slower of two searches won — whichever answered last.)\n// · A response that can change later (`onChange`) is followed until a newer\n// call lands or the instance unmounts — never two at once, or an old\n// search's updates would keep writing over the new one's rows.\n//\n// Absent in a bare step context (a test driving `executeSteps` directly):\n// every response then lands as before and none is followed.\nexport type EndpointCalls = {\n // A ticket for a call that is about to start.\n begin: (endpoint: string) => number;\n // Record that this call's response landed. False when a newer call to the\n // same endpoint landed first — the caller must then leave `target` alone.\n land: (endpoint: string, ticket: number) => boolean;\n // Follow this call's later bodies, replacing whatever the endpoint followed.\n follow: (endpoint: string, ticket: number, stop: Unsubscribe) => void;\n};\n\nexport type StepContext = {\n dataStore: DataStore;\n endpoints: Record<string, EndpointConfig>;\n functions: Record<string, FunctionHandler>;\n // The shell's default wait for a reply; an endpoint's `timeoutMs` wins.\n endpointTimeoutMs?: number;\n eventBus: EventBus;\n messageBus: MessageBus;\n fetch?: FetchFn;\n transform?: TransformFn;\n onNavigate?: NavigateHandler;\n // Re-runs this instance's `mount` hook (the `reload` effect), one hop on\n // from `cause`. Supplied by the runtime, which owns the definition and its\n // lifecycle.\n onReload?: (cause: Cause | undefined) => Promise<void>;\n // How far this chain has run from the gesture that started it (./cause.ts).\n // Absent in a bare step context: the steps are then a root.\n cause?: Cause;\n // Reports a completed `call` step upward (the runtime stamps instance/canvas\n // and forwards to telemetry). Aborted calls are not reported.\n onEndpoint?: (event: EndpointEventInit) => void;\n calls?: EndpointCalls;\n extras: ExtraScopes;\n // The action's data as it was built at spawn — what `reset` restores a path\n // to. Absent in a bare step context: there is then nothing to restore from.\n initial?: Record<string, unknown>;\n strict: boolean;\n onError: OnErrorHandler;\n signal: AbortSignal;\n // True when the owning action is suspended (backgrounded under a stack). Event\n // triggers no-op while suspended — only the active action reacts.\n suspended?: boolean;\n // When set, this step execution is running inside a lifecycle hook.\n // In strict mode, hard failures (unknown endpoint, fetch error without\n // a handler) propagate as LifecycleError instead of being swallowed.\n lifecycleHook?: LifecycleHook;\n};\n\nexport const noopOnError: OnErrorHandler = (_error: NovaError): void => {\n // default no-op; users install their own via config\n};\n\n// Template surfaces that get pre-resolved so the mutation subsystem stays\n// scope-unaware (ops receive already-literal values): `set`/`push` carry a\n// user value (e.g. `{{@error.message}}`); `removeAt`/`move` carry indices\n// that can reference the firing event (e.g. `{{@event.payload}}`). A string\n// index is resolved and coerced to a number; everything else passes through.\nconst resolveMutationValues = (\n list: Mutation[],\n chain: ScopeChain,\n extras: ExtraScopes,\n): Mutation[] => {\n return list.map((m) => {\n if ('set' in m && 'value' in m) {\n return { ...m, value: resolve(m.value, chain, extras) };\n }\n if ('push' in m && typeof m.push === 'string' && 'value' in m) {\n return { ...m, value: resolve(m.value, chain, extras) };\n }\n if ('removeAt' in m && typeof m.index === 'string') {\n return { ...m, index: Number(resolve(m.index, chain, extras)) };\n }\n if ('move' in m) {\n return {\n ...m,\n from: typeof m.from === 'string' ? Number(resolve(m.from, chain, extras)) : m.from,\n to: typeof m.to === 'string' ? Number(resolve(m.to, chain, extras)) : m.to,\n };\n }\n return m;\n });\n};\n\n\nconst writeTarget = (\n dataStore: DataStore,\n target: string | undefined,\n value: unknown,\n): void => {\n if (target === undefined) return;\n dataStore.update((curr) => {\n const next = setPath(curr, target, value);\n return isObject(next) ? next : curr;\n });\n};\n\n// Shared fallback for \"target name not resolvable\" cases (unknown endpoint,\n// unknown function). Runs `onError` with a synthetic @error, else throws a\n// LifecycleError inside a lifecycle hook, else throws the caller-supplied\n// strict error, else silently returns.\nconst raiseUnknown = async (\n message: string,\n onError: Step[] | undefined,\n ctx: StepContext,\n strictError?: NovaError,\n): Promise<void> => {\n if (onError) {\n const errorExtras: ExtraScopes = {\n ...ctx.extras,\n '@error': { message, status: 0 },\n };\n await executeSteps(onError, { ...ctx, extras: errorExtras });\n return;\n }\n if (ctx.lifecycleHook !== undefined) {\n throw new LifecycleError(message, { hook: ctx.lifecycleHook });\n }\n if (ctx.strict && strictError !== undefined) throw strictError;\n};\n\nconst runCall = async (\n callName: string,\n onSuccess: Step[] | undefined,\n onError: Step[] | undefined,\n ctx: StepContext,\n): Promise<void> => {\n const raw = ctx.endpoints[callName];\n if (raw === undefined) {\n await raiseUnknown(`unknown endpoint: ${callName}`, onError, ctx);\n return;\n }\n // Resolve a function endpoint's `fn` through the data scope before dispatch, so\n // `fn: '{{$.saveFn}}'` lets one action pick its handler from data — the same way\n // push/replace already resolve their `action` target (see resolveNavTarget).\n // Literal fn names (no template) pass through resolve() unchanged.\n let endpoint = raw;\n if ('fn' in raw) {\n const chain = createScopeChain(ctx.dataStore.get());\n const fn = String(resolve(raw.fn, chain, ctx.extras) ?? '');\n endpoint = { ...raw, fn };\n if (ctx.functions[fn] === undefined) {\n await raiseUnknown(`unknown function: ${fn}`, onError, ctx, new UnknownFunctionError(fn));\n return;\n }\n }\n const ticket = ctx.calls?.begin(callName);\n const t0 = now();\n const result = await callEndpoint({\n endpoint,\n data: ctx.dataStore.get(),\n fetch: ctx.fetch,\n transform: ctx.transform,\n signal: ctx.signal,\n functions: ctx.functions,\n ...(ctx.endpointTimeoutMs === undefined ? {} : { timeoutMs: ctx.endpointTimeoutMs }),\n });\n if (ctx.signal.aborted) return;\n if (!result.ok && result.error.aborted === true) return;\n // Telemetry: the call completed (ok or error, not aborted) — report it. The\n // endpoint's kind is structural: `fn` in the config means an in-process\n // function endpoint, otherwise an HTTP one.\n ctx.onEndpoint?.({\n name: callName,\n kind: 'fn' in endpoint ? 'fn' : 'http',\n ok: result.ok,\n status: result.ok ? result.status : result.error.status,\n ms: now() - t0,\n });\n if (result.ok) {\n const isCurrent = ticket === undefined || ctx.calls === undefined || ctx.calls.land(callName, ticket);\n if (isCurrent) {\n writeTarget(ctx.dataStore, endpoint.target, result.data);\n const { dataStore } = ctx;\n const { target } = endpoint;\n if (result.onChange !== undefined && ticket !== undefined && ctx.calls !== undefined) {\n ctx.calls.follow(callName, ticket, result.onChange((data) => writeTarget(dataStore, target, data)));\n }\n }\n if (onSuccess) await executeSteps(onSuccess, ctx);\n return;\n }\n writeTarget(ctx.dataStore, endpoint.errorTarget, result.error);\n if (onError) {\n const errorExtras: ExtraScopes = { ...ctx.extras, '@error': result.error };\n await executeSteps(onError, { ...ctx, extras: errorExtras });\n return;\n }\n if (ctx.lifecycleHook !== undefined) {\n throw new LifecycleError(`endpoint '${callName}' failed: ${result.error.message}`, {\n hook: ctx.lifecycleHook,\n });\n }\n};\n\n// The mount a navigation starts is one hop further down this chain: the shell\n// spawns and mounts synchronously, and the mount reads the cause from here.\nconst navigate = (effect: NavigationEffect, ctx: StepContext): void => {\n const { onNavigate } = ctx;\n if (onNavigate === undefined) return;\n withCause(ctx.cause, () => onNavigate(effect));\n};\n\n// Resolve a push/replace effect's `input` against the firing scope (current\n// data + `@event`), so a trigger can pass dynamic data to the action it opens\n// — e.g. `input: { record: '@event.payload' }`. Mirrors how `emit.payload` is\n// resolved; without it, input values reach the new action as raw templates.\nconst resolveInputMap = (\n input: Record<string, unknown>,\n ctx: StepContext,\n): Record<string, unknown> => {\n const chain = createScopeChain(ctx.dataStore.get());\n return Object.fromEntries(\n Object.entries(input).map(([key, value]) => [key, resolve(value, chain, ctx.extras)]),\n );\n};\n\n// Resolve a push/replace target: its `action` (so a trigger can open the action\n// a binding names — e.g. `action: '{{@event.payload}}'` to launch the clicked\n// result; literal ids pass through unchanged) and its `input` map.\nconst resolveNavTarget = <T extends { action: string; input?: Record<string, unknown> }>(\n nav: T,\n ctx: StepContext,\n): T => {\n const chain = createScopeChain(ctx.dataStore.get());\n const out: T = { ...nav, action: String(resolve(nav.action, chain, ctx.extras) ?? '') };\n if (nav.input !== undefined) out.input = resolveInputMap(nav.input, ctx);\n return out;\n};\n\nconst resolveNavInput = (effect: NavigationEffect, ctx: StepContext): NavigationEffect => {\n if ('push' in effect) return { push: resolveNavTarget(effect.push, ctx) };\n if ('replace' in effect) return { replace: resolveNavTarget(effect.replace, ctx) };\n if ('resetTo' in effect) return { resetTo: resolveNavTarget(effect.resetTo, ctx) };\n if ('popTo' in effect) {\n const chain = createScopeChain(ctx.dataStore.get());\n return { popTo: { ...effect.popTo, instance: String(resolve(effect.popTo.instance, chain, ctx.extras) ?? '') } };\n }\n if ('removeInstance' in effect) {\n const chain = createScopeChain(ctx.dataStore.get());\n return { removeInstance: { ...effect.removeInstance, instance: String(resolve(effect.removeInstance.instance, chain, ctx.extras) ?? '') } };\n }\n return effect;\n};\n\n// Resolve a `reconcile` step: read its list and turn each row into the action it\n// names (and that action's input, when the step names a field for it). A value\n// that is not a list is an empty one — the canvas empties, which is what an\n// empty list means.\nconst resolveReconcile = (step: ReconcileEffect, ctx: StepContext): NavigationEffect => {\n const { to, action, input, ...rest } = step.reconcile;\n const rows = resolve(to, createScopeChain(ctx.dataStore.get()), ctx.extras);\n const desired = (Array.isArray(rows) ? rows : []).flatMap((row: unknown) => {\n if (!isObject(row)) return [];\n const actionId = row[action];\n if (typeof actionId !== 'string' || actionId === '') return [];\n const seeded = input === undefined ? undefined : row[input];\n return [isObject(seeded) ? { actionId, input: seeded } : { actionId }];\n });\n return { reconcile: { ...rest, desired } };\n};\n\nexport const executeSteps = async (steps: Step[], ctx: StepContext): Promise<void> => {\n let buffer: Mutation[] = [];\n\n const flush = (): void => {\n if (buffer.length === 0) return;\n const list = buffer;\n buffer = [];\n // Resolve templates against the state at flush entry, matching\n // how `emit` captures data before publishing. The `@error` (and\n // any other) scope lives in ctx.extras.\n const chain = createScopeChain(ctx.dataStore.get());\n const resolved = resolveMutationValues(list, chain, ctx.extras);\n ctx.dataStore.update((curr) =>\n applyMutations(curr, resolved, { ...(ctx.initial === undefined ? {} : { initial: ctx.initial }), strict: ctx.strict }),\n );\n };\n\n for (const step of steps) {\n if (ctx.signal.aborted) {\n buffer = [];\n return;\n }\n if (isMutationStep(step)) {\n buffer.push(step);\n continue;\n }\n flush();\n\n if ('call' in step) {\n await runCall(step.call, step.onSuccess, step.onError, ctx);\n if (ctx.signal.aborted) return;\n continue;\n }\n if ('emit' in step) {\n const data = ctx.dataStore.get();\n const chain = createScopeChain(data);\n const resolvedChannel = resolve(step.emit.channel, chain, ctx.extras);\n const channel =\n typeof resolvedChannel === 'string' ? resolvedChannel : String(resolvedChannel ?? '');\n const payload =\n step.emit.payload === undefined\n ? undefined\n : resolve(step.emit.payload, chain, ctx.extras);\n // PUBLISHED AFTER THE TURN SETTLES, not inside it. The confirm pattern\n // emits then pops: the listener is the action UNDERNEATH, suspended\n // while the confirm sits over it, and a suspended action reacts to\n // nothing. Publishing synchronously delivers to it before the pop\n // reveals it — the message is lost. Deferring lets the same turn's pop\n // resume the listener (its status flips active synchronously) so the\n // message lands on a live subscriber. Resolved values are captured\n // above, so a later data change cannot alter what was announced.\n //\n // A TASK, NOT A MICROTASK. A listener that emits again queues another\n // delivery, and a chain of microtasks never lets the event loop turn:\n // under a server hosting many shells, one action whose trigger re-emits\n // its own channel froze every other principal's shell, the socket and\n // HTTP with it. A task (./next-task.ts) yields between hops, so a chain costs its own\n // shell time and nobody else's; ./cause.ts is what ends it.\n const { messageBus, cause } = ctx;\n nextTask(() => messageBus.publish(channel, payload, cause));\n continue;\n }\n if ('push' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('pop' in step) {\n navigate(step, ctx);\n continue;\n }\n if ('replace' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('popTo' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('resetTo' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('removeInstance' in step) {\n navigate(resolveNavInput(step, ctx), ctx);\n continue;\n }\n if ('reconcile' in step) {\n navigate(resolveReconcile(step, ctx), ctx);\n continue;\n }\n if ('removeSelf' in step) {\n // The runtime desugars this to removeInstance with its own id — the step\n // carries no id to resolve.\n navigate(step, ctx);\n continue;\n }\n if ('reload' in step) {\n // Re-read in place. The runtime supplies the handler (it owns the\n // definition and the lifecycle); an action with no mount hook reloads to\n // nothing, which is correct rather than an error.\n await ctx.onReload?.(ctx.cause);\n if (ctx.signal.aborted) return;\n continue;\n }\n }\n\n flush();\n};\n","import { LifecycleError, type LifecycleHook } from '@shared/errors';\nimport type { ActionDefinition } from '../schemas';\nimport { executeSteps, type StepContext } from './steps';\n\nexport const buildInitialData = (\n definition: ActionDefinition,\n input: Record<string, unknown> | undefined,\n): Record<string, unknown> => {\n const defaults = definition.data ?? {};\n // Deep-clone so the runtime owns an isolated data tree: neither\n // `definition.data` nor the caller's `input` can be mutated by later in-place\n // mutations. Initial data is NOT transformed — the injected `transform` is\n // endpoint-only (request/response), never applied to the data on mount.\n return structuredClone({ ...defaults, ...(input ?? {}) });\n};\n\nexport const runLifecycleHook = async (\n hook: LifecycleHook,\n definition: ActionDefinition,\n buildContext: () => StepContext,\n): Promise<void> => {\n const lifecycle = definition.lifecycle;\n if (lifecycle === undefined) return;\n const steps = lifecycle[hook];\n if (steps === undefined || steps.length === 0) return;\n const ctx: StepContext = { ...buildContext(), lifecycleHook: hook };\n try {\n await executeSteps(steps, ctx);\n } catch (err) {\n if (!ctx.strict) {\n ctx.onError(\n err instanceof LifecycleError\n ? err\n : new LifecycleError(\n err instanceof Error ? err.message : String(err),\n { hook },\n { cause: err },\n ),\n );\n return;\n }\n if (err instanceof LifecycleError) throw err;\n throw new LifecycleError(\n err instanceof Error ? err.message : String(err),\n { hook },\n { cause: err },\n );\n }\n};\n","import type { RenderNode } from '@layout/types';\n\n// ═══════════════════════════════════════════════════════════\n// Walk a RenderNode[] tree and collect every model binding.\n// Used by the action runtime to install listeners on the event bus\n// that write `ui:model` payloads back into the data store.\n// ═══════════════════════════════════════════════════════════\n\nexport type ModelBinding = {\n ref: string;\n path: string;\n};\n\nconst walk = (node: RenderNode, out: ModelBinding[]): void => {\n if (node.type === 'component') {\n if (node.model !== undefined) {\n out.push({ ref: node.model.ref, path: node.model.path });\n }\n for (const child of node.children) walk(child, out);\n return;\n }\n if (node.type === 'fragment') {\n for (const child of node.children) walk(child, out);\n }\n};\n\nexport const collectModelBindings = (nodes: RenderNode[]): ModelBinding[] => {\n const out: ModelBinding[] = [];\n for (const node of nodes) walk(node, out);\n return out;\n};\n","import { renderLayoutFromStore } from '@layout/renderer';\nimport type { LayoutNode } from '@layout/schemas';\nimport type {\n ComponentRegistry,\n DataStoreView,\n LayoutStore,\n RenderContext,\n RenderNode,\n RenderOnError,\n} from '@layout/types';\nimport { isArray, isObject } from '@shared/common';\nimport type { ActionDefinition } from '../schemas';\n\nexport type RenderRuntimeContext = {\n store: LayoutStore;\n registry: ComponentRegistry;\n strict?: boolean;\n onError?: RenderOnError;\n // Passed straight through to the renderer, which is where a language enters.\n phrases?: RenderContext['phrases'];\n phraseKeys?: RenderContext['phraseKeys'];\n onPhraseMiss?: RenderContext['onPhraseMiss'];\n};\n\nconst isLayoutNode = (value: unknown): value is LayoutNode => {\n if (value === null) return true;\n const t = typeof value;\n if (t === 'string' || t === 'number' || t === 'boolean') return true;\n if (isArray(value)) return true;\n if (isObject(value)) return true;\n return false;\n};\n\nexport const renderRuntime = (\n definition: ActionDefinition,\n dataStore: DataStoreView,\n ctx: RenderRuntimeContext,\n): RenderNode[] => {\n const layout = definition.layout;\n if (layout === undefined) return [];\n if (typeof layout === 'string') {\n const target = ctx.store.get(layout);\n if (target === undefined) return [];\n return renderLayoutFromStore(target, dataStore, ctx);\n }\n if (!isLayoutNode(layout)) return [];\n return renderLayoutFromStore(layout, dataStore, ctx);\n};\n","import type { EventBus } from '@shared/event-bus';\nimport { hasKey } from '@shared/common';\nimport { ErrorCodes, NovaError } from '@shared/errors';\nimport type { MessageBus } from '@shared/message-bus';\nimport type { Unsubscribe } from '@shared/common';\nimport type { TriggerConfig } from '../schemas';\nimport { executeSteps, type StepContext } from './steps';\nimport { asCause, isRunaway, nextCause, rootCause, runawayMessage, type Cause } from './cause';\n\n// ═══════════════════════════════════════════════════════════\n// Trigger subscriptions for an action.\n//\n// Event triggers subscribe to the event bus on the declared `type`\n// (e.g. \"ui:click\"). If a `ref` is set, only events whose `ref` field\n// matches fire.\n//\n// Message triggers subscribe to the message bus by channel — no\n// `msg:` prefixing, no bridging through the event bus.\n//\n// Trigger step failures flow to the context's onError hook instead of\n// being silently dropped. If the runtime has been aborted (e.g. mid-\n// unmount), late-arriving events are dropped.\n// ═══════════════════════════════════════════════════════════\n\nexport type TriggerHandle = {\n detach: () => void;\n};\n\nconst eventRef = (event: unknown): string | undefined => {\n if (!hasKey(event, 'ref')) return undefined;\n const candidate = event['ref'];\n return typeof candidate === 'string' ? candidate : undefined;\n};\n\nconst eventKey = (event: unknown): string | undefined => {\n if (!hasKey(event, 'key')) return undefined;\n const candidate = event['key'];\n return typeof candidate === 'string' ? candidate : undefined;\n};\n\nconst toNovaError = (err: unknown): NovaError => {\n if (err instanceof NovaError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new NovaError(ErrorCodes.lifecycle, message, {}, { cause: err });\n};\n\nconst fireTrigger = (\n trigger: TriggerConfig,\n buildContext: () => StepContext,\n event: unknown,\n cause: Cause,\n): void => {\n const built = buildContext();\n if (built.signal.aborted) return;\n // A suspended action (backgrounded under a stack) reacts to nothing — only the\n // active top of a canvas handles events/messages.\n if (built.suspended === true) return;\n // A chain past its budget stops here, and says so (./cause.ts).\n if (isRunaway(cause)) {\n const what = trigger.message === undefined ? 'A trigger' : `The trigger on \"${trigger.message}\"`;\n built.onError(new NovaError(ErrorCodes.runaway, runawayMessage(cause, what), { channel: trigger.message, depth: cause.depth, hops: cause.root.hops }));\n return;\n }\n const base: StepContext = { ...built, cause };\n // Expose the firing event to the trigger's steps as `@event`, mirroring\n // how `@error` is injected on failed calls — so a step can reference\n // `{{@event.payload}}` (e.g. the clicked list index).\n const ctx: StepContext =\n event === undefined ? base : { ...base, extras: { ...base.extras, '@event': event } };\n void executeSteps(trigger.do, ctx).catch((err: unknown) => {\n ctx.onError(toNovaError(err));\n });\n};\n\nconst eventOrigin = (event: unknown): string | undefined => {\n if (!hasKey(event, 'origin')) return undefined;\n const candidate = event['origin'];\n return typeof candidate === 'string' ? candidate : undefined;\n};\n\nexport const attachTriggers = (\n triggers: TriggerConfig[],\n eventBus: EventBus,\n messageBus: MessageBus,\n buildContext: () => StepContext,\n ownInstanceId: string,\n): TriggerHandle => {\n const unsubscribes: Unsubscribe[] = [];\n\n for (const trigger of triggers) {\n if (trigger.event !== undefined) {\n const expectedRef = trigger.ref;\n const expectedKey = trigger.key;\n const triggerType: string = trigger.event;\n const off = eventBus.on(triggerType, (event) => {\n // A UI event stamped with an origin is delivered to that instance only;\n // events with no origin (programmatic `shell.dispatch`) stay global.\n const origin = eventOrigin(event);\n if (origin !== undefined && origin !== ownInstanceId) return;\n if (expectedRef !== undefined && eventRef(event) !== expectedRef) return;\n if (expectedKey !== undefined && eventKey(event) !== expectedKey) return;\n // A gesture starts a chain.\n fireTrigger(trigger, buildContext, event, rootCause());\n });\n unsubscribes.push(off);\n continue;\n }\n if (trigger.message !== undefined) {\n // A MESSAGE CARRIES ITS PAYLOAD THE SAME WAY A UI EVENT DOES. `emit`\n // takes one, steps resolve it, and the bus delivers it — so dropping it\n // here made `{ emit: { channel, payload } }` a declaration with no\n // reader, and an announcement that could only ever say \"something\n // happened\". Wrapped as `{ payload }` so a listener writes\n // `@event.payload` whether it was woken by a click or by an\n // announcement; `@event` is the firing thing in both cases.\n // One hop on from whatever emitted it; a host's publish carries no\n // cause and starts a chain of its own.\n const off = messageBus.subscribe(trigger.message, (payload: unknown, _from?: string, cause?: unknown) => {\n fireTrigger(trigger, buildContext, { payload }, nextCause(asCause(cause)));\n });\n unsubscribes.push(off);\n }\n }\n\n const detach = (): void => {\n for (const off of unsubscribes) off();\n };\n\n return { detach };\n};\n","import { z } from 'zod';\nimport { createDataStore } from '@shared/data-store';\nimport type { DataStore } from '@shared/data-store';\nimport { createIdFactory } from '@shared/ids';\nimport { DefinitionValidationError, ErrorCodes, NovaError } from '@shared/errors';\nimport type { RenderNode } from '@layout/types';\nimport type { Mutation, Step } from '../schemas';\nimport { StepSchema } from '../schemas';\nimport type {\n ActionInstance,\n ActionRuntime,\n ActionRuntimeConfig,\n ActionStatus,\n DataChangeHandler,\n NavigationEffect,\n OnErrorHandler,\n StatusChangeHandler,\n Unsubscribe,\n} from '../types';\nimport { applyMutations } from '../mutations';\nimport { buildInitialData, runLifecycleHook } from './lifecycle';\nimport { collectModelBindings } from './model-bindings';\nimport { renderRuntime } from './render';\nimport { executeSteps, noopOnError, type EndpointCalls, type StepContext } from './steps';\nimport { attachTriggers, type TriggerHandle } from './triggers';\nimport { ambientCause, isRunaway, nextCause, runawayMessage, type Cause } from './cause';\n\nconst defaultInstanceIdFactory = createIdFactory('act');\n\nexport const createActionRuntime = (config: ActionRuntimeConfig): ActionRuntime => {\n const definition = config.definition;\n const initialData = buildInitialData(definition, config.input);\n // Deep-clone so `reset` can restore nested structures without sharing\n // references with the live data store. Fixes correctness bug where\n // mutating nested objects would corrupt the snapshot used by reset.\n const initialSnapshot: Record<string, unknown> = structuredClone(initialData);\n const dataStore: DataStore = createDataStore(initialData);\n\n const abortController = new AbortController();\n const strict = config.strict ?? false;\n const onError: OnErrorHandler = config.onError ?? noopOnError;\n const instanceIdFn = config.instanceIdFn ?? defaultInstanceIdFactory;\n\n const instance: ActionInstance = {\n id: config.instanceId ?? instanceIdFn(),\n definitionId: definition.id,\n canvasId: config.canvasId ?? 'default',\n status: 'initializing',\n data: dataStore.get(),\n };\n\n const statusSubscribers: StatusChangeHandler[] = [];\n let triggerHandle: TriggerHandle | undefined;\n // The single `ui:model` write subscription, made in `attach()` BEFORE any\n // trigger so the model write is always first in the bus's insertion order —\n // a trigger listening to `ui:model` reads the value the event just wrote, not\n // the one the field held before the keystroke. See `attach()`.\n let modelWriteOff: Unsubscribe | undefined;\n // ref → path, the model bindings the current render carries. Reconciled every\n // render; consulted by the ONE subscription above at event time. Keeping this\n // a map (not a subscription per binding) is what lets a binding appear or\n // vanish across renders without ever touching the bus's ordering.\n const modelListeners = new Map<string, string>();\n\n dataStore.subscribe((next) => {\n instance.data = next;\n });\n\n // Per endpoint: the last ticket handed out, the newest that landed, and the\n // later-bodies subscription it holds. See `EndpointCalls` in steps.ts.\n const ledger = new Map<string, { issued: number; landed: number; stop?: Unsubscribe }>();\n const entryOf = (endpoint: string): { issued: number; landed: number; stop?: Unsubscribe } => {\n const existing = ledger.get(endpoint);\n if (existing !== undefined) return existing;\n const created = { issued: 0, landed: 0 };\n ledger.set(endpoint, created);\n return created;\n };\n const calls: EndpointCalls = {\n begin: (endpoint) => {\n const entry = entryOf(endpoint);\n entry.issued += 1;\n return entry.issued;\n },\n land: (endpoint, ticket) => {\n const entry = entryOf(endpoint);\n if (ticket < entry.landed) return false;\n entry.landed = ticket;\n // Whatever the endpoint followed belongs to an older call now.\n entry.stop?.();\n delete entry.stop;\n return true;\n },\n follow: (endpoint, ticket, stop) => {\n const entry = entryOf(endpoint);\n if (ticket !== entry.landed || abortController.signal.aborted) {\n stop();\n return;\n }\n entry.stop?.();\n entry.stop = stop;\n },\n };\n const stopFollowing = (): void => {\n for (const entry of ledger.values()) {\n entry.stop?.();\n delete entry.stop;\n }\n };\n\n // The runtime is the only place that knows THIS instance, so it desugars\n // `{ removeSelf: true }` — a card's \"close me\" — into a `removeInstance`\n // carrying the real id, and stamps a `reconcile` with who is placing things:\n // the firing action's definition id, which outlives any one instance of it\n // (a remounted deck still owns what it placed). Every other effect passes\n // through untouched.\n const stamp = (effect: NavigationEffect): NavigationEffect => {\n if ('removeSelf' in effect) return { removeInstance: { instance: instance.id } };\n if ('reconcile' in effect) return { reconcile: { origin: instance.definitionId, ...effect.reconcile } };\n return effect;\n };\n const onNavigate =\n config.onNavigate === undefined ? undefined : (effect: NavigationEffect): void => config.onNavigate!(stamp(effect));\n\n // RELOADS MERGE. A `reload` asked for while one is running does not start a\n // second mount beside it (a trigger that reloads and re-emits would double\n // them every turn): it marks the running one to go round once more, with\n // the newest cause, and returns. Each round is one hop, so a mount that\n // reloads itself ends where its budget does (./cause.ts).\n let reloading = false;\n let reloadAgain: { cause: Cause | undefined } | undefined;\n const reload = async (cause: Cause | undefined): Promise<void> => {\n if (reloading) {\n reloadAgain = { cause };\n return;\n }\n reloading = true;\n try {\n let next: { cause: Cause | undefined } | undefined = { cause };\n while (next !== undefined) {\n reloadAgain = undefined;\n const hop = nextCause(next.cause);\n if (isRunaway(hop)) {\n onError(new NovaError(ErrorCodes.runaway, runawayMessage(hop, `Reloading \"${definition.id}\"`), { depth: hop.depth, hops: hop.root.hops }));\n return;\n }\n await runLifecycleHook('mount', definition, () => buildContext(abortController.signal, hop));\n next = reloadAgain;\n }\n } finally {\n reloading = false;\n reloadAgain = undefined;\n }\n };\n\n const buildContext = (signal: AbortSignal = abortController.signal, cause?: Cause): StepContext => ({\n dataStore,\n endpoints: definition.endpoints ?? {},\n functions: config.functions ?? {},\n ...(config.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: config.endpointTimeoutMs }),\n eventBus: config.eventBus,\n messageBus: config.messageBus,\n ...(config.fetch === undefined ? {} : { fetch: config.fetch }),\n ...(config.transform === undefined ? {} : { transform: config.transform }),\n ...(onNavigate === undefined ? {} : { onNavigate }),\n // Stamp the call event with this instance's identity before it flows up to\n // the shell's telemetry — `runCall` only knows the endpoint, the runtime\n // knows who made it.\n ...(config.onEndpoint === undefined\n ? {}\n : { onEndpoint: (event) => config.onEndpoint!({ ...event, instanceId: instance.id, canvasId: instance.canvasId }) }),\n calls,\n extras: {},\n initial: initialSnapshot,\n strict,\n onError,\n signal,\n suspended: instance.status === 'suspended',\n // `reload` — re-run this instance's own mount hook. The same refresh\n // `resume` performs, made available as a step for canvases that never\n // suspend (a list keeps every card active, so nothing else would ever\n // re-read one).\n onReload: reload,\n ...(cause === undefined ? {} : { cause }),\n });\n\n const setStatus = (next: ActionStatus): void => {\n if (instance.status === next) return;\n instance.status = next;\n for (const handler of statusSubscribers.slice()) {\n try {\n handler(next);\n } catch {\n // ignore\n }\n }\n };\n\n const attach = (): void => {\n // FIRST, and unconditionally — before the trigger subscriptions below and\n // before either early return, so it wins the bus's insertion order even for\n // an action that has model bindings but no triggers (an inspector field\n // that only previews). The handler resolves the ref against the render-time\n // map at event time and applies the same origin/suspension checks and the\n // same write the per-binding listener used to.\n if (modelWriteOff === undefined) {\n modelWriteOff = config.eventBus.on('ui:model', (event) => {\n if (event.type !== 'ui:model' || instance.status === 'suspended') return;\n // A stamped model event reaches its own instance only; an unstamped\n // (global) one reaches every instance holding the ref.\n if (event.origin !== undefined && event.origin !== instance.id) return;\n if (event.ref === undefined) return;\n const path = modelListeners.get(event.ref);\n if (path === undefined) return;\n dataStore.update((curr) =>\n applyMutations(curr, [{ set: path, value: event.payload }], { initial: initialSnapshot, strict }),\n );\n });\n }\n if (triggerHandle !== undefined) return;\n const triggers = definition.triggers;\n if (triggers === undefined || triggers.length === 0) return;\n triggerHandle = attachTriggers(triggers, config.eventBus, config.messageBus, buildContext, instance.id);\n };\n\n const detach = (): void => {\n if (modelWriteOff !== undefined) {\n modelWriteOff();\n modelWriteOff = undefined;\n }\n if (triggerHandle === undefined) return;\n triggerHandle.detach();\n triggerHandle = undefined;\n };\n\n const getData = (): Record<string, unknown> => dataStore.get();\n\n const updateData = (updates: Record<string, unknown>): void => {\n dataStore.update((curr) => ({ ...curr, ...updates }));\n };\n\n const setData = (next: Record<string, unknown>): void => {\n dataStore.update(() => next);\n };\n\n const applyMutationList = (mutations: Mutation[]): void => {\n if (mutations.length === 0) return;\n dataStore.update((curr) =>\n applyMutations(curr, mutations, { initial: initialSnapshot, strict }),\n );\n };\n\n const StepArraySchema = z.array(StepSchema);\n\n const runSteps = async (steps: Step[]): Promise<void> => {\n const parsed = StepArraySchema.safeParse(steps);\n if (!parsed.success) {\n const error = new DefinitionValidationError(\n 'Invalid steps passed to runtime.executeSteps',\n { failures: [{ id: definition.id, issues: parsed.error.issues }] },\n );\n if (strict) throw error;\n onError(error);\n return;\n }\n await executeSteps(parsed.data, buildContext());\n };\n\n const mount = async (input?: Record<string, unknown>): Promise<void> => {\n if (input !== undefined) {\n const next = buildInitialData(definition, input);\n dataStore.update(() => next);\n }\n attach();\n // A mount a chain caused (a trigger's push) is one hop further down it;\n // one nothing caused starts its own. Read before the first await — the\n // navigation that set it is still on the stack (./cause.ts).\n const parent = ambientCause();\n const cause = nextCause(parent);\n if (isRunaway(cause)) {\n onError(new NovaError(ErrorCodes.runaway, runawayMessage(cause, `Mounting \"${definition.id}\"`), { depth: cause.depth, hops: cause.root.hops }));\n } else {\n await runLifecycleHook('mount', definition, () => buildContext(abortController.signal, cause));\n }\n // Only if nothing moved it meanwhile: an instance covered (or removed)\n // while its mount hook was still running stays suspended (or unmounted).\n if (instance.status === 'initializing') setStatus('active');\n };\n\n const unmount = async (): Promise<void> => {\n // Cancel any in-flight step execution before running unmount hooks, and\n // stop following every endpoint whose answer could still change.\n abortController.abort();\n stopFollowing();\n detach();\n teardownModelListeners();\n // Unmount hooks run on a fresh (non-aborted) signal so they can\n // perform their own async work (e.g. final telemetry calls).\n const unmountController = new AbortController();\n await runLifecycleHook('unmount', definition, () =>\n buildContext(unmountController.signal),\n );\n setStatus('unmounted');\n };\n\n const suspend = async (): Promise<void> => {\n await runLifecycleHook('suspend', definition, buildContext);\n setStatus('suspended');\n };\n\n const resume = async (): Promise<void> => {\n // Becoming active again re-runs `mount` to refresh the action's data — so a\n // backgrounded action (which ignored everything while suspended) is current\n // when it's revealed, with no need to keep it live underneath — then the\n // `resume` hook, if the action defines one.\n setStatus('active');\n await runLifecycleHook('mount', definition, buildContext);\n await runLifecycleHook('resume', definition, buildContext);\n };\n\n // The map the ONE `ui:model` subscription (see `attach()`) consults at event\n // time. Rebuilt from the render tree every render — a binding inside a loop\n // depends on the data, so the set is not knowable before a render. This only\n // ever touches the map, never the bus, so the write's position ahead of the\n // triggers is unaffected by a binding appearing or vanishing across renders.\n const reconcileModelBindings = (nodes: RenderNode[]): void => {\n modelListeners.clear();\n for (const b of collectModelBindings(nodes)) modelListeners.set(b.ref, b.path);\n };\n\n const teardownModelListeners = (): void => {\n modelListeners.clear();\n };\n\n const render = (): RenderNode[] => {\n // Asked per render, not held: `shell.setPhrases` has to reach the screens\n // that are already open, and a book captured at spawn could not.\n const language = config.i18n?.();\n const out = renderRuntime(definition, dataStore, {\n store: config.layoutStore,\n registry: config.registry,\n strict,\n onError,\n ...(language?.phrases === undefined ? {} : { phrases: language.phrases }),\n ...(language?.phraseKeys === undefined ? {} : { phraseKeys: language.phraseKeys }),\n ...(language?.onPhraseMiss === undefined ? {} : { onPhraseMiss: language.onPhraseMiss }),\n });\n reconcileModelBindings(out);\n return out;\n };\n\n const onDataChange = (handler: DataChangeHandler): Unsubscribe => dataStore.subscribe(handler);\n\n const onStatusChange = (handler: StatusChangeHandler): Unsubscribe => {\n statusSubscribers.push(handler);\n return (): void => {\n const idx = statusSubscribers.indexOf(handler);\n if (idx >= 0) statusSubscribers.splice(idx, 1);\n };\n };\n\n const dispose = (): void => {\n stopFollowing();\n detach();\n teardownModelListeners();\n statusSubscribers.length = 0;\n };\n\n return {\n get instance() {\n return instance;\n },\n get definition() {\n return definition;\n },\n get dataStore() {\n return dataStore;\n },\n getData,\n setData,\n updateData,\n applyMutations: applyMutationList,\n executeSteps: runSteps,\n mount,\n unmount,\n suspend,\n resume,\n render,\n onDataChange,\n onStatusChange,\n dispose,\n };\n};\n","import type {\n ActionDefinition,\n ActionFragment,\n ActionRuntime,\n EndpointHandler,\n FunctionHandler,\n LanguageOptions,\n NavigationEffect,\n OnErrorHandler,\n} from '../action';\nimport { ActionDefinitionSchema, ActionFragmentSchema } from '../action';\nimport { createActionRuntime } from '../action/runtime/runtime';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport type { RuntimeRegistry } from './runtime-registry';\nimport type { Shell } from './types';\nimport type { ComponentRegistry, LayoutStore } from '../layout';\nimport type { EventBus } from '../shared/event-bus';\nimport type { MessageBus } from '../shared/message-bus';\nimport {\n DefinitionValidationError,\n type DefinitionValidationFailure,\n} from '../shared/errors';\nimport type { IdFactory } from '../shared/ids';\nimport type { FetchFn, TransformFn } from '../action';\nimport type { Canvas } from './canvas';\nimport type { CanvasState } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Internal helpers for shell.ts — kept here to keep that file's\n// public-facing assembly short and scannable.\n// ═══════════════════════════════════════════════════════════\n\nexport const validateActions = (actions: Record<string, ActionDefinition>): void => {\n const failures: DefinitionValidationFailure[] = [];\n for (const [actionId, def] of Object.entries(actions)) {\n // Asked before the schema reads it: a recursive schema overflows the\n // stack on a deep enough document instead of refusing it (strata depth.ts).\n if (exceedsDepth(def)) {\n failures.push({ id: actionId, issues: [{ code: 'custom', path: [], message: depthRefusal(), input: undefined }] });\n continue;\n }\n const result = ActionDefinitionSchema.safeParse(def);\n if (!result.success) failures.push({ id: actionId, issues: result.error.issues });\n }\n if (failures.length > 0) {\n throw new DefinitionValidationError(\n `${failures.length} action definition(s) failed validation`,\n { failures },\n );\n }\n};\n\nexport const validateFragments = (fragments: Record<string, ActionFragment>): void => {\n const failures: DefinitionValidationFailure[] = [];\n for (const [fragmentId, frag] of Object.entries(fragments)) {\n if (exceedsDepth(frag)) {\n failures.push({ id: fragmentId, issues: [{ code: 'custom', path: [], message: depthRefusal(), input: undefined }] });\n continue;\n }\n const result = ActionFragmentSchema.safeParse(frag);\n if (!result.success) failures.push({ id: fragmentId, issues: result.error.issues });\n }\n if (failures.length > 0) {\n throw new DefinitionValidationError(\n `${failures.length} action fragment(s) failed validation`,\n { failures },\n );\n }\n};\n\nexport const snapshotCanvas = (canvas: Canvas): CanvasState => {\n const stack = canvas.stack.slice();\n return {\n id: canvas.id,\n stack,\n active: stack.length === 0 ? undefined : stack[stack.length - 1],\n };\n};\n\nexport type RuntimeFactoryDeps = {\n eventBus: EventBus;\n messageBus: MessageBus;\n layoutStore: LayoutStore;\n registry: ComponentRegistry;\n transform?: TransformFn;\n fetch?: FetchFn;\n functions?: Record<string, FunctionHandler>;\n endpointTimeoutMs?: number;\n strict: boolean;\n onError?: OnErrorHandler;\n instanceIdFn: IdFactory;\n onNavigate: (canvasId: string, effect: NavigationEffect) => void;\n onEndpoint?: EndpointHandler;\n // The shell's language cell, read per render. See ActionRuntimeConfig.i18n.\n i18n?: () => LanguageOptions | undefined;\n};\n\nexport const createRuntimeFactory = (deps: RuntimeFactoryDeps) => (\n canvasId: string,\n definition: ActionDefinition,\n input: Record<string, unknown> | undefined,\n): ActionRuntime =>\n createActionRuntime({\n definition,\n canvasId,\n ...(input === undefined ? {} : { input }),\n eventBus: deps.eventBus,\n messageBus: deps.messageBus,\n layoutStore: deps.layoutStore,\n registry: deps.registry,\n ...(deps.transform === undefined ? {} : { transform: deps.transform }),\n ...(deps.fetch === undefined ? {} : { fetch: deps.fetch }),\n ...(deps.functions === undefined ? {} : { functions: deps.functions }),\n ...(deps.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: deps.endpointTimeoutMs }),\n onNavigate: (effect) => deps.onNavigate(canvasId, effect),\n ...(deps.onEndpoint === undefined ? {} : { onEndpoint: deps.onEndpoint }),\n strict: deps.strict,\n ...(deps.onError === undefined ? {} : { onError: deps.onError }),\n ...(deps.i18n === undefined ? {} : { i18n: deps.i18n }),\n instanceIdFn: deps.instanceIdFn,\n });\n\n// ═══════════════════════════════════════════════════════════\n// Internal escape hatch for tests that need the full ActionRuntime\n// (executeSteps, applyMutations, etc.) — NOT re-exported from the\n// package root. Tests reach this via `@shell/shell-internals`.\n// ═══════════════════════════════════════════════════════════\n\nconst shellRegistries = new WeakMap<Shell, RuntimeRegistry>();\n\nexport const rememberShellRegistry = (shell: Shell, registry: RuntimeRegistry): void => {\n shellRegistries.set(shell, registry);\n};\n\nexport const getInternalRuntime = (\n shell: Shell,\n instanceId: string,\n): ActionRuntime | undefined => {\n const registry = shellRegistries.get(shell);\n if (registry === undefined) return undefined;\n return registry.get(instanceId);\n};\n","import type { ActionInstance } from '../action';\n\nexport type Canvas = {\n readonly id: string;\n readonly stack: ActionInstance[];\n peek: () => ActionInstance | undefined;\n pushInstance: (inst: ActionInstance) => void;\n popInstance: () => ActionInstance | undefined;\n replaceTop: (inst: ActionInstance) => ActionInstance | undefined;\n clearStack: () => ActionInstance[];\n};\n\nexport const createCanvas = (id: string): Canvas => {\n const stack: ActionInstance[] = [];\n\n const peek = (): ActionInstance | undefined => {\n if (stack.length === 0) return undefined;\n return stack[stack.length - 1];\n };\n\n const pushInstance = (inst: ActionInstance): void => {\n stack.push(inst);\n };\n\n const popInstance = (): ActionInstance | undefined => {\n return stack.pop();\n };\n\n const replaceTop = (inst: ActionInstance): ActionInstance | undefined => {\n const prev = stack.pop();\n stack.push(inst);\n return prev;\n };\n\n const clearStack = (): ActionInstance[] => {\n const removed = stack.slice();\n stack.length = 0;\n return removed;\n };\n\n return { id, stack, peek, pushInstance, popInstance, replaceTop, clearStack };\n};\n","// ═══════════════════════════════════════════════════════════\n// Slot component name constants.\n//\n// Every framework adapter (React, future Vue/Svelte/etc.) must\n// register components under these names in its ComponentRegistry\n// to participate in shell/canvas layout rendering:\n//\n// CANVAS_SLOT_NAME — renders a canvas by id (props: canvasId?)\n// ACTION_SLOT_NAME — renders an action instance by id (props: instanceId?)\n//\n// The shell uses these names in its default layouts and when\n// flattening a render tree for non-React consumers (evaluators,\n// export, testing), so they are part of the package's public\n// contract — not React-only.\n// ═══════════════════════════════════════════════════════════\n\nexport const CANVAS_SLOT_NAME = 'CanvasSlot';\nexport const ACTION_SLOT_NAME = 'ActionSlot';\n","import type { LayoutNode } from '../layout';\nimport { ACTION_SLOT_NAME, CANVAS_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// Default layouts used when a shell or canvas does not declare\n// its own. Preserves pre-layout-aware behaviour:\n// - shell: flex row over canvases, one CanvasSlot per canvas\n// - canvas: render only the top-of-stack instance\n// ═══════════════════════════════════════════════════════════\n\nexport const DEFAULT_SHELL_LAYOUT: LayoutNode = {\n component: 'Stack',\n props: { direction: 'row' },\n children: [\n {\n for: '$.canvases',\n as: 'c',\n key: 'id',\n do: {\n component: CANVAS_SLOT_NAME,\n props: { canvasId: '$.c.id' },\n },\n },\n ],\n};\n\nexport const DEFAULT_ACTION_LAYOUT: LayoutNode = {\n component: ACTION_SLOT_NAME,\n props: { instanceId: '$.active.id' },\n};\n","import type { RenderNode } from '../layout';\nimport type { Shell } from './types';\nimport { ACTION_SLOT_NAME, CANVAS_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// flattenRenderTree — expand slot markers into their resolved\n// content. A shell render tree contains CanvasSlot / ActionSlot\n// component nodes that only recurse at React render time; tests\n// and framework-agnostic consumers need a fully materialised tree.\n//\n// CanvasSlot → inline getCanvasRenderTree(canvasId), flattened.\n// ActionSlot → the marker SURVIVES, carrying identity (instanceId /\n// canvasId / definitionId) with runtime.render() as its children —\n// the per-instance boundary is part of the tree, so a remote\n// renderer can key reconciliation by instance and an app-supplied\n// slotWrapper can wrap each instance (animation, gating, chips).\n// A target with no wrapper renders the children straight through.\n// Unknown / missing ids resolve to an empty fragment (an empty slot\n// is NOT a marker — an empty canvas must stay visibly empty).\n// ═══════════════════════════════════════════════════════════\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === 'string' && value.length > 0 ? value : undefined;\n\nconst emptyFragment = (): RenderNode => ({ type: 'fragment', children: [] });\n\nexport const flattenRenderTree = (tree: RenderNode[], shell: Shell): RenderNode[] =>\n tree.map((node) => flattenNode(node, shell));\n\nconst flattenNode = (node: RenderNode, shell: Shell): RenderNode => {\n if (node.type !== 'component') {\n if (node.type === 'fragment') {\n return { type: 'fragment', children: flattenRenderTree(node.children, shell) };\n }\n return node;\n }\n\n if (node.name === CANVAS_SLOT_NAME) {\n const canvasId = asString(node.props['canvasId']);\n if (canvasId === undefined) return emptyFragment();\n return { type: 'fragment', children: flattenRenderTree(shell.getCanvasRenderTree(canvasId), shell) };\n }\n\n if (node.name === ACTION_SLOT_NAME) {\n const instanceId = asString(node.props['instanceId']);\n if (instanceId === undefined) return emptyFragment();\n const runtime = shell.getRuntime(instanceId);\n if (runtime === undefined) return emptyFragment();\n return {\n type: 'component',\n name: ACTION_SLOT_NAME,\n // identity only — never the definition itself (wire weight)\n props: { instanceId, canvasId: runtime.instance.canvasId, definitionId: runtime.instance.definitionId },\n children: runtime.render(),\n // keyed by instance so a renderer remounts when the instance changes\n // (no stale DOM state across instance swaps, enter animations fire)\n key: instanceId,\n };\n }\n\n return { ...node, children: flattenRenderTree(node.children, shell) };\n};\n","import type { ActionDefinition } from '@action';\nimport { mutationPaths, rootOf } from '@action/grammar';\n\n// What an action does with its DATA KEYS, read off its own definition.\n//\n// Four questions, each a pure function of the artifact and each with more than\n// one consumer: an audit asking whether declared state is reachable, an agent\n// asking whether a change was a person or a re-read, a devtools pane asking what\n// fills a field. Every one of them was being re-derived outside nova, which is\n// how a hand-copied list of mutation ops ended up in an application.\n\n// What a FINGER can write: every data path a `ui:` trigger sets.\nexport const gesturedKeys = (definition: ActionDefinition): readonly string[] => [\n ...new Set(\n (definition.triggers ?? [])\n .filter((trigger) => typeof trigger.event === 'string' && trigger.event.startsWith('ui:'))\n .flatMap((trigger) => mutationPaths(trigger.do))\n .map(rootOf),\n ),\n];\n\n// What an OPENER may set: the declared input contract.\nexport const declaredKeys = (definition: ActionDefinition): readonly string[] =>\n Object.keys((definition.input as { properties?: Record<string, unknown> } | undefined)?.properties ?? {});\n\n// What the DATABASE writes: every endpoint's landing place.\nexport const loadedKeys = (definition: ActionDefinition): readonly string[] => {\n const loaded = new Set<string>();\n for (const endpoint of Object.values(definition.endpoints ?? {})) {\n const spec = endpoint as { target?: string; errorTarget?: string };\n if (spec.target !== undefined) loaded.add(rootOf(spec.target));\n if (spec.errorTarget !== undefined) loaded.add(rootOf(spec.errorTarget));\n }\n return [...loaded];\n};\n\n// What a surface writes to ITSELF when it opens or resumes: a loading flag\n// clearing, a working flag resetting.\nexport const lifecycleKeys = (definition: ActionDefinition): readonly string[] => [\n ...new Set(\n Object.values((definition.lifecycle ?? {}) as Record<string, unknown>)\n .flatMap(mutationPaths)\n .map(rootOf),\n ),\n];\n\n// Endpoint names a `mount` step calls, at any depth.\nconst mountCalls = (definition: ActionDefinition): Set<string> => {\n const names = new Set<string>();\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n const step = node as Record<string, unknown>;\n if (typeof step['call'] === 'string') names.add(step['call']);\n walk(step['onSuccess']);\n walk(step['onError']);\n };\n walk((definition.lifecycle as { mount?: unknown } | undefined)?.mount);\n return names;\n};\n\n// Every `$.<key>` an endpoint's request reads. `{ id: { $ref: '$.issueId' } }`\n// and the bare form `'$.issueId'` both count.\nconst requestKeys = (request: unknown): string[] => {\n const found: string[] = [];\n const walk = (node: unknown): void => {\n if (typeof node === 'string') {\n if (node.startsWith('$.')) found.push(rootOf(node.slice(2)));\n return;\n }\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (node === null || typeof node !== 'object') return;\n for (const value of Object.values(node as Record<string, unknown>)) walk(value);\n };\n walk(request);\n return found.filter((key) => key !== '');\n};\n\nconst mountInputCache = new WeakMap<ActionDefinition, ReadonlySet<string>>();\n\n// Input keys the surface consumes WHEN IT OPENS: an id its own mount-time load\n// sends. Writing one into a live instance leaves the previous record's data on\n// screen, so a caller that wants to re-aim must re-mount instead.\n//\n// Cached per definition object: definitions are read on every telemetry event,\n// and a bundle sync replaces them wholesale, so identity is the right key.\nexport const mountInputKeys = (definition: ActionDefinition): ReadonlySet<string> => {\n const cached = mountInputCache.get(definition);\n if (cached !== undefined) return cached;\n const called = mountCalls(definition);\n const declared = new Set(declaredKeys(definition));\n const keys = new Set<string>();\n for (const [name, endpoint] of Object.entries(definition.endpoints ?? {})) {\n if (!called.has(name)) continue;\n for (const key of requestKeys((endpoint as { request?: unknown }).request)) if (declared.has(key)) keys.add(key);\n }\n mountInputCache.set(definition, keys);\n return keys;\n};\n","import type { ActionDefinition } from '../action';\nimport { mountInputKeys } from '../reflect/grammar';\nimport type { Shell } from './types';\n\n// Make a canvas equal a desired list.\n//\n// nova's other navigation verbs are imperative — push, pop, replace,\n// removeInstance — and describe a screen as a sequence of edits to one nobody\n// holds a picture of. Every caller that produces a whole desired state (a\n// server-driven layout, a restored workspace, an agent's answer) then has to\n// diff it by hand, and each of them writes the same four bugs: duplicates,\n// forgetting to close, closing what somebody else opened, and re-aiming a card\n// whose data no longer matches its id.\n//\n// This is the declarative verb. The caller says what should be there; nova works\n// out push, write or replace.\n//\n// OWNERSHIP `own` decides what the caller may move — see below.\n// RE-AIM writing an input key that the surface's own mount-time load reads\n// would leave the previous record's data on screen under a new id,\n// so those re-mount instead of being written.\n\nexport type Desired = {\n actionId: string;\n input?: Record<string, unknown>;\n // Fragments to compose, as `push` takes them.\n with?: string[];\n};\n\nexport type ReconcileOptions = {\n // Stamped on everything this call pushes. Required whichever `own` is in\n // force: it is how a later call, a telemetry reader or an audit answers \"who\n // put this here\".\n origin: string;\n // Resolves an action id to its definition, for the re-aim rule. Without it,\n // every change to a live card is written in place.\n definitionOf?: (actionId: string) => ActionDefinition | undefined;\n // WHAT THIS CALL MAY MOVE.\n //\n // 'pushed' (default) — only instances carrying `origin`. Anything else on\n // the canvas is left exactly as it is: the safe reading\n // for a caller that SHARES a canvas with a person.\n // 'canvas' — every instance on the canvas, whoever pushed it. For\n // a caller that OWNS the canvas outright.\n //\n // \"Only what I pushed\" is authorship, not ownership, and the two come apart\n // wherever a person and an agent work the same column: an agent granted a\n // canvas cannot write into or take down a record the person opened onto it,\n // while its complete-state answer says it has.\n own?: 'pushed' | 'canvas';\n};\n\nexport type ReconcileResult = {\n changed: boolean;\n // What moved, in order, for a caller that wants to log or trace it.\n notes: string[];\n};\n\nconst differs = (before: Record<string, unknown>, input: Record<string, unknown>): boolean =>\n Object.entries(input).some(([key, value]) => JSON.stringify(before[key]) !== JSON.stringify(value));\n\nexport const reconcileCanvas = (shell: Shell, canvasId: string, desired: readonly Desired[], options: ReconcileOptions): ReconcileResult => {\n const { origin, definitionOf } = options;\n // Asked once, so the close scope and the write scope cannot drift apart: a\n // caller allowed to take a card down is allowed to write into it.\n const ownsCanvas = options.own === 'canvas';\n const notes: string[] = [];\n let changed = false;\n\n if (shell.getState().canvases[canvasId] === undefined) return { changed: false, notes: [`no canvas \"${canvasId}\"`] };\n\n // A canvas is a set, not a bag: one instance per action id.\n const wanted: Desired[] = [];\n for (const entry of desired) if (!wanted.some((other) => other.actionId === entry.actionId)) wanted.push(entry);\n\n const mine = (shell.getState().canvases[canvasId]?.stack ?? []).filter((item) => ownsCanvas || shell.originOf(item.id) === origin);\n for (const item of mine) {\n if (wanted.some((entry) => entry.actionId === item.definitionId)) continue;\n shell.removeInstance(canvasId, item.id);\n changed = true;\n notes.push(`closed ${item.definitionId}`);\n }\n\n for (const entry of wanted) {\n const input = entry.input ?? {};\n const existing = (shell.getState().canvases[canvasId]?.stack ?? []).find((item) => item.definitionId === entry.actionId);\n\n if (existing !== undefined && !ownsCanvas && shell.originOf(existing.id) !== origin) {\n notes.push(`left ${entry.actionId}: not mine`);\n continue;\n }\n\n if (existing !== undefined) {\n const runtime = shell.getRuntime(existing.id);\n const before = runtime?.getData() ?? {};\n if (runtime === undefined || Object.keys(input).length === 0 || !differs(before, input)) continue;\n\n const definition = definitionOf?.(entry.actionId);\n const reAims = definition !== undefined && Object.keys(input).some((key) => mountInputKeys(definition).has(key));\n if (!reAims) {\n runtime.setData({ ...before, ...input });\n changed = true;\n notes.push(`set ${Object.keys(input).join(', ')} on ${entry.actionId}`);\n continue;\n }\n shell.removeInstance(canvasId, existing.id);\n notes.push(`re-opened ${entry.actionId}`);\n }\n\n shell.push(canvasId, entry.actionId, input, entry.with, { origin });\n changed = true;\n notes.push(`placed ${entry.actionId}`);\n }\n\n return { changed, notes };\n};\n","// ═══════════════════════════════════════════════════════════\n// The navigation journal — what BACK undoes.\n//\n// A canvas stack remembers where you ARE; nothing remembered where you WERE.\n// Every navigation destroys some of that: a push buries the top, a replace\n// unmounts it, a resetTo takes the whole deck. So the journal writes the canvas\n// down just BEFORE each of those. One entry is one position somebody can be\n// returned to, and `shell.back()` is \"put the newest one back\".\n//\n// GLOBAL AND ORDERED — one list across every canvas, each entry naming the one\n// canvas it describes. Global because back is a single gesture: somebody who\n// opened a card on `aside` after a screen on `main` expects it to walk back\n// through both, in the order they happened. One canvas per entry because back\n// must undo THEIR last move and not revert a canvas that changed underneath\n// them — a delivered notice, an agent's card — while they were elsewhere.\n//\n// A frame records the instance id it described AND the birth details behind it,\n// because those answer two different questions on the way back: is this the\n// very instance I recorded (keep it, with everything it holds), or is it gone\n// (build a new one from what made it).\n// ═══════════════════════════════════════════════════════════\n\n// One position in a recorded stack.\nexport type HistoryFrame = {\n // The live instance this frame described when it was recorded. Meaningless\n // on its own — its whole job is to be compared against what is standing now.\n instance: string;\n action: string;\n input?: Record<string, unknown>;\n with?: string[];\n};\n\n// One restorable position: a canvas, and the stack it held before the\n// navigation that displaced it.\nexport type HistoryEntry = {\n canvas: string;\n stack: readonly HistoryFrame[];\n};\n\nexport type Journal = {\n record: (canvas: string, stack: readonly HistoryFrame[]) => void;\n // The person went back by hand — spend the entry that gesture satisfied.\n consume: (canvas: string) => void;\n // The newest entry, removed. The restore itself is the shell's business.\n take: () => HistoryEntry | undefined;\n // Drop every entry that would bring a revoked action back.\n forgetAction: (actionId: string) => void;\n // Drop every entry for a canvas that no longer exists.\n forgetCanvas: (canvas: string) => void;\n // Run `fn` with recording off — for the movements that are not navigation\n // (seeding a canvas, restoring one).\n mute: <T>(fn: () => T) => T;\n depth: () => number;\n};\n\n// Deep enough that nobody walks off the end of a session's worth of moving\n// about, shallow enough to be a rounding error beside the instances themselves.\nexport const DEFAULT_HISTORY_DEPTH = 50;\n\nexport const createJournal = (limit: number): Journal => {\n const entries: HistoryEntry[] = [];\n // A counter, not a flag: seeding a canvas from inside a restore is one mute\n // nested in another, and the inner one must not un-mute the outer.\n let mutes = 0;\n\n const off = (): boolean => limit <= 0 || mutes > 0;\n\n return {\n record: (canvas, stack) => {\n if (off()) return;\n entries.push({ canvas, stack });\n // BOUNDED, because a durable shell can stand for hours. The oldest\n // position is the one nobody is walking back to.\n if (entries.length > limit) entries.shift();\n },\n\n // A pop somebody performed themselves IS a back. Without this the journal\n // would still hold the entry that pop just satisfied, and the next press of\n // the back button would spend itself restoring a position already on screen\n // — the double-tap that makes a back button feel broken.\n consume: (canvas) => {\n if (off()) return;\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n if (entries[i]?.canvas !== canvas) continue;\n entries.splice(i, 1);\n return;\n }\n },\n\n take: () => entries.pop(),\n\n // REVOCATION REACHES THE JOURNAL OR IT IS NOT REVOCATION. An entry naming\n // an action this shell no longer serves would hand it back on the way out —\n // a grant dropped at the front door and returned through the back one.\n forgetAction: (actionId) => {\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n if (entries[i]?.stack.some((frame) => frame.action === actionId) === true) entries.splice(i, 1);\n }\n },\n\n forgetCanvas: (canvas) => {\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n if (entries[i]?.canvas === canvas) entries.splice(i, 1);\n }\n },\n\n mute: (fn) => {\n mutes += 1;\n try {\n return fn();\n } finally {\n mutes -= 1;\n }\n },\n\n depth: () => entries.length,\n };\n};\n","import type { Canvas } from './canvas';\nimport type { RuntimeRegistry } from './runtime-registry';\nimport type { Telemetry } from './telemetry';\n\n// ═══════════════════════════════════════════════════════════\n// Shell lifecycle ops — small helpers that the shell public API\n// composes with its own guards. Factored out to keep `shell.ts`\n// focused on assembly and navigation wiring.\n// ═══════════════════════════════════════════════════════════\n\nexport type LifecycleOpsDeps = {\n registry: RuntimeRegistry;\n telemetry: Telemetry;\n onLifecycleError: (err: unknown) => void;\n // Called as an instance is torn down, so per-instance bookkeeping the shell\n // holds beside the registry (push origins) never outlives what it describes.\n onUnmount?: (instanceId: string) => void;\n};\n\nexport type LifecycleOps = {\n unmountInstance: (instanceId: string) => void;\n suspendTop: (canvas: Canvas) => void;\n resumeTop: (canvas: Canvas) => void;\n};\n\nexport const createLifecycleOps = (deps: LifecycleOpsDeps): LifecycleOps => {\n const { registry, onLifecycleError, onUnmount } = deps;\n\n // Track instances we've already unmounted so a redundant unmount is a\n // no-op (idempotency) — never re-fires hooks, never re-disposes.\n const unmounted = new Set<string>();\n\n const unmountInstance = (instanceId: string): void => {\n if (unmounted.has(instanceId)) return;\n const runtime = registry.get(instanceId);\n if (runtime === undefined) return;\n unmounted.add(instanceId);\n runtime.unmount().catch(onLifecycleError);\n runtime.dispose();\n registry.unregister(instanceId);\n onUnmount?.(instanceId);\n // BOUNDED, not forever. Once the registry no longer holds the instance,\n // the `registry.get` guard above returns early on its own — the set only\n // has to cover re-entry inside THIS call. Keeping the id would grow this\n // set by one string per navigation for the life of a durable shell: the\n // one genuinely unbounded structure the memory hunt found.\n unmounted.delete(instanceId);\n };\n\n const suspendTop = (canvas: Canvas): void => {\n const top = canvas.peek();\n if (top === undefined) return;\n // Already suspended is already done. A push onto a fresh stack always finds\n // an active top, so this changes nothing there; `back` restoring a position\n // ABOVE the one on screen finds a top that was suspended when the screen it\n // is undoing went up, and re-firing that action's suspend hook would be a\n // lifecycle event nothing happened to cause.\n if (top.status === 'suspended') return;\n const runtime = registry.get(top.id);\n if (runtime !== undefined) runtime.suspend().catch(onLifecycleError);\n };\n\n const resumeTop = (canvas: Canvas): void => {\n const top = canvas.peek();\n if (top === undefined) return;\n const runtime = registry.get(top.id);\n if (runtime !== undefined) runtime.resume().catch(onLifecycleError);\n };\n\n return { unmountInstance, suspendTop, resumeTop };\n};\n","import type { NavigationEffect } from '../action';\n\n// ═══════════════════════════════════════════════════════════\n// WHERE A CANVAS IS, ANNOUNCED.\n//\n// A canvas knows what is standing on it; nothing else did. Chrome around a\n// canvas — a sidebar highlight, a tab strip, a breadcrumb — used to learn where\n// somebody went from the CLICK that sent them, which is a copy of the fact\n// rather than the fact. It agreed with the canvas right up until something\n// moved the canvas without a click: `back`, an agent opening a screen, a\n// delivered card, a deep link later. Then the sidebar lit one screen while the\n// canvas showed another.\n//\n// So the canvas says where it is. One message per canvas whenever its ACTIVE\n// screen changes, whatever caused the change, on a channel named for the\n// canvas — triggers carry no guard clause, so a listener that wants `main`\n// should not have to hear about `sheet` to ignore it. The payload names the\n// canvas anyway, so nothing has to parse a channel to know what it was told.\n// ═══════════════════════════════════════════════════════════\n\nexport const navigatedChannel = (canvasId: string): string => `nova:navigated:${canvasId}`;\n\n// What lands on that channel. `action`/`instance` are absent when the canvas\n// went empty — which is a position too, and a listener that renders chrome for\n// \"nothing is open\" needs to hear it.\nexport type NavigatedMessage = {\n canvas: string;\n action?: string;\n instance?: string;\n};\n\nexport type ShellNavOps = {\n push: (canvasId: string, actionId: string, input?: Record<string, unknown>, fragments?: string[]) => string;\n pop: (canvasId: string) => void;\n replace: (canvasId: string, actionId: string, input?: Record<string, unknown>, fragments?: string[]) => string;\n clear: (canvasId: string) => void;\n // Clear and push in one movement. Its own op rather than the two calls it\n // used to decompose into, because the journal has to see ONE navigation here:\n // as `clear` then `push` it recorded two positions, and back walked somebody\n // through a blank canvas on the way to the screen they wanted.\n resetTo: (canvasId: string, actionId: string, input?: Record<string, unknown>, fragments?: string[]) => void;\n popTo: (canvasId: string, instanceId: string) => void;\n removeInstance: (canvasId: string, instanceId: string) => void;\n // Make a canvas hold exactly `desired` (shell/reconcile.ts), as one movement.\n reconcile: (\n canvasId: string,\n desired: readonly { actionId: string; input?: Record<string, unknown> }[],\n options: { origin: string; own?: 'pushed' | 'canvas'; with?: string[] },\n ) => void;\n};\n\nexport type NavigationHandler = (currentCanvasId: string, effect: NavigationEffect) => void;\n\nexport const createNavigationHandler = (ops: ShellNavOps): NavigationHandler => {\n return (currentCanvasId, effect): void => {\n if ('push' in effect) {\n const target = effect.push.canvas ?? currentCanvasId;\n ops.push(target, effect.push.action, effect.push.input, effect.push.with);\n return;\n }\n if ('pop' in effect) {\n ops.pop(currentCanvasId);\n return;\n }\n if ('replace' in effect) {\n const target = effect.replace.canvas ?? currentCanvasId;\n ops.replace(target, effect.replace.action, effect.replace.input, effect.replace.with);\n return;\n }\n if ('popTo' in effect) {\n ops.popTo(effect.popTo.canvas ?? currentCanvasId, effect.popTo.instance);\n return;\n }\n if ('resetTo' in effect) {\n const target = effect.resetTo.canvas ?? currentCanvasId;\n ops.resetTo(target, effect.resetTo.action, effect.resetTo.input, effect.resetTo.with);\n return;\n }\n if ('removeInstance' in effect) {\n ops.removeInstance(effect.removeInstance.canvas ?? currentCanvasId, effect.removeInstance.instance);\n return;\n }\n if ('reconcile' in effect) {\n const { canvas, desired, origin, own, with: fragments } = effect.reconcile;\n ops.reconcile(canvas ?? currentCanvasId, desired, {\n origin: origin ?? 'reconcile',\n ...(own === undefined ? {} : { own }),\n ...(fragments === undefined ? {} : { with: fragments }),\n });\n }\n };\n};\n","import type { ActionRuntime } from '../action';\nimport type { Unsubscribe } from '../shared/common';\n\nexport type RuntimeRegistry = {\n register: (runtime: ActionRuntime, onData: (data: Record<string, unknown>) => void) => void;\n unregister: (instanceId: string) => void;\n get: (instanceId: string) => ActionRuntime | undefined;\n disposeAll: () => void;\n};\n\nexport const createRuntimeRegistry = (): RuntimeRegistry => {\n const runtimes = new Map<string, ActionRuntime>();\n const unsubs = new Map<string, Unsubscribe>();\n\n const register = (\n runtime: ActionRuntime,\n onData: (data: Record<string, unknown>) => void,\n ): void => {\n const id = runtime.instance.id;\n runtimes.set(id, runtime);\n unsubs.set(id, runtime.onDataChange(onData));\n };\n\n const unregister = (instanceId: string): void => {\n const off = unsubs.get(instanceId);\n if (off !== undefined) off();\n unsubs.delete(instanceId);\n runtimes.delete(instanceId);\n };\n\n const get = (instanceId: string): ActionRuntime | undefined => runtimes.get(instanceId);\n\n const disposeAll = (): void => {\n for (const off of unsubs.values()) off();\n unsubs.clear();\n runtimes.clear();\n };\n\n return { register, unregister, get, disposeAll };\n};\n","import type { EndpointEvent, EndpointHandler } from '../action';\nimport type { Unsubscribe } from '../shared/common';\nimport type {\n DataChangeEvent,\n DataChangeHandler,\n ShellTelemetry,\n StateChangeHandler,\n StateSnapshot,\n} from './types';\n\nexport type Telemetry = {\n fireStateChange: (snapshot: StateSnapshot) => void;\n fireDataChange: (change: DataChangeEvent) => void;\n fireEndpoint: (event: EndpointEvent) => void;\n onStateChange: (handler: StateChangeHandler) => Unsubscribe;\n onDataChange: (handler: DataChangeHandler) => Unsubscribe;\n onEndpoint: (handler: EndpointHandler) => Unsubscribe;\n clear: () => void;\n};\n\nconst safeCall = <T>(fn: ((arg: T) => void) | undefined, arg: T): void => {\n if (fn === undefined) return;\n try {\n fn(arg);\n } catch {\n // telemetry handlers must not crash the shell\n }\n};\n\nexport const createTelemetry = (config: ShellTelemetry | undefined): Telemetry => {\n const stateSubscribers: StateChangeHandler[] = [];\n const dataSubscribers: DataChangeHandler[] = [];\n const endpointSubscribers: EndpointHandler[] = [];\n\n const fireStateChange = (snapshot: StateSnapshot): void => {\n safeCall(config?.onStateChange, snapshot);\n for (const handler of stateSubscribers.slice()) safeCall(handler, snapshot);\n };\n\n const fireDataChange = (change: DataChangeEvent): void => {\n safeCall(config?.onDataChange, change);\n for (const handler of dataSubscribers.slice()) safeCall(handler, change);\n };\n\n const fireEndpoint = (event: EndpointEvent): void => {\n safeCall(config?.onEndpoint, event);\n for (const handler of endpointSubscribers.slice()) safeCall(handler, event);\n };\n\n const onStateChange = (handler: StateChangeHandler): Unsubscribe => {\n stateSubscribers.push(handler);\n return (): void => {\n const idx = stateSubscribers.indexOf(handler);\n if (idx >= 0) stateSubscribers.splice(idx, 1);\n };\n };\n\n const onDataChange = (handler: DataChangeHandler): Unsubscribe => {\n dataSubscribers.push(handler);\n return (): void => {\n const idx = dataSubscribers.indexOf(handler);\n if (idx >= 0) dataSubscribers.splice(idx, 1);\n };\n };\n\n const onEndpoint = (handler: EndpointHandler): Unsubscribe => {\n endpointSubscribers.push(handler);\n return (): void => {\n const idx = endpointSubscribers.indexOf(handler);\n if (idx >= 0) endpointSubscribers.splice(idx, 1);\n };\n };\n\n const clear = (): void => {\n stateSubscribers.length = 0;\n dataSubscribers.length = 0;\n endpointSubscribers.length = 0;\n };\n\n return { fireStateChange, fireDataChange, fireEndpoint, onStateChange, onDataChange, onEndpoint, clear };\n};\n","import type { ActionDefinition, ActionFragment, ActionInstance, ActionRuntime, EndpointHandler, LanguageOptions, PublicActionRuntime } from '../action';\n// Note: ActionRuntime is used as the internal runtime type returned by spawn/registry.\nimport { composeAction } from '../action';\nimport { createScopeChain, resolve } from '../shared/bindings';\nimport type { LayoutNode, RenderNode } from '../layout';\nimport type { Phrasebook } from '../i18n/phrases';\nimport { createComponentRegistry, createLayoutStore, renderLayoutFromStore } from '../layout';\nimport { createEventBus } from '../shared/event-bus';\nimport { createMessageBus } from '../shared/message-bus';\nimport type { Unsubscribe } from '../shared/common';\nimport {\n LifecycleError,\n NovaError,\n ShellDisposedError,\n UnknownActionError,\n UnknownFragmentError,\n} from '../shared/errors';\nimport { createIdFactory } from '../shared/ids';\nimport { rememberShellRegistry } from './shell-internals';\nimport { createCanvas, type Canvas } from './canvas';\nimport { DEFAULT_ACTION_LAYOUT, DEFAULT_SHELL_LAYOUT } from './default-layouts';\nimport { flattenRenderTree } from './flatten-render-tree';\nimport { reconcileCanvas } from './reconcile';\nimport { createJournal, DEFAULT_HISTORY_DEPTH } from './journal';\nimport type { HistoryEntry, HistoryFrame } from './journal';\nimport { createLifecycleOps } from './lifecycle-ops';\nimport { createNavigationHandler, navigatedChannel } from './navigation';\nimport type { NavigatedMessage } from './navigation';\nimport { createRuntimeRegistry } from './runtime-registry';\nimport { createRuntimeFactory, snapshotCanvas, validateActions, validateFragments } from './shell-internals';\nimport { createTelemetry } from './telemetry';\nimport type {\n CanvasChangeHandler,\n CanvasConfig,\n CanvasState,\n DataChangeHandler,\n PushOptions,\n Shell,\n ShellConfig,\n StateChangeHandler,\n StateSnapshot,\n} from './types';\n\nconst defaultShellIdFactory = createIdFactory('shell');\n\nexport const createShell = (config: ShellConfig): Shell => {\n validateActions(config.actions);\n\n const id = (config.shellIdFn ?? defaultShellIdFactory)();\n const instanceIdFn = config.instanceIdFn ?? createIdFactory('act');\n const strict = config.strict ?? false;\n const eventBus = config.eventBus ?? createEventBus();\n const messageBus = config.messageBus ?? createMessageBus();\n const registry = createRuntimeRegistry();\n const telemetry = createTelemetry(config.telemetry);\n\n // Resolve component registry + layout store: use caller-provided ones when\n // present, otherwise fabricate empty defaults. `components` (if provided) is\n // merged into whichever registry we end up using.\n const componentRegistry = config.registry ?? createComponentRegistry();\n if (config.components !== undefined) componentRegistry.registerAll(config.components);\n const layoutStore = config.layoutStore ?? createLayoutStore();\n\n // In strict mode, the next public shell call rethrows this error.\n // Lifecycle hooks are async fire-and-forget, so failures cannot\n // propagate synchronously to the original push/pop caller; instead\n // we surface them at the boundary of the next operation.\n let pendingStrictError: LifecycleError | undefined;\n\n const toLifecycleError = (err: unknown): LifecycleError => {\n if (err instanceof LifecycleError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new LifecycleError(message, {}, { cause: err });\n };\n\n const handleLifecycleRejection = (err: unknown): void => {\n const lifecycleErr = toLifecycleError(err);\n if (strict && pendingStrictError === undefined) {\n pendingStrictError = lifecycleErr;\n }\n if (config.onError === undefined) return;\n if (err instanceof NovaError) {\n config.onError(err);\n return;\n }\n config.onError(lifecycleErr);\n };\n\n // WHO PUT THIS HERE. A caller that pushes with an `origin` can ask later\n // whether an instance is still one of its own — the question any server-driven\n // or agent-driven layout must answer before it closes something, and one\n // nobody can answer by inspecting the screen. Dropped with the instance.\n const origins = new Map<string, string>();\n\n // WHAT MADE THIS INSTANCE. The stack holds instances; an instance holds its\n // data and no memory of the call that spawned it, so a canvas can say what is\n // standing on it but not how to stand it up again. `back` needs the second\n // question answered for anything a navigation destroyed — hence the birth\n // details, kept beside the instance and dropped with it.\n //\n // `input` is held by REFERENCE, exactly as push already hands it to the\n // runtime: cloning would quietly break an input carrying anything a structured\n // clone cannot take, and would be a copy nobody asked for.\n const births = new Map<string, { action: string; input?: Record<string, unknown>; with?: string[] }>();\n\n const journal = createJournal(config.historyDepth ?? DEFAULT_HISTORY_DEPTH);\n\n const ops = createLifecycleOps({\n registry,\n telemetry,\n onLifecycleError: handleLifecycleRejection,\n onUnmount: (instanceId) => {\n origins.delete(instanceId);\n births.delete(instanceId);\n },\n });\n\n const canvases = new Map<string, Canvas>();\n const actionLayouts = new Map<string, LayoutNode | string>();\n // Canvases declared `mode: 'list'` keep EVERY instance live and visible at\n // once (a tray of cards), instead of the default stack where only the top is\n // active and the rest are suspended. Two behaviours follow: push does not\n // suspend the previous top, and removing a card does not resume another.\n const listCanvases = new Set<string>();\n for (const cfg of config.canvases) {\n canvases.set(cfg.id, createCanvas(cfg.id));\n if (cfg.actionLayout !== undefined) actionLayouts.set(cfg.id, cfg.actionLayout);\n if (cfg.mode === 'list') listCanvases.add(cfg.id);\n }\n\n // Mutable so addCanvas / removeCanvas / setCanvasLayout can change the rendered\n // canvas set and arrangement after creation. Seeded from config; the canvas\n // ids keep declaration order (getShellRenderTree renders them in this order).\n const canvasOrder: string[] = config.canvases.map((cfg) => cfg.id);\n let canvasLayout = config.canvasLayout;\n\n // Mutable so registerAction can add definitions at runtime (push/seed resolve\n // through this, not config.actions).\n const actions: Record<string, ActionDefinition> = { ...config.actions };\n\n // ONE CELL FOR THE LANGUAGE, read at every render by everything that renders.\n // Mutable so `setPhrases` reaches instances that are already mounted; the key\n // set and the miss handler are fixed at build, because they describe the\n // application rather than the reader.\n let phrases = config.phrases;\n\n // WITHDRAWING A BOOK IS THE SOURCE LANGUAGE, NOT SWITCHING i18n OFF — and the\n // difference is not cosmetic. A shell that has stopped doing i18n leaves a\n // counted phrase as the `{ phrase, slots }` object it travels as, and the\n // renderer below has nobody left to close its holes; the object reaches the\n // adapter, which is handed a structure where a word should be and throws.\n //\n // So the question \"is this shell language-bearing\" is answered ONCE, by\n // whether it was ever given a book or a key set, and `setPhrases(undefined)`\n // cannot un-answer it. Only a shell that never mentioned language at all pays\n // nothing — which is still the common case, and still free.\n let bearing = config.phrases !== undefined || config.phraseKeys !== undefined;\n const SOURCE: Phrasebook = {};\n\n const language = (): LanguageOptions | undefined => {\n if (!bearing) return undefined;\n return {\n // An empty book translates nothing and still fills patterns, which is\n // exactly what the source language needs.\n phrases: phrases ?? SOURCE,\n ...(config.phraseKeys === undefined ? {} : { phraseKeys: config.phraseKeys }),\n ...(config.onPhraseMiss === undefined ? {} : { onPhraseMiss: config.onPhraseMiss }),\n };\n };\n\n // Reusable partial actions, composed into a concrete action at push/replace\n // time via the effect's `with: [...]`. Abstract — never instantiated alone.\n const fragments: Record<string, ActionFragment> = { ...(config.fragments ?? {}) };\n\n let disposed = false;\n\n const guardNotDisposed = (): void => {\n if (disposed) throw new ShellDisposedError('Shell disposed');\n };\n\n const guardNoPendingStrictError = (): void => {\n if (pendingStrictError === undefined) return;\n const err = pendingStrictError;\n pendingStrictError = undefined;\n throw err;\n };\n\n const guard = (): void => {\n guardNotDisposed();\n guardNoPendingStrictError();\n };\n\n const getCanvas = (canvasId: string): Canvas => {\n const existing = canvases.get(canvasId);\n if (existing !== undefined) return existing;\n const created = createCanvas(canvasId);\n canvases.set(canvasId, created);\n return created;\n };\n\n const getDefinition = (actionId: string): ActionDefinition => {\n const def = actions[actionId];\n if (def === undefined) throw new UnknownActionError(`Unknown action: ${actionId}`, { actionId });\n return def;\n };\n\n const registerAction = (definition: ActionDefinition): void => {\n guard();\n validateActions({ [definition.id]: definition });\n actions[definition.id] = definition;\n };\n\n // Remove a definition and unmount its live instances (revocation: a\n // removed action is gone, not zombie-running). Other instances keep their\n // stack positions; when a canvas's top was removed, the new top resumes.\n // Unknown ids are a no-op; fragments are untouched.\n const removeAction = (actionId: string): void => {\n guard();\n if (actions[actionId] === undefined) return;\n delete actions[actionId];\n // Revocation reaches the journal too, or back would hand the action back.\n journal.forgetAction(actionId);\n let changed = false;\n for (const [, canvas] of canvases) {\n if (!canvas.stack.some((inst) => inst.definitionId === actionId)) continue;\n const previousTop = canvas.peek();\n for (const inst of canvas.clearStack()) {\n if (inst.definitionId === actionId) ops.unmountInstance(inst.id);\n else canvas.pushInstance(inst);\n }\n if (canvas.peek() !== previousTop) ops.resumeTop(canvas);\n changed = true;\n }\n if (changed) fireState();\n };\n\n const getFragment = (fragmentId: string): ActionFragment => {\n const frag = fragments[fragmentId];\n if (frag === undefined) throw new UnknownFragmentError(`Unknown fragment: ${fragmentId}`, { fragmentId });\n return frag;\n };\n\n const registerFragment = (fragment: ActionFragment): void => {\n guard();\n if (fragment.id === undefined) throw new UnknownFragmentError('Fragment is missing an id', { fragmentId: '' });\n validateFragments({ [fragment.id]: fragment });\n fragments[fragment.id] = fragment;\n };\n\n // Resolve an action id to its (optionally fragment-composed) definition. The\n // effect's `with: [...]` names fragments to merge in; the action wins on\n // conflict. See composeAction.\n const resolveDefinition = (actionId: string, fragmentIds?: string[]): ActionDefinition => {\n const def = getDefinition(actionId);\n if (fragmentIds === undefined || fragmentIds.length === 0) return def;\n return composeAction(def, fragmentIds.map(getFragment));\n };\n\n // The active screen last announced per canvas — see navigatedChannel. Absent\n // and `undefined` mean the same thing (nothing was open), which is why an\n // empty canvas at build announces nothing: there is no move to report.\n const announced = new Map<string, string | undefined>();\n let announcing = false;\n\n // DEFERRED AND COALESCED, for two reasons. A listener woken mid-mutation runs\n // steps against a half-moved shell, which is the re-entrancy `emit` already\n // defers to avoid. And a burst — a resetTo is a clear and a push — should say\n // where the canvas ENDED, once, not narrate every position it passed through.\n // The message is state, not history.\n const announceNavigation = (): void => {\n if (announcing || disposed) return;\n announcing = true;\n queueMicrotask(() => {\n announcing = false;\n if (disposed) return;\n for (const [canvasId, canvas] of canvases) {\n const active = canvas.peek();\n if (announced.get(canvasId) === active?.id) continue;\n announced.set(canvasId, active?.id);\n const message: NavigatedMessage =\n active === undefined\n ? { canvas: canvasId }\n : { canvas: canvasId, action: active.definitionId, instance: active.id };\n messageBus.publish(navigatedChannel(canvasId), message);\n }\n });\n };\n\n const fireState = (): void => {\n if (disposed) return;\n const out: Record<string, CanvasState> = {};\n for (const [cid, c] of canvases) out[cid] = snapshotCanvas(c);\n const snapshot: StateSnapshot = { canvases: out };\n telemetry.fireStateChange(snapshot);\n announceNavigation();\n };\n\n // The canvas as the journal has to remember it: every instance standing on it\n // paired with what would build it again. Taken BEFORE the navigation that\n // displaces it — a position recorded afterwards is the place you already are.\n const positionOf = (canvasId: string): readonly HistoryFrame[] => {\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return [];\n return canvas.stack.map((inst) => {\n const birth = births.get(inst.id);\n return {\n instance: inst.id,\n action: birth?.action ?? inst.definitionId,\n ...(birth?.input === undefined ? {} : { input: birth.input }),\n ...(birth?.with === undefined ? {} : { with: birth.with }),\n };\n });\n };\n\n const record = (canvasId: string): void => journal.record(canvasId, positionOf(canvasId));\n\n const navigationHandler = createNavigationHandler({\n push: (cid, aid, input, frags) => push(cid, aid, input, frags),\n pop: (cid) => pop(cid),\n replace: (cid, aid, input, frags) => replace(cid, aid, input, frags),\n clear: (cid) => clear(cid),\n // ONE position, then both halves — see ShellNavOps.resetTo. The record is\n // taken outside the mute so the deck being thrown away is what back returns\n // to; the calls inside it record nothing of their own.\n resetTo: (cid, aid, input, frags) => {\n record(cid);\n journal.mute(() => {\n clear(cid);\n push(cid, aid, input, frags);\n });\n },\n popTo: (cid, iid) => popTo(cid, iid),\n removeInstance: (cid, iid) => removeInstance(cid, iid),\n // ONE movement, like resetTo: the position before it is what back returns\n // to — recorded only when something actually moved, so a reconcile that\n // found the canvas already right leaves no empty step in history. Rows\n // naming an action this shell does not have are skipped: ungranted is\n // absent, as an ungranted `initial` candidate is.\n reconcile: (cid, desired, options) => {\n const before = positionOf(cid);\n const known = desired\n .filter((entry) => actions[entry.actionId] !== undefined)\n .map((entry) => (options.with === undefined ? entry : { ...entry, with: options.with }));\n const result = journal.mute(() =>\n reconcileCanvas(shell, cid, known, {\n origin: options.origin,\n ...(options.own === undefined ? {} : { own: options.own }),\n definitionOf: (actionId) => actions[actionId],\n }),\n );\n if (result.changed) journal.record(cid, before);\n },\n });\n\n const buildRuntime = createRuntimeFactory({\n eventBus,\n messageBus,\n layoutStore,\n registry: componentRegistry,\n ...(config.transform === undefined ? {} : { transform: config.transform }),\n ...(config.fetch === undefined ? {} : { fetch: config.fetch }),\n ...(config.functions === undefined ? {} : { functions: config.functions }),\n ...(config.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: config.endpointTimeoutMs }),\n strict,\n ...(config.onError === undefined ? {} : { onError: config.onError }),\n i18n: language,\n instanceIdFn,\n onNavigate: (cid, effect) => navigationHandler(cid, effect),\n // Every endpoint call an action makes flows to telemetry — the shell's one\n // observability surface (state, data, and now endpoints all land here).\n onEndpoint: (event) => telemetry.fireEndpoint(event),\n });\n\n const spawn = (\n canvasId: string,\n definition: ActionDefinition,\n input: Record<string, unknown> | undefined,\n ): ActionRuntime => {\n const runtime = buildRuntime(canvasId, definition, input);\n const instId = runtime.instance.id;\n registry.register(runtime, (data) => {\n if (disposed) return;\n telemetry.fireDataChange({ instanceId: instId, canvasId: runtime.instance.canvasId, data });\n });\n runtime.mount(input).catch(handleLifecycleRejection);\n return runtime;\n };\n\n const push = (\n canvasId: string,\n actionId: string,\n input?: Record<string, unknown>,\n fragmentIds?: string[],\n options?: PushOptions,\n ): string => {\n guard();\n if (options?.history !== false) record(canvasId);\n const canvas = getCanvas(canvasId);\n const definition = resolveDefinition(actionId, fragmentIds);\n // A list canvas keeps its existing cards live; only a stack suspends the top.\n if (!listCanvases.has(canvasId)) ops.suspendTop(canvas);\n const runtime = spawn(canvasId, definition, input);\n canvas.pushInstance(runtime.instance);\n births.set(runtime.instance.id, {\n action: actionId,\n ...(input === undefined ? {} : { input }),\n ...(fragmentIds === undefined ? {} : { with: fragmentIds }),\n });\n if (options?.origin !== undefined) origins.set(runtime.instance.id, options.origin);\n fireState();\n return runtime.instance.id;\n };\n\n // Remove ONE instance anywhere in a canvas's stack. On a list canvas this is\n // a card dismissing itself (its X fires `removeSelf`); on a stack, removing\n // the top resumes the one beneath, like `pop`. A no-op if the instance is not\n // in the canvas (a stale close can't clear the wrong card).\n const removeInstance = (canvasId: string, instanceId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n if (!canvas.stack.some((i) => i.id === instanceId)) return;\n const previousTop = canvas.peek();\n for (const inst of canvas.clearStack()) {\n if (inst.id === instanceId) ops.unmountInstance(inst.id);\n else canvas.pushInstance(inst);\n }\n journal.consume(canvasId);\n // Stack canvases resume a newly-exposed top; list canvases never suspended,\n // so there is nothing to resume.\n if (!listCanvases.has(canvasId) && canvas.peek() !== previousTop) ops.resumeTop(canvas);\n fireState();\n };\n\n const pop = (canvasId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n const top = canvas.popInstance();\n if (top === undefined) return;\n ops.unmountInstance(top.id);\n // Going back by hand spends a journal entry — see Journal.consume.\n journal.consume(canvasId);\n ops.resumeTop(canvas);\n fireState();\n };\n\n // Pop a canvas down to a given instance — unmount everything above it, then\n // resume the target once. A no-op if the instance isn't in this canvas's stack\n // (so a stale breadcrumb can't clear the canvas). Powers the breadcrumb jump.\n const popTo = (canvasId: string, instanceId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n if (!snapshotCanvas(canvas).stack.some((i) => i.id === instanceId)) return;\n let changed = false;\n for (;;) {\n const active = snapshotCanvas(canvas).active;\n if (active === undefined || active.id === instanceId) break;\n const top = canvas.popInstance();\n if (top === undefined) break;\n ops.unmountInstance(top.id);\n changed = true;\n }\n if (changed) {\n journal.consume(canvasId);\n ops.resumeTop(canvas);\n fireState();\n }\n };\n\n const replace = (\n canvasId: string,\n actionId: string,\n input?: Record<string, unknown>,\n fragmentIds?: string[],\n ): string => {\n guard();\n record(canvasId);\n const canvas = getCanvas(canvasId);\n const definition = resolveDefinition(actionId, fragmentIds);\n const old = canvas.popInstance();\n if (old !== undefined) ops.unmountInstance(old.id);\n const runtime = spawn(canvasId, definition, input);\n canvas.pushInstance(runtime.instance);\n births.set(runtime.instance.id, {\n action: actionId,\n ...(input === undefined ? {} : { input }),\n ...(fragmentIds === undefined ? {} : { with: fragmentIds }),\n });\n fireState();\n return runtime.instance.id;\n };\n\n const clear = (canvasId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n // RECORDED, not consumed: emptying a canvas is somewhere you went, not a\n // step you retraced, and back should put the deck back.\n if (canvas.stack.length > 0) record(canvasId);\n for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);\n fireState();\n };\n\n // ── BACK ────────────────────────────────────────────────────\n // Put one recorded position back. `false` means this entry had nothing left\n // to undo — the canvas is gone, or somebody already popped their own way to\n // exactly this — and `back` should walk on to the next one.\n const restore = (entry: HistoryEntry): boolean => {\n const canvas = canvases.get(entry.canvas);\n if (canvas === undefined) return false;\n\n // How far up the recorded position the LIVE instances still agree with it.\n // Matched by instance id and nothing else: an instance is either the very\n // one recorded — kept, with everything it holds — or it is not, and comes\n // back derived. There is no third case worth guessing at, because two\n // instances of one action with equal input are not interchangeable, as any\n // half-filled form proves.\n let common = 0;\n while (\n common < canvas.stack.length &&\n common < entry.stack.length &&\n canvas.stack[common]?.id === entry.stack[common]?.instance\n ) {\n common += 1;\n }\n if (common === canvas.stack.length && common === entry.stack.length) return false;\n\n // Anything re-derived has to name an action this shell still serves. It\n // normally does — a revoked action takes its entries with it — and when it\n // does not, the whole entry is refused: a position half put back is a screen\n // nobody authored.\n for (let i = common; i < entry.stack.length; i += 1) {\n const frame = entry.stack[i];\n if (frame !== undefined && actions[frame.action] === undefined) return false;\n }\n\n journal.mute(() => {\n const standing = canvas.clearStack();\n for (let i = 0; i < standing.length; i += 1) {\n const inst = standing[i];\n if (inst === undefined) continue;\n if (i < common) canvas.pushInstance(inst);\n else ops.unmountInstance(inst.id);\n }\n if (common === entry.stack.length) {\n // Nothing to build — the newly exposed top resumes, exactly as on a pop.\n if (!listCanvases.has(entry.canvas)) ops.resumeTop(canvas);\n return;\n }\n for (let i = common; i < entry.stack.length; i += 1) {\n const frame = entry.stack[i];\n if (frame === undefined) continue;\n push(entry.canvas, frame.action, frame.input, frame.with);\n }\n });\n fireState();\n return true;\n };\n\n const back = (): boolean => {\n if (disposed) return false;\n guardNoPendingStrictError();\n // Newest first, past the entries that have nothing to say. Terminates\n // because every pass removes one — an empty journal is a shell standing on\n // its landing screen, and the honest answer there is `false`.\n for (;;) {\n const entry = journal.take();\n if (entry === undefined) return false;\n if (restore(entry)) return true;\n }\n };\n\n // Push a canvas's `initial` action(s), if any. Shared by createShell's seeding\n // loop and addCanvas, so both seed identically.\n const seedCanvas = (cfg: CanvasConfig): void => {\n if (cfg.initial === undefined) return;\n const seeds = Array.isArray(cfg.initial) ? cfg.initial : [cfg.initial];\n // MUTED: a seed is the floor, not a place somebody navigated to. Recorded,\n // it would make `back` able to empty the landing screen — the one move a\n // back button must never have.\n journal.mute(() => {\n for (const seed of seeds) {\n if (typeof seed === 'string') push(cfg.id, seed);\n else push(cfg.id, seed.action, seed.input, seed.with);\n }\n });\n };\n\n const addCanvas = (cfg: CanvasConfig): void => {\n guard();\n if (canvases.has(cfg.id)) return;\n canvases.set(cfg.id, createCanvas(cfg.id));\n if (cfg.actionLayout !== undefined) actionLayouts.set(cfg.id, cfg.actionLayout);\n if (cfg.mode === 'list') listCanvases.add(cfg.id);\n canvasOrder.push(cfg.id);\n seedCanvas(cfg);\n fireState();\n };\n\n const removeCanvas = (canvasId: string): void => {\n if (disposed) return;\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return;\n for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);\n canvases.delete(canvasId);\n journal.forgetCanvas(canvasId);\n // Or a canvas re-added under the same id would be silently held to the\n // position its predecessor last announced.\n announced.delete(canvasId);\n actionLayouts.delete(canvasId);\n listCanvases.delete(canvasId);\n const index = canvasOrder.indexOf(canvasId);\n if (index >= 0) canvasOrder.splice(index, 1);\n fireState();\n };\n\n const setCanvasLayout = (layout: LayoutNode | string): void => {\n guard();\n canvasLayout = layout;\n fireState();\n };\n\n // Swap the target of a LayoutRef. The frame (canvasLayout) embeds\n // `{ ref: id }` placeholders for dynamic regions; this replaces what one\n // resolves to and re-renders. The frame/chrome itself is never touched, so\n // a swap can't remove the sidebar/topbar — they live in the frame, not the\n // ref. This is the hook an LLM/agent uses to hot-swap a region's layout.\n const setLayout = (refId: string, layout: LayoutNode): void => {\n guard();\n layoutStore.set(refId, layout);\n fireState();\n };\n\n // Swap the book. Every tree this shell renders from here on wears the new\n // words, including the instances already mounted — they ask for the book at\n // render rather than holding one from spawn, which is the whole reason\n // `i18n` is a function and not a value.\n //\n // A state change, not a rebuild: the words are the only thing that moved, so\n // canvases keep their stacks and instances keep their data. An application\n // whose SERVER-derived text was composed in the old language (a greeting, a\n // seeded label) still needs its own rebuild — this reaches what nova renders,\n // and nova does not know what a host built before handing it over.\n const setPhrases = (next: Phrasebook | undefined): void => {\n guard();\n phrases = next;\n // A host may build first and find its book later. Handing one over is the\n // same declaration as naming one at build.\n if (next !== undefined) bearing = true;\n fireState();\n };\n\n const getPhrases = (): Phrasebook | undefined => phrases;\n\n const getCanvasState = (canvasId: string): CanvasState => {\n guardNoPendingStrictError();\n const canvas = canvases.get(canvasId);\n if (canvas === undefined) return { id: canvasId, stack: [], active: undefined };\n return snapshotCanvas(canvas);\n };\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n for (const [, canvas] of canvases) {\n for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);\n }\n registry.disposeAll();\n canvases.clear();\n telemetry.clear();\n };\n\n const getRuntime = (iid: string): PublicActionRuntime | undefined => registry.get(iid);\n const onStateChange = (h: StateChangeHandler): Unsubscribe => telemetry.onStateChange(h);\n const onDataChange = (h: DataChangeHandler): Unsubscribe => telemetry.onDataChange(h);\n const onEndpoint = (h: EndpointHandler): Unsubscribe => telemetry.onEndpoint(h);\n\n // The shell's definition of \"this canvas changed\": stack length, item\n // ids/statuses, or the active instance. Snapshot objects are rebuilt on\n // every state change, so identity can't be used.\n const sameCanvasState = (a: CanvasState, b: CanvasState): boolean => {\n if (a.stack.length !== b.stack.length) return false;\n if (a.active?.id !== b.active?.id) return false;\n for (let i = 0; i < a.stack.length; i += 1) {\n const aItem = a.stack[i];\n const bItem = b.stack[i];\n if (aItem === undefined || bItem === undefined) return false;\n if (aItem.id !== bItem.id || aItem.status !== bItem.status) return false;\n }\n return true;\n };\n\n const onCanvasChange = (canvasId: string, handler: CanvasChangeHandler): Unsubscribe => {\n let prev = getCanvasState(canvasId);\n return telemetry.onStateChange(() => {\n const next = getCanvasState(canvasId);\n if (sameCanvasState(prev, next)) return;\n prev = next;\n handler(next);\n });\n };\n\n const getState = (): StateSnapshot => {\n const out: Record<string, CanvasState> = {};\n for (const [cid, c] of canvases) out[cid] = snapshotCanvas(c);\n return { canvases: out };\n };\n\n const renderLayoutOrRef = (\n layout: LayoutNode | string,\n data: Record<string, unknown>,\n ): RenderNode[] => {\n const resolved = typeof layout === 'string' ? layoutStore.get(layout) : layout;\n if (resolved === undefined) return [];\n const current = language();\n return renderLayoutFromStore(\n resolved,\n { get: () => data },\n {\n store: layoutStore,\n registry: componentRegistry,\n strict,\n ...(config.onError === undefined ? {} : { onError: config.onError }),\n ...(current?.phrases === undefined ? {} : { phrases: current.phrases }),\n ...(current?.phraseKeys === undefined ? {} : { phraseKeys: current.phraseKeys }),\n ...(current?.onPhraseMiss === undefined ? {} : { onPhraseMiss: current.onPhraseMiss }),\n },\n );\n };\n\n const getShellRenderTree = (): RenderNode[] => {\n const canvasList: CanvasState[] = [];\n for (const cid of canvasOrder) {\n const c = canvases.get(cid);\n canvasList.push(c === undefined ? { id: cid, stack: [], active: undefined } : snapshotCanvas(c));\n }\n return renderLayoutOrRef(canvasLayout ?? DEFAULT_SHELL_LAYOUT, { canvases: canvasList });\n };\n\n // An instance's display label: the (composed) definition's `title` resolvable\n // evaluated against the instance's own live data, falling back to `name` then\n // the action id. Surfaced as `instance.title` on the actionLayout scope so\n // stack-nav chrome (crumbs, tabs) can label without reaching into raw data.\n const titleOf = (instance: ActionInstance): string => {\n const def = registry.get(instance.id)?.definition ?? actions[instance.definitionId];\n if (def?.title !== undefined) {\n const resolved = resolve(def.title, createScopeChain(instance.data));\n if (resolved !== undefined && resolved !== null && resolved !== '') return String(resolved);\n }\n return def?.name ?? instance.definitionId;\n };\n\n const getCanvasRenderTree = (canvasId: string): RenderNode[] => {\n const canvas = canvases.get(canvasId);\n const state: CanvasState =\n canvas === undefined ? { id: canvasId, stack: [], active: undefined } : snapshotCanvas(canvas);\n const instances = state.stack.map((i) => ({ ...i, title: titleOf(i) }));\n const scope = {\n instances,\n active: instances.length === 0 ? undefined : instances[instances.length - 1],\n count: instances.length,\n };\n return renderLayoutOrRef(actionLayouts.get(canvasId) ?? DEFAULT_ACTION_LAYOUT, scope);\n };\n\n const dispatch = (event: Parameters<typeof eventBus.emit>[0]): void => {\n eventBus.emit(event);\n };\n\n const publish = (channel: string, payload?: unknown): void => {\n messageBus.publish(channel, payload);\n };\n\n const shell: Shell = {\n id,\n registry: componentRegistry,\n layoutStore,\n push,\n originOf: (instanceId) => origins.get(instanceId),\n pop,\n popTo,\n removeInstance,\n replace,\n clear,\n back,\n registerAction,\n removeAction,\n registerFragment,\n addCanvas,\n removeCanvas,\n setCanvasLayout,\n setPhrases,\n getPhrases,\n setLayout,\n getCanvasState,\n getRuntime,\n getState,\n getShellRenderTree,\n getCanvasRenderTree,\n flattenRenderTree: (tree) => flattenRenderTree(tree, shell),\n dispatch,\n publish,\n onStateChange,\n onDataChange,\n onEndpoint,\n onCanvasChange,\n dispose,\n };\n rememberShellRegistry(shell, registry);\n\n // Seed canvases whose config declares an `initial` action (or list). Done\n // after the shell object is assembled so `push` works exactly as it would\n // for a consumer calling push themselves.\n for (const cfg of config.canvases) seedCanvas(cfg);\n\n return shell;\n};\n","import { HEAD_LINK_NAME, HEAD_META_NAME, HEAD_NAME, HEAD_SCRIPT_NAME, HEAD_TITLE_NAME, headKeyOf } from '../layout/head';\nimport type { HeadElement } from '../layout/head';\nimport type { RenderNode } from '../layout';\nimport type { RenderApi } from './types';\nimport { ACTION_SLOT_NAME, CANVAS_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// The head a screen has, read off its render tree.\n//\n// The frame is walked in the order it is drawn, into each canvas where its\n// slot stands and into each instance on it, and every `nova:head` it meets\n// gives its elements in turn. A screen can hold more than one head — the\n// shell's chrome says what holds on every screen, an action says its own, a\n// dialog opens over a page. An element that says the same thing as an earlier\n// one (the title, a <meta> of that name) takes its place; anything else stands\n// beside what came before.\n//\n// What a head may not hold is refused here, once, for every writer: the\n// element is left out and the reason is given. See ../layout/head.\n// ═══════════════════════════════════════════════════════════\n\nexport type ScreenHead = {\n // what the document's head is to hold, in the order the screen said it\n elements: HeadElement[];\n // the actions whose instances said any of it (none: only the shell's chrome did)\n actions: string[];\n // what a head held that it may not — left out, each with why\n refused: string[];\n};\n\ntype ComponentNode = Extract<RenderNode, { type: 'component' }>;\ntype Read = { element: HeadElement } | { refused: string } | undefined;\n\nconst ATTRIBUTE_NAME = /^[A-Za-z][A-Za-z0-9:._-]*$/;\n// a data block: a type no browser runs\nconst DATA_TYPE = /^application\\/([a-z0-9.-]+\\+)?json$/i;\n\n// A prop, as the attribute it is written as — or nothing, when it says nothing.\nconst written = (value: unknown): string | undefined => {\n if (typeof value === 'string') return value.trim() === '' ? undefined : value;\n if (typeof value === 'number') return String(value);\n return value === true ? '' : undefined;\n};\n\n// An element's attributes, from its props — or why it may not be written.\nconst attributesOf = (what: string, props: Record<string, unknown>, skip: readonly string[] = []): { attributes: Record<string, string> } | { refused: string } => {\n const attributes: Record<string, string> = {};\n for (const [name, value] of Object.entries(props)) {\n if (skip.includes(name)) continue;\n if (!ATTRIBUTE_NAME.test(name)) return { refused: `${what}: \"${name}\" is not an attribute’s name` };\n if (/^on/i.test(name)) return { refused: `${what}: \\`${name}\\` is a handler, and a layout does not run` };\n const text = written(value);\n if (text !== undefined) attributes[name] = text;\n }\n return { attributes };\n};\n\nconst has = (attributes: Record<string, string>, name: string): boolean => Object.keys(attributes).some((key) => key.toLowerCase() === name);\nconst valueOf = (attributes: Record<string, string>, name: string): string => Object.entries(attributes).find(([key]) => key.toLowerCase() === name)?.[1] ?? '';\n\nconst textOf = (nodes: readonly RenderNode[]): string =>\n nodes.map((node) => (node.type === 'text' ? node.value : node.type === 'fragment' ? textOf(node.children) : '')).join('');\n\nconst titleOf = (node: ComponentNode): Read => {\n const text = textOf(node.children).trim();\n return text === '' ? undefined : { element: { tag: 'title', attributes: {}, text } };\n};\n\nconst metaOf = (node: ComponentNode): Read => {\n const read = attributesOf(HEAD_META_NAME, node.props);\n if ('refused' in read) return read;\n if (has(read.attributes, 'http-equiv')) return { refused: `${HEAD_META_NAME}: \\`http-equiv\\` instructs the browser, and a layout does not` };\n // nothing to say yet: its value is not answered\n return has(read.attributes, 'content') ? { element: { tag: 'meta', attributes: read.attributes } } : undefined;\n};\n\nconst linkOf = (node: ComponentNode): Read => {\n const read = attributesOf(HEAD_LINK_NAME, node.props);\n if ('refused' in read) return read;\n if (valueOf(read.attributes, 'rel').toLowerCase().split(/\\s+/).includes('stylesheet')) return { refused: `${HEAD_LINK_NAME}: a stylesheet styles the page, and a layout does not` };\n return has(read.attributes, 'href') ? { element: { tag: 'link', attributes: read.attributes } } : undefined;\n};\n\nconst scriptOf = (node: ComponentNode): Read => {\n const read = attributesOf(HEAD_SCRIPT_NAME, node.props, ['data']);\n if ('refused' in read) return read;\n if (has(read.attributes, 'src')) return { refused: `${HEAD_SCRIPT_NAME}: a script with a \\`src\\` runs, and a layout does not` };\n const type = valueOf(read.attributes, 'type');\n if (!DATA_TYPE.test(type)) return { refused: `${HEAD_SCRIPT_NAME}: only a data block may be written (a JSON \\`type\\`), and \"${type}\" is not one` };\n const data = node.props['data'];\n if (data === undefined || data === null || data === '') return undefined;\n return { element: { tag: 'script', attributes: read.attributes, text: JSON.stringify(data) } };\n};\n\nconst READERS: Record<string, (node: ComponentNode) => Read> = {\n [HEAD_TITLE_NAME]: titleOf,\n [HEAD_META_NAME]: metaOf,\n [HEAD_LINK_NAME]: linkOf,\n [HEAD_SCRIPT_NAME]: scriptOf,\n};\n\nexport const isHeadNode = (node: RenderNode): boolean => node.type === 'component' && node.name === HEAD_NAME;\n\nexport const headOf = (api: Pick<RenderApi, 'frame' | 'canvasTree'>): ScreenHead | undefined => {\n let heads = 0;\n const said: { element: HeadElement; action: string | undefined }[] = [];\n const refused: string[] = [];\n // a canvas whose own tree names it again would never end\n const open = new Set<string>();\n\n const hold = (nodes: readonly RenderNode[], action: string | undefined): void => {\n for (const node of nodes) {\n if (node.type === 'fragment') {\n hold(node.children, action);\n continue;\n }\n if (node.type === 'error') {\n refused.push(`${HEAD_NAME}: ${node.message}`);\n continue;\n }\n // text between a head's elements is nothing\n if (node.type !== 'component') continue;\n const read = READERS[node.name];\n if (read === undefined) {\n refused.push(`${HEAD_NAME}: \"${node.name}\" is not something a head holds`);\n continue;\n }\n const found = read(node);\n if (found === undefined) continue;\n if ('refused' in found) {\n refused.push(found.refused);\n continue;\n }\n const key = headKeyOf(found.element);\n const earlier = key === undefined ? -1 : said.findIndex((other) => headKeyOf(other.element) === key);\n if (earlier >= 0) said.splice(earlier, 1);\n said.push({ element: found.element, action });\n }\n };\n\n const walk = (nodes: readonly RenderNode[], action: string | undefined): void => {\n for (const node of nodes) {\n if (node.type === 'fragment') {\n walk(node.children, action);\n continue;\n }\n if (node.type !== 'component') continue;\n if (node.name === HEAD_NAME) {\n heads += 1;\n hold(node.children, action);\n continue;\n }\n if (node.name === CANVAS_SLOT_NAME) {\n const canvasId = node.props['canvasId'];\n if (typeof canvasId !== 'string' || canvasId === '' || open.has(canvasId)) continue;\n open.add(canvasId);\n walk(api.canvasTree(canvasId), undefined);\n open.delete(canvasId);\n continue;\n }\n const definitionId = node.name === ACTION_SLOT_NAME ? node.props['definitionId'] : undefined;\n walk(node.children, typeof definitionId === 'string' ? definitionId : action);\n }\n };\n\n walk(api.frame(), undefined);\n if (heads === 0) return undefined;\n const actions = [...new Set(said.flatMap((one) => (one.action === undefined ? [] : [one.action])))];\n return { elements: said.map((one) => one.element), actions, refused };\n};\n","import type { RenderNode } from '../layout';\nimport type { RenderApi, Shell } from './types';\nimport { isHeadNode } from './head';\nimport { ACTION_SLOT_NAME } from './slot-names';\n\n// ═══════════════════════════════════════════════════════════\n// A shell, as something an adapter draws.\n//\n// Every adapter that draws a SERVED screen draws it through `RenderApi` — the\n// frame, a tree per canvas, events up, messages across — and has always been\n// handed one by a transport (moss's socket wire). A shell that lives in the\n// same process as its adapter is the other case that type was written for, and\n// this is it: the shell's own trees, read as they stand, and its own dispatch.\n// The DOM and TTY adapters draw a local shell through this exactly as they draw\n// a remote one; nothing about them knows the difference.\n//\n// It is also what makes a shell DRAWABLE AHEAD OF TIME. A build runs the app's\n// own boot, waits for the screen to be whole (`shellSettled`), and has an\n// adapter draw this view to markup; the browser runs the same boot and draws\n// the same view over that markup. Where the shell lives was never the\n// adapter's business.\n// ═══════════════════════════════════════════════════════════\n\nexport type ShellView = {\n api: RenderApi;\n // Called after the shell changed — coalesced, so a burst of changes (a press\n // that sets three keys) is one call. Returns the unsubscribe.\n subscribe: (listener: () => void) => () => void;\n};\n\n// NO VISIBLE CONTENT IS AN EMPTY TREE. A canvas whose layout renders nothing but\n// empty text and empty wrappers is handed to an adapter as `[]`, so an adapter\n// collapses the chrome around it on `length` alone, knowing nothing about node\n// shapes. An ActionSlot marker is a boundary, not content — what is inside it\n// decides — and a head is the document's, not something the screen shows.\n// One rule for a canvas that is served and one that is local, so a frame looks\n// the same over both.\nexport const hasVisibleContent = (nodes: readonly RenderNode[]): boolean =>\n nodes.some((node) => {\n if (node.type === 'text') return node.value !== '';\n if (node.type === 'fragment') return hasVisibleContent(node.children);\n if (node.type === 'component' && node.name === ACTION_SLOT_NAME) return hasVisibleContent(node.children);\n if (isHeadNode(node)) return false;\n return true;\n });\n\n// One canvas, as an adapter is handed it.\nexport const canvasTreeOf = (shell: Shell, canvasId: string): RenderNode[] => {\n const tree = shell.flattenRenderTree(shell.getCanvasRenderTree(canvasId));\n return hasVisibleContent(tree) ? tree : [];\n};\n\nexport const shellView = (shell: Shell): ShellView => ({\n api: {\n frame: () => shell.getShellRenderTree(),\n canvasTree: (canvasId) => canvasTreeOf(shell, canvasId),\n // An event that names no origin belongs to the canvas's ACTIVE instance — on\n // a card deck that is the only one drawn. One that names its own (an\n // adapter stamps it at the instance boundary, `scopeDispatch`) keeps it. A\n // canvas with nothing mounted dispatches unstamped.\n dispatch: (canvasId, event) => {\n const active = shell.getState().canvases[canvasId]?.active;\n shell.dispatch(event.origin === undefined && active !== undefined ? { ...event, origin: active.id } : event);\n },\n publish: (channel, payload) => shell.publish(channel, payload),\n },\n subscribe: (listener) => {\n let pending = false;\n let stopped = false;\n const changed = (): void => {\n if (pending || stopped) return;\n pending = true;\n queueMicrotask(() => {\n pending = false;\n if (!stopped) listener();\n });\n };\n const offState = shell.onStateChange(changed);\n const offData = shell.onDataChange(changed);\n return () => {\n stopped = true;\n offState();\n offData();\n };\n },\n});\n\n// THE FIRST SCREEN IS WHOLE. An instance is `initializing` until its mount hook\n// — the loads, and whatever they chain to — has been awaited, so \"nothing is\n// initializing\" is the shell saying its opening screen is complete. A mount can\n// open another action, which starts initializing in turn, so the question is\n// asked again on every change and answered true only when it still holds a\n// macrotask later.\n//\n// Resolves `false` when `waitMs` runs out first: the screen is then drawn as it\n// stands, with whatever is still loading drawn as loading. Default 300ms — a\n// page should not hang on one slow endpoint.\nexport const DEFAULT_SETTLE_WAIT_MS = 300;\n\nexport const shellSettled = async (shell: Shell, options: { waitMs?: number; stopped?: () => boolean } = {}): Promise<boolean> => {\n const waitMs = options.waitMs ?? DEFAULT_SETTLE_WAIT_MS;\n const mounting = (): boolean =>\n Object.values(shell.getState().canvases).some((canvas) => canvas.stack.some((instance) => instance.status === 'initializing'));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), waitMs);\n });\n const quiet = (async (): Promise<boolean> => {\n for (;;) {\n if (options.stopped?.() === true) return false;\n if (!mounting()) {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n if (!mounting()) return true;\n }\n await new Promise<void>((resolve) => {\n const off = shell.onStateChange(() => {\n off();\n resolve();\n });\n // a change that lands with no notification must not leave this waiting\n setTimeout(() => {\n off();\n resolve();\n }, 10);\n });\n }\n })();\n const settled = await Promise.race([quiet, deadline]);\n clearTimeout(timer);\n return settled;\n};\n"]}
|