@mgamadeus/ddd-agents 0.1.0-alpha.25 → 0.1.0-alpha.26

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.
Files changed (23) hide show
  1. package/dist/chat.js +6 -6
  2. package/dist/chunks/{ConversationMessageInputComposerWidgets-BxyaFBA6.js → ConversationMessageInputComposerWidgets-CzQnpW0h.js} +4 -4
  3. package/dist/chunks/{ConversationMessageInputComposerWidgets-BxyaFBA6.js.map → ConversationMessageInputComposerWidgets-CzQnpW0h.js.map} +1 -1
  4. package/dist/chunks/{WebSearchResultsConversationWidget-as3p5bHw.js → WebSearchResultsConversationWidget-tDhawe9f.js} +55 -50
  5. package/dist/chunks/{WebSearchResultsConversationWidget-as3p5bHw.js.map → WebSearchResultsConversationWidget-tDhawe9f.js.map} +1 -1
  6. package/dist/chunks/{canvas-reducers-Bfp_i7lc.js → canvas-reducers-BdIPZW_6.js} +2 -2
  7. package/dist/chunks/{canvas-reducers-Bfp_i7lc.js.map → canvas-reducers-BdIPZW_6.js.map} +1 -1
  8. package/dist/chunks/{canvasBodies-Cvu3l38p.js → canvasBodies-BiUt8MUG.js} +3 -3
  9. package/dist/chunks/{canvasBodies-Cvu3l38p.js.map → canvasBodies-BiUt8MUG.js.map} +1 -1
  10. package/dist/chunks/{widget-click-signal-sources-DulRkNvZ.js → widget-click-signal-sources-BR82QygL.js} +3 -3
  11. package/dist/chunks/{widget-click-signal-sources-DulRkNvZ.js.map → widget-click-signal-sources-BR82QygL.js.map} +1 -1
  12. package/dist/chunks/{widget-name-resolver-BGN3HpoG.js → widget-name-resolver-BaxKaRa3.js} +2 -2
  13. package/dist/chunks/{widget-name-resolver-BGN3HpoG.js.map → widget-name-resolver-BaxKaRa3.js.map} +1 -1
  14. package/dist/client-testing.js +3 -3
  15. package/dist/image-render.js +4 -4
  16. package/dist/index.js +3 -3
  17. package/dist/kit.js +2 -2
  18. package/dist/preview.js +5 -5
  19. package/dist/renderer.js +7 -7
  20. package/dist/types/entries/widgets.d.ts +1 -0
  21. package/dist/widgets.js +34 -32
  22. package/package.json +1 -1
  23. package/public-api.json +2 -0
@@ -1 +1 @@
1
- {"version":3,"file":"widget-name-resolver-BGN3HpoG.js","sources":["../../src/renderer/widget-fence-syntax.ts","../../src/renderer/canvas/entity-detail-instance.ts","../../src/renderer/widget-tree/composed-node-schema.ts","../../src/renderer/widget-tree/bounded-json.ts","../../src/renderer/widget-tree/composed-view-tree.ts","../../src/renderer/widget-tree/expression/parse-expression.ts","../../src/renderer/widget-tree/expression/evaluate-expression.ts","../../src/renderer/widget-tree/use-composed-view-state.ts","../../src/renderer/widget-tree/resolve-composed-view-values.ts","../../src/renderer/widget-tree/composed-view-data-sources.ts","../../src/kit/components/data/apex-chart-component.ts","../../src/kit/composed-view-tones.ts","../../src/kit/components/data/data-value-format.ts","../../src/kit/components/data/chart-model.ts","../../src/kit/components/data/data-tones.ts","../../src/kit/components/data/ChartBarRows/ChartBarRows.tsx","../../src/kit/components/data/ChartFunnelRows/ChartFunnelRows.tsx","../../src/kit/components/data/use-chart-palette.ts","../../src/kit/components/data/use-number-locale.ts","../../src/kit/components/data/DataFootnote/DataFootnote.tsx","../../src/kit/components/data/DataEmptyLine/DataEmptyLine.tsx","../../src/kit/components/data/use-report-data-node-status.ts","../../src/kit/components/data/Chart.composed.tsx","../../src/kit/components/data/Icon.composed.tsx","../../src/kit/components/layout/layout-nesting-context.ts","../../src/kit/components/data/KpiMeter/KpiMeter.tsx","../../src/kit/components/data/KpiToneAccent/KpiToneAccent.tsx","../../src/kit/components/data/kpi-value-parts.ts","../../src/kit/components/data/KpiTile.composed.tsx","../../src/kit/components/data/data-containers.ts","../../src/kit/components/data/ListEntry/ListEntry.tsx","../../src/kit/components/data/List.composed.tsx","../../src/kit/components/data/ListItem.composed.tsx","../../src/kit/components/data/Repeat.composed.tsx","../../src/kit/components/data/table-columns.ts","../../src/kit/components/data/TableValue/TableValue.tsx","../../src/kit/components/data/Table.composed.tsx","../../src/kit/components/data/TableCell.composed.tsx","../../src/kit/components/data/TableRow.composed.tsx","../../src/renderer/ConversationWidgetErrorBoundary.tsx","../../src/renderer/_access/ConversationWidgetFeatureGate.tsx","../../src/kit/components/embedding/EmbeddedConversationWidget.tsx","../../src/kit/components/embedding/WidgetNode.composed.tsx","../../src/kit/components/entity/entity-link-target.ts","../../src/kit/components/entity/EntityLink.composed.tsx","../../src/kit/components/form/compose-form-signal.ts","../../src/kit/components/form/Form.composed.tsx","../../src/kit/components/inputs/shared/date-pattern-of-locale.ts","../../src/kit/components/inputs/shared/composed-input-values.ts","../../src/kit/components/inputs/Button.composed.tsx","../../src/kit/components/inputs/shared/ComposedInputField.tsx","../../src/kit/components/inputs/shared/use-composed-input-value.ts","../../src/kit/components/inputs/Checkbox.composed.tsx","../../src/kit/components/inputs/shared/ComposedInputFrozenValue.tsx","../../src/kit/components/inputs/shared/use-composed-input-language.ts","../../src/kit/components/inputs/DatePicker.composed.tsx","../../src/kit/components/inputs/Input.composed.tsx","../../src/kit/components/inputs/shared/use-report-missing-options.ts","../../src/kit/components/inputs/RadioGroup.composed.tsx","../../src/kit/components/inputs/Select.composed.tsx","../../src/kit/components/inputs/Slider.composed.tsx","../../src/kit/components/inputs/Tabs.composed.tsx","../../src/kit/components/inputs/Textarea.composed.tsx","../../src/kit/components/layout/layout-props.ts","../../src/kit/components/layout/Carousel.composed.tsx","../../src/kit/components/layout/Divider.composed.tsx","../../src/kit/components/layout/layout-gap-class.ts","../../src/kit/components/layout/Flow.composed.tsx","../../src/kit/components/layout/Grid.composed.tsx","../../src/kit/components/layout/Popover.composed.tsx","../../src/kit/components/layout/Pressable.composed.tsx","../../src/kit/components/layout/Quote.composed.tsx","../../src/kit/components/layout/Spacer.composed.tsx","../../src/kit/components/layout/Stack.composed.tsx","../../src/kit/components/layout/Surface.composed.tsx","../../src/kit/components/map/map-points.ts","../../src/kit/components/map/map-presentation-context.ts","../../src/renderer/widget-fence-json.ts","../../src/renderer/remarkWidgetFencePlugin.ts","../../src/renderer/canvas/find-widget-fences-in-markdown.ts","../../src/kit/components/map/map-full-screen-instance.ts","../../src/kit/components/map/MapPointMarker.tsx","../../src/kit/components/map/MapGoogleMap.tsx","../../src/kit/components/map/MapPointCard.tsx","../../src/kit/components/map/MapPointCarousel.tsx","../../src/kit/components/map/ComposedMapView.tsx","../../src/kit/components/map/use-google-maps-auth-failure.ts","../../src/kit/components/map/Map.composed.tsx","../../src/kit/components/media/MediaCaption.tsx","../../src/kit/components/media/use-image-load-state.ts","../../src/kit/components/media/MediaImageTile.tsx","../../src/kit/components/media/media-values.ts","../../src/kit/components/media/Image.composed.tsx","../../src/kit/components/media/ImageGroup.composed.tsx","../../src/kit/components/media/Video.composed.tsx","../../src/kit/components/media/video-card/video-card-values.ts","../../src/kit/components/media/video-card/VideoCard.composed.tsx","../../src/kit/components/rich/rich-libraries.ts","../../src/kit/components/rich/RichNodeFrame.tsx","../../src/kit/components/rich/Code.composed.tsx","../../src/kit/components/rich/sanitize-svg-markup.ts","../../src/kit/components/rich/diagram-theme.ts","../../src/kit/components/rich/Diagram.composed.tsx","../../src/kit/components/rich/Math.composed.tsx","../../src/kit/components/rich/Svg.composed.tsx","../../src/kit/components/text/Badge.composed.tsx","../../src/kit/components/text/Caption.composed.tsx","../../src/kit/components/text/shared/SiteFavicon.tsx","../../src/kit/components/text/Favicon.composed.tsx","../../src/kit/components/text/Label.composed.tsx","../../src/kit/components/text/Link.composed.tsx","../../src/kit/components/text/Markdown.composed.tsx","../../src/kit/components/text/shared/source-ref-entries.ts","../../src/kit/components/text/SourceRef.composed.tsx","../../src/kit/components/text/Text.composed.tsx","../../src/kit/components/text/Title.composed.tsx","../../src/kit/composed-view-components.ts","../../src/kit/ComposedViewSlotErrorBoundary.tsx","../../src/kit/hooks/use-debounced-value.ts","../../src/kit/ComposedViewDataSourceLoader.tsx","../../src/image-render/composed-view-data-times.ts","../../src/image-render/ComposedViewEmailDataTimes/ComposedViewEmailDataTimes.tsx","../../src/kit/ComposedViewRenderer.tsx","../../src/kit/ComposedViewConversationWidget.tsx","../../src/kit/ComposedViewConversationWidget.widget-registration.ts","../../src/widgets/ClockConversationWidget/ClockConversationWidget.widget-registration.ts","../../src/widgets/ConceptExplainerConversationWidget/ConceptExplainerConversationWidget.widget-registration.ts","../../src/widgets/CurrencyConverterConversationWidget/CurrencyConverterConversationWidget.widget-registration.ts","../../src/widgets/CustomVisualizationConversationWidget/CustomVisualizationConversationWidget.widget-registration.ts","../../src/widgets/EntityMentionConversationWidget/EntityMentionChip/EntityMentionChip.tsx","../../src/widgets/EntityMentionConversationWidget/EntityMentionComposerWidget.tsx","../../src/widgets/EntityMentionConversationWidget/EntityMentionConversationWidget.widget-registration.ts","../../src/widgets/WritingDraftConversationWidget/WritingDraftConversationWidget.widget-registration.ts","../../src/renderer/conversationWidgetRegistry.ts","../../src/renderer/widget-name-resolver.ts"],"sourcesContent":["/**\n * WIRE SYNTAX — the ```widget fence and bare `widget { … }` forms, as import-free constants.\n *\n * Deliberately a leaf module (no imports): `widget-name-resolver.ts` reads the registry at module scope, and the\n * registry pulls in every widget → AgentChat → the unrendered-widget detector, which builds a RegExp from\n * WIDGET_FENCE_LANG at ITS module scope. When a story loads a widget before anything has evaluated the resolver, that\n * chain reaches the detector while the resolver is still in its temporal dead zone (\"Cannot access 'WIDGET_FENCE_LANG'\n * before initialization\"). Keeping the syntax here, outside the registry cycle, makes evaluation order irrelevant.\n */\n\n/**\n * The ```widget fence's info-string language — the ONE definition every fence regex in the pipeline (the render\n * plugin's `node.lang` check, the malformed-fence repairer, the drawer-reset scan, the unrendered-widget detector)\n * is built from, so \"``` widget\" (a space before the lang — remark accepts it, the model sometimes writes it) is\n * recognized identically everywhere.\n */\nexport const WIDGET_FENCE_LANG = \"widget\";\n\n/**\n * A bare `widget { …json… }` line (no ```widget fence) that IS the whole paragraph — the fallback form the model\n * emits when it drops the backticks. Capture group 1 is the JSON object. Anchored to the whole paragraph text so a\n * prose mention (\"the widget shows…\") never matches. Shared by the render plugin (rewrites it) so there is one\n * definition of the bare form. The detector uses {@link BARE_WIDGET_LINE_GLOBAL} to scan a raw message the same way.\n */\nexport const BARE_WIDGET_PARAGRAPH = /^\\s*widget\\s*(\\{[\\s\\S]*\\})\\s*$/;\n\n/** The bare `widget { … }` form scanned line-by-line across a raw message string (detector side of {@link BARE_WIDGET_PARAGRAPH}). */\nexport const BARE_WIDGET_LINE_GLOBAL = /^[ \\t]*widget[ \\t]*(\\{.*\\})[ \\t]*$/gm;\n","/**\n * The instance id of the `entityDetail` canvas: one instance per entity — `entityDetail:<entityType>:<id>`.\n * The entity type is the backend resolver's `ENTITY_TYPE` (a lowercase-first name like `review`, `keyword`); the id is\n * the one the backend resolved the platform-minted reference to when it stored the row (`openEntity` action) — a string, as `EntityReferenceRow::$entityId` is (a row id, or an external id such as a place's). A\n * module that imports only the environment accessor, safe for every layer.\n */\nimport { getWidgetSelfHydrationKeyFieldName } from \"../../provider/environment\";\n\nexport interface EntityDetailTarget {\n entityType: string;\n entityId: string;\n}\n\n/** The entity an `openEntity` action opens: its type, its id and the key of its agent space when the entity names one. */\nexport interface OpenEntityActionTarget extends EntityDetailTarget {\n agentSpaceKey?: number;\n}\n\nconst ENTITY_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9]*$/;\n/** An entity id: letters, digits, `_`, `-`, `.` — a row id or an external id, never a path or markup. */\nconst ENTITY_ID_PATTERN = /^[A-Za-z0-9_.-]{1,256}$/;\nconst ENTITY_DETAIL_INSTANCE_ID = /^entityDetail:([a-zA-Z][a-zA-Z0-9]*):([A-Za-z0-9_.-]{1,256})$/;\n\nexport const canvasInstanceIdForEntityDetail = (target: EntityDetailTarget): string =>\n `entityDetail:${target.entityType}:${target.entityId}`;\n\n/** The entity an `entityDetail` instance id names, or undefined for another instance id. */\nexport const readEntityDetailInstanceId = (instanceId: string): EntityDetailTarget | undefined => {\n const match = ENTITY_DETAIL_INSTANCE_ID.exec(instanceId);\n return match ? { entityType: match[1], entityId: match[2] } : undefined;\n};\n\n/** The `refState` the backend writes on an `openEntity` action whose `ref` is bound to the current row. */\nexport const OPEN_ENTITY_REF_STATE_FROM_ROW = \"row\";\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Whether an `openEntity` action opens the entity of the row it fires in — its `ref` is a `{\"$item\": \"<key>\"}`\n * binding (`{\"$item\":\"entityRef\"}` inside a `Repeat`, a `Map` point, a list row), or the backend marked it\n * `refState: \"row\"` (`ComposedViewBindingResolution::STATE_FROM_ROW`). Such an action carries no entity of its own.\n */\nexport const isRowBoundOpenEntityAction = (action: Record<string, unknown>): boolean => {\n if (action.refState === OPEN_ENTITY_REF_STATE_FROM_ROW) return true;\n const reference = action.ref;\n if (!isPlainRecord(reference)) return false;\n const referenceKeys = Object.keys(reference);\n return (\n referenceKeys.length === 1 &&\n referenceKeys[0] === \"$item\" &&\n typeof reference.$item === \"string\" &&\n reference.$item !== \"\"\n );\n};\n\n/**\n * The entity of an `{entityType, entityId, <agent space key field>}` object (`EntityReferenceRow::toWireArray()`), or\n * undefined. The key sits under the block field the app declares (`AgentsEnvironment.widgetSelfHydrationKeyFieldName`).\n */\nconst readEntityDetailTargetOfEntity = (\n entity: unknown,\n): OpenEntityActionTarget | undefined => {\n if (!isPlainRecord(entity)) return undefined;\n const { entityType, entityId } = entity;\n const agentSpaceKey = entity[getWidgetSelfHydrationKeyFieldName()];\n if (typeof entityType !== \"string\" || !ENTITY_TYPE_PATTERN.test(entityType)) return undefined;\n const entityIdText = typeof entityId === \"number\" && Number.isInteger(entityId) ? String(entityId) : entityId;\n if (typeof entityIdText !== \"string\" || !ENTITY_ID_PATTERN.test(entityIdText)) return undefined;\n return {\n entityType,\n entityId: entityIdText,\n agentSpaceKey: typeof agentSpaceKey === \"number\" ? agentSpaceKey : undefined,\n };\n};\n\n/**\n * The entity an `openEntity` action opens, or undefined (the action then does nothing):\n * - an action with a platform-minted reference — `{\"type\":\"openEntity\", \"ref\":\"<toolCallId>:<entityType>:<index>\",\n * \"entity\":{\"entityType\",\"entityId\",<agent space key field>}}` — opens the `entity` the backend resolved it to; undefined while\n * the reference is unresolved;\n * - a row-bound action ({@link isRowBoundOpenEntityAction}) opens the `entity` of `currentRow`, the row of the item\n * scope the event fires in (each row of a resolved `$from` list carries its own `entityRef` + `entity`) — NEVER an\n * `entity` written on the action; undefined without a row or for a row without an entity.\n */\nexport const readOpenEntityActionTarget = (\n action: Record<string, unknown>,\n currentRow?: unknown,\n): OpenEntityActionTarget | undefined => {\n if (isRowBoundOpenEntityAction(action)) {\n return isPlainRecord(currentRow) ? readEntityDetailTargetOfEntity(currentRow.entity) : undefined;\n }\n return readEntityDetailTargetOfEntity(action.entity);\n};\n","import { getAgentsEnvironment } from \"../../provider/environment\";\nimport generatedComposedNodeSchema from \"./composed-node-schema.json\";\n\n/**\n * THE schema of the `ComposedView` kit, GENERATED by the backend from its classes (`ComposedViewNodeSchema.php`) —\n * never edited by hand. The committed file holds the types the package's own classes declare; an app adds the node\n * types, widgets, data sources and entity types its classes declare as its part (`AgentsEnvironment.composedNodeSchemaApplicationPart`,\n * generated by the app's backend the same way), and `getComposedNodeSchema()` reads both. The frontend parser, the\n * renderer and the evaluator read the node types, slots, props, size classes and budgets from here, so both sides apply\n * the same contract. `kit/_ComposedViewRenderer.spec.tsx` checks that every node type has a registered component and\n * every component a node type.\n */\n\nexport type ComposedNodeCategory = \"inline\" | \"block\" | \"data\" | \"media\" | \"input\" | \"layout\" | \"heavy\";\nexport type ComposedSizeClass = \"compact\" | \"regular\" | \"full\";\nexport type ComposedPropType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\" | \"event\";\n\nexport interface ComposedNodeSlotSchema {\n name: string;\n acceptsCategories: ComposedNodeCategory[];\n acceptsNodeTypes: string[];\n minChildren: number;\n maxChildren: number | null;\n sizeClass: ComposedSizeClass;\n description: string;\n /** The node prop the slot's size class follows (a Grid's `columns`); absent = the size class is fixed. */\n sizeClassFromProp?: string;\n /** Prop value (as text) → size class; a value not listed keeps `sizeClass`. */\n sizeClassesByPropValue?: Record<string, ComposedSizeClass>;\n /** A heavy node (a map, an embedded widget) may sit in the slot while it is compact. */\n acceptsHeavyWhenCompact?: boolean;\n}\n\nexport interface ComposedNodePropSchema {\n name: string;\n types: ComposedPropType[];\n isRequired: boolean;\n isBindable: boolean;\n allowedValues: Array<string | number | boolean> | null;\n description: string;\n}\n\n/**\n * The type's part in the source rule (`ComposedViewNode::buildSourcingSchemaArray()`): a data node that `needsSource`\n * and holds inline figures in its subtree — written rows in a `rowsProps` prop, a written figure in a `figureProps`\n * prop — needs its `source`, a source on a data node around it, or a node that `namesSources` in the tree.\n */\nexport interface ComposedNodeSourcingSchema {\n needsSource: boolean;\n namesSources: boolean;\n rowsProps: string[];\n figureProps: string[];\n}\n\nexport interface ComposedNodeTypeSchema {\n categories: ComposedNodeCategory[];\n providesItemScope: boolean;\n summary: string;\n props: ComposedNodePropSchema[];\n slots: ComposedNodeSlotSchema[];\n /** Absent for a type that takes no part in the source rule. */\n sourcing?: ComposedNodeSourcingSchema;\n /** The prop that lists the node's choices (`ComposedViewNode::OPTIONS_PROP_NAME`); absent without choices. */\n optionsProp?: string;\n /** The prop a node that repeats its children repeats over (`ComposedViewNode::ITEMS_PROP_NAME`). */\n itemsProp?: string;\n /** The node sends the state of the inputs inside it (`Form`); absent otherwise. */\n submitsInputs?: boolean;\n}\n\nexport interface ComposedViewBudgets {\n maxSourceBytes: number;\n maxNodes: number;\n maxDepth: number;\n maxStateKeys: number;\n maxStateStringLength: number;\n maxComputedExpressions: number;\n maxExpressionSourceLength: number;\n maxExpressionAstNodes: number;\n maxComputedDependencyDepth: number;\n maxOperationsPerUpdate: number;\n maxCollectionItems: number;\n maxAllocatedItemsPerEvaluation: number;\n maxRepeatRows: number;\n maxRenderedNodes: number;\n maxInlineArrayItems: number;\n maxInlineCells: number;\n maxTextLength: number;\n maxActions: number;\n maxInputUpdatesPerSecond: number;\n maxSourceRequestsPerTreePerMinute: number;\n}\n\nexport interface ComposedDataSourceSchema {\n summary: string;\n /** The client endpoint, method and path with `{param}` placeholders. */\n clientEndpoint: string;\n /** Where the rows sit in the response (`$` or `$.field`). */\n rowsPath: string;\n freshnessSeconds: number;\n params: Array<{ name: string; type: string; isRequired: boolean; description: string }>;\n columns: Array<{ name: string; type: string; description: string }>;\n}\n\nexport interface ComposedNodeSchema {\n version: number;\n budgets: ComposedViewBudgets;\n categories: ComposedNodeCategory[];\n sizeClasses: ComposedSizeClass[];\n actionTypes: string[];\n bindingKinds: string[];\n findingCodes: string[];\n /** The codes of findings that drop nothing — the block mounts with the code as a note. */\n noteFindingCodes: string[];\n nodeTypes: Record<string, ComposedNodeTypeSchema>;\n embeddableWidgets: Record<string, { sizeClass: ComposedSizeClass }>;\n /** Every registered widget type: a `Widget` node naming one its slot refuses is lifted out of the tree. */\n widgetTypes?: string[];\n dataSources: Record<string, ComposedDataSourceSchema>;\n entityTypes: string[];\n}\n\n/** The sections of the schema an app adds for the types its own classes declare; every section is optional. */\nexport type ComposedNodeSchemaApplicationPart = Partial<\n Pick<ComposedNodeSchema, \"nodeTypes\" | \"embeddableWidgets\" | \"widgetTypes\" | \"dataSources\" | \"entityTypes\">\n>;\n\n/**\n * The package's committed schema, typed: its budgets and rules and the types the package itself declares. A reader of\n * types an app may add (node types, widgets, data sources, entity types) reads `getComposedNodeSchema()`.\n */\nexport const composedNodeSchema = generatedComposedNodeSchema as unknown as ComposedNodeSchema;\n\n/** Byte order of the type names, as the backend sorts them. */\nconst compareTypeNames = (first: string, second: string): number => (first < second ? -1 : first > second ? 1 : 0);\n\nconst mergeSortedByTypeName = <Entry>(\n packageEntries: Record<string, Entry> | undefined,\n applicationEntries: Record<string, Entry> | undefined,\n): Record<string, Entry> =>\n Object.fromEntries(\n Object.entries({ ...packageEntries, ...applicationEntries }).sort(([firstType], [secondType]) =>\n compareTypeNames(firstType, secondType),\n ),\n );\n\nconst mergeTypeNames = (packageTypeNames: string[] | undefined, applicationTypeNames: string[] | undefined): string[] =>\n [...new Set([...(packageTypeNames ?? []), ...(applicationTypeNames ?? [])])].sort(compareTypeNames);\n\n/** A schema with an app's part added: every section holds both sides' types, sorted by type name. */\nexport const addComposedNodeSchemaApplicationPart = (\n schema: ComposedNodeSchema,\n applicationPart: ComposedNodeSchemaApplicationPart,\n): ComposedNodeSchema => ({\n ...schema,\n nodeTypes: mergeSortedByTypeName(schema.nodeTypes, applicationPart.nodeTypes),\n embeddableWidgets: mergeSortedByTypeName(schema.embeddableWidgets, applicationPart.embeddableWidgets),\n widgetTypes: mergeTypeNames(schema.widgetTypes, applicationPart.widgetTypes),\n dataSources: mergeSortedByTypeName(schema.dataSources, applicationPart.dataSources),\n entityTypes: mergeTypeNames(schema.entityTypes, applicationPart.entityTypes),\n});\n\nlet schemaWithApplicationPart:\n | { applicationPart: ComposedNodeSchemaApplicationPart; schema: ComposedNodeSchema }\n | undefined;\n\n/**\n * The schema the readers apply: the package's schema with the part the app declares\n * (`AgentsEnvironment.composedNodeSchemaApplicationPart`); the package's schema alone when the app declares none.\n * Read at call time — an app installs its environment after this module is loaded. The same object while the part is.\n */\nexport const getComposedNodeSchema = (): ComposedNodeSchema => {\n const applicationPart = getAgentsEnvironment().composedNodeSchemaApplicationPart;\n if (!applicationPart) return composedNodeSchema;\n if (schemaWithApplicationPart?.applicationPart !== applicationPart) {\n schemaWithApplicationPart = {\n applicationPart,\n schema: addComposedNodeSchemaApplicationPart(composedNodeSchema, applicationPart),\n };\n }\n return schemaWithApplicationPart.schema;\n};\n\n/**\n * The slot of one node — `ComposedViewNodeSlot::buildForNodeProps()`: its size class read from the node's\n * `sizeClassFromProp` (a Grid with `columns: 3` gives compact cells); the declaration itself otherwise.\n */\nexport const resolveComposedSlotForNodeProps = (\n slot: ComposedNodeSlotSchema,\n nodeProps: Record<string, unknown>,\n): ComposedNodeSlotSchema => {\n if (!slot.sizeClassFromProp || !slot.sizeClassesByPropValue) return slot;\n const propValue = Object.prototype.hasOwnProperty.call(nodeProps, slot.sizeClassFromProp)\n ? nodeProps[slot.sizeClassFromProp]\n : undefined;\n if (typeof propValue !== \"number\" && typeof propValue !== \"string\") return slot;\n const propValueKey = String(propValue);\n const sizeClassOfPropValue = Object.prototype.hasOwnProperty.call(slot.sizeClassesByPropValue, propValueKey)\n ? slot.sizeClassesByPropValue[propValueKey]\n : undefined;\n return sizeClassOfPropValue === undefined || sizeClassOfPropValue === slot.sizeClass\n ? slot\n : { ...slot, sizeClass: sizeClassOfPropValue };\n};\n\n/** Whether a size class fits a slot's size class (compact ≤ regular ≤ full). */\nexport const sizeClassFitsSlot = (sizeClass: ComposedSizeClass, slotSizeClass: ComposedSizeClass): boolean => {\n const order: ComposedSizeClass[] = [\"compact\", \"regular\", \"full\"];\n return order.indexOf(sizeClass) !== -1 && order.indexOf(sizeClass) <= order.indexOf(slotSizeClass);\n};\n","/**\n * Bounded walks over decoded JSON: the widget payloads come from the model, so no\n * walk may recurse without a bound, run in the size of a shared sub-structure, or throw. The depth rule is the\n * backend's: a block is decoded with `json_decode(…, depth: 32)` (`WidgetBlocks.php`), which admits 31 nested\n * containers — a deeper block is MALFORMED there and is dropped here the same way.\n */\n\n/** The deepest container nesting `json_decode(…, 32)` admits (the top-level object counts as 1). */\nexport const MAX_JSON_CONTAINER_DEPTH = 31;\n\n/** Whether `value` nests containers deeper than `maxDepth` — iterative, never throws. */\nexport const exceedsJsonContainerDepth = (value: unknown, maxDepth: number = MAX_JSON_CONTAINER_DEPTH): boolean => {\n const pending: Array<[unknown, number]> = [[value, 1]];\n while (pending.length > 0) {\n const [current, depth] = pending.pop() as [unknown, number];\n if (typeof current !== \"object\" || current === null) continue;\n if (depth > maxDepth) return true;\n for (const nested of Object.values(current)) {\n if (typeof nested === \"object\" && nested !== null) pending.push([nested, depth + 1]);\n }\n }\n return false;\n};\n\nconst isSequentialIndexObject = (value: Record<string, unknown>): boolean => {\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((key, position) => key === String(position));\n};\n\n/**\n * The value as `json_decode(…, true)` sees it: an object whose keys are `\"0\"`, `\"1\"`, … in order is a LIST there\n * (`array_is_list`), so it becomes an array here. Bounded by the depth rule (call it on a value within the depth).\n */\nexport const normalizeToPhpArrays = (value: unknown, depth = 1): unknown => {\n if (typeof value !== \"object\" || value === null || depth > MAX_JSON_CONTAINER_DEPTH) return value;\n if (Array.isArray(value)) return value.map((element) => normalizeToPhpArrays(element, depth + 1));\n const objectValue = value as Record<string, unknown>;\n if (isSequentialIndexObject(objectValue)) {\n return Object.values(objectValue).map((element) => normalizeToPhpArrays(element, depth + 1));\n }\n const normalized: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(objectValue)) {\n // defineProperty, not assignment: a `__proto__` key stays an own data property instead of replacing the prototype.\n Object.defineProperty(normalized, key, {\n value: normalizeToPhpArrays(nested, depth + 1),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return normalized;\n};\n\nconst structuralSizes = new WeakMap<object, number>();\n\n/**\n * The size of a value as a TREE (every container and scalar counted where it appears) — a shared sub-structure counts\n * once per use, as serialising it would. Memoised per object, so the cost is the number of DISTINCT objects even for a\n * DAG whose tree is exponential; the result saturates at `Number.MAX_SAFE_INTEGER`.\n */\nexport const structuralSizeOf = (value: unknown, depth = 1): number => {\n if (typeof value !== \"object\" || value === null) return 1;\n const memoised = structuralSizes.get(value);\n if (memoised !== undefined) return memoised;\n if (depth > 256) return Number.MAX_SAFE_INTEGER;\n let size = 1;\n for (const nested of Object.values(value)) {\n size = Math.min(Number.MAX_SAFE_INTEGER, size + structuralSizeOf(nested, depth + 1));\n }\n structuralSizes.set(value, size);\n return size;\n};\n\n/** `JSON.stringify(value, null, 2)` — or undefined once the text would pass `maxLength` (checked before it is built). */\nexport const stringifyWithinLimit = (value: unknown, maxLength: number): string | undefined => {\n if (structuralSizeOf(value) > maxLength) return undefined;\n const text = JSON.stringify(value ?? null, null, 2);\n return text.length > maxLength ? undefined : text;\n};\n","import {\n getComposedNodeSchema,\n ComposedNodePropSchema,\n ComposedNodeSchema,\n ComposedNodeSlotSchema,\n ComposedSizeClass,\n resolveComposedSlotForNodeProps,\n sizeClassFitsSlot,\n} from \"./composed-node-schema\";\nimport { resolveCanonicalWidgetName } from \"../widget-name-resolver\";\nimport { exceedsJsonContainerDepth, MAX_JSON_CONTAINER_DEPTH, normalizeToPhpArrays } from \"./bounded-json\";\n\n/**\n * The `ComposedView` tree as typed objects: the frontend twin of the backend reader\n * `ComposedViewTreeReading.php`. The fence plugin hands the widget its `payload` string; this module turns it into\n * {@link ComposedViewTree} — state, datasets, computed expressions, actions and the node tree — and applies THE SAME\n * rules as the backend, read from the generated schema: unknown types, slot mismatches, undeclared props, bad bindings,\n * budgets and three backticks are dropped where they stand and reported as findings; the rest is kept. A `set` on an\n * undeclared name declares it with null; a choice state outside its choices, a set state nothing reads and an `$item`\n * field missing from resolved `$from` rows are kept with a note (`noteFindingCodes` of the schema). The shared\n * fixture `composed-view-parity.json` holds both readers to the same kept tree and the same finding codes.\n *\n * Never throws, never evaluates anything (expressions are compiled by `expression/`).\n */\n\nexport type ComposedViewFindingCode =\n | \"INVALID_NODE\"\n | \"INVALID_PROP\"\n | \"UNKNOWN_BINDING\"\n | \"INVALID_EXPRESSION\"\n | \"INVALID_STATE\"\n | \"INVALID_ACTION\"\n | \"BUDGET_EXCEEDED\"\n | \"INLINE_VALUE_WITHOUT_SOURCE\"\n | \"INVALID_INITIAL_CHOICE\"\n | \"UNREAD_STATE\"\n | \"UNKNOWN_ITEM_KEY\"\n | \"INVALID_SLOT_NODE_COUNT\"\n | \"WIDGET_LIFTED\";\n\nexport interface ComposedViewFinding {\n code: ComposedViewFindingCode;\n path: string;\n message: string;\n}\n\nexport type ComposedViewBindingKind = \"state\" | \"computed\" | \"data\" | \"item\" | \"from\" | \"source\";\n\n/** A bound value (`{\"$state\":\"x\"}` …), see `ComposedViewBinding.php`. */\nexport interface ComposedViewBinding {\n kind: ComposedViewBindingKind | string;\n target: string;\n path: string | null;\n sourceParams: Record<string, unknown>;\n isWellFormed: boolean;\n /** The wire value itself (a `$from` carries its resolution state and snapshot inside, written when the row is stored). */\n wireValue: Record<string, unknown>;\n}\n\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\nexport interface ComposedViewNode {\n type: string;\n id: string | null;\n /** The kept props: literals and bindings as JSON values. */\n props: Record<string, JsonValue>;\n /** The kept nodes per slot name (`children` = the default slot), in wire order. */\n nodesBySlotName: Record<string, ComposedViewNode[]>;\n}\n\nexport interface ComposedViewAction {\n type: string;\n [field: string]: JsonValue;\n}\n\n/**\n * A `Widget` node the reader LIFTED out of the tree (`ComposedViewTreeReading::$liftedWidgetNodesByPath`):\n * its wire path, the widget's canonical name and its fields — shown as its own widget after the view.\n */\nexport interface ComposedViewLiftedWidget {\n path: string;\n widget: string;\n fields: Record<string, JsonValue>;\n}\n\nexport interface ComposedViewTree {\n title: string | null;\n state: Record<string, string | number | boolean | null>;\n data: Record<string, JsonValue>;\n computed: Record<string, string>;\n actions: Record<string, ComposedViewAction>;\n view: ComposedViewNode | null;\n findings: ComposedViewFinding[];\n /** The widgets lifted out of the tree, reading order — never part of `view`. */\n liftedWidgets: ComposedViewLiftedWidget[];\n}\n\nconst RESERVED_WIRE_KEYS = [\"type\", \"id\", \"children\", \"slots\"];\nconst DEFAULT_SLOT_NAME = \"children\";\nconst NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;\n/** Names the pattern admits that would reach an object's prototype — refused for state, data, computed and actions. */\nconst RESERVED_NAMES = [\"__proto__\", \"constructor\", \"prototype\"];\n/** `ComposedViewTreeReading::isAllowedName()`. */\nconst isAllowedName = (name: string): boolean => NAME_PATTERN.test(name) && !RESERVED_NAMES.includes(name);\nconst BINDING_KINDS = [\"state\", \"computed\", \"data\", \"item\", \"from\", \"source\"];\n/** `ComposedViewTreeReading::FIGURE_TEXT_PATTERN` — a text that reads as a figure (\"4,32 %\", \"-3\", \"+2\"). */\nconst FIGURE_TEXT_PATTERN = /^[-+\\u2212]?[0-9]/u;\nconst ACTION_TYPES = [\"copy\", \"resetState\", \"openEntity\", \"openUrl\"];\n/** `ComposedViewTreeReading::readChoiceValues()` — the keys a choice object may be picked by. */\nconst CHOICE_VALUE_KEYS = [\"id\", \"value\", \"key\", \"label\", \"title\", \"name\", \"text\"];\n/** `ComposedViewBindingResolution::STATE_RESOLVED` — a `$from` snapshot that carries its rows. */\nconst RESOLVED_FROM_STATE = \"resolved\";\n/** `ComposedViewBindablePathListing::MAX_LISTED_ROW_KEYS` / `MAX_ROW_LEAF_DEPTH` — the field list of an `$item` finding. */\nconst MAX_LISTED_ROW_KEYS = 12;\nconst MAX_ROW_LEAF_DEPTH = 2;\n\ntype PlainObject = Record<string, unknown>;\n\n/** Own key only — never a prototype key (`toString`, `__proto__`). */\nconst hasOwn = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key);\n\n/** A JSON object (not an array) — PHP's associative array; an EMPTY array counts as both, as `json_decode(…, true)` makes `{}` and `[]` one. */\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst isEmptyContainer = (value: unknown): boolean =>\n (Array.isArray(value) && value.length === 0) || (isPlainObject(value) && Object.keys(value).length === 0);\n/** PHP `is_array`. */\nconst isPhpArray = (value: unknown): value is unknown[] | PlainObject => Array.isArray(value) || isPlainObject(value);\n/** PHP `array_is_list` on a decoded value. */\nconst isPhpList = (value: unknown): boolean => Array.isArray(value) || isEmptyContainer(value);\n/** PHP `mb_strlen` — code points, not UTF-16 units. */\nconst codePointLength = (text: string): number => [...text].length;\nconst entriesOf = (value: unknown[] | PlainObject): Array<[string, unknown]> =>\n Array.isArray(value) ? value.map((entry, index) => [String(index), entry]) : Object.entries(value);\n\n/** The binding a wire value stands for, or null for a literal — `ComposedViewBinding::fromWireValue()`. */\nexport const readComposedViewBinding = (wireValue: unknown): ComposedViewBinding | null => {\n if (!isPlainObject(wireValue)) return null;\n const keys = Object.keys(wireValue);\n if (keys.length !== 1 || !keys[0].startsWith(\"$\")) return null;\n const kind = keys[0].slice(1);\n const bindingValue = wireValue[keys[0]];\n const binding: ComposedViewBinding = {\n kind,\n target: \"\",\n path: null,\n sourceParams: {},\n isWellFormed: true,\n wireValue,\n };\n if (!BINDING_KINDS.includes(kind)) {\n binding.isWellFormed = false;\n return binding;\n }\n if (kind === \"state\" || kind === \"computed\" || kind === \"data\" || kind === \"item\") {\n binding.isWellFormed = typeof bindingValue === \"string\" && bindingValue !== \"\";\n binding.target = typeof bindingValue === \"string\" ? bindingValue : \"\";\n return binding;\n }\n const bindingObject = isPhpArray(bindingValue) ? (bindingValue as PlainObject) : null;\n if (kind === \"from\") {\n binding.target = bindingObject && typeof bindingObject.toolCall === \"string\" ? bindingObject.toolCall : \"\";\n binding.path = bindingObject && typeof bindingObject.path === \"string\" ? bindingObject.path : null;\n binding.isWellFormed = binding.target !== \"\" && binding.path !== null && binding.path !== \"\";\n return binding;\n }\n binding.target = bindingObject && typeof bindingObject.name === \"string\" ? bindingObject.name : \"\";\n const sourceParams = bindingObject ? (bindingObject.params ?? []) : null;\n binding.sourceParams = isPhpArray(sourceParams) ? Object.fromEntries(entriesOf(sourceParams)) : {};\n binding.isWellFormed = binding.target !== \"\" && isPhpArray(sourceParams);\n return binding;\n};\n\n/**\n * The field an `$item` binding names in one row — `ComposedViewBinding::readRowField()`: the key as written, else for a\n * dotted name (`author.name`) the path through the row's nested objects. `found` tells a null field from a missing one.\n */\nexport const readComposedViewRowField = (row: unknown, fieldName: string): { found: boolean; value: unknown } => {\n if (!isPlainObject(row)) return { found: false, value: undefined };\n if (hasOwn(row, fieldName)) return { found: true, value: row[fieldName] };\n if (!fieldName.includes(\".\")) return { found: false, value: undefined };\n let fieldValue: unknown = row;\n for (const fieldNamePart of fieldName.split(\".\")) {\n if (!isPlainObject(fieldValue) || !hasOwn(fieldValue, fieldNamePart)) return { found: false, value: undefined };\n fieldValue = fieldValue[fieldNamePart];\n }\n return { found: true, value: fieldValue };\n};\n\n/** `ComposedViewBindablePathListing::buildListedRowKeys()` — scalar and list keys first, then dotted object leaves. */\nconst collectRowKeys = (row: PlainObject, keyPrefix: string, leafDepth: number): string[] => {\n const ownKeys: string[] = [];\n const leafKeys: string[] = [];\n for (const [rowKey, rowValue] of Object.entries(row)) {\n if (rowKey === \"objectType\") continue;\n const dottedKey = `${keyPrefix}${rowKey}`;\n if (isPlainObject(rowValue) && !isEmptyContainer(rowValue) && leafDepth < MAX_ROW_LEAF_DEPTH) {\n leafKeys.push(...collectRowKeys(rowValue, `${dottedKey}.`, leafDepth + 1));\n continue;\n }\n ownKeys.push(dottedKey);\n }\n return [...ownKeys, ...leafKeys];\n};\n\nconst buildListedRowKeys = (row: PlainObject): string[] => {\n const rowKeys = collectRowKeys(row, \"\", 0);\n const listedRowKeys = rowKeys.slice(0, MAX_LISTED_ROW_KEYS);\n return rowKeys.length > listedRowKeys.length ? [...listedRowKeys, \"…\"] : listedRowKeys;\n};\n\n/** `ComposedViewTreeReading::readChoiceValues()` — the values a choice may be picked by, as text. */\nconst readChoiceValues = (choices: unknown[]): string[] => {\n const choiceValues = new Set<string>();\n for (const choice of choices) {\n const choiceFields = isPhpArray(choice)\n ? CHOICE_VALUE_KEYS.filter((choiceKey) => hasOwn(choice, choiceKey)).map(\n (choiceKey) => (choice as PlainObject)[choiceKey],\n )\n : [choice];\n for (const choiceField of choiceFields) {\n if (typeof choiceField === \"string\" || typeof choiceField === \"number\") choiceValues.add(String(choiceField));\n }\n }\n return [...choiceValues];\n};\n\n/** `ComposedViewTreeReading::findIdentifiersOfExpression()` — identifiers outside string literals, not after a `.`. */\nexport const findComposedViewExpressionIdentifiers = (expressionSource: string): string[] => {\n const sourceWithoutStrings = expressionSource.replace(/'(?:[^'\\\\]|\\\\[^])*'|\"(?:[^\"\\\\]|\\\\[^])*\"/g, \" \");\n const identifierMatches = sourceWithoutStrings.matchAll(/(^|[^A-Za-z0-9_$.])([A-Za-z_][A-Za-z0-9_]*)/g);\n return [...new Set([...identifierMatches].map((identifierMatch) => identifierMatch[2]))];\n};\n\n/** `ComposedViewTreeReading::collectStateBindingTargets()` — every `$state` target inside a value, `$source` params included. */\nconst collectStateBindingTargets = (value: unknown, stateNames: Set<string>): void => {\n if (!isPhpArray(value)) return;\n const binding = readComposedViewBinding(value);\n if (binding !== null) {\n if (binding.kind === \"state\" && binding.isWellFormed) stateNames.add(binding.target);\n if (binding.kind === \"source\") collectStateBindingTargets(binding.sourceParams, stateNames);\n return;\n }\n for (const [, nestedValue] of entriesOf(value)) collectStateBindingTargets(nestedValue, stateNames);\n};\n\n/** `ComposedViewNode::collectBindings()` — the bindings of a node's props by prop path (`data`, `source.url`). */\nconst collectBindingsByPropPath = (\n propPath: string,\n propValue: unknown,\n bindingsByPropPath: Array<[string, ComposedViewBinding]>,\n): void => {\n const binding = readComposedViewBinding(propValue);\n if (binding !== null) {\n bindingsByPropPath.push([propPath, binding]);\n return;\n }\n if (!isPhpArray(propValue)) return;\n for (const [nestedKey, nestedValue] of entriesOf(propValue))\n collectBindingsByPropPath(`${propPath}.${nestedKey}`, nestedValue, bindingsByPropPath);\n};\n\n/**\n * Whether an `openEntity` `ref` names the current row's reference — a well-formed `{\"$item\": \"<key>\"}` binding\n * (`ComposedViewBindingResolution::isRowBoundReference()`): the entity is the row's own, never the action's.\n */\nconst isRowBoundEntityReference = (reference: unknown): boolean => {\n const binding = readComposedViewBinding(reference);\n return binding !== null && binding.kind === \"item\" && binding.isWellFormed;\n};\n\n/** `ComposedViewNodeProp::acceptsLiteral()`. */\nconst propAcceptsLiteral = (prop: ComposedNodePropSchema, value: unknown): boolean => {\n if (prop.allowedValues !== null && !prop.allowedValues.some((allowedValue) => allowedValue === value)) return false;\n return prop.types.some((type) => {\n switch (type) {\n case \"string\":\n return typeof value === \"string\";\n case \"number\":\n return typeof value === \"number\";\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"array\":\n return isPhpArray(value) && isPhpList(value);\n case \"object\":\n return isPhpArray(value) && (isEmptyContainer(value) || !isPhpList(value));\n default:\n return false;\n }\n });\n};\n\nconst containsTripleBackticks = (value: unknown): boolean => {\n if (typeof value === \"string\") return value.includes(\"```\");\n if (!isPhpArray(value)) return false;\n return entriesOf(value).some(([key, nested]) => key.includes(\"```\") || containsTripleBackticks(nested));\n};\n\n/** The reader — one instance per tree, like the PHP `ComposedViewTreeReading`. */\nclass ComposedViewTreeReader {\n readonly tree: ComposedViewTree = {\n title: null,\n state: {},\n data: {},\n computed: {},\n actions: {},\n view: null,\n findings: [],\n liftedWidgets: [],\n };\n protected readNodeCount = 0;\n protected inlineCellCount = 0;\n\n constructor(protected readonly schema: ComposedNodeSchema) {}\n\n get budgets() {\n return this.schema.budgets;\n }\n\n addFinding(code: ComposedViewFindingCode, path: string, message: string) {\n this.tree.findings.push({ code, path, message });\n }\n\n read(widgetFields: PlainObject) {\n this.readTitle(widgetFields.title);\n this.readState(widgetFields.state ?? []);\n this.readData(widgetFields.data ?? []);\n this.readComputed(widgetFields.computed ?? []);\n this.readActions(widgetFields.actions ?? []);\n this.declareStateNamesSetByEvents(widgetFields.view);\n if (widgetFields.view !== undefined && widgetFields.view !== null) {\n this.tree.view = this.readRootNode(widgetFields.view);\n }\n this.flagInlineFiguresWithoutSource();\n this.flagInitialStatesOutsideTheirChoices();\n this.flagStateNamesNothingReads();\n this.flagItemFieldsMissingFromTheirRows();\n this.dedupeFindings();\n }\n\n /**\n * `ComposedViewTreeReading::declareStateNamesSetByEvents()` — every `{\"set\": <name>}` event of a node of a known type\n * declares an undeclared, allowed name that is no dataset or computed value with null (within the state budget).\n */\n declareStateNamesSetByEvents(wireNode: unknown) {\n if (!isPlainObject(wireNode) || typeof wireNode.type !== \"string\" || !hasOwn(this.schema.nodeTypes, wireNode.type))\n return;\n for (const prop of this.schema.nodeTypes[wireNode.type].props) {\n const eventValue = hasOwn(wireNode, prop.name) ? wireNode[prop.name] : undefined;\n if (\n prop.types.includes(\"event\") &&\n isPlainObject(eventValue) &&\n Object.keys(eventValue).length === 1 &&\n typeof eventValue.set === \"string\"\n ) {\n this.declareStateNameSetByEvent(eventValue.set);\n }\n }\n const slotWireNodeLists: unknown[] = [wireNode.children];\n if (isPhpArray(wireNode.slots)) {\n for (const [slotName, slotWireNodes] of entriesOf(wireNode.slots)) {\n if (slotName !== DEFAULT_SLOT_NAME || !hasOwn(wireNode, \"children\")) slotWireNodeLists.push(slotWireNodes);\n }\n }\n for (const slotWireNodes of slotWireNodeLists) {\n if (!isPhpArray(slotWireNodes) || !isPhpList(slotWireNodes)) continue;\n for (const [, slotWireNode] of entriesOf(slotWireNodes)) this.declareStateNamesSetByEvents(slotWireNode);\n }\n }\n\n declareStateNameSetByEvent(stateName: string) {\n if (\n !isAllowedName(stateName) ||\n hasOwn(this.tree.state, stateName) ||\n hasOwn(this.tree.data, stateName) ||\n hasOwn(this.tree.computed, stateName) ||\n Object.keys(this.tree.state).length >= this.budgets.maxStateKeys\n ) {\n return;\n }\n this.tree.state[stateName] = null;\n }\n\n /** `ComposedViewNode::getStateNamesSetByEvents()`. */\n stateNamesSetByEvents(node: ComposedViewNode): string[] {\n const stateNames: string[] = [];\n for (const prop of this.schema.nodeTypes[node.type]?.props ?? []) {\n const eventValue = hasOwn(node.props, prop.name) ? node.props[prop.name] : undefined;\n if (prop.types.includes(\"event\") && isPlainObject(eventValue) && typeof eventValue.set === \"string\")\n stateNames.push(eventValue.set);\n }\n return stateNames;\n }\n\n /** `ComposedViewTreeReading::flagInitialStatesOutsideTheirChoices()`. */\n flagInitialStatesOutsideTheirChoices() {\n if (this.tree.view === null) return;\n for (const [nodePath, node] of getComposedViewSubtreeNodesByPath(this.tree.view, \"view\")) {\n const optionsProp = this.schema.nodeTypes[node.type]?.optionsProp;\n const choices =\n optionsProp !== undefined && hasOwn(node.props, optionsProp) ? node.props[optionsProp] : undefined;\n if (!Array.isArray(choices)) continue;\n const choiceValues = readChoiceValues(choices);\n for (const stateName of new Set(this.stateNamesSetByEvents(node))) {\n const initialValue = hasOwn(this.tree.state, stateName) ? this.tree.state[stateName] : null;\n if (initialValue === null || initialValue === \"\") continue;\n if (\n (typeof initialValue === \"string\" || typeof initialValue === \"number\") &&\n choiceValues.includes(String(initialValue))\n )\n continue;\n this.addFinding(\n \"INVALID_INITIAL_CHOICE\",\n nodePath,\n `the state \"${stateName}\" starts as ${JSON.stringify(initialValue)}, none of the choices (${choiceValues.join(\", \")}) — start it with a choice's id`,\n );\n }\n }\n }\n\n /** `ComposedViewTreeReading::flagStateNamesNothingReads()` — a state a node sets that nothing else reads. */\n flagStateNamesNothingReads() {\n if (Object.keys(this.tree.state).length === 0) return;\n const readStateNames = new Set<string>();\n const setStateNames = new Set<string>();\n for (const expressionSource of Object.values(this.tree.computed)) {\n for (const identifier of findComposedViewExpressionIdentifiers(expressionSource)) readStateNames.add(identifier);\n }\n collectStateBindingTargets(this.tree.data, readStateNames);\n collectStateBindingTargets(this.tree.actions, readStateNames);\n for (const node of this.tree.view === null ? [] : getComposedViewSubtreeNodes(this.tree.view)) {\n const ownSetStateNames = this.stateNamesSetByEvents(node);\n ownSetStateNames.forEach((setStateName) => setStateNames.add(setStateName));\n const nodeReadStateNames = new Set<string>();\n collectStateBindingTargets(node.props, nodeReadStateNames);\n nodeReadStateNames.forEach((readStateName) => {\n if (!ownSetStateNames.includes(readStateName)) readStateNames.add(readStateName);\n });\n if (this.schema.nodeTypes[node.type]?.submitsInputs !== true) continue;\n for (const formSubtreeNode of getComposedViewSubtreeNodes(node)) {\n collectStateBindingTargets(formSubtreeNode.props, readStateNames);\n this.stateNamesSetByEvents(formSubtreeNode).forEach((submittedStateName) =>\n readStateNames.add(submittedStateName),\n );\n }\n }\n for (const stateName of Object.keys(this.tree.state)) {\n if (setStateNames.has(stateName) && !readStateNames.has(stateName)) {\n this.addFinding(\n \"UNREAD_STATE\",\n `state.${stateName}`,\n `nothing reads the state \"${stateName}\" — a Tab or input changes only what reads its state: bind a node to {\"$state\":\"${stateName}\"} or name it in a computed value`,\n );\n }\n }\n }\n\n /** `ComposedViewTreeReading::flagItemFieldsMissingFromTheirRows()`. */\n flagItemFieldsMissingFromTheirRows() {\n if (this.tree.view !== null) this.flagItemFieldsOfSubtree(this.tree.view, \"view\", null);\n }\n\n flagItemFieldsOfSubtree(node: ComposedViewNode, path: string, itemRows: PlainObject[] | null) {\n if (itemRows !== null) {\n const bindingsByPropPath: Array<[string, ComposedViewBinding]> = [];\n for (const [propName, propValue] of Object.entries(node.props))\n collectBindingsByPropPath(propName, propValue, bindingsByPropPath);\n for (const [propPath, binding] of bindingsByPropPath) {\n if (binding.kind !== \"item\" || !binding.isWellFormed) continue;\n if (itemRows.some((row) => readComposedViewRowField(row, binding.target).found)) continue;\n this.addFinding(\n \"UNKNOWN_ITEM_KEY\",\n `${path}.${propPath}`,\n `no row of the bound rows has the field \"${binding.target}\" — it renders empty; the rows have: ${buildListedRowKeys(itemRows[0]).join(\", \")}`,\n );\n }\n }\n const itemsProp = this.schema.nodeTypes[node.type]?.itemsProp;\n const childItemRows = this.schema.nodeTypes[node.type]?.providesItemScope\n ? this.findResolvedRowsOfItems(\n itemsProp !== undefined && hasOwn(node.props, itemsProp) ? node.props[itemsProp] : undefined,\n )\n : itemRows;\n for (const [slotName, slotNodes] of Object.entries(node.nodesBySlotName)) {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n slotNodes.forEach((slotNode, childPosition) =>\n this.flagItemFieldsOfSubtree(slotNode, `${slotPath}[${childPosition}]`, childItemRows),\n );\n }\n }\n\n /** `ComposedViewTreeReading::findResolvedRowsOfItems()` — the object rows of a resolved `$from` list, or null. */\n findResolvedRowsOfItems(itemsValue: unknown): PlainObject[] | null {\n const binding = readComposedViewBinding(itemsValue);\n let fromBinding: unknown = undefined;\n if (binding?.kind === \"from\") fromBinding = binding.wireValue.$from;\n if (binding?.kind === \"data\" && hasOwn(this.tree.data, binding.target)) {\n const dataset = this.tree.data[binding.target];\n fromBinding = isPlainObject(dataset) ? dataset.$from : undefined;\n }\n if (!isPlainObject(fromBinding) || fromBinding.state !== RESOLVED_FROM_STATE || !isPhpList(fromBinding.value))\n return null;\n const objectRows = (fromBinding.value as unknown[]).filter(\n (row): row is PlainObject => isPlainObject(row) && !isEmptyContainer(row),\n );\n return objectRows.length === 0 ? null : objectRows;\n }\n\n /**\n * `ComposedViewTreeReading::flagInlineFiguresWithoutSource()` — each data node of the KEPT view that shows inline\n * figures without its `source`, a source on a data node around it or a source line (`SourceRef`) in the tree gets\n * one `INLINE_VALUE_WITHOUT_SOURCE`; the node stays.\n */\n flagInlineFiguresWithoutSource() {\n const view = this.tree.view;\n if (view === null) return;\n if (getComposedViewSubtreeNodes(view).some((node) => this.sourcingOf(node.type)?.namesSources === true)) return;\n this.flagUnsourcedDataNodesOfSubtree(view, \"view\", false, false);\n }\n\n sourcingOf(nodeType: string) {\n return hasOwn(this.schema.nodeTypes, nodeType) ? this.schema.nodeTypes[nodeType].sourcing : undefined;\n }\n\n flagUnsourcedDataNodesOfSubtree(\n node: ComposedViewNode,\n path: string,\n isSourcedAround: boolean,\n itemsAreInline: boolean,\n ) {\n const needsSource = this.sourcingOf(node.type)?.needsSource === true;\n let isSourced = isSourcedAround || (needsSource && hasOwn(node.props, \"source\"));\n if (needsSource && !isSourced && this.subtreeHoldsInlineFigures(node, itemsAreInline)) {\n this.addFinding(\n \"INLINE_VALUE_WITHOUT_SOURCE\",\n path,\n `a ${node.type} shows figures written inline without \\`source\\` — give it the publisher and page as \\`source\\` {\"name\",\"url\"} (or a SourceRef beside it)`,\n );\n isSourced = true;\n }\n const childItemsAreInline = this.schema.nodeTypes[node.type]?.providesItemScope\n ? this.nodeHoldsInlineRows(node, itemsAreInline)\n : itemsAreInline;\n for (const [slotName, slotNodes] of Object.entries(node.nodesBySlotName)) {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n slotNodes.forEach((slotNode, childPosition) =>\n this.flagUnsourcedDataNodesOfSubtree(slotNode, `${slotPath}[${childPosition}]`, isSourced, childItemsAreInline),\n );\n }\n }\n\n subtreeHoldsInlineFigures(node: ComposedViewNode, itemsAreInline: boolean): boolean {\n if (this.nodeHoldsInlineRows(node, itemsAreInline) || this.nodeHoldsInlineFigure(node, itemsAreInline)) return true;\n const childItemsAreInline = this.schema.nodeTypes[node.type]?.providesItemScope\n ? this.nodeHoldsInlineRows(node, itemsAreInline)\n : itemsAreInline;\n return Object.values(node.nodesBySlotName).some((slotNodes) =>\n slotNodes.some((slotNode) => this.subtreeHoldsInlineFigures(slotNode, childItemsAreInline)),\n );\n }\n\n nodeHoldsInlineRows(node: ComposedViewNode, itemsAreInline: boolean): boolean {\n return (this.sourcingOf(node.type)?.rowsProps ?? []).some((rowsPropName) => {\n if (!hasOwn(node.props, rowsPropName)) return false;\n const rowsValue = node.props[rowsPropName];\n const binding = readComposedViewBinding(rowsValue);\n if (binding === null) return isPhpArray(rowsValue) && !isEmptyContainer(rowsValue);\n if (binding.kind === \"data\") return this.isInlineDataset(binding.target);\n return binding.kind === \"item\" && itemsAreInline;\n });\n }\n\n nodeHoldsInlineFigure(node: ComposedViewNode, itemsAreInline: boolean): boolean {\n return (this.sourcingOf(node.type)?.figureProps ?? []).some((figurePropName) => {\n if (!hasOwn(node.props, figurePropName)) return false;\n const figureValue = node.props[figurePropName];\n const binding = readComposedViewBinding(figureValue);\n if (binding !== null) return binding.kind === \"item\" && itemsAreInline;\n if (typeof figureValue === \"number\") return true;\n return typeof figureValue === \"string\" && FIGURE_TEXT_PATTERN.test(figureValue);\n });\n }\n\n /** Written rows (not a `$from` / `$source` binding) with at least one row. */\n isInlineDataset(dataName: string): boolean {\n if (!hasOwn(this.tree.data, dataName)) return false;\n const dataset = this.tree.data[dataName];\n return isPhpArray(dataset) && !isEmptyContainer(dataset) && readComposedViewBinding(dataset) === null;\n }\n\n readTitle(titleField: unknown) {\n if (typeof titleField !== \"string\") return;\n if (titleField.includes(\"```\")) {\n this.addFinding(\"INVALID_PROP\", \"title\", \"a string with three backticks would end the widget fence\");\n return;\n }\n this.tree.title = titleField;\n }\n\n /**\n * `ComposedViewTreeReading::readRootNode()` — the root held to the root rule; a refused `Widget` root naming a known\n * widget is lifted, a layout root the lift emptied is no view.\n */\n readRootNode(wireRootNode: unknown): ComposedViewNode | null {\n const liftedCountBefore = this.tree.liftedWidgets.length;\n const rootNode = this.readNode(wireRootNode, \"view\", 1, false);\n if (rootNode !== null && this.isPrunedByTheLift(rootNode, liftedCountBefore)) {\n this.pruneNodeEmptiedByTheLift(rootNode, \"view\");\n return null;\n }\n if (rootNode === null || this.isNodeAcceptedAsRoot(rootNode)) return rootNode;\n this.readNodeCount -= countComposedViewNodes(rootNode);\n if (this.isLiftedWhenRefused(rootNode)) {\n this.liftWidgetNode(rootNode, \"view\", null);\n return null;\n }\n this.addFinding(\n \"INVALID_NODE\",\n \"view\",\n rootNode.type === \"Widget\"\n ? this.buildNotEmbeddableMessage(rootNode)\n : `a ${rootNode.type} cannot be the root of the view`,\n );\n return null;\n }\n\n /** `WidgetComposedViewNode::isLiftedWhenRefused()` — a `Widget` node naming a known widget (any registered type). */\n isLiftedWhenRefused(node: ComposedViewNode): boolean {\n return node.type === \"Widget\" && this.findKnownWidgetName(node) !== undefined;\n }\n\n /** The canonical name of the known widget a `Widget` node names (a legacy `…Directive` name resolved), or undefined. */\n findKnownWidgetName(node: ComposedViewNode): string | undefined {\n if (typeof node.props.widget !== \"string\") return undefined;\n return resolveCanonicalWidgetName(node.props.widget, new Set(this.schema.widgetTypes ?? []));\n }\n\n /** `ComposedViewTreeReading::liftWidgetNode()` — out of the tree with its note, shown as its own widget after the view. */\n liftWidgetNode(node: ComposedViewNode, path: string, refusingSlot: ComposedNodeSlotSchema | null) {\n const widget = this.findKnownWidgetName(node) ?? \"\";\n const fields = isPlainObject(node.props.fields) ? (node.props.fields as Record<string, JsonValue>) : {};\n this.tree.liftedWidgets.push({ path, widget, fields });\n const embeddableWidget = this.findEmbeddableWidget(node);\n const reason =\n embeddableWidget !== undefined && refusingSlot !== null\n ? `\"${widget}\" needs a ${embeddableWidget.sizeClass} slot, the slot \"${refusingSlot.name}\" is ${refusingSlot.sizeClass}`\n : `\"${widget}\" does not embed`;\n this.addFinding(\"WIDGET_LIFTED\", path, `${reason} — it is shown as its own widget block after the view`);\n }\n\n /** `ComposedViewTreeReading::isPrunedByTheLift()` — a layout node the lift left with no node. */\n isPrunedByTheLift(node: ComposedViewNode, liftedCountBefore: number): boolean {\n if (this.tree.liftedWidgets.length === liftedCountBefore) return false;\n if (!(this.schema.nodeTypes[node.type]?.categories ?? []).includes(\"layout\")) return false;\n return Object.values(node.nodesBySlotName).every((slotNodes) => slotNodes.length === 0);\n }\n\n /** `ComposedViewTreeReading::pruneNodeEmptiedByTheLift()` — its count back, its slot-minimum notes gone. */\n pruneNodeEmptiedByTheLift(node: ComposedViewNode, path: string) {\n this.readNodeCount -= countComposedViewNodes(node);\n this.tree.findings = this.tree.findings.filter(\n (finding) =>\n finding.code !== \"INVALID_SLOT_NODE_COUNT\" || (finding.path !== path && !finding.path.startsWith(`${path}.`)),\n );\n }\n\n /** `ComposedViewNode::isAcceptedAsRoot()` — every node, but an embedded widget only when it is embeddable. */\n isNodeAcceptedAsRoot(node: ComposedViewNode): boolean {\n return node.type !== \"Widget\" || this.findEmbeddableWidget(node) !== undefined;\n }\n\n /** The embeddable widget a `Widget` node names (a legacy `…Directive` name resolved as everywhere), or undefined. */\n findEmbeddableWidget(node: ComposedViewNode): { sizeClass: ComposedSizeClass } | undefined {\n if (typeof node.props.widget !== \"string\") return undefined;\n const embeddableWidgetName = resolveCanonicalWidgetName(\n node.props.widget,\n new Set(Object.keys(this.schema.embeddableWidgets ?? {})),\n );\n return embeddableWidgetName === undefined ? undefined : this.schema.embeddableWidgets[embeddableWidgetName];\n }\n\n /** The PHP findings are an ObjectSet keyed by code, path and message — a repeat is kept once there, so here too. */\n dedupeFindings() {\n const seenFindingKeys = new Set<string>();\n this.tree.findings = this.tree.findings.filter((finding) => {\n const findingKey = `${finding.code}@${finding.path}@${finding.message}`;\n if (seenFindingKeys.has(findingKey)) return false;\n seenFindingKeys.add(findingKey);\n return true;\n });\n }\n\n readState(stateField: unknown) {\n if (!isPhpArray(stateField) || (!isEmptyContainer(stateField) && isPhpList(stateField))) {\n this.addFinding(\"INVALID_STATE\", \"state\", \"`state` must be an object of name → initial value\");\n return;\n }\n for (const [stateName, initialValue] of entriesOf(stateField)) {\n if (Object.keys(this.tree.state).length >= this.budgets.maxStateKeys) {\n this.addFinding(\"BUDGET_EXCEEDED\", `state.${stateName}`, `more than ${this.budgets.maxStateKeys} state names`);\n break;\n }\n if (!isAllowedName(stateName)) {\n this.addFinding(\n \"INVALID_STATE\",\n `state.${stateName}`,\n \"a state name is an identifier (letters, digits, underscore)\",\n );\n continue;\n }\n const isScalar = [\"string\", \"number\", \"boolean\"].includes(typeof initialValue);\n if (!isScalar && initialValue !== null) {\n this.addFinding(\"INVALID_STATE\", `state.${stateName}`, \"an initial value is a string, number, boolean or null\");\n continue;\n }\n if (typeof initialValue === \"string\" && initialValue.includes(\"```\")) {\n this.addFinding(\n \"INVALID_STATE\",\n `state.${stateName}`,\n \"a string with three backticks would end the widget fence\",\n );\n continue;\n }\n if (typeof initialValue === \"string\" && codePointLength(initialValue) > this.budgets.maxStateStringLength) {\n this.addFinding(\n \"BUDGET_EXCEEDED\",\n `state.${stateName}`,\n `an initial string longer than ${this.budgets.maxStateStringLength} characters`,\n );\n continue;\n }\n this.tree.state[stateName] = initialValue as string | number | boolean | null;\n }\n }\n\n readData(dataField: unknown) {\n if (!isPhpArray(dataField) || (!isEmptyContainer(dataField) && isPhpList(dataField))) {\n this.addFinding(\"INVALID_PROP\", \"data\", \"`data` must be an object of name → rows\");\n return;\n }\n for (const [dataName, dataset] of entriesOf(dataField)) {\n const path = `data.${dataName}`;\n if (!isAllowedName(dataName) || hasOwn(this.tree.state, dataName)) {\n this.addFinding(\"INVALID_PROP\", path, \"a data name is an identifier that is not also a state name\");\n continue;\n }\n const binding = readComposedViewBinding(dataset);\n if (binding !== null) {\n if (binding.kind !== \"from\" && binding.kind !== \"source\") {\n this.addFinding(\"UNKNOWN_BINDING\", path, \"a dataset binds a tool result ($from) or a data source ($source)\");\n continue;\n }\n if (containsTripleBackticks(dataset)) {\n this.addFinding(\"INVALID_PROP\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n if (this.isValidBinding(binding, path, false)) this.tree.data[dataName] = dataset as JsonValue;\n continue;\n }\n if (!isPhpArray(dataset) || !isPhpList(dataset)) {\n this.addFinding(\"INVALID_PROP\", path, \"a dataset is a list of rows, a $from or a $source\");\n continue;\n }\n if (containsTripleBackticks(dataset)) {\n this.addFinding(\"INVALID_PROP\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n // `json_decode(…, true)` makes `{}` and `[]` one empty array — kept as the empty LIST on both sides.\n if (this.isValidInlineData(dataset, path, false))\n this.tree.data[dataName] = (isEmptyContainer(dataset) ? [] : dataset) as JsonValue;\n }\n }\n\n readComputed(computedField: unknown) {\n if (!isPhpArray(computedField) || (!isEmptyContainer(computedField) && isPhpList(computedField))) {\n this.addFinding(\"INVALID_EXPRESSION\", \"computed\", \"`computed` must be an object of name → expression\");\n return;\n }\n for (const [computedName, expressionSource] of entriesOf(computedField)) {\n const path = `computed.${computedName}`;\n if (Object.keys(this.tree.computed).length >= this.budgets.maxComputedExpressions) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `more than ${this.budgets.maxComputedExpressions} computed values`);\n break;\n }\n if (\n !isAllowedName(computedName) ||\n hasOwn(this.tree.state, computedName) ||\n hasOwn(this.tree.data, computedName)\n ) {\n this.addFinding(\n \"INVALID_EXPRESSION\",\n path,\n \"a computed name is an identifier that is not also a state or data name\",\n );\n continue;\n }\n if (typeof expressionSource !== \"string\" || expressionSource.trim() === \"\") {\n this.addFinding(\"INVALID_EXPRESSION\", path, \"an expression is a non-empty string\");\n continue;\n }\n if (codePointLength(expressionSource) > this.budgets.maxExpressionSourceLength) {\n this.addFinding(\n \"BUDGET_EXCEEDED\",\n path,\n `an expression longer than ${this.budgets.maxExpressionSourceLength} characters`,\n );\n continue;\n }\n if (expressionSource.includes(\"```\")) {\n this.addFinding(\"INVALID_EXPRESSION\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n this.tree.computed[computedName] = expressionSource;\n }\n }\n\n readActions(actionsField: unknown) {\n if (!isPhpArray(actionsField) || (!isEmptyContainer(actionsField) && isPhpList(actionsField))) {\n this.addFinding(\"INVALID_ACTION\", \"actions\", \"`actions` must be an object of name → action\");\n return;\n }\n for (const [actionName, action] of entriesOf(actionsField)) {\n const path = `actions.${actionName}`;\n if (Object.keys(this.tree.actions).length >= this.budgets.maxActions) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `more than ${this.budgets.maxActions} actions`);\n break;\n }\n const actionObject = isPhpArray(action) ? (action as PlainObject) : null;\n const actionType = actionObject?.type;\n if (!isAllowedName(actionName) || typeof actionType !== \"string\" || !ACTION_TYPES.includes(actionType)) {\n this.addFinding(\n \"INVALID_ACTION\",\n path,\n `an action has an identifier name and a type of ${ACTION_TYPES.join(\", \")}`,\n );\n continue;\n }\n if (\n actionType === \"openUrl\" &&\n !(typeof actionObject?.url === \"string\" && /^https?:\\/\\//i.test(actionObject.url))\n ) {\n this.addFinding(\"INVALID_ACTION\", path, \"`openUrl` needs an http(s) `url`\");\n continue;\n }\n // `{\"$item\":\"entityRef\"}` — inside a Repeat over a resolved `$from` list, each row opens its own entity\n if (\n actionType === \"openEntity\" &&\n !isRowBoundEntityReference(actionObject?.ref) &&\n !(typeof actionObject?.ref === \"string\" && actionObject.ref !== \"\")\n ) {\n this.addFinding(\n \"INVALID_ACTION\",\n path,\n '`openEntity` needs the platform-minted `ref` of a tool result row, or {\"$item\":\"entityRef\"} inside a Repeat',\n );\n continue;\n }\n if (containsTripleBackticks(action)) {\n this.addFinding(\"INVALID_ACTION\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n this.tree.actions[actionName] = action as ComposedViewAction;\n }\n }\n\n readNode(wireNode: unknown, path: string, depth: number, isInItemScope: boolean): ComposedViewNode | null {\n if (!isPlainObject(wireNode) || typeof wireNode.type !== \"string\") {\n this.addFinding(\"INVALID_NODE\", path, \"a node is an object with a string `type`\");\n return null;\n }\n const nodeType = wireNode.type;\n const nodeTypeSchema = Object.prototype.hasOwnProperty.call(this.schema.nodeTypes, nodeType)\n ? this.schema.nodeTypes[nodeType]\n : undefined;\n if (!nodeTypeSchema) {\n this.addFinding(\"INVALID_NODE\", path, `unknown node type \"${nodeType}\"`);\n return null;\n }\n if (depth > this.budgets.maxDepth) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `deeper than ${this.budgets.maxDepth} levels`);\n return null;\n }\n if (this.readNodeCount >= this.budgets.maxNodes) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `more than ${this.budgets.maxNodes} nodes`);\n return null;\n }\n const ownWireFields = Object.fromEntries(\n Object.entries(wireNode).filter(([key]) => key !== \"children\" && key !== \"slots\"),\n );\n if (containsTripleBackticks(ownWireFields)) {\n this.addFinding(\"INVALID_NODE\", path, \"a string with three backticks would end the widget fence\");\n return null;\n }\n this.readNodeCount++;\n const node: ComposedViewNode = {\n type: nodeType,\n id: typeof wireNode.id === \"string\" ? wireNode.id : null,\n props: {},\n nodesBySlotName: {},\n };\n if (!this.readProps(node, wireNode, path, isInItemScope)) {\n this.readNodeCount--;\n return null;\n }\n const childScope = isInItemScope || nodeTypeSchema.providesItemScope;\n const wireNodesBySlotName: Array<[string, unknown]> = [];\n if (hasOwn(wireNode, \"children\")) wireNodesBySlotName.push([DEFAULT_SLOT_NAME, wireNode.children]);\n if (isPhpArray(wireNode.slots)) {\n for (const [slotName, slotWireNodes] of entriesOf(wireNode.slots)) {\n if (slotName === DEFAULT_SLOT_NAME && hasOwn(wireNode, \"children\")) {\n this.addFinding(\n \"INVALID_NODE\",\n `${path}.slots.${slotName}`,\n \"the default slot is written twice (`children` and `slots.children`) — `slots.children` is dropped\",\n );\n continue;\n }\n wireNodesBySlotName.push([slotName, slotWireNodes]);\n }\n }\n for (const [slotName, slotWireNodes] of wireNodesBySlotName) {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n // the slot of THIS node: a Grid's cells narrow with its `columns` — the props are read above\n const declaredSlot = nodeTypeSchema.slots.find((candidate) => candidate.name === slotName);\n const slot = declaredSlot ? resolveComposedSlotForNodeProps(declaredSlot, node.props) : undefined;\n if (!slot) {\n this.addFinding(\"INVALID_NODE\", slotPath, `${nodeType} has no slot \"${slotName}\" — its nodes are dropped`);\n continue;\n }\n node.nodesBySlotName[slotName] = this.readSlotNodes(slot, slotWireNodes, slotPath, depth, childScope);\n }\n for (const slot of nodeTypeSchema.slots) {\n const slotNodeCount = node.nodesBySlotName[slot.name]?.length ?? 0;\n if (slotNodeCount < slot.minChildren) {\n // the node is kept and renders what it has: a note, never a dropped node\n this.addFinding(\n \"INVALID_SLOT_NODE_COUNT\",\n `${path}.${slot.name}`,\n `${nodeType} needs at least ${slot.minChildren} node(s) in \"${slot.name}\", it has ${slotNodeCount}`,\n );\n }\n }\n return node;\n }\n\n readSlotNodes(\n slot: ComposedNodeSlotSchema,\n slotWireNodes: unknown,\n slotPath: string,\n depth: number,\n isInItemScope: boolean,\n ): ComposedViewNode[] {\n if (!isPhpArray(slotWireNodes) || !isPhpList(slotWireNodes)) {\n this.addFinding(\"INVALID_NODE\", slotPath, \"a slot holds a list of nodes\");\n return [];\n }\n const slotNodes: ComposedViewNode[] = [];\n for (const [childPosition, slotWireNode] of entriesOf(slotWireNodes)) {\n const childPath = `${slotPath}[${childPosition}]`;\n if (slot.maxChildren !== null && slotNodes.length >= slot.maxChildren) {\n this.addFinding(\"INVALID_NODE\", childPath, `the slot \"${slot.name}\" holds at most ${slot.maxChildren} node(s)`);\n break;\n }\n const liftedCountBefore = this.tree.liftedWidgets.length;\n const slotNode = this.readNode(slotWireNode, childPath, depth + 1, isInItemScope);\n if (slotNode === null) continue;\n if (this.isPrunedByTheLift(slotNode, liftedCountBefore)) {\n this.pruneNodeEmptiedByTheLift(slotNode, childPath);\n continue;\n }\n if (!this.isNodeAcceptedBySlot(slotNode, slot)) {\n this.readNodeCount -= countComposedViewNodes(slotNode);\n // a refused widget is lifted, never dropped — inside a repeat it would be lifted once per row\n if (this.isLiftedWhenRefused(slotNode) && !isInItemScope) {\n this.liftWidgetNode(slotNode, childPath, slot);\n continue;\n }\n this.addFinding(\"INVALID_NODE\", childPath, this.buildSlotRefusalMessage(slotNode, slot));\n continue;\n }\n slotNodes.push(slotNode);\n }\n return slotNodes;\n }\n\n /**\n * `ComposedViewNode::buildSlotRefusalMessage()` — with `WidgetComposedViewNode`'s: a widget that does not embed names\n * the way out (its own block next to the ComposedView), an embeddable one too large for the slot names its size class.\n */\n buildSlotRefusalMessage(node: ComposedViewNode, slot: ComposedNodeSlotSchema): string {\n if (node.type === \"Widget\") {\n const embeddedWidget = this.findEmbeddableWidget(node);\n if (embeddedWidget === undefined) return this.buildNotEmbeddableMessage(node);\n if (!sizeClassFitsSlot(embeddedWidget.sizeClass, slot.sizeClass as ComposedSizeClass)) {\n return `the widget \"${String(node.props.widget)}\" needs a ${embeddedWidget.sizeClass} slot — the slot \"${slot.name}\" is ${slot.sizeClass}`;\n }\n }\n return `a ${node.type} does not fit the slot \"${slot.name}\" (${slot.sizeClass}) — it accepts ${[\n ...slot.acceptsCategories,\n ...slot.acceptsNodeTypes,\n ].join(\", \")}`;\n }\n\n /** `WidgetComposedViewNode::buildNotEmbeddableMessage()` — the embeddable widgets in schema order. */\n buildNotEmbeddableMessage(node: ComposedViewNode): string {\n const embeddableWidgetNames = Object.keys(this.schema.embeddableWidgets ?? {});\n const writtenWidgetName = typeof node.props.widget === \"string\" ? node.props.widget : \"\";\n return `\"${writtenWidgetName}\" is no embeddable widget — show it as its own widget block next to the ComposedView, never as a Widget node; ${\n embeddableWidgetNames.length === 0 ? \"no widget embeds\" : `only ${embeddableWidgetNames.join(\", \")} embed`\n }`;\n }\n\n /** `ComposedViewNode::isAcceptedBySlot()` — with the embedded-widget rule of `WidgetComposedViewNode`. */\n isNodeAcceptedBySlot(node: ComposedViewNode, slot: ComposedNodeSlotSchema): boolean {\n const categories = this.schema.nodeTypes[node.type]?.categories ?? [];\n if (node.type === \"Widget\") {\n const embeddedWidget = this.findEmbeddableWidget(node);\n return (\n embeddedWidget !== undefined &&\n sizeClassFitsSlot(embeddedWidget.sizeClass, slot.sizeClass as ComposedSizeClass) &&\n (slot.acceptsNodeTypes.includes(\"Widget\") || slot.acceptsCategories.includes(\"heavy\"))\n );\n }\n if (categories.includes(\"heavy\") && slot.sizeClass === \"compact\" && slot.acceptsHeavyWhenCompact !== true)\n return false;\n return (\n slot.acceptsNodeTypes.includes(node.type) ||\n categories.some((category) => slot.acceptsCategories.includes(category))\n );\n }\n\n readProps(node: ComposedViewNode, wireNode: PlainObject, path: string, isInItemScope: boolean): boolean {\n const nodeTypeSchema = this.schema.nodeTypes[node.type];\n for (const [propName, propValue] of Object.entries(wireNode)) {\n if (RESERVED_WIRE_KEYS.includes(propName)) continue;\n const propPath = `${path}.${propName}`;\n const prop = nodeTypeSchema.props.find((candidate) => candidate.name === propName);\n if (!prop) {\n this.addFinding(\"INVALID_PROP\", propPath, `${node.type} has no prop \"${propName}\" — dropped`);\n continue;\n }\n if (this.isValidPropValue(prop, propValue, propPath, isInItemScope))\n node.props[propName] = propValue as JsonValue;\n }\n for (const prop of nodeTypeSchema.props) {\n if (prop.isRequired && !hasOwn(node.props, prop.name)) {\n this.addFinding(\"INVALID_NODE\", path, `${node.type} needs the prop \"${prop.name}\" — the node is dropped`);\n return false;\n }\n }\n return true;\n }\n\n isValidPropValue(\n prop: ComposedNodePropSchema,\n propValue: unknown,\n propPath: string,\n isInItemScope: boolean,\n ): boolean {\n if (prop.types.includes(\"event\")) return this.isValidEvent(propValue, propPath);\n const binding = readComposedViewBinding(propValue);\n if (binding !== null) {\n if (!prop.isBindable) {\n this.addFinding(\"INVALID_PROP\", propPath, \"this prop takes a literal, not a binding\");\n return false;\n }\n return this.isValidBinding(binding, propPath, isInItemScope);\n }\n if (!propAcceptsLiteral(prop, propValue)) {\n this.addFinding(\n \"INVALID_PROP\",\n propPath,\n `a ${prop.types.join(\" or \")} is expected${prop.allowedValues !== null ? ` (one of ${prop.allowedValues.join(\", \")})` : \"\"}`,\n );\n return false;\n }\n if (typeof propValue === \"string\" && codePointLength(propValue) > this.budgets.maxTextLength) {\n this.addFinding(\"BUDGET_EXCEEDED\", propPath, `a text longer than ${this.budgets.maxTextLength} characters`);\n return false;\n }\n return !isPhpArray(propValue) || this.isValidInlineData(propValue, propPath, isInItemScope);\n }\n\n isValidEvent(propValue: unknown, propPath: string): boolean {\n const eventObject = isPlainObject(propValue) && Object.keys(propValue).length === 1 ? propValue : null;\n if (eventObject && typeof eventObject.set === \"string\" && hasOwn(this.tree.state, eventObject.set)) return true;\n if (eventObject && typeof eventObject.action === \"string\" && hasOwn(this.tree.actions, eventObject.action))\n return true;\n this.addFinding(\n \"UNKNOWN_BINDING\",\n propPath,\n 'an event is {\"set\": <a state name>} or {\"action\": <an action name>} of this tree',\n );\n return false;\n }\n\n isValidBinding(binding: ComposedViewBinding, propPath: string, isInItemScope: boolean): boolean {\n let bindingProblem: string | null = null;\n if (!binding.isWellFormed) {\n bindingProblem =\n \"a malformed binding (one of $state, $computed, $data, $item, $from {toolCall, path}, $source {name, params})\";\n } else if (binding.kind === \"state\" && !hasOwn(this.tree.state, binding.target)) {\n bindingProblem = `no state \"${binding.target}\"`;\n } else if (binding.kind === \"computed\" && !hasOwn(this.tree.computed, binding.target)) {\n bindingProblem = `no computed value \"${binding.target}\"`;\n } else if (binding.kind === \"data\" && !hasOwn(this.tree.data, binding.target)) {\n bindingProblem = `no dataset \"${binding.target}\"`;\n } else if (binding.kind === \"item\" && !isInItemScope) {\n bindingProblem = \"$item outside a node that repeats its children\";\n } else if (binding.kind === \"source\") {\n bindingProblem = this.findSourceBindingProblem(binding);\n }\n if (bindingProblem === null) return true;\n this.addFinding(\"UNKNOWN_BINDING\", propPath, `${bindingProblem} — the prop is dropped`);\n return false;\n }\n\n /** `ComposedViewTreeReading::findSourceBindingProblem()`. */\n findSourceBindingProblem(binding: ComposedViewBinding): string | null {\n const dataSource = hasOwn(this.schema.dataSources ?? {}, binding.target)\n ? this.schema.dataSources[binding.target]\n : undefined;\n if (!dataSource) return `no data source \"${binding.target}\"`;\n const declaredParams = new Map(dataSource.params.map((param) => [param.name, param]));\n for (const [paramName, paramValue] of Object.entries(binding.sourceParams)) {\n if (!declaredParams.has(paramName)) return `the data source \"${binding.target}\" has no param \"${paramName}\"`;\n const paramBinding = readComposedViewBinding(paramValue);\n if (paramBinding !== null && (paramBinding.kind !== \"state\" || !hasOwn(this.tree.state, paramBinding.target))) {\n return `the param \"${paramName}\" binds a declared state name only`;\n }\n }\n for (const [paramName, param] of declaredParams) {\n if (param.isRequired && !hasOwn(binding.sourceParams, paramName)) {\n return `the data source \"${binding.target}\" needs the param \"${paramName}\"`;\n }\n }\n return null;\n }\n\n isValidInlineData(inlineData: unknown[] | PlainObject, propPath: string, isInItemScope: boolean): boolean {\n const isList = isPhpList(inlineData);\n if (isList && entriesOf(inlineData).length > this.budgets.maxInlineArrayItems) {\n this.addFinding(\"BUDGET_EXCEEDED\", propPath, `more than ${this.budgets.maxInlineArrayItems} inline items`);\n return false;\n }\n if (\n isPlainObject(inlineData) &&\n hasOwn(inlineData, \"value\") &&\n !hasOwn(inlineData, \"source\") &&\n !hasOwn(inlineData, \"derivedFrom\")\n ) {\n this.addFinding(\n \"INLINE_VALUE_WITHOUT_SOURCE\",\n propPath,\n \"a value without `source` or `derivedFrom` — rendered without a source line\",\n );\n }\n for (const [inlineKey, inlineValue] of entriesOf(inlineData)) {\n const nestedPath = isList ? `${propPath}[${inlineKey}]` : `${propPath}.${inlineKey}`;\n const binding = readComposedViewBinding(inlineValue);\n if (binding !== null) {\n if (!this.isValidBinding(binding, nestedPath, isInItemScope)) return false;\n continue;\n }\n if (isPhpArray(inlineValue)) {\n if (!this.isValidInlineData(inlineValue, nestedPath, isInItemScope)) return false;\n continue;\n }\n if (++this.inlineCellCount > this.budgets.maxInlineCells) {\n this.addFinding(\n \"BUDGET_EXCEEDED\",\n nestedPath,\n `more than ${this.budgets.maxInlineCells} inline cells in the block`,\n );\n return false;\n }\n }\n return true;\n }\n}\n\n/** Nodes in a subtree, the node included. */\nexport const countComposedViewNodes = (node: ComposedViewNode): number =>\n 1 +\n Object.values(node.nodesBySlotName).reduce(\n (slotNodeCount, slotNodes) =>\n slotNodeCount + slotNodes.reduce((sum, slotNode) => sum + countComposedViewNodes(slotNode), 0),\n 0,\n );\n\n/**\n * The tree of the decoded block fields (without `type`), read and checked against `schema`. Fields nested deeper than\n * the backend decodes give no view; objects keyed `\"0\"`, `\"1\"`, … are lists, as `json_decode` makes them.\n */\nexport const readComposedViewTree = (\n widgetFields: Record<string, unknown>,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): ComposedViewTree => {\n const reader = new ComposedViewTreeReader(schema);\n if (exceedsJsonContainerDepth(widgetFields)) {\n reader.addFinding(\n \"BUDGET_EXCEEDED\",\n \"block\",\n `nested deeper than ${MAX_JSON_CONTAINER_DEPTH} levels — malformed, as the backend decodes it; no view is rendered`,\n );\n return reader.tree;\n }\n reader.read(normalizeToPhpArrays(widgetFields) as PlainObject);\n return reader.tree;\n};\n\nconst utf8ByteLength = (text: string): number => new TextEncoder().encode(text).length;\n\n/**\n * The tree of a widget `payload` (the fence's non-`type` fields as a JSON string). A payload that is not a JSON object\n * gives an empty tree; one over the source budget (counted on the canonical bytes, `measureComposedViewSourceBytes`)\n * gives no view and one `BUDGET_EXCEEDED` finding, as on the backend.\n */\nexport const parseComposedViewTree = (\n payload: string,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): ComposedViewTree => {\n const emptyTree: ComposedViewTree = {\n title: null,\n state: {},\n data: {},\n computed: {},\n actions: {},\n view: null,\n findings: [],\n liftedWidgets: [],\n };\n let widgetFields: unknown;\n try {\n widgetFields = JSON.parse(payload);\n } catch {\n return emptyTree;\n }\n if (!isPlainObject(widgetFields)) return emptyTree;\n // The depth check FIRST: measuring serialises the fields, and a deeper value than the backend decodes would throw.\n if (exceedsJsonContainerDepth(widgetFields)) return readComposedViewTree(widgetFields, schema);\n const sourceBytes = measureComposedViewSourceBytes(widgetFields);\n if (sourceBytes > schema.budgets.maxSourceBytes) {\n emptyTree.findings.push({\n code: \"BUDGET_EXCEEDED\",\n path: \"block\",\n message: `the block has ${sourceBytes} bytes, the budget is ${schema.budgets.maxSourceBytes} — no view is rendered`,\n });\n return emptyTree;\n }\n return readComposedViewTree(widgetFields, schema);\n};\n\n/**\n * The bytes the source budget counts — `ComposedViewTreeReading::measureSourceBytes()`: the fields without `type` as\n * compact JSON, so the written fence's whitespace never decides; the legacy `writtenSyntax` field some stored fences carry\n * (`WidgetBlock::LEGACY_WRITTEN_SYNTAX_FIELD`) does not count.\n */\nexport const measureComposedViewSourceBytes = (widgetFields: Record<string, unknown>): number => {\n const { type: unusedType, writtenSyntax: unusedWrittenSyntax, ...fieldsWithoutType } = widgetFields;\n // Measured as PHP encodes the decoded block: objects keyed \"0\", \"1\", … are lists there (`[…]`, without the keys).\n return utf8ByteLength(JSON.stringify(normalizeToPhpArrays(fieldsWithoutType)));\n};\n\n/** The node in its wire form — `ComposedViewNode::toWireArray()`. */\nexport const composedViewNodeToWire = (node: ComposedViewNode): Record<string, JsonValue> => {\n const wireNode: Record<string, JsonValue> = { type: node.type };\n if (node.id !== null) wireNode.id = node.id;\n Object.assign(wireNode, node.props);\n const namedSlots: Record<string, JsonValue> = {};\n for (const [slotName, slotNodes] of Object.entries(node.nodesBySlotName)) {\n if (slotNodes.length === 0) continue;\n const slotWireNodes = slotNodes.map(composedViewNodeToWire);\n if (slotName === DEFAULT_SLOT_NAME) wireNode.children = slotWireNodes;\n else namedSlots[slotName] = slotWireNodes;\n }\n if (Object.keys(namedSlots).length > 0) wireNode.slots = namedSlots;\n return wireNode;\n};\n\n/** The kept tree in its wire form — `ComposedViewConversationWidget::getWidgetFields()` (empty parts left out). */\nexport const composedViewTreeToWire = (tree: ComposedViewTree): Record<string, JsonValue> => {\n const wireFields: Record<string, JsonValue> = {};\n if (tree.title !== null) wireFields.title = tree.title;\n if (Object.keys(tree.state).length > 0) wireFields.state = tree.state;\n if (Object.keys(tree.data).length > 0) wireFields.data = tree.data;\n if (Object.keys(tree.computed).length > 0) wireFields.computed = tree.computed;\n if (tree.view !== null) wireFields.view = composedViewNodeToWire(tree.view);\n if (Object.keys(tree.actions).length > 0) wireFields.actions = tree.actions as unknown as JsonValue;\n return wireFields;\n};\n\n/** `ComposedViewNode::getNodesOfSubtreeByPath()` — every node of a subtree with its kept-tree path, depth first. */\nexport const getComposedViewSubtreeNodesByPath = (\n node: ComposedViewNode,\n path: string,\n): Array<[string, ComposedViewNode]> => [\n [path, node],\n ...Object.entries(node.nodesBySlotName).flatMap(([slotName, slotNodes]) => {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n return slotNodes.flatMap((slotNode, childPosition) =>\n getComposedViewSubtreeNodesByPath(slotNode, `${slotPath}[${childPosition}]`),\n );\n }),\n];\n\n/** Every node of a subtree, depth first, the node first. */\nexport const getComposedViewSubtreeNodes = (node: ComposedViewNode): ComposedViewNode[] => [\n node,\n ...Object.values(node.nodesBySlotName).flatMap((slotNodes) => slotNodes.flatMap(getComposedViewSubtreeNodes)),\n];\n\n/** The slot schema of a node type, or undefined. */\nexport const findComposedViewSlotSchema = (\n nodeType: string,\n slotName: string,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): ComposedNodeSlotSchema | undefined => schema.nodeTypes[nodeType]?.slots.find((slot) => slot.name === slotName);\n\n/**\n * Whether a kept view shows nothing: every node of it is a layout node (a Grid, a Stack or a Surface without a node to\n * hold). The renderer shows the explicit fallback line instead — never a title over an empty Grid.\n */\nexport const isComposedViewWithoutContent = (\n view: ComposedViewNode,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): boolean =>\n getComposedViewSubtreeNodes(view).every((node) => {\n const categories = schema.nodeTypes[node.type]?.categories ?? [];\n return categories.length > 0 && categories.every((category) => category === \"layout\");\n });\n","/**\n * The parser of the `ComposedView` expression language — our own tokenizer and recursive-descent\n * parser, never `eval` or `new Function`. The language is closed:\n *\n * literals 12, 3.5, \"text\", 'text', true, false, null, [a, b], {name: expr, \"key\": expr}\n * names a state, dataset or computed name; a lambda parameter\n * member a.b, a[\"b\"], a[0] (own properties of JSON values only — checked when evaluating)\n * operators + - * / % == != < <= > >= && || ! unary - cond ? a : b\n * calls one of the closed functions (`EXPRESSION_FUNCTION_NAMES`), e.g. sum(rows, r => r.visits)\n * lambdas x => expr, (x) => expr, (x, i) => expr — only as an argument of a call\n *\n * There are no statements, assignments, loops or method calls; a call names a function of the closed list, never a\n * value. The AST node count is capped (`maxExpressionAstNodes`); an expression over it does not compile.\n */\n\nexport type ExpressionNode =\n | { kind: \"literal\"; value: string | number | boolean | null }\n | { kind: \"name\"; name: string }\n | { kind: \"array\"; elements: ExpressionNode[] }\n | { kind: \"object\"; entries: Array<{ key: string; value: ExpressionNode }> }\n | { kind: \"member\"; object: ExpressionNode; property: ExpressionNode }\n | { kind: \"unary\"; operator: \"!\" | \"-\"; operand: ExpressionNode }\n | { kind: \"binary\"; operator: string; left: ExpressionNode; right: ExpressionNode }\n | { kind: \"conditional\"; test: ExpressionNode; consequent: ExpressionNode; alternate: ExpressionNode }\n | { kind: \"call\"; functionName: string; args: ExpressionNode[] }\n | { kind: \"lambda\"; params: string[]; body: ExpressionNode };\n\n/** The closed function list (the evaluator implements exactly these). */\nexport const EXPRESSION_FUNCTION_NAMES = [\n \"round\",\n \"floor\",\n \"ceil\",\n \"abs\",\n \"min\",\n \"max\",\n \"sum\",\n \"avg\",\n \"count\",\n \"len\",\n \"filter\",\n \"map\",\n \"sortBy\",\n \"first\",\n \"last\",\n \"concat\",\n \"join\",\n \"string\",\n \"number\",\n \"fixed\",\n \"percent\",\n] as const;\n\nexport type ExpressionFunctionName = (typeof EXPRESSION_FUNCTION_NAMES)[number];\n\nexport type ExpressionCompileResult =\n | { ok: true; ast: ExpressionNode; nodeCount: number }\n | { ok: false; error: string };\n\ntype Token =\n | { type: \"number\"; value: number }\n | { type: \"string\"; value: string }\n | { type: \"name\"; value: string }\n | { type: \"punct\"; value: string }\n | { type: \"end\" };\n\nconst PUNCTUATORS = [\n \"=>\",\n \"==\",\n \"!=\",\n \"<=\",\n \">=\",\n \"&&\",\n \"||\",\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"%\",\n \"<\",\n \">\",\n \"!\",\n \"?\",\n \":\",\n \".\",\n \",\",\n \"(\",\n \")\",\n \"[\",\n \"]\",\n \"{\",\n \"}\",\n];\n\nclass ExpressionSyntaxError extends Error {}\n\nconst tokenize = (source: string): Token[] => {\n const tokens: Token[] = [];\n let position = 0;\n while (position < source.length) {\n const character = source[position];\n if (/\\s/.test(character)) {\n position++;\n continue;\n }\n if (/[0-9]/.test(character) || (character === \".\" && /[0-9]/.test(source[position + 1] ?? \"\"))) {\n const numberMatch = /^(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(source.slice(position));\n if (!numberMatch) throw new ExpressionSyntaxError(`bad number at ${position}`);\n tokens.push({ type: \"number\", value: Number(numberMatch[0]) });\n position += numberMatch[0].length;\n continue;\n }\n if (character === '\"' || character === \"'\") {\n let text = \"\";\n let cursor = position + 1;\n while (cursor < source.length && source[cursor] !== character) {\n if (source[cursor] === \"\\\\\" && cursor + 1 < source.length) {\n const escaped = source[cursor + 1];\n text += escaped === \"n\" ? \"\\n\" : escaped === \"t\" ? \"\\t\" : escaped;\n cursor += 2;\n continue;\n }\n text += source[cursor];\n cursor++;\n }\n if (cursor >= source.length) throw new ExpressionSyntaxError(\"unclosed string\");\n tokens.push({ type: \"string\", value: text });\n position = cursor + 1;\n continue;\n }\n if (/[A-Za-z_$]/.test(character)) {\n const nameMatch = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(source.slice(position));\n tokens.push({ type: \"name\", value: nameMatch![0] });\n position += nameMatch![0].length;\n continue;\n }\n const punctuator = PUNCTUATORS.find((candidate) => source.startsWith(candidate, position));\n if (!punctuator) throw new ExpressionSyntaxError(`unexpected \"${character}\" at ${position}`);\n tokens.push({ type: \"punct\", value: punctuator });\n position += punctuator.length;\n }\n tokens.push({ type: \"end\" });\n return tokens;\n};\n\nconst BINARY_PRECEDENCE: Array<string[]> = [\n [\"||\"],\n [\"&&\"],\n [\"==\", \"!=\"],\n [\"<\", \"<=\", \">\", \">=\"],\n [\"+\", \"-\"],\n [\"*\", \"/\", \"%\"],\n];\n\nclass ExpressionParser {\n protected position = 0;\n nodeCount = 0;\n\n constructor(\n protected readonly tokens: Token[],\n protected readonly maxNodes: number,\n ) {}\n\n protected peek(): Token {\n return this.tokens[this.position];\n }\n\n protected next(): Token {\n return this.tokens[this.position++];\n }\n\n protected isPunct(value: string, offset = 0): boolean {\n const token = this.tokens[this.position + offset];\n return token !== undefined && token.type === \"punct\" && token.value === value;\n }\n\n protected expectPunct(value: string): void {\n if (!this.isPunct(value)) throw new ExpressionSyntaxError(`\"${value}\" expected`);\n this.position++;\n }\n\n protected node<T extends ExpressionNode>(expressionNode: T): T {\n if (++this.nodeCount > this.maxNodes)\n throw new ExpressionSyntaxError(`more than ${this.maxNodes} expression nodes`);\n return expressionNode;\n }\n\n parseExpression(): ExpressionNode {\n const test = this.parseBinary(0);\n if (!this.isPunct(\"?\")) return test;\n this.position++;\n const consequent = this.parseExpression();\n this.expectPunct(\":\");\n const alternate = this.parseExpression();\n return this.node({ kind: \"conditional\", test, consequent, alternate });\n }\n\n protected parseBinary(level: number): ExpressionNode {\n if (level >= BINARY_PRECEDENCE.length) return this.parseUnary();\n let left = this.parseBinary(level + 1);\n for (;;) {\n const token = this.peek();\n if (token.type !== \"punct\" || !BINARY_PRECEDENCE[level].includes(token.value)) return left;\n this.position++;\n const right = this.parseBinary(level + 1);\n left = this.node({ kind: \"binary\", operator: token.value, left, right });\n }\n }\n\n protected parseUnary(): ExpressionNode {\n if (this.isPunct(\"!\") || this.isPunct(\"-\")) {\n const operator = (this.next() as { value: \"!\" | \"-\" }).value;\n return this.node({ kind: \"unary\", operator, operand: this.parseUnary() });\n }\n return this.parsePostfix(this.parsePrimary());\n }\n\n protected parsePostfix(target: ExpressionNode): ExpressionNode {\n let expressionNode = target;\n for (;;) {\n if (this.isPunct(\".\")) {\n this.position++;\n const propertyToken = this.next();\n if (propertyToken.type !== \"name\") throw new ExpressionSyntaxError('a property name expected after \".\"');\n expressionNode = this.node({\n kind: \"member\",\n object: expressionNode,\n property: this.node({ kind: \"literal\", value: propertyToken.value }),\n });\n continue;\n }\n if (this.isPunct(\"[\")) {\n this.position++;\n const property = this.parseExpression();\n this.expectPunct(\"]\");\n expressionNode = this.node({ kind: \"member\", object: expressionNode, property });\n continue;\n }\n if (this.isPunct(\"(\")) throw new ExpressionSyntaxError(\"only the closed functions can be called\");\n return expressionNode;\n }\n }\n\n protected parseArguments(): ExpressionNode[] {\n const args: ExpressionNode[] = [];\n this.expectPunct(\"(\");\n while (!this.isPunct(\")\")) {\n args.push(this.parseLambdaOrExpression());\n if (!this.isPunct(\",\")) break;\n this.position++;\n }\n this.expectPunct(\")\");\n return args;\n }\n\n /** A lambda (`x => …`, `(x, i) => …`) where a call argument may hold one, else an expression. */\n protected parseLambdaOrExpression(): ExpressionNode {\n const token = this.peek();\n if (token.type === \"name\" && this.isPunct(\"=>\", 1)) {\n this.position += 2;\n return this.node({ kind: \"lambda\", params: [token.value], body: this.parseExpression() });\n }\n if (this.isPunct(\"(\")) {\n let cursor = this.position + 1;\n const params: string[] = [];\n while (this.tokens[cursor]?.type === \"name\") {\n params.push((this.tokens[cursor] as { value: string }).value);\n cursor++;\n const separator = this.tokens[cursor];\n if (separator?.type === \"punct\" && separator.value === \",\") {\n cursor++;\n continue;\n }\n break;\n }\n const closing = this.tokens[cursor];\n const arrow = this.tokens[cursor + 1];\n if (closing?.type === \"punct\" && closing.value === \")\" && arrow?.type === \"punct\" && arrow.value === \"=>\") {\n this.position = cursor + 2;\n return this.node({ kind: \"lambda\", params, body: this.parseExpression() });\n }\n }\n return this.parseExpression();\n }\n\n protected parsePrimary(): ExpressionNode {\n const token = this.next();\n if (token.type === \"number\" || token.type === \"string\") return this.node({ kind: \"literal\", value: token.value });\n if (token.type === \"name\") {\n if (token.value === \"true\" || token.value === \"false\")\n return this.node({ kind: \"literal\", value: token.value === \"true\" });\n if (token.value === \"null\") return this.node({ kind: \"literal\", value: null });\n if (this.isPunct(\"(\")) {\n if (!(EXPRESSION_FUNCTION_NAMES as readonly string[]).includes(token.value)) {\n throw new ExpressionSyntaxError(`\"${token.value}\" is not a function of the closed list`);\n }\n return this.node({ kind: \"call\", functionName: token.value, args: this.parseArguments() });\n }\n return this.node({ kind: \"name\", name: token.value });\n }\n if (token.type === \"punct\" && token.value === \"(\") {\n const inner = this.parseExpression();\n this.expectPunct(\")\");\n return inner;\n }\n if (token.type === \"punct\" && token.value === \"[\") {\n const elements: ExpressionNode[] = [];\n while (!this.isPunct(\"]\")) {\n elements.push(this.parseExpression());\n if (!this.isPunct(\",\")) break;\n this.position++;\n }\n this.expectPunct(\"]\");\n return this.node({ kind: \"array\", elements });\n }\n if (token.type === \"punct\" && token.value === \"{\") {\n const entries: Array<{ key: string; value: ExpressionNode }> = [];\n while (!this.isPunct(\"}\")) {\n const keyToken = this.next();\n if (keyToken.type !== \"name\" && keyToken.type !== \"string\")\n throw new ExpressionSyntaxError(\"an object key expected\");\n this.expectPunct(\":\");\n entries.push({ key: String(keyToken.value), value: this.parseExpression() });\n if (!this.isPunct(\",\")) break;\n this.position++;\n }\n this.expectPunct(\"}\");\n return this.node({ kind: \"object\", entries });\n }\n throw new ExpressionSyntaxError(token.type === \"end\" ? \"unexpected end of expression\" : \"unexpected token\");\n }\n\n parseAll(): ExpressionNode {\n const ast = this.parseExpression();\n if (this.peek().type !== \"end\") throw new ExpressionSyntaxError(\"unexpected text after the expression\");\n return ast;\n }\n}\n\nconst compiledExpressions = new Map<string, ExpressionCompileResult>();\n\n/** Compiles an expression once (cached by source and node budget); never throws. */\nexport const compileExpression = (source: string, maxAstNodes: number): ExpressionCompileResult => {\n const cacheKey = `${maxAstNodes}\\u0000${source}`;\n const cached = compiledExpressions.get(cacheKey);\n if (cached) return cached;\n let compileResult: ExpressionCompileResult;\n try {\n const parser = new ExpressionParser(tokenize(source), maxAstNodes);\n const ast = parser.parseAll();\n compileResult = { ok: true, ast, nodeCount: parser.nodeCount };\n } catch (error) {\n compileResult = { ok: false, error: error instanceof Error ? error.message : \"invalid expression\" };\n }\n if (compiledExpressions.size > 2000) compiledExpressions.clear();\n compiledExpressions.set(cacheKey, compileResult);\n return compileResult;\n};\n\n/** The names an expression reads (lambda parameters excluded) — the computed dependency graph. */\nexport const collectExpressionNames = (\n ast: ExpressionNode,\n boundNames: ReadonlySet<string> = new Set(),\n): Set<string> => {\n const names = new Set<string>();\n const visitNode = (expressionNode: ExpressionNode, scope: ReadonlySet<string>): void => {\n switch (expressionNode.kind) {\n case \"name\":\n if (!scope.has(expressionNode.name)) names.add(expressionNode.name);\n return;\n case \"array\":\n expressionNode.elements.forEach((element) => visitNode(element, scope));\n return;\n case \"object\":\n expressionNode.entries.forEach((entry) => visitNode(entry.value, scope));\n return;\n case \"member\":\n visitNode(expressionNode.object, scope);\n visitNode(expressionNode.property, scope);\n return;\n case \"unary\":\n visitNode(expressionNode.operand, scope);\n return;\n case \"binary\":\n visitNode(expressionNode.left, scope);\n visitNode(expressionNode.right, scope);\n return;\n case \"conditional\":\n visitNode(expressionNode.test, scope);\n visitNode(expressionNode.consequent, scope);\n visitNode(expressionNode.alternate, scope);\n return;\n case \"call\":\n expressionNode.args.forEach((arg) => visitNode(arg, scope));\n return;\n case \"lambda\":\n visitNode(expressionNode.body, new Set([...scope, ...expressionNode.params]));\n return;\n default:\n return;\n }\n };\n visitNode(ast, boundNames);\n return names;\n};\n","import type { ComposedViewBudgets } from \"../composed-node-schema\";\nimport { collectExpressionNames, compileExpression, ExpressionNode } from \"./parse-expression\";\n\n/**\n * The evaluator of the `ComposedView` expression language. Values are JSON values; one value\n * means \"empty\": `undefined` — a missing name or member, a division by zero, a non-finite result, an operation on an\n * empty or wrongly typed operand all give it, and it renders as nothing. Member access reads OWN properties of arrays and\n * plain objects only (never `__proto__`, `constructor`, `prototype`, never a method). Every evaluated node and every\n * element a function walks is charged against ONE operation budget per state update (`maxOperationsPerUpdate`), so a\n * nested `map` / `filter` / `sortBy` cannot run away; collections are capped (`maxCollectionItems`), the elements\n * allocated for intermediate collections are charged by their size as a tree (`maxAllocatedItemsPerEvaluation`), and a\n * text result may not pass `maxTextLength`.\n */\n\nexport type ExpressionValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ExpressionValue[]\n | { [key: string]: ExpressionValue };\n\n/** Why an expression gave no value: it did not compile, it ran over a budget, or it read itself (a cycle). */\nexport type ExpressionErrorCode = \"INVALID_EXPRESSION\" | \"BUDGET_EXCEEDED\";\n\nexport class ExpressionBudgetExceededError extends Error {}\n\nconst BLOCKED_MEMBER_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\ninterface LambdaValue {\n readonly isLambda: true;\n readonly params: string[];\n readonly body: ExpressionNode;\n readonly scope: ReadonlyMap<string, ExpressionValue>;\n}\n\ntype RuntimeValue = ExpressionValue | LambdaValue;\n\nconst isLambda = (value: unknown): value is LambdaValue =>\n typeof value === \"object\" && value !== null && (value as { isLambda?: unknown }).isLambda === true;\nconst isPlainObject = (value: unknown): value is Record<string, ExpressionValue> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && !isLambda(value);\nconst isFiniteNumber = (value: unknown): value is number => typeof value === \"number\" && Number.isFinite(value);\nconst toFiniteOrEmpty = (value: number): number | undefined => (Number.isFinite(value) ? value : undefined);\nconst isTruthy = (value: RuntimeValue): boolean => Boolean(value);\n\n/** The budget counters of one state update, shared by every expression it evaluates. */\nexport class ExpressionBudget {\n operationsLeft: number;\n allocatedItemsLeft: number;\n\n constructor(readonly budgets: ComposedViewBudgets) {\n this.operationsLeft = budgets.maxOperationsPerUpdate;\n this.allocatedItemsLeft = budgets.maxAllocatedItemsPerEvaluation;\n }\n\n charge(operations = 1): void {\n this.operationsLeft -= operations;\n if (this.operationsLeft < 0) throw new ExpressionBudgetExceededError(\"operation budget exceeded\");\n }\n\n allocate(items: number): void {\n this.allocatedItemsLeft -= items;\n if (this.allocatedItemsLeft < 0) throw new ExpressionBudgetExceededError(\"allocation budget exceeded\");\n }\n\n checkCollection(items: ExpressionValue[]): void {\n if (items.length > this.budgets.maxCollectionItems) throw new ExpressionBudgetExceededError(\"collection too large\");\n }\n\n /** A text result may not pass `maxTextLength` — checked on the lengths BEFORE the text is built. */\n checkTextLength(textLength: number): void {\n if (textLength > this.budgets.maxTextLength) throw new ExpressionBudgetExceededError(\"text too long\");\n }\n\n /** The containers this update's expressions built, with their size as a tree (a shared one counted per use). */\n protected readonly createdValueSizes = new WeakMap<object, number>();\n\n /**\n * Charges a container an expression just built by its size as a TREE — a value built from earlier results counts\n * them again wherever it repeats them, so `{l: o, r: o}` over `o` doubles and a chain of such values cannot grow\n * past the allocation budget. A value the expression did not build (a dataset) counts 1.\n */\n allocateCreatedValue(createdValue: ExpressionValue[] | Record<string, ExpressionValue>): void {\n let treeSize = 1;\n for (const element of Object.values(createdValue)) {\n treeSize += typeof element === \"object\" && element !== null ? (this.createdValueSizes.get(element) ?? 1) : 1;\n }\n this.allocate(treeSize);\n this.createdValueSizes.set(createdValue, treeSize);\n }\n}\n\n/** Where a name comes from: lambda parameters first, then the tree's names (state, datasets, computed). */\nexport type ExpressionNameResolver = (name: string) => ExpressionValue;\n\nclass ExpressionEvaluator {\n constructor(\n protected readonly budget: ExpressionBudget,\n protected readonly resolveName: ExpressionNameResolver,\n ) {}\n\n evaluate(expressionNode: ExpressionNode, scope: ReadonlyMap<string, ExpressionValue>): RuntimeValue {\n this.budget.charge();\n switch (expressionNode.kind) {\n case \"literal\":\n return expressionNode.value;\n case \"name\":\n return scope.has(expressionNode.name) ? scope.get(expressionNode.name) : this.resolveName(expressionNode.name);\n case \"array\": {\n const arrayValue = expressionNode.elements.map((element) => this.evaluateValue(element, scope));\n this.budget.allocateCreatedValue(arrayValue);\n return arrayValue;\n }\n case \"object\": {\n const objectValue: Record<string, ExpressionValue> = {};\n for (const entry of expressionNode.entries) {\n if (BLOCKED_MEMBER_NAMES.has(entry.key)) continue;\n objectValue[entry.key] = this.evaluateValue(entry.value, scope);\n }\n this.budget.allocateCreatedValue(objectValue);\n return objectValue;\n }\n case \"member\":\n return this.readMember(\n this.evaluateValue(expressionNode.object, scope),\n this.evaluateValue(expressionNode.property, scope),\n );\n case \"unary\": {\n const operand = this.evaluateValue(expressionNode.operand, scope);\n if (expressionNode.operator === \"!\") return !isTruthy(operand);\n return isFiniteNumber(operand) ? -operand : undefined;\n }\n case \"binary\":\n return this.evaluateBinary(expressionNode.operator, expressionNode.left, expressionNode.right, scope);\n case \"conditional\":\n return isTruthy(this.evaluateValue(expressionNode.test, scope))\n ? this.evaluateValue(expressionNode.consequent, scope)\n : this.evaluateValue(expressionNode.alternate, scope);\n case \"lambda\":\n return { isLambda: true, params: expressionNode.params, body: expressionNode.body, scope };\n case \"call\":\n return this.callFunction(\n expressionNode.functionName,\n expressionNode.args.map((arg) => this.evaluate(arg, scope)),\n );\n default:\n return undefined;\n }\n }\n\n /** A value that is never a lambda (a lambda outside a call argument is empty). */\n evaluateValue(expressionNode: ExpressionNode, scope: ReadonlyMap<string, ExpressionValue>): ExpressionValue {\n const value = this.evaluate(expressionNode, scope);\n return isLambda(value) ? undefined : value;\n }\n\n protected readMember(objectValue: ExpressionValue, propertyValue: ExpressionValue): ExpressionValue {\n if (typeof propertyValue !== \"string\" && typeof propertyValue !== \"number\") return undefined;\n const propertyName = String(propertyValue);\n if (BLOCKED_MEMBER_NAMES.has(propertyName)) return undefined;\n if (Array.isArray(objectValue)) {\n if (propertyName === \"length\") return objectValue.length;\n return Object.prototype.hasOwnProperty.call(objectValue, propertyName)\n ? objectValue[Number(propertyName)]\n : undefined;\n }\n if (isPlainObject(objectValue) && Object.prototype.hasOwnProperty.call(objectValue, propertyName)) {\n return objectValue[propertyName];\n }\n return undefined;\n }\n\n protected evaluateBinary(\n operator: string,\n leftNode: ExpressionNode,\n rightNode: ExpressionNode,\n scope: ReadonlyMap<string, ExpressionValue>,\n ): ExpressionValue {\n if (operator === \"&&\" || operator === \"||\") {\n const left = this.evaluateValue(leftNode, scope);\n if (operator === \"&&\") return isTruthy(left) ? this.evaluateValue(rightNode, scope) : left;\n return isTruthy(left) ? left : this.evaluateValue(rightNode, scope);\n }\n const left = this.evaluateValue(leftNode, scope);\n const right = this.evaluateValue(rightNode, scope);\n switch (operator) {\n case \"==\":\n return left === right;\n case \"!=\":\n return left !== right;\n case \"<\":\n case \"<=\":\n case \">\":\n case \">=\": {\n const comparable =\n (isFiniteNumber(left) && isFiniteNumber(right)) || (typeof left === \"string\" && typeof right === \"string\");\n if (!comparable) return undefined;\n if (operator === \"<\") return (left as number) < (right as number);\n if (operator === \"<=\") return (left as number) <= (right as number);\n if (operator === \">\") return (left as number) > (right as number);\n return (left as number) >= (right as number);\n }\n case \"+\":\n if (isFiniteNumber(left) && isFiniteNumber(right)) return toFiniteOrEmpty(left + right);\n if (\n (typeof left === \"string\" || isFiniteNumber(left)) &&\n (typeof right === \"string\" || isFiniteNumber(right))\n ) {\n const leftText = String(left);\n const rightText = String(right);\n this.budget.checkTextLength(leftText.length + rightText.length);\n return leftText + rightText;\n }\n return undefined;\n case \"-\":\n return isFiniteNumber(left) && isFiniteNumber(right) ? toFiniteOrEmpty(left - right) : undefined;\n case \"*\":\n return isFiniteNumber(left) && isFiniteNumber(right) ? toFiniteOrEmpty(left * right) : undefined;\n case \"/\":\n return isFiniteNumber(left) && isFiniteNumber(right) && right !== 0 ? toFiniteOrEmpty(left / right) : undefined;\n case \"%\":\n return isFiniteNumber(left) && isFiniteNumber(right) && right !== 0 ? toFiniteOrEmpty(left % right) : undefined;\n default:\n return undefined;\n }\n }\n\n protected invokeLambda(lambda: RuntimeValue, args: ExpressionValue[]): ExpressionValue {\n if (!isLambda(lambda)) return undefined;\n const lambdaScope = new Map(lambda.scope);\n lambda.params.forEach((param, index) => lambdaScope.set(param, args[index]));\n return this.evaluateValue(lambda.body, lambdaScope);\n }\n\n /** The list argument of a collection function, capped and charged; undefined when it is no list. */\n protected readList(value: RuntimeValue): ExpressionValue[] | undefined {\n if (!Array.isArray(value)) return undefined;\n this.budget.checkCollection(value);\n this.budget.charge(value.length);\n return value;\n }\n\n /** The numbers of a list, through an optional lambda; non-numbers are skipped. */\n protected readNumbers(listValue: RuntimeValue, lambda?: RuntimeValue): number[] | undefined {\n const list = this.readList(listValue);\n if (list === undefined) return undefined;\n const values =\n lambda === undefined ? list : list.map((element, index) => this.invokeLambda(lambda, [element, index]));\n return values.filter(isFiniteNumber);\n }\n\n protected callFunction(functionName: string, args: RuntimeValue[]): ExpressionValue {\n const [first, second, third] = args;\n switch (functionName) {\n case \"round\": {\n if (!isFiniteNumber(first)) return undefined;\n const digits = isFiniteNumber(second) ? Math.max(0, Math.min(10, Math.trunc(second))) : 0;\n const factor = 10 ** digits;\n return toFiniteOrEmpty(Math.round(first * factor) / factor);\n }\n case \"floor\":\n return isFiniteNumber(first) ? Math.floor(first) : undefined;\n case \"ceil\":\n return isFiniteNumber(first) ? Math.ceil(first) : undefined;\n case \"abs\":\n return isFiniteNumber(first) ? Math.abs(first) : undefined;\n case \"min\":\n case \"max\": {\n const numbers = Array.isArray(first) ? this.readNumbers(first, second) : args.filter(isFiniteNumber);\n if (numbers === undefined || numbers.length === 0) return undefined;\n return functionName === \"min\" ? Math.min(...numbers) : Math.max(...numbers);\n }\n case \"sum\": {\n const numbers = this.readNumbers(first, second);\n return numbers === undefined ? undefined : toFiniteOrEmpty(numbers.reduce((total, value) => total + value, 0));\n }\n case \"avg\": {\n const numbers = this.readNumbers(first, second);\n if (numbers === undefined || numbers.length === 0) return undefined;\n return toFiniteOrEmpty(numbers.reduce((total, value) => total + value, 0) / numbers.length);\n }\n case \"count\": {\n const list = this.readList(first);\n if (list === undefined) return undefined;\n if (second === undefined) return list.length;\n return list.filter((element, index) => isTruthy(this.invokeLambda(second, [element, index]))).length;\n }\n case \"len\":\n if (typeof first === \"string\") return [...first].length;\n return Array.isArray(first) ? first.length : undefined;\n case \"filter\": {\n const list = this.readList(first);\n if (list === undefined || !isLambda(second)) return undefined;\n const kept = list.filter((element, index) => isTruthy(this.invokeLambda(second, [element, index])));\n this.budget.allocateCreatedValue(kept);\n return kept;\n }\n case \"map\": {\n const list = this.readList(first);\n if (list === undefined || !isLambda(second)) return undefined;\n const mapped = list.map((element, index) => this.invokeLambda(second, [element, index]));\n this.budget.allocateCreatedValue(mapped);\n return mapped;\n }\n case \"sortBy\": {\n const list = this.readList(first);\n if (list === undefined || !isLambda(second)) return undefined;\n this.budget.charge(Math.ceil(list.length * Math.log2(list.length + 1)));\n const direction = third === \"desc\" ? -1 : 1;\n const keyed = list.map((element, index) => ({\n element,\n key: this.invokeLambda(second, [element, index]),\n index,\n }));\n keyed.sort((a, b) => {\n const comparison =\n isFiniteNumber(a.key) && isFiniteNumber(b.key)\n ? a.key - b.key\n : typeof a.key === \"string\" && typeof b.key === \"string\"\n ? a.key.localeCompare(b.key)\n : a.key === undefined\n ? 1\n : b.key === undefined\n ? -1\n : 0;\n return comparison !== 0 ? comparison * direction : a.index - b.index;\n });\n const sorted = keyed.map((entry) => entry.element);\n this.budget.allocateCreatedValue(sorted);\n return sorted;\n }\n case \"first\": {\n const list = this.readList(first);\n return list === undefined ? undefined : list[0];\n }\n case \"last\": {\n const list = this.readList(first);\n return list === undefined ? undefined : list[list.length - 1];\n }\n case \"concat\": {\n const lists = args.map((arg) => this.readList(arg));\n if (lists.some((list) => list === undefined)) return undefined;\n const joined = (lists as ExpressionValue[][]).flat(1);\n this.budget.checkCollection(joined);\n this.budget.allocateCreatedValue(joined);\n return joined;\n }\n case \"join\": {\n const list = this.readList(first);\n if (list === undefined) return undefined;\n const separator = typeof second === \"string\" ? second : \", \";\n const joinedParts = list\n .filter((element) => typeof element === \"string\" || isFiniteNumber(element))\n .map((element) => String(element));\n this.budget.checkTextLength(\n joinedParts.reduce((textLength, part) => textLength + part.length, 0) +\n separator.length * Math.max(0, joinedParts.length - 1),\n );\n return joinedParts.join(separator);\n }\n case \"string\": {\n if (typeof first !== \"string\" && !isFiniteNumber(first) && typeof first !== \"boolean\") return undefined;\n const text = String(first);\n this.budget.checkTextLength(text.length);\n return text;\n }\n case \"number\": {\n if (isFiniteNumber(first)) return first;\n if (typeof first !== \"string\" || first.trim() === \"\") return undefined;\n return toFiniteOrEmpty(Number(first));\n }\n case \"fixed\": {\n if (!isFiniteNumber(first)) return undefined;\n const digits = isFiniteNumber(second) ? Math.max(0, Math.min(10, Math.trunc(second))) : 0;\n return first.toFixed(digits);\n }\n case \"percent\": {\n if (!isFiniteNumber(first) || !isFiniteNumber(second) || second === 0) return undefined;\n const digits = isFiniteNumber(third) ? Math.max(0, Math.min(10, Math.trunc(third))) : 0;\n const factor = 10 ** digits;\n return toFiniteOrEmpty(Math.round((first / second) * 100 * factor) / factor);\n }\n default:\n return undefined;\n }\n }\n}\n\nexport type ExpressionEvaluationResult =\n | { ok: true; value: ExpressionValue }\n | { ok: false; errorCode: ExpressionErrorCode; message: string };\n\n/** Compiles (cached) and evaluates one expression; never throws. */\nexport const evaluateExpression = (\n source: string,\n resolveName: ExpressionNameResolver,\n budget: ExpressionBudget,\n): ExpressionEvaluationResult => {\n const compiled = compileExpression(source, budget.budgets.maxExpressionAstNodes);\n if (!compiled.ok) return { ok: false, errorCode: \"INVALID_EXPRESSION\", message: compiled.error };\n try {\n return { ok: true, value: new ExpressionEvaluator(budget, resolveName).evaluateValue(compiled.ast, new Map()) };\n } catch (error) {\n if (error instanceof ExpressionBudgetExceededError)\n return { ok: false, errorCode: \"BUDGET_EXCEEDED\", message: error.message };\n return {\n ok: false,\n errorCode: \"INVALID_EXPRESSION\",\n message: error instanceof Error ? error.message : \"evaluation failed\",\n };\n }\n};\n\nexport interface ComputedValuesResult {\n values: Record<string, ExpressionValue>;\n errors: Record<string, { errorCode: ExpressionErrorCode; message: string }>;\n}\n\n/**\n * Every computed value of a tree for one state: each expression evaluated once, in dependency order (a computed value\n * may read state, datasets and other computed values), under ONE budget. A cycle or a dependency chain deeper than\n * `maxComputedDependencyDepth` leaves the values involved empty with `INVALID_EXPRESSION`.\n */\nexport const computeComposedViewValues = (\n computed: Record<string, string>,\n state: Record<string, ExpressionValue>,\n datasets: Record<string, ExpressionValue>,\n budgets: ComposedViewBudgets,\n): ComputedValuesResult => {\n const budget = new ExpressionBudget(budgets);\n const result: ComputedValuesResult = { values: {}, errors: {} };\n const evaluating: string[] = [];\n const done = new Set<string>();\n\n const resolveTreeName = (name: string): ExpressionValue => {\n if (Object.prototype.hasOwnProperty.call(state, name)) return state[name];\n if (Object.prototype.hasOwnProperty.call(datasets, name)) return datasets[name];\n if (Object.prototype.hasOwnProperty.call(computed, name)) return computeOne(name);\n return undefined;\n };\n\n const computeOne = (name: string): ExpressionValue => {\n if (done.has(name)) return result.values[name];\n if (evaluating.includes(name)) {\n for (const cycleName of evaluating.slice(evaluating.indexOf(name))) {\n result.errors[cycleName] = {\n errorCode: \"INVALID_EXPRESSION\",\n message: `a cycle: ${[...evaluating, name].join(\" → \")}`,\n };\n }\n return undefined;\n }\n if (evaluating.length >= budgets.maxComputedDependencyDepth) {\n result.errors[name] = {\n errorCode: \"INVALID_EXPRESSION\",\n message: `deeper than ${budgets.maxComputedDependencyDepth} computed values`,\n };\n return undefined;\n }\n evaluating.push(name);\n const evaluation = evaluateExpression(computed[name], resolveTreeName, budget);\n evaluating.pop();\n done.add(name);\n if (result.errors[name]) {\n result.values[name] = undefined;\n return undefined;\n }\n if (!evaluation.ok) {\n result.errors[name] = { errorCode: evaluation.errorCode, message: evaluation.message };\n result.values[name] = undefined;\n return undefined;\n }\n result.values[name] = evaluation.value;\n return evaluation.value;\n };\n\n for (const name of Object.keys(computed)) computeOne(name);\n return result;\n};\n\n/** The tree names a computed expression reads, for its dependency list (empty when it does not compile). */\nexport const findExpressionDependencies = (source: string, maxAstNodes: number): string[] => {\n const compiled = compileExpression(source, maxAstNodes);\n return compiled.ok ? [...collectExpressionNames(compiled.ast)] : [];\n};\n","import { useCallback, useMemo, useReducer, useRef } from \"react\";\nimport type { ComposedViewBudgets } from \"./composed-node-schema\";\nimport type { ComposedViewTree } from \"./composed-view-tree\";\n\n/**\n * The local state of one `ComposedView` instance: initialised from the tree's `state`, changed only by\n * the tree's own inputs (`onChange: {\"set\": …}`) and the `resetState` action — never written anywhere, so a replayed\n * message's inputs stay usable. Budgets: a string longer than `maxStateStringLength` is cut, a name the tree did\n * not declare is ignored, and at most `maxInputUpdatesPerSecond` updates per second are applied (a dragged slider\n * cannot flood the evaluator). A new tree (the payload changed under the same instance) starts from its own state.\n */\n\nexport type ComposedViewStateValue = string | number | boolean | null;\n\ntype StateValues = Record<string, ComposedViewStateValue>;\n\n/** The values with the tree state they started from — a NEW tree (another payload) starts again from its own state. */\ninterface StateBox {\n initialState: StateValues;\n values: StateValues;\n}\n\ntype StateAction =\n | { kind: \"set\"; name: string; value: ComposedViewStateValue; initialState: StateValues }\n | { kind: \"reset\"; initialState: StateValues };\n\n/** The values for `initialState`: the box's while it still belongs to that tree, else the tree's own initial state. */\nconst valuesOfTree = (stateBox: StateBox, initialState: StateValues): StateValues =>\n stateBox.initialState === initialState ? stateBox.values : initialState;\n\nconst stateReducer = (stateBox: StateBox, action: StateAction): StateBox => {\n const { initialState } = action;\n if (action.kind === \"reset\") return { initialState, values: initialState };\n const currentValues = valuesOfTree(stateBox, initialState);\n if (!Object.prototype.hasOwnProperty.call(initialState, action.name)) return { initialState, values: currentValues };\n if (currentValues[action.name] === action.value) return { initialState, values: currentValues };\n return { initialState, values: { ...currentValues, [action.name]: action.value } };\n};\n\nexport interface ComposedViewStateStore {\n state: Record<string, ComposedViewStateValue>;\n setStateValue: (name: string, value: unknown) => void;\n resetState: () => void;\n}\n\nconst toStateValue = (value: unknown, budgets: ComposedViewBudgets): ComposedViewStateValue | undefined => {\n if (typeof value === \"string\") return [...value].slice(0, budgets.maxStateStringLength).join(\"\");\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value === \"boolean\" || value === null) return value;\n return undefined;\n};\n\nexport const useComposedViewState = (tree: ComposedViewTree, budgets: ComposedViewBudgets): ComposedViewStateStore => {\n const initialState = tree.state;\n const [stateBox, dispatch] = useReducer(stateReducer, { initialState, values: initialState });\n const state = valuesOfTree(stateBox, initialState);\n const updateTimestamps = useRef<number[]>([]);\n\n const setStateValue = useCallback(\n (name: string, value: unknown) => {\n const stateValue = toStateValue(value, budgets);\n if (stateValue === undefined) return;\n const now = Date.now();\n updateTimestamps.current = updateTimestamps.current.filter((timestamp) => now - timestamp < 1000);\n if (updateTimestamps.current.length >= budgets.maxInputUpdatesPerSecond) return;\n updateTimestamps.current.push(now);\n dispatch({ kind: \"set\", name, value: stateValue, initialState });\n },\n [budgets, initialState],\n );\n const resetState = useCallback(() => dispatch({ kind: \"reset\", initialState }), [initialState]);\n\n return useMemo(() => ({ state, setStateValue, resetState }), [state, setStateValue, resetState]);\n};\n","import type { ExpressionValue } from \"./expression/evaluate-expression\";\nimport { JsonValue, readComposedViewBinding, readComposedViewRowField } from \"./composed-view-tree\";\n\n/**\n * Turns bound props and datasets of a `ComposedView` tree into values. A binding is resolved in the\n * browser from what the tree already holds: `$state` (the instance state), `$computed` (the evaluated expressions),\n * `$data` (a dataset), `$item` (a field of the current row of an item scope — a dotted `author.name` reads a nested\n * object, `readComposedViewRowField`), `$from` (the snapshot the backend writes INTO the\n * binding when the row is stored — `{\"$from\": {\"toolCall\", \"path\", \"state\": \"resolved\", \"value\": …}}`;\n * before that the binding is `pending`) and `$source` (a registered data source the frontend hydrates through the\n * widget-hydration mechanism, `composed-view-data-sources.ts`; looked up by its binding key, `pending` until the rows\n * arrive). A value that does not resolve is `undefined` and the prop renders empty.\n */\n\nexport type ResolvedBindingStatus = \"resolved\" | \"pending\" | \"failed\";\n\nexport interface ComposedViewValueScope {\n state: Record<string, ExpressionValue>;\n computed: Record<string, ExpressionValue>;\n datasets: Record<string, ExpressionValue>;\n /**\n * Each dataset's binding status (`resolveComposedViewDatasets().statusByDatasetName`): a prop bound with `$data` to a\n * dataset whose `$from` / `$source` is still pending is pending itself, exactly like a direct `$from` binding.\n */\n datasetStatuses?: Record<string, ResolvedBindingStatus>;\n /** The current row of the innermost item scope (`Repeat`), when inside one. */\n item?: ExpressionValue;\n /** The hydrated `$source` values, by binding key (`composedViewSourceBindingKey`). */\n sources?: Record<string, ComposedViewSourceValue>;\n}\n\nexport interface ComposedViewSourceValue {\n status: ResolvedBindingStatus;\n value: ExpressionValue;\n}\n\n/** The identity of a `$source` wire value — its name and parameters as written; null for another value. */\nexport const composedViewSourceBindingKey = (wireValue: unknown): string | null => {\n const binding = readComposedViewBinding(wireValue);\n if (binding === null || binding.kind !== \"source\" || !binding.isWellFormed) return null;\n return `${binding.target}|${JSON.stringify(binding.sourceParams)}`;\n};\n\nconst readSourceValue = (\n wireValue: unknown,\n sourceValuesByBindingKey: Record<string, ComposedViewSourceValue> | undefined,\n): ComposedViewSourceValue => {\n const bindingKey = composedViewSourceBindingKey(wireValue);\n if (bindingKey === null) return { status: \"failed\", value: undefined };\n return sourceValuesByBindingKey?.[bindingKey] ?? { status: \"pending\", value: undefined };\n};\n\nexport interface ResolvedComposedViewDatasets {\n datasets: Record<string, ExpressionValue>;\n statusByDatasetName: Record<string, ResolvedBindingStatus>;\n}\n\nconst hasOwn = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key);\n\n/** The value and status a `$from` binding's stored snapshot carries. */\nexport const readFromBindingSnapshot = (\n fromBindingObject: Record<string, unknown>,\n): { status: ResolvedBindingStatus; value: ExpressionValue } => {\n const snapshotState = fromBindingObject.state;\n if (snapshotState === \"resolved\") return { status: \"resolved\", value: fromBindingObject.value as ExpressionValue };\n if (snapshotState === \"failed\") return { status: \"failed\", value: undefined };\n return { status: \"pending\", value: undefined };\n};\n\n/**\n * The tree's datasets as values: inline rows as written, `$from` from its snapshot, `$source` from\n * `sourceValuesByBindingKey` (filled by the data-source hydration; pending without).\n */\nexport const resolveComposedViewDatasets = (\n data: Record<string, JsonValue>,\n sourceValuesByBindingKey: Record<string, ComposedViewSourceValue> = {},\n): ResolvedComposedViewDatasets => {\n const resolved: ResolvedComposedViewDatasets = { datasets: {}, statusByDatasetName: {} };\n for (const [datasetName, dataset] of Object.entries(data)) {\n const binding = readComposedViewBinding(dataset);\n if (binding === null) {\n resolved.datasets[datasetName] = dataset as ExpressionValue;\n resolved.statusByDatasetName[datasetName] = \"resolved\";\n continue;\n }\n const snapshot =\n binding.kind === \"from\"\n ? readFromBindingSnapshot((binding.wireValue.$from ?? {}) as Record<string, unknown>)\n : readSourceValue(dataset, sourceValuesByBindingKey);\n resolved.datasets[datasetName] = snapshot.value;\n resolved.statusByDatasetName[datasetName] = snapshot.status;\n }\n return resolved;\n};\n\n/** One prop value with its bindings resolved (nested bindings in inline data included). */\nexport const resolveComposedViewValue = (\n wireValue: JsonValue | undefined,\n scope: ComposedViewValueScope,\n onBindingStatus?: (status: ResolvedBindingStatus) => void,\n): ExpressionValue => {\n const binding = readComposedViewBinding(wireValue);\n if (binding !== null) {\n switch (binding.kind) {\n case \"state\":\n return hasOwn(scope.state, binding.target) ? scope.state[binding.target] : undefined;\n case \"computed\":\n return hasOwn(scope.computed, binding.target) ? scope.computed[binding.target] : undefined;\n case \"data\": {\n const datasetStatus = scope.datasetStatuses?.[binding.target];\n if (datasetStatus !== undefined) onBindingStatus?.(datasetStatus);\n return hasOwn(scope.datasets, binding.target) ? scope.datasets[binding.target] : undefined;\n }\n case \"item\": {\n const rowField = readComposedViewRowField(scope.item, binding.target);\n return rowField.found ? (rowField.value as ExpressionValue) : undefined;\n }\n case \"from\": {\n const snapshot = readFromBindingSnapshot((binding.wireValue.$from ?? {}) as Record<string, unknown>);\n onBindingStatus?.(snapshot.status);\n return snapshot.value;\n }\n case \"source\": {\n const sourceValue = readSourceValue(wireValue, scope.sources);\n onBindingStatus?.(sourceValue.status);\n return sourceValue.value;\n }\n default:\n onBindingStatus?.(\"pending\");\n return undefined;\n }\n }\n if (Array.isArray(wireValue))\n return wireValue.map((element) => resolveComposedViewValue(element, scope, onBindingStatus));\n if (typeof wireValue === \"object\" && wireValue !== null) {\n return Object.fromEntries(\n Object.entries(wireValue).map(([key, nested]) => [key, resolveComposedViewValue(nested, scope, onBindingStatus)]),\n );\n }\n return wireValue;\n};\n","import { registerWidgetHydrator } from \"../widget-hydration\";\nimport { getComposedNodeSchema, ComposedNodeSchema } from \"./composed-node-schema\";\nimport {\n ComposedViewNode,\n ComposedViewTree,\n getComposedViewSubtreeNodes,\n JsonValue,\n readComposedViewBinding,\n} from \"./composed-view-tree\";\nimport type { ExpressionValue } from \"./expression/evaluate-expression\";\nimport { composedViewSourceBindingKey } from \"./resolve-composed-view-values\";\n\n/**\n * The frontend side of the `$source` data path: a registered source is read through the existing\n * widget-hydration mechanism (`widget-hydration/`), so the e-mail capture waits for it like for any self-hydrating\n * widget. A source is added with TWO files: the backend `<Name>ComposedViewDataSource` (endpoint, params,\n * columns — exported into the schema) and the frontend fetcher `<name>.composed-data-source.ts` anywhere below\n * `widgets/` exporting `composedViewDataSourceFetcher` (it reads the endpoint through the generated SDK store and returns\n * the response; the rows are taken at the schema's `rowsPath`). The read rights are the endpoint's own entity rights,\n * server-side — the fetcher passes the agent space key and the parameters, nothing else.\n */\n\nexport interface ComposedViewDataSourceFetcher {\n /** The source name (the backend `NAME`). */\n name: string;\n /** Reads the source for an agent space and the resolved parameters; resolves with the endpoint's response. */\n fetchResponse: (\n params: Record<string, ExpressionValue>,\n agentSpaceKey: number | undefined,\n signal: AbortSignal,\n ) => Promise<unknown>;\n}\n\nexport interface ComposedViewDataSourcePayload {\n params: Record<string, ExpressionValue>;\n agentSpaceKey: number | undefined;\n}\n\n/** The hydration type a source registers under. */\nexport const composedViewDataSourceHydrationType = (dataSourceName: string): string =>\n `ComposedViewDataSource:${dataSourceName}`;\n\n/** The rows at a schema `rowsPath` (`$`, `$.field`, `$.a.b`) of a response; undefined when the path does not hold a list. */\nexport const readRowsAtPath = (response: unknown, rowsPath: string): ExpressionValue[] | undefined => {\n let current: unknown = response;\n for (const segment of rowsPath\n .replace(/^\\$\\.?/, \"\")\n .split(\".\")\n .filter(Boolean)) {\n if (typeof current !== \"object\" || current === null || !Object.prototype.hasOwnProperty.call(current, segment)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return Array.isArray(current) ? (current as ExpressionValue[]) : undefined;\n};\n\nconst registeredFetcherNames = new Set<string>();\n\n/** Registers a fetcher as a widget hydrator; the rows land in the hydration memory like any widget's data. */\nexport const registerComposedViewDataSourceFetcher = (\n fetcher: ComposedViewDataSourceFetcher,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): void => {\n const dataSourceSchema = schema.dataSources?.[fetcher.name];\n registeredFetcherNames.add(fetcher.name);\n registerWidgetHydrator<ComposedViewDataSourcePayload, ExpressionValue[]>(\n composedViewDataSourceHydrationType(fetcher.name),\n {\n hydrator: async (payload, context) => {\n const response = await fetcher.fetchResponse(payload.params, payload.agentSpaceKey, context.signal);\n const rows = readRowsAtPath(response, dataSourceSchema?.rowsPath ?? \"$\");\n if (rows === undefined)\n throw new Error(`the data source \"${fetcher.name}\" returned no rows at ${dataSourceSchema?.rowsPath ?? \"$\"}`);\n return rows.slice(0, schema.budgets.maxCollectionItems);\n },\n deriveKey: (type, payload) => `${type}:${payload.agentSpaceKey ?? \"active\"}:${JSON.stringify(payload.params)}`,\n staleMs: (dataSourceSchema?.freshnessSeconds ?? 300) * 1000,\n },\n );\n};\n\n/** Whether a fetcher is registered for a source name. */\nexport const hasComposedViewDataSourceFetcher = (dataSourceName: string): boolean =>\n registeredFetcherNames.has(dataSourceName);\n\nconst fetcherModules = import.meta.glob<{ composedViewDataSourceFetcher?: ComposedViewDataSourceFetcher }>(\n [\"../../widgets/**/*.composed-data-source.ts\", \"../../kit/**/*.composed-data-source.ts\"],\n { eager: true },\n);\nfor (const fetcherModule of Object.values(fetcherModules)) {\n if (fetcherModule.composedViewDataSourceFetcher)\n registerComposedViewDataSourceFetcher(fetcherModule.composedViewDataSourceFetcher);\n}\n\n/** One `$source` binding of a tree, with its parameters as written (`$state` bindings inside). */\nexport interface ComposedViewSourceBinding {\n /** The binding's identity in the tree: name + parameters as written. */\n bindingKey: string;\n dataSourceName: string;\n writtenParams: Record<string, JsonValue>;\n}\n\nconst collectFromValue = (value: unknown, sourceBindings: Map<string, ComposedViewSourceBinding>): void => {\n const binding = readComposedViewBinding(value);\n if (binding !== null) {\n const bindingKey = composedViewSourceBindingKey(value);\n if (bindingKey !== null && !sourceBindings.has(bindingKey)) {\n sourceBindings.set(bindingKey, {\n bindingKey,\n dataSourceName: binding.target,\n writtenParams: binding.sourceParams as Record<string, JsonValue>,\n });\n }\n return;\n }\n if (Array.isArray(value)) value.forEach((element) => collectFromValue(element, sourceBindings));\n else if (typeof value === \"object\" && value !== null)\n Object.values(value).forEach((nested) => collectFromValue(nested, sourceBindings));\n};\n\n/** Every distinct `$source` binding of a tree — its datasets and every node's props — in tree order. */\nexport const collectComposedViewSourceBindings = (tree: ComposedViewTree): ComposedViewSourceBinding[] => {\n const sourceBindings = new Map<string, ComposedViewSourceBinding>();\n collectFromValue(tree.data, sourceBindings);\n const nodes: ComposedViewNode[] = tree.view ? getComposedViewSubtreeNodes(tree.view) : [];\n for (const node of nodes) collectFromValue(node.props, sourceBindings);\n return [...sourceBindings.values()];\n};\n\n/** The parameters with their `$state` bindings resolved against the instance state. */\nexport const resolveComposedViewSourceParams = (\n writtenParams: Record<string, JsonValue>,\n state: Record<string, ExpressionValue>,\n): Record<string, ExpressionValue> =>\n Object.fromEntries(\n Object.entries(writtenParams).map(([paramName, paramValue]) => {\n const paramBinding = readComposedViewBinding(paramValue);\n if (paramBinding?.kind === \"state\") {\n return [\n paramName,\n Object.prototype.hasOwnProperty.call(state, paramBinding.target) ? state[paramBinding.target] : undefined,\n ];\n }\n return [paramName, paramValue as ExpressionValue];\n }),\n );\n","import type { ComponentType } from \"react\";\nimport ReactApexChartImport from \"react-apexcharts\";\nimport type { Props as ReactApexChartProps } from \"react-apexcharts\";\n\n/**\n * The `react-apexcharts` component, whatever the bundler made of its CommonJS export: the app build hands the\n * component itself, the Storybook / preview Vite dev server the module object with the component on `default`\n * (rendering that object throws \"Element type is invalid … got: object\").\n */\nconst moduleWithDefault = ReactApexChartImport as unknown as { default?: ComponentType<ReactApexChartProps> };\n\nexport const ApexChart: ComponentType<ReactApexChartProps> =\n moduleWithDefault.default ?? (ReactApexChartImport as unknown as ComponentType<ReactApexChartProps>);\n","/**\n * The ONE tone list of the composable kit (the backend twin is `ComposedViewTone.php`):\n * the judgement or role a text, a badge, a value, an icon or a map status line takes. Every node with a `tone` prop\n * reads it through {@link readComposedViewTone}, so a model that learned one word uses it everywhere. The words some\n * nodes accepted before the list existed stay accepted on the wire (both tree readers list them as allowed values) and\n * read as their tone here: `default` (Text) is `neutral`, `positive` / `negative` (Map status lines) are `success` /\n * `danger`.\n */\nexport const COMPOSED_VIEW_TONES = [\"neutral\", \"muted\", \"success\", \"warning\", \"danger\", \"info\"] as const;\n\nexport type ComposedViewTone = (typeof COMPOSED_VIEW_TONES)[number];\n\n/** The older words, accepted on the wire and read as their tone. */\nexport const COMPOSED_VIEW_TONE_ALIASES: Readonly<Record<string, ComposedViewTone>> = {\n default: \"neutral\",\n positive: \"success\",\n negative: \"danger\",\n};\n\nconst isComposedViewTone = (value: string): value is ComposedViewTone =>\n (COMPOSED_VIEW_TONES as readonly string[]).includes(value);\n\n/** The tone a prop names — one of the list or an alias — else `fallback` (a bound value may hold anything). */\nexport const readComposedViewTone = (value: unknown, fallback: ComposedViewTone = \"neutral\"): ComposedViewTone => {\n if (typeof value !== \"string\") return fallback;\n if (isComposedViewTone(value)) return value;\n return Object.prototype.hasOwnProperty.call(COMPOSED_VIEW_TONE_ALIASES, value)\n ? COMPOSED_VIEW_TONE_ALIASES[value]\n : fallback;\n};\n\n/** The tone a prop names, or `undefined` when it names none (a status line without a tone stays plain). */\nexport const readOptionalComposedViewTone = (value: unknown): ComposedViewTone | undefined =>\n typeof value === \"string\" && (isComposedViewTone(value) || value in COMPOSED_VIEW_TONE_ALIASES)\n ? readComposedViewTone(value)\n : undefined;\n\n/** The text colour of a tone, for the component library's `Text`'s `color` prop — judgement text in the 900 step (500 on dark). */\nexport const COMPOSED_VIEW_TONE_TEXT_COLOR: Readonly<Record<ComposedViewTone, string>> = {\n neutral: \"var(--agents-fg)\",\n muted: \"var(--agents-fg-light)\",\n success: \"light-dark(var(--agents-success-900), var(--agents-success-500))\",\n warning: \"light-dark(var(--agents-warning-900), var(--agents-warning-500))\",\n danger: \"light-dark(var(--agents-danger-900), var(--agents-danger-500))\",\n info: \"light-dark(var(--agents-info-900), var(--agents-info-500))\",\n};\n\n/** The graphic colour of a tone — an icon fill in the 500 step. */\nexport const COMPOSED_VIEW_TONE_GRAPHIC_COLOR: Readonly<Record<ComposedViewTone, string>> = {\n neutral: \"var(--agents-fg)\",\n muted: \"var(--agents-fg-light)\",\n success: \"var(--agents-success-500)\",\n warning: \"var(--agents-warning-500)\",\n danger: \"var(--agents-danger-500)\",\n info: \"var(--agents-info-500)\",\n};\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n ComposedViewTone,\n readComposedViewTone,\n} from \"../../composed-view-tones\";\n\n/**\n * How the data nodes show a value — the frontend twin of `ComposedViewDataValueFormat.php`: the\n * closed `format`, `tone` and `align` words every data node accepts, and the one formatter they all use, so a number\n * reads the same in a KPI tile, a table cell and a chart axis. Pure functions, no React.\n */\n\nexport type DataValueFormat = \"number\" | \"percent\" | \"currency\" | \"compact\" | \"date\" | \"text\";\n/** The kit's one tone list (`composed-view-tones.ts`). */\nexport type DataValueTone = ComposedViewTone;\nexport type DataValueAlign = \"start\" | \"center\" | \"end\";\n\nconst DATA_VALUE_FORMATS: readonly DataValueFormat[] = [\"number\", \"percent\", \"currency\", \"compact\", \"date\", \"text\"];\nconst DATA_VALUE_ALIGNS: readonly DataValueAlign[] = [\"start\", \"center\", \"end\"];\n\n/** The value as one of `allowed`, or `fallback` (a resolved binding may carry anything). */\nconst readOneOf = <T extends string>(value: unknown, allowed: readonly T[], fallback: T): T =>\n typeof value === \"string\" && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;\n\nexport const readDataValueFormat = (value: unknown, fallback: DataValueFormat = \"number\"): DataValueFormat =>\n readOneOf(value, DATA_VALUE_FORMATS, fallback);\nexport const readDataValueTone = (value: unknown, fallback: DataValueTone = \"neutral\"): DataValueTone =>\n readComposedViewTone(value, fallback);\nexport const readDataValueAlign = (value: unknown, fallback: DataValueAlign = \"start\"): DataValueAlign =>\n readOneOf(value, DATA_VALUE_ALIGNS, fallback);\n\n/** A finite number from a number or a numeric string (\"1207\", \"36.5\"); undefined otherwise. */\nexport const readFiniteNumber = (value: unknown): number | undefined => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value === \"string\" && value.trim() !== \"\" && /^[-+]?\\d*\\.?\\d+(e[-+]?\\d+)?$/i.test(value.trim())) {\n const parsed = Number(value.trim());\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n};\n\n/** A string prop, or undefined (a binding resolved to a non-string, an absent prop). */\nexport const readText = (value: unknown): string | undefined =>\n typeof value === \"string\" && value !== \"\" ? value : typeof value === \"number\" ? String(value) : undefined;\n\n/** The plain object a resolved prop holds, or undefined. */\nexport const readObject = (value: unknown): Record<string, ExpressionValue> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, ExpressionValue>)\n : undefined;\n\n/** The rows (plain objects) a resolved `data` / `rows` / `items` prop holds; non-object entries are skipped. */\nexport const readRows = (value: unknown): Record<string, ExpressionValue>[] | undefined =>\n Array.isArray(value)\n ? value.filter(\n (row): row is Record<string, ExpressionValue> => typeof row === \"object\" && row !== null && !Array.isArray(row),\n )\n : undefined;\n\n/** The locale the numbers are written in: the app's UI language, `en` when it is unset or invalid. */\nexport const toNumberLocale = (languageCode: string | undefined): string => {\n if (!languageCode) return \"en\";\n try {\n return Intl.NumberFormat.supportedLocalesOf([languageCode.replace(\"_\", \"-\")])[0] ?? \"en\";\n } catch {\n return \"en\";\n }\n};\n\nexport interface DataValueFormatOptions {\n format?: DataValueFormat;\n currency?: string;\n decimals?: number;\n /** A unit written after the value (\"km\", \"visits\"). */\n unit?: string;\n /** A positive number gets a plus sign. */\n signed?: boolean;\n locale: string;\n}\n\nconst readCurrencyCode = (currency: string | undefined): string =>\n typeof currency === \"string\" && /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : \"EUR\";\n\nconst readFractionDigits = (decimals: number | undefined): number | undefined =>\n typeof decimals === \"number\" && Number.isInteger(decimals) && decimals >= 0 && decimals <= 6 ? decimals : undefined;\n\nconst formatNumberWithOptions = (value: number, options: DataValueFormatOptions): string => {\n const { format = \"number\", currency, decimals, signed = false, locale } = options;\n const fractionDigits = readFractionDigits(decimals);\n const signDisplay: Intl.NumberFormatOptions[\"signDisplay\"] = signed ? \"exceptZero\" : \"auto\";\n const digitOptions: Intl.NumberFormatOptions =\n fractionDigits === undefined\n ? { maximumFractionDigits: 2 }\n : { minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits };\n switch (format) {\n case \"currency\":\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: readCurrencyCode(currency),\n signDisplay,\n ...(fractionDigits === undefined\n ? {\n minimumFractionDigits: 0,\n maximumFractionDigits: Number.isInteger(value) || Math.abs(value) >= 1000 ? 0 : 2,\n }\n : digitOptions),\n }).format(value);\n case \"percent\":\n // The value IS the percentage (36 → 36 %); Intl's percent style would multiply by 100.\n return `${new Intl.NumberFormat(locale, { signDisplay, ...digitOptions }).format(value)} %`;\n case \"compact\":\n return new Intl.NumberFormat(locale, {\n notation: \"compact\",\n signDisplay,\n maximumFractionDigits: fractionDigits ?? 1,\n }).format(value);\n default:\n return new Intl.NumberFormat(locale, { signDisplay, ...digitOptions }).format(value);\n }\n};\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(T[\\d:.]+(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\nconst formatDate = (value: string, locale: string): string | undefined => {\n if (!ISO_DATE.test(value)) return undefined;\n const date = new Date(value.length === 10 ? `${value}T00:00:00` : value);\n if (Number.isNaN(date.getTime())) return undefined;\n return new Intl.DateTimeFormat(locale, { day: \"numeric\", month: \"short\", year: \"numeric\" }).format(date);\n};\n\n/**\n * One value as the owner reads it: a number in the locale and `format`, a date in the locale's short form, text as\n * written; the `unit` after it. `undefined` / `null` give the empty string (the caller decides what an empty cell\n * shows); a boolean gives an empty string too — a table shows a boolean as an `Icon`, never as \"true\".\n */\nexport const formatDataValue = (value: unknown, options: DataValueFormatOptions): string => {\n const { format = \"number\", unit, locale } = options;\n let formatted: string;\n const numericValue = format === \"text\" ? undefined : readFiniteNumber(value);\n if (numericValue !== undefined && format !== \"date\") {\n formatted = formatNumberWithOptions(numericValue, options);\n } else if (typeof value === \"string\") {\n formatted = format === \"date\" ? (formatDate(value, locale) ?? value) : value;\n } else if (typeof value === \"number\") {\n formatted = String(value);\n } else {\n return \"\";\n }\n return unit ? `${formatted} ${unit}` : formatted;\n};\n\n/** Whether `value` reads as a number — numeric columns and cells align at the end. */\nexport const isNumericValue = (value: unknown): boolean => readFiniteNumber(value) !== undefined;\n\n/** A value clamped to 0..1, or undefined (the `bar` and `heat` props). */\nexport const readFraction = (value: unknown): number | undefined => {\n const numericValue = readFiniteNumber(value);\n if (numericValue === undefined) return undefined;\n return Math.min(1, Math.max(0, numericValue));\n};\n","import { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ApexOptions } from \"apexcharts\";\nimport type { ComposedSizeClass } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n DataValueFormat,\n DataValueTone,\n formatDataValue,\n readDataValueFormat,\n readFiniteNumber,\n readObject,\n readRows,\n readText,\n} from \"./data-value-format\";\n\n/**\n * The `Chart` node's props turned into ApexCharts input — pure, so the spec checks what reaches the\n * chart library without drawing it. Every value goes through `formatDataValue`, so the axis, the tooltip and a KPI\n * tile write the same number the same way.\n */\n\nexport type ChartKind = \"line\" | \"area\" | \"bar\" | \"pie\" | \"donut\" | \"scatter\" | \"heatmap\" | \"funnel\" | \"radar\";\n\nconst CHART_KINDS: readonly ChartKind[] = [\n \"line\",\n \"area\",\n \"bar\",\n \"pie\",\n \"donut\",\n \"scatter\",\n \"heatmap\",\n \"funnel\",\n \"radar\",\n];\n\nexport interface ChartSeriesDeclaration {\n field: string;\n label: string;\n /** The model wrote the label — a single named series gets its legend entry (ChatGPT's \"MRR\"). */\n hasExplicitLabel: boolean;\n}\n\n/** The theme colours the chart draws with, resolved from the `--agents-*` tokens at render time. */\nexport interface ChartPalette {\n seriesColors: string[];\n axisTextColor: string;\n /** The main text colour, for the total in a donut's middle. */\n textColor: string;\n gridColor: string;\n surfaceColor: string;\n}\n\nexport interface ChartModel {\n kind: ChartKind;\n apexType: \"line\" | \"area\" | \"bar\" | \"pie\" | \"donut\" | \"scatter\" | \"heatmap\" | \"radar\";\n series: ApexAxisChartSeries | ApexNonAxisChartSeries;\n options: ApexOptions;\n height: number;\n /** The plotted series names, for the accessible label. */\n seriesLabels: string[];\n}\n\nexport type ChartModelResult =\n | { status: \"ok\"; model: ChartModel }\n | { status: \"empty\"; detail: string }\n | { status: \"invalid\"; detail: string };\n\nexport interface ChartModelInput {\n props: Record<string, ExpressionValue>;\n sizeClass: ComposedSizeClass;\n locale: string;\n palette: ChartPalette;\n isEmailRender: boolean;\n /** The measured width of the plot in px (0 before the first measurement): a narrow plot gets fewer numeric ticks. */\n plotWidth?: number;\n}\n\nconst APEX_HTML_ENTITIES: Record<string, string> = { \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&#39;\" };\n\n/**\n * A plain text as ApexCharts' legend and tooltip take it: they write their texts as HTML, so the characters that open\n * markup or an attribute are escaped here, whatever the host does to the texts of its own components.\n */\nconst escapeApexHtml = (text: string): string =>\n text.replace(/[&<>\"']/g, (character) => APEX_HTML_ENTITIES[character]);\n\n/** Below this plot width a numeric category axis (a scatter's) gets about three ticks instead of five. */\nconst NARROW_PLOT_WIDTH = 320;\n\nconst HEIGHT_BY_SIZE_CLASS: Record<ComposedSizeClass, number> = { compact: 40, regular: 280, full: 320 };\n\n/** What a per-bar change counts (`ChartComposedViewNode::DELTA_UNITS`): percentage points or percent. */\nexport type ChartDeltaUnit = \"pp\" | \"%\";\n\nconst CHART_DELTA_UNITS: readonly ChartDeltaUnit[] = [\"pp\", \"%\"];\n\n/** The theme's series colour tokens, one per bar of a single-series bar chart (the distributed colours). */\nexport const CHART_SERIES_COLOR_TOKENS = [\n \"--agents-chart-01\",\n \"--agents-chart-02\",\n \"--agents-chart-03\",\n \"--agents-chart-04\",\n \"--agents-chart-05\",\n \"--agents-chart-06\",\n \"--agents-chart-07\",\n \"--agents-chart-08\",\n] as const;\n\n/** One bar of a bar chart with a change per bar. */\nexport interface ChartBarRow {\n label: string;\n valueText: string;\n /** The filled part of the track, 0 to 1. */\n fraction: number;\n /** The colour token of the bar (`--agents-chart-0N`). */\n colorToken: string;\n /** The signed change (\"+2\", \"-3\", \"0\"); undefined when the row has no number in the delta field. */\n deltaText?: string;\n /** Plus green, minus red, zero (and no change) muted. */\n deltaTone: DataValueTone;\n}\n\nexport interface ChartBarRowsModel {\n rows: ChartBarRow[];\n /** The plotted series' label, for the accessible label. */\n seriesLabel: string;\n deltaUnit?: ChartDeltaUnit;\n}\n\nexport type ChartBarRowsModelResult =\n | { status: \"ok\"; model: ChartBarRowsModel }\n | { status: \"empty\"; detail: string }\n | { status: \"invalid\"; detail: string };\n\n/** The row field of the change per bar — set on a bar chart only (another kind ignores it). */\nexport const readChartDeltaField = (props: Record<string, ExpressionValue>): string | undefined =>\n readChartKind(props.kind) === \"bar\" ? readText(props.deltaField) : undefined;\n\nexport const readChartDeltaUnit = (value: unknown): ChartDeltaUnit | undefined =>\n CHART_DELTA_UNITS.find((deltaUnit) => deltaUnit === value);\n\n/** The tone of a change by its sign: a rise green, a fall red, no change muted. */\nexport const readChartDeltaTone = (delta: number | undefined): DataValueTone =>\n delta === undefined || delta === 0 ? \"muted\" : delta > 0 ? \"success\" : \"danger\";\n\n/**\n * A bar chart with a change per bar (`deltaField`): one horizontal bar per row of the first plotted\n * series on a track, its value at the right, the signed change after it. The track's end is `max`, else the largest\n * value with a tenth of room (the longest bar never fills the track, as in the reference). A change counted in\n * percent (`deltaUnit` `%`) carries its unit; percentage points and a plain change show the figure alone — the line\n * under the bars (`deltaLabel`) says what it counts.\n */\nexport const buildChartBarRowsModel = (input: {\n props: Record<string, ExpressionValue>;\n locale: string;\n}): ChartBarRowsModelResult => {\n const { props, locale } = input;\n const rows = readRows(props.data) ?? [];\n const xField = readText(props.x) ?? \"\";\n const deltaField = readChartDeltaField(props) ?? \"\";\n const seriesDeclaration = readChartSeries(props.series).find((candidate) =>\n rows.some((row) => readFiniteNumber(row[candidate.field]) !== undefined),\n );\n if (rows.length === 0) return { status: \"empty\", detail: \"the Chart has no rows\" };\n if (!seriesDeclaration) {\n return { status: \"invalid\", detail: \"no row has a number in the Chart's series\" };\n }\n const valueFormat = readDataValueFormat(props.valueFormat);\n const currency = readText(props.currency);\n const deltaUnit = readChartDeltaUnit(props.deltaUnit);\n const plottedRows = rows\n .map((row) => ({ row, value: readFiniteNumber(row[seriesDeclaration.field]) }))\n .filter(\n (plottedRow): plottedRow is { row: (typeof rows)[number]; value: number } => plottedRow.value !== undefined,\n );\n const largestValue = Math.max(0, ...plottedRows.map((plottedRow) => plottedRow.value));\n const axisMax = readFiniteNumber(props.max) ?? largestValue * 1.1;\n return {\n status: \"ok\",\n model: {\n seriesLabel: seriesDeclaration.label,\n deltaUnit,\n rows: plottedRows.map((plottedRow, rowIndex) => {\n const delta = readFiniteNumber(plottedRow.row[deltaField]);\n return {\n label: readText(plottedRow.row[xField]) ?? \"\",\n valueText: formatDataValue(plottedRow.value, { format: valueFormat, currency, locale }),\n fraction: axisMax > 0 ? Math.min(1, Math.max(0, plottedRow.value / axisMax)) : 0,\n colorToken: CHART_SERIES_COLOR_TOKENS[rowIndex % CHART_SERIES_COLOR_TOKENS.length],\n deltaText:\n delta === undefined\n ? undefined\n : formatDataValue(delta, { format: deltaUnit === \"%\" ? \"percent\" : \"number\", signed: true, locale }),\n deltaTone: readChartDeltaTone(delta),\n };\n }),\n },\n };\n};\n\n/** One stage of a funnel chart: its bar (centered, as wide as its share of the largest stage) and its figures. */\nexport interface ChartFunnelStage {\n label: string;\n valueText: string;\n /** The bar's width, 0 to 1 of the largest stage. */\n fraction: number;\n /** The stage's value as a percentage of the stage before it (\"62 %\"); undefined for the first stage. */\n conversionText?: string;\n}\n\nexport interface ChartFunnelModel {\n stages: ChartFunnelStage[];\n /** The plotted series' label, for the accessible label. */\n seriesLabel: string;\n}\n\nexport type ChartFunnelModelResult =\n | { status: \"ok\"; model: ChartFunnelModel }\n | { status: \"empty\"; detail: string }\n | { status: \"invalid\"; detail: string };\n\n/** The narrowest bar a stage with a positive value gets, so a small last stage stays visible. */\nconst MIN_FUNNEL_BAR_FRACTION = 0.04;\n\n/**\n * A funnel chart (`kind` `funnel`): the rows are the stages of a process in their written order, the first plotted\n * series their values; each stage is a centered bar as wide as its share of the largest stage, with its value and its\n * conversion from the stage before it in percent (one decimal at most). A stage without a number is left out.\n */\n/**\n * The radius of a radar polygon that leaves room for its axis names (ApexCharts sizes the polygon by the plot alone and\n * clips a long name at the side): half the plot width minus the longest side-axis name, at most what the height\n * leaves under the names and the legend. Undefined before the plot is measured (ApexCharts' own size).\n */\nexport const readRadarRadius = (input: {\n axisNames: string[];\n plotWidth: number;\n height: number;\n fontSizePx: number;\n hasLegend: boolean;\n}): number | undefined => {\n const { axisNames, plotWidth, height, fontSizePx, hasLegend } = input;\n if (plotWidth <= 0 || axisNames.length === 0) return undefined;\n // a side axis points left or right (the top and bottom names only need a line of height)\n const sideAxisNameLengths = axisNames\n .filter((_axisName, axisIndex) => Math.abs(Math.sin((2 * Math.PI * axisIndex) / axisNames.length)) > 0.3)\n .map((axisName) => axisName.length);\n const nameRoom = Math.max(0, ...sideAxisNameLengths) * fontSizePx * 0.5 + 8;\n const heightRoom = (height - (hasLegend ? 48 : 0)) / 2 - fontSizePx * 2;\n return Math.max(40, Math.round(Math.min(plotWidth / 2 - nameRoom, heightRoom)));\n};\n\nexport const buildChartFunnelModel = (input: {\n props: Record<string, ExpressionValue>;\n locale: string;\n}): ChartFunnelModelResult => {\n const { props, locale } = input;\n const rows = readRows(props.data) ?? [];\n const xField = readText(props.x) ?? \"\";\n const seriesDeclaration = readChartSeries(props.series).find((candidate) =>\n rows.some((row) => readFiniteNumber(row[candidate.field]) !== undefined),\n );\n if (rows.length === 0) return { status: \"empty\", detail: \"the Chart has no rows\" };\n if (!seriesDeclaration) return { status: \"invalid\", detail: \"no row has a number in the Chart's series\" };\n const valueFormat = readDataValueFormat(props.valueFormat);\n const currency = readText(props.currency);\n const stageValues = rows\n .map((row) => ({ label: readText(row[xField]) ?? \"\", value: readFiniteNumber(row[seriesDeclaration.field]) }))\n .filter((stageValue): stageValue is { label: string; value: number } => stageValue.value !== undefined);\n const largestValue = Math.max(0, ...stageValues.map((stageValue) => stageValue.value));\n return {\n status: \"ok\",\n model: {\n seriesLabel: seriesDeclaration.label,\n stages: stageValues.map((stageValue, stageIndex) => {\n const previousValue = stageIndex > 0 ? stageValues[stageIndex - 1].value : undefined;\n const fraction = largestValue > 0 ? Math.min(1, Math.max(0, stageValue.value / largestValue)) : 0;\n return {\n label: stageValue.label,\n valueText: formatDataValue(stageValue.value, { format: valueFormat, currency, locale }),\n fraction: stageValue.value > 0 ? Math.max(MIN_FUNNEL_BAR_FRACTION, fraction) : 0,\n conversionText:\n previousValue !== undefined && previousValue > 0\n ? formatDataValue(Math.round((stageValue.value / previousValue) * 1000) / 10, {\n format: \"percent\",\n locale,\n })\n : undefined,\n };\n }),\n },\n };\n};\n\nexport const readChartKind = (value: unknown): ChartKind | undefined =>\n CHART_KINDS.find((chartKind) => chartKind === value);\n\n/** The visible series: entries with a string `field`; `visible: false` (often a bound state) hides one. */\nexport const readChartSeries = (seriesValue: ExpressionValue): ChartSeriesDeclaration[] => {\n if (!Array.isArray(seriesValue)) return [];\n const seriesDeclarations: ChartSeriesDeclaration[] = [];\n for (const seriesEntry of seriesValue) {\n const seriesObject = readObject(seriesEntry);\n const field = readText(seriesObject?.field) ?? readText(seriesObject?.key);\n if (!seriesObject || !field || seriesObject.visible === false) continue;\n const explicitLabel = readText(seriesObject.label);\n seriesDeclarations.push({ field, label: explicitLabel ?? field, hasExplicitLabel: explicitLabel !== undefined });\n }\n return seriesDeclarations;\n};\n\n/**\n * With both bounds written, the tick count that gives whole steps (0–45 → 3 ticks of 15); 4 otherwise.\n * Without both bounds ApexCharts picks a nice scale itself (undefined).\n */\nconst readTickAmountForBounds = (axisMin: number | undefined, axisMax: number | undefined): number | undefined => {\n if (axisMin === undefined || axisMax === undefined || axisMax <= axisMin) return undefined;\n return [3, 4, 5].find((tickAmount) => Number.isInteger((axisMax - axisMin) / tickAmount)) ?? 4;\n};\n\n/** The largest plotted number of axis series (0 when none). */\nconst readLargestValue = (series: ApexAxisChartSeries): number =>\n Math.max(\n 0,\n ...series.flatMap((seriesEntry) =>\n (seriesEntry.data as unknown[]).filter((value): value is number => typeof value === \"number\"),\n ),\n );\n\n/** A step of 1, 2, 2.5 or 5 times a power of ten that is at least `roughStep` — the steps an axis reads naturally. */\nconst readNiceStep = (roughStep: number): number => {\n const magnitude = 10 ** Math.floor(Math.log10(roughStep));\n return ([1, 2, 2.5, 5, 10].find((factor) => factor * magnitude >= roughStep) ?? 10) * magnitude;\n};\n\n/**\n * Round bounds and the tick count for a numeric axis over `values` (ChatGPT's scatter: 900 … 1500 in steps of\n * 150, never 980, 1076, 1172): the bounds snap outward to whole steps of about `targetTickAmount` ticks.\n */\nexport const readNiceAxisBounds = (\n values: number[],\n targetTickAmount: number,\n): { min: number; max: number; tickAmount: number } | undefined => {\n if (values.length === 0) return undefined;\n const smallestValue = Math.min(...values);\n const largestValue = Math.max(...values);\n if (smallestValue === largestValue) return undefined;\n const step = readNiceStep((largestValue - smallestValue) / targetTickAmount);\n const min = Math.floor(smallestValue / step) * step;\n const max = Math.ceil(largestValue / step) * step;\n return { min, max, tickAmount: Math.round((max - min) / step) };\n};\n\nconst buildValueFormatter =\n (format: DataValueFormat, currency: string | undefined, locale: string) =>\n (value: number | null | undefined): string =>\n value === null || value === undefined ? \"\" : formatDataValue(value, { format, currency, locale });\n\n/**\n * The ApexCharts series and options for the props, or why there is nothing to draw: no rows / no plottable value\n * (`empty`), or no series field present in the rows (`invalid`).\n */\nexport const buildChartModel = (input: ChartModelInput): ChartModelResult => {\n const { props, sizeClass, locale, palette, isEmailRender, plotWidth = 0 } = input;\n const writtenKind = readChartKind(props.kind);\n // A funnel draws its own rows (`buildChartFunnelModel`); in a compact slot it is a bar sparkline.\n const kind = writtenKind === \"funnel\" ? \"bar\" : writtenKind;\n if (!kind) return { status: \"invalid\", detail: `the Chart kind \"${String(props.kind)}\" is not a chart kind` };\n const rows = readRows(props.data) ?? [];\n const xField = readText(props.x) ?? \"\";\n const seriesDeclarations = readChartSeries(props.series);\n if (rows.length === 0) return { status: \"empty\", detail: \"the Chart has no rows\" };\n if (seriesDeclarations.length === 0) return { status: \"empty\", detail: \"the Chart shows no series\" };\n const presentSeries = seriesDeclarations.filter((seriesDeclaration) =>\n rows.some((row) => readFiniteNumber(row[seriesDeclaration.field]) !== undefined),\n );\n if (presentSeries.length === 0) {\n return {\n status: \"invalid\",\n detail: `no row has a number in ${seriesDeclarations.map((seriesDeclaration) => `\"${seriesDeclaration.field}\"`).join(\", \")}`,\n };\n }\n const isSparkline = sizeClass === \"compact\";\n const valueFormat = readDataValueFormat(props.valueFormat);\n const formatValue = buildValueFormatter(valueFormat, readText(props.currency), locale);\n const categories = rows.map((row) => readText(row[xField]) ?? \"\");\n const height = HEIGHT_BY_SIZE_CLASS[sizeClass];\n const isHorizontalBar = kind === \"bar\" && props.horizontal === true;\n const isDistributedBar = kind === \"bar\" && presentSeries.length === 1;\n const textStyle = { colors: palette.axisTextColor, fontSize: \"12px\", fontFamily: \"inherit\" };\n const baseOptions: ApexOptions = {\n chart: {\n type: kind,\n toolbar: { show: false },\n zoom: { enabled: false },\n animations: { enabled: !isEmailRender, speed: 250 },\n sparkline: { enabled: isSparkline },\n background: \"transparent\",\n fontFamily: \"inherit\",\n foreColor: palette.axisTextColor,\n stacked: (kind === \"bar\" || kind === \"area\") && props.stacked === true,\n },\n colors: palette.seriesColors,\n dataLabels: { enabled: false },\n legend: {\n show:\n !isSparkline &&\n (presentSeries.length > 1 ||\n kind === \"pie\" ||\n kind === \"donut\" ||\n presentSeries.some((seriesDeclaration) => seriesDeclaration.hasExplicitLabel)),\n showForSingleSeries: true,\n // ApexCharts writes legend and tooltip texts as HTML: the model's names are escaped there (axis labels are SVG text).\n formatter: (seriesName: string) => escapeApexHtml(String(seriesName)),\n position: \"bottom\",\n horizontalAlign: \"center\",\n fontSize: \"13px\",\n labels: { colors: palette.axisTextColor },\n // ApexCharts before 3.45 rounds legend markers with `radius`, later versions with `shape`; the peer range spans both\n markers: { radius: 12, shape: \"circle\" } as ApexLegend[\"markers\"],\n itemMargin: { horizontal: 8, vertical: 4 },\n },\n grid: {\n borderColor: palette.gridColor,\n strokeDashArray: 4,\n xaxis: { lines: { show: isHorizontalBar } },\n yaxis: { lines: { show: !isHorizontalBar } },\n padding: { left: 8, right: 24 },\n },\n tooltip: {\n enabled: !isEmailRender,\n theme: \"light\",\n x: { formatter: (value: number | string) => escapeApexHtml(String(value)) },\n y: {\n formatter: (value: number) => formatValue(value),\n title: {\n formatter: (seriesName: string) => (seriesName ? `${escapeApexHtml(String(seriesName))}: ` : \"\"),\n },\n },\n },\n stroke: {\n width: kind === \"line\" || kind === \"area\" ? 2 : kind === \"pie\" || kind === \"donut\" ? 2 : 0,\n curve: \"straight\",\n colors: kind === \"pie\" || kind === \"donut\" ? [palette.surfaceColor] : undefined,\n },\n markers: {\n size: kind === \"scatter\" ? 6 : kind === \"line\" && !isSparkline && rows.length <= 24 ? 4 : 0,\n strokeWidth: 0,\n },\n states: { active: { filter: { type: \"none\" } } },\n };\n const axisMin = readFiniteNumber(props.min);\n const axisMax = readFiniteNumber(props.max);\n const valueAxis = {\n min: axisMin,\n max: axisMax,\n tickAmount: readTickAmountForBounds(axisMin, axisMax),\n forceNiceScale: axisMax === undefined,\n title: { text: readText(props.yLabel), style: { color: palette.axisTextColor, fontWeight: 400 } },\n labels: { formatter: (value: number) => formatValue(value), style: textStyle },\n };\n const seriesLabels = presentSeries.map((seriesDeclaration) => seriesDeclaration.label);\n // The tooltip header names the category of the hovered point (`Jan. 2026`), never ApexCharts' 1-based index.\n const categoryTooltip = {\n ...baseOptions.tooltip,\n x: {\n formatter: (value: number | string, tooltipContext?: { dataPointIndex?: number }) =>\n escapeApexHtml(\n String(\n tooltipContext?.dataPointIndex !== undefined ? (categories[tooltipContext.dataPointIndex] ?? value) : value,\n ),\n ),\n },\n };\n\n if (kind === \"pie\" || kind === \"donut\") {\n const valueField = presentSeries[0].field;\n const slices = rows\n .map((row, rowIndex) => ({ label: categories[rowIndex], value: readFiniteNumber(row[valueField]) }))\n .filter((slice): slice is { label: string; value: number } => slice.value !== undefined && slice.value > 0);\n if (slices.length === 0) return { status: \"empty\", detail: \"the Chart has no positive slice\" };\n return {\n status: \"ok\",\n model: {\n kind,\n apexType: kind,\n series: slices.map((slice) => slice.value),\n height,\n seriesLabels: slices.map((slice) => slice.label),\n options: {\n ...baseOptions,\n labels: slices.map((slice) => slice.label),\n dataLabels: {\n enabled: !isSparkline,\n formatter: (percent: number) => `${Math.round(percent)} %`,\n dropShadow: { enabled: false },\n },\n plotOptions: {\n pie: {\n expandOnClick: false,\n donut: {\n size: \"62%\",\n // A donut names the whole in its middle: the total under the series' label (\"130 · Bewertungen\"), a\n // hovered slice's name and value instead. A pie has no middle.\n labels: {\n show: kind === \"donut\" && !isSparkline,\n name: { show: true, fontSize: \"13px\", color: palette.axisTextColor, offsetY: 20 },\n value: {\n show: true,\n fontSize: \"24px\",\n fontWeight: 700,\n color: palette.textColor,\n offsetY: -12,\n formatter: (value: string) => formatValue(Number(value)),\n },\n total: {\n show: true,\n showAlways: false,\n label: presentSeries[0].hasExplicitLabel ? escapePlainTextForText(presentSeries[0].label) : \"\",\n fontSize: \"13px\",\n color: palette.axisTextColor,\n formatter: () => formatValue(slices.reduce((total, slice) => total + slice.value, 0)),\n },\n },\n },\n },\n },\n },\n },\n };\n }\n\n if (kind === \"radar\") {\n // One axis per data row (named by x), one polygon per series: a profile across its dimensions.\n if (rows.length < 3) return { status: \"invalid\", detail: \"a radar Chart needs at least 3 rows (one per axis)\" };\n const valueValues = presentSeries.flatMap((seriesDeclaration) =>\n rows\n .map((row) => readFiniteNumber(row[seriesDeclaration.field]))\n .filter((value): value is number => value !== undefined),\n );\n const radarMax = axisMax ?? readNiceAxisBounds([0, ...valueValues], 4)?.max;\n const radarFontSizePx = plotWidth > 0 && plotWidth < NARROW_PLOT_WIDTH ? 11 : 12;\n const hasRadarLegend = baseOptions.legend?.show === true;\n const radarRadius = isSparkline\n ? undefined\n : readRadarRadius({\n axisNames: categories,\n plotWidth,\n height: Math.max(height, 320),\n fontSizePx: radarFontSizePx,\n hasLegend: hasRadarLegend,\n });\n // A radar the width holds smaller than the height allows (a phone) gets only the height it fills.\n const radarHeight = isSparkline\n ? height\n : Math.min(\n Math.max(height, 320),\n radarRadius === undefined\n ? Number.POSITIVE_INFINITY\n : radarRadius * 2 + radarFontSizePx * 4 + (hasRadarLegend ? 48 : 0) + 16,\n );\n return {\n status: \"ok\",\n model: {\n kind,\n apexType: \"radar\",\n series: presentSeries.map((seriesDeclaration) => ({\n name: seriesDeclaration.label,\n data: rows.map((row) => readFiniteNumber(row[seriesDeclaration.field]) ?? 0),\n })),\n height: radarHeight,\n seriesLabels,\n options: {\n ...baseOptions,\n chart: { ...baseOptions.chart, type: \"radar\" },\n stroke: { width: 2 },\n fill: { opacity: 0.18 },\n markers: { size: isSparkline ? 0 : 3, strokeWidth: 0 },\n plotOptions: {\n radar: {\n size: radarRadius,\n polygons: {\n strokeColors: palette.gridColor,\n connectorColors: palette.gridColor,\n fill: { colors: [\"transparent\"] },\n },\n },\n },\n tooltip: categoryTooltip,\n xaxis: {\n categories,\n labels: {\n show: !isSparkline,\n style: {\n ...textStyle,\n fontSize: `${radarFontSizePx}px`,\n colors: categories.map(() => palette.axisTextColor),\n },\n },\n },\n yaxis: {\n show: false,\n min: axisMin ?? 0,\n max: radarMax,\n tickAmount: 4,\n labels: { formatter: (value: number) => formatValue(value) },\n },\n },\n },\n };\n }\n\n if (kind === \"heatmap\") {\n // One heat row per data row (top to bottom as written), one column per series: a cohort table.\n const heatRows = rows\n .map((row, rowIndex) => ({\n name: categories[rowIndex],\n data: presentSeries.map((seriesDeclaration) => ({\n x: seriesDeclaration.label,\n y: readFiniteNumber(row[seriesDeclaration.field]) ?? null,\n })),\n }))\n .reverse();\n const heatValues = heatRows.flatMap((heatRow) =>\n heatRow.data.map((heatCell) => heatCell.y).filter((value): value is number => value !== null),\n );\n const smallestHeat = Math.min(...heatValues);\n const heatRange = Math.max(...heatValues) - smallestHeat;\n // A count on a dark cell is written in the surface colour, on a pale cell in the text colour (ApexCharts shades a\n // cell by its place between the smallest and the largest value).\n const readHeatLabelColor = (labelContext: { seriesIndex: number; dataPointIndex: number }): string => {\n const heatValue = heatRows[labelContext.seriesIndex]?.data[labelContext.dataPointIndex]?.y;\n return typeof heatValue === \"number\" && heatRange > 0 && (heatValue - smallestHeat) / heatRange > 0.55\n ? palette.surfaceColor\n : palette.textColor;\n };\n return {\n status: \"ok\",\n model: {\n kind,\n apexType: \"heatmap\",\n series: heatRows as ApexAxisChartSeries,\n height: Math.max(height, rows.length * 44 + 16),\n seriesLabels,\n options: {\n ...baseOptions,\n colors: [palette.seriesColors[0]],\n legend: { show: false },\n dataLabels: {\n enabled: !isSparkline,\n formatter: (value: number) => formatValue(value),\n style: { colors: [readHeatLabelColor] as unknown as string[], fontWeight: 500 },\n },\n stroke: { width: 4, colors: [palette.surfaceColor] },\n plotOptions: { heatmap: { radius: 8, shadeIntensity: 0.6, enableShades: true } },\n xaxis: {\n position: \"top\",\n labels: { style: textStyle },\n axisBorder: { show: false },\n axisTicks: { show: false },\n },\n yaxis: { labels: { style: textStyle } },\n },\n },\n };\n }\n\n const series: ApexAxisChartSeries =\n kind === \"scatter\"\n ? presentSeries.map((seriesDeclaration) => ({\n name: seriesDeclaration.label,\n data: rows\n .map((row) => [readFiniteNumber(row[xField]), readFiniteNumber(row[seriesDeclaration.field])])\n .filter((point): point is [number, number] => point[0] !== undefined && point[1] !== undefined),\n }))\n : presentSeries.map((seriesDeclaration) => ({\n name: seriesDeclaration.label,\n data: rows.map((row) => readFiniteNumber(row[seriesDeclaration.field]) ?? null),\n }));\n const scatterAxisBounds =\n kind === \"scatter\"\n ? readNiceAxisBounds(\n rows.map((row) => readFiniteNumber(row[xField])).filter((value): value is number => value !== undefined),\n plotWidth > 0 && plotWidth < NARROW_PLOT_WIDTH ? 3 : 5,\n )\n : undefined;\n const formatAxisNumber = buildValueFormatter(\"number\", undefined, locale);\n const categoryAxisTitle = { text: readText(props.xLabel), style: { color: palette.axisTextColor, fontWeight: 400 } };\n return {\n status: \"ok\",\n model: {\n kind: writtenKind ?? kind,\n apexType: kind,\n series,\n height: isHorizontalBar ? Math.max(height, rows.length * 36 + 40) : height,\n seriesLabels,\n options: {\n ...baseOptions,\n tooltip: kind === \"scatter\" ? baseOptions.tooltip : categoryTooltip,\n fill: kind === \"area\" ? { type: \"gradient\", gradient: { opacityFrom: 0.35, opacityTo: 0.02 } } : { opacity: 1 },\n plotOptions: {\n bar: {\n horizontal: isHorizontalBar,\n distributed: isDistributedBar,\n borderRadius: 4,\n columnWidth: \"60%\",\n barHeight: \"60%\",\n dataLabels: { position: isHorizontalBar ? \"top\" : \"center\" },\n },\n },\n dataLabels: isHorizontalBar\n ? {\n enabled: true,\n formatter: (value: number) => formatValue(value),\n offsetX: 28,\n style: { colors: [palette.axisTextColor], fontWeight: 500 },\n }\n : { enabled: false },\n legend: { ...baseOptions.legend, show: baseOptions.legend?.show === true && !isDistributedBar },\n xaxis:\n kind === \"scatter\"\n ? {\n type: \"numeric\",\n min: scatterAxisBounds?.min,\n max: scatterAxisBounds?.max,\n tickAmount: scatterAxisBounds?.tickAmount ?? 5,\n title: categoryAxisTitle,\n labels: {\n style: textStyle,\n rotate: 0,\n hideOverlappingLabels: true,\n formatter: (value: string) => formatAxisNumber(Number(value)),\n },\n }\n : isHorizontalBar\n ? {\n categories,\n title: categoryAxisTitle,\n labels: { show: false, formatter: (value: string) => formatValue(Number(value)) },\n axisBorder: { show: false },\n axisTicks: { show: false },\n }\n : {\n categories,\n title: categoryAxisTitle,\n labels: { style: textStyle, hideOverlappingLabels: true, rotate: 0, trim: false },\n axisBorder: { show: false },\n axisTicks: { show: false },\n tickAmount: categories.length > 12 ? 6 : undefined,\n tooltip: { enabled: false },\n },\n // Horizontal bars: the value labels sit right of the bar end — the axis leaves room for the longest one.\n yaxis: isHorizontalBar\n ? {\n max: axisMax ?? readLargestValue(series) * 1.15,\n min: axisMin ?? 0,\n labels: { style: { ...textStyle, fontSize: \"14px\" }, maxWidth: 160 },\n }\n : valueAxis,\n },\n },\n };\n};\n","import {\n COMPOSED_VIEW_TONE_GRAPHIC_COLOR,\n COMPOSED_VIEW_TONE_TEXT_COLOR,\n} from \"../../composed-view-tones\";\nimport type { DataValueTone } from \"./data-value-format\";\nimport styles from \"./data-tones.module.scss\";\n\n/** The text class of a tone (judgement text in the 900 tone, through light-dark()). */\nexport const TONE_TEXT_CLASS: Record<DataValueTone, string> = {\n neutral: styles.textNeutral,\n muted: styles.textMuted,\n success: styles.textSuccess,\n warning: styles.textWarning,\n danger: styles.textDanger,\n info: styles.textInfo,\n};\n\n/** The graphic colour of a tone — the kit's (`composed-view-tones.ts`). */\nexport const TONE_GRAPHIC_COLOR: Readonly<Record<DataValueTone, string>> = COMPOSED_VIEW_TONE_GRAPHIC_COLOR;\n\n/** The same judgement text colours as values for the component library's `Text`'s `color` prop — the kit's. */\nexport const TONE_TEXT_COLOR: Readonly<Record<DataValueTone, string>> = COMPOSED_VIEW_TONE_TEXT_COLOR;\n","import { Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { CSSProperties } from \"react\";\nimport type { ChartBarRowsModel } from \"../chart-model\";\nimport { TONE_TEXT_COLOR } from \"../data-tones\";\nimport styles from \"./ChartBarRows.module.scss\";\n\nexport interface ChartBarRowsProps {\n model: ChartBarRowsModel;\n /** The chart's accessible name (title and series). */\n accessibleLabel?: string;\n testId?: string;\n}\n\n/**\n * The bars of a bar chart with a change per bar: per row the category, the bar on\n * its track in the row's chart colour, the value, and the signed change coloured by its sign. A table, because it is\n * one: each row reads \"CSU · 36 % · -3\" to a screen reader. The bar's length and colour travel as CSS custom\n * properties — the one dynamic value, no inline style rule.\n */\nexport const ChartBarRows = (props: ChartBarRowsProps) => {\n const { model, accessibleLabel, testId } = props;\n const hasDeltas = model.rows.some((row) => row.deltaText !== undefined);\n return (\n <table className={styles.rows} aria-label={accessibleLabel} data-testid={testId}>\n <tbody>\n {model.rows.map((row, rowIndex) => (\n <tr\n key={`${row.label}-${rowIndex}`}\n className={styles.row}\n data-testid={testId ? `${testId}-row-${rowIndex}` : undefined}\n >\n <th scope=\"row\" className={styles.label}>\n <Text role=\"help\" className={styles.labelText} translate={false}>\n {escapePlainTextForText(row.label)}\n </Text>\n </th>\n <td className={styles.track} aria-hidden=\"true\">\n <span\n className={styles.bar}\n style={\n {\n \"--agents-chart-bar-fraction\": `${Math.round(row.fraction * 1000) / 10}%`,\n \"--agents-chart-bar-color\": `var(${row.colorToken})`,\n } as CSSProperties\n }\n />\n </td>\n <td className={styles.value}>\n <Text\n role=\"help\"\n weight=\"medium\"\n className={styles.figure}\n translate={false}\n >\n {escapePlainTextForText(row.valueText)}\n </Text>\n </td>\n {hasDeltas ? (\n <td className={styles.delta}>\n {row.deltaText !== undefined ? (\n <Text\n role=\"help\"\n color={TONE_TEXT_COLOR[row.deltaTone]}\n className={styles.figure}\n translate={false}\n >\n {escapePlainTextForText(row.deltaText)}\n </Text>\n ) : null}\n </td>\n ) : null}\n </tr>\n ))}\n </tbody>\n </table>\n );\n};\n","import { Icon, Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { CSSProperties } from \"react\";\nimport type { ChartFunnelModel } from \"../chart-model\";\nimport styles from \"./ChartFunnelRows.module.scss\";\n\nexport interface ChartFunnelRowsProps {\n model: ChartFunnelModel;\n /** The chart's accessible name (title and series). */\n accessibleLabel?: string;\n testId?: string;\n}\n\n/**\n * The stages of a funnel chart (ChatGPT composes its funnel from SVG): per\n * stage its name and value on one line, under it a centered bar as wide as the stage's share of the largest one, and\n * between two stages the conversion from the stage before. An ordered list, because the stages are a sequence: each\n * item reads \"Link opened · 41 · 64 % of the previous stage\" to a screen reader. The bar's width travels as a CSS\n * custom property — the one dynamic value, no inline style rule.\n */\nexport const ChartFunnelRows = (props: ChartFunnelRowsProps) => {\n const { model, accessibleLabel, testId } = props;\n return (\n <ol className={styles.stages} aria-label={accessibleLabel} data-testid={testId}>\n {model.stages.map((stage, stageIndex) => (\n <li\n key={`${stage.label}-${stageIndex}`}\n className={styles.stage}\n data-testid={testId ? `${testId}-stage-${stageIndex}` : undefined}\n >\n {stage.conversionText !== undefined ? (\n <div className={styles.conversion}>\n <Icon className={styles.conversionIcon} name=\"arrowDown\" />\n <Text\n role=\"caption\"\n color=\"var(--agents-fg-light)\"\n className={styles.figure}\n replacements={{ conversion: stage.conversionText }}\n >\n {\"%conversion% of the previous stage\"}\n </Text>\n </div>\n ) : null}\n <div className={styles.stageHead}>\n <Text role=\"help\" className={styles.label} translate={false}>\n {escapePlainTextForText(stage.label)}\n </Text>\n <Text role=\"help\" weight=\"bold\" className={styles.figure} translate={false}>\n {escapePlainTextForText(stage.valueText)}\n </Text>\n </div>\n <span\n className={styles.bar}\n aria-hidden=\"true\"\n style={{ \"--agents-chart-funnel-fraction\": `${Math.round(stage.fraction * 1000) / 10}%` } as CSSProperties}\n />\n </li>\n ))}\n </ol>\n );\n};\n","import { useMemo } from \"react\";\nimport { CHART_SERIES_COLOR_TOKENS, type ChartPalette } from \"./chart-model\";\n\n/** Fallbacks for a host without the theme stylesheet (a spec): the direct-channel values are irrelevant there. */\nconst FALLBACK_SERIES_COLOR = \"#4f7fe8\";\nconst FALLBACK_TEXT_COLOR = \"#6b7280\";\nconst FALLBACK_STRONG_TEXT_COLOR = \"#111827\";\nconst FALLBACK_GRID_COLOR = \"#e5e7eb\";\nconst FALLBACK_SURFACE_COLOR = \"#ffffff\";\n\nconst readToken = (computedStyle: CSSStyleDeclaration | undefined, token: string, fallback: string): string =>\n computedStyle?.getPropertyValue(token).trim() || fallback;\n\n/**\n * The chart's colours, read from the theme tokens (`--agents-chart-01` … `--agents-chart-08` for the series,\n * `--agents-fg-light` for the axis text, `--agents-fg` for a donut's total,\n * `--agents-divider-gl` for the grid, `--agents-bg-surface` for the slice gaps). ApexCharts writes colours into SVG attributes\n * and computes shades from them, where a `var()` does not resolve — so the values are read once per scheme from the\n * element's computed style, never written as hex in the component.\n */\nexport const useChartPalette = (element: HTMLElement | null, colorScheme: string | null): ChartPalette =>\n useMemo(() => {\n const computedStyle = element && typeof window !== \"undefined\" ? window.getComputedStyle(element) : undefined;\n return {\n seriesColors: CHART_SERIES_COLOR_TOKENS.map((token) => readToken(computedStyle, token, FALLBACK_SERIES_COLOR)),\n axisTextColor: readToken(computedStyle, \"--agents-fg-light\", FALLBACK_TEXT_COLOR),\n textColor: readToken(computedStyle, \"--agents-fg\", FALLBACK_STRONG_TEXT_COLOR),\n gridColor: readToken(computedStyle, \"--agents-divider-gl\", FALLBACK_GRID_COLOR),\n surfaceColor: readToken(computedStyle, \"--agents-bg-surface\", FALLBACK_SURFACE_COLOR),\n };\n // The scheme is read so a light/dark switch re-reads the tokens.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [element, colorScheme]);\n","import { useAgentsOwnerSettings } from \"../../../provider/AgentsProvider\";\nimport { toNumberLocale } from \"./data-value-format\";\n\n/**\n * The locale the data nodes write numbers in — the owner's UI language from the app (`useOwnerSettings`), read\n * defensively: a tree renders in hosts without it too (the e-mail capture, a spec, the preview), and then numbers are `en`.\n */\nexport const useNumberLocale = (): string => {\n const { languageCode } = useAgentsOwnerSettings();\n return toNumberLocale(languageCode ?? undefined);\n};\n","import { Button, Icon, Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport styles from \"./DataFootnote.module.scss\";\nimport type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { readObject, readText } from \"../data-value-format\";\n\nexport interface DataFootnoteProps {\n /** The model's muted line under the data (what the figures are, the period). */\n caption?: ExpressionValue;\n /** `{\"name\",\"url\"}` — where the figures come from; a list of them (a Table whose values come from several pages). */\n source?: ExpressionValue;\n /** The e-mail capture: chip sources are plain text; KPI sources are omitted. */\n isEmailRender: boolean;\n appearance?: \"chip\" | \"quiet\";\n testId?: string;\n}\n\n/** An http(s) link target; the quiet KPI appearance additionally requires a parseable host. */\nconst readHttpUrl = (value: unknown): string | undefined =>\n typeof value === \"string\" && /^https?:\\/\\//i.test(value) ? value : undefined;\n\n/** The host name of a URL for a source without a name, or undefined for a URL that does not parse. */\nconst readHostName = (url: string | undefined): string | undefined => {\n if (!url) return undefined;\n try {\n return new URL(url).hostname;\n } catch {\n return undefined;\n }\n};\n\n/** One source chip: the name (or the page's host name) and the http(s) page, when it has one. */\ninterface FootnoteSource {\n name: string;\n url: string | undefined;\n}\n\n/** The sources a `source` prop holds — one object or a list of them; entries without a name or a page are left out. */\nconst readFootnoteSources = (source: ExpressionValue | undefined): FootnoteSource[] => {\n const sourceValues: unknown[] = Array.isArray(source) ? source : [source];\n const footnoteSources: FootnoteSource[] = [];\n for (const sourceValue of sourceValues) {\n const sourceObject = readObject(sourceValue);\n const url = readHttpUrl(sourceObject?.url);\n const name = readText(sourceObject?.name) ?? readHostName(url);\n if (name) footnoteSources.push({ name, url });\n }\n return footnoteSources;\n};\n\ninterface SourceChipProps {\n footnoteSource: FootnoteSource;\n isEmailRender: boolean;\n appearance: \"chip\" | \"quiet\";\n testId?: string;\n}\n\n/** A small flat chip: a link opening in a new tab, plain text in the e-mail capture or without a page. */\nconst SourceChip = (props: SourceChipProps) => {\n const { footnoteSource, isEmailRender, appearance, testId } = props;\n const openSource = () => {\n if (footnoteSource.url) window.open(footnoteSource.url, \"_blank\", \"noopener,noreferrer\");\n };\n if (appearance === \"quiet\") {\n return (\n <Button\n variant=\"default\"\n size=\"small\"\n icon=\"link\"\n iconPosition=\"left\"\n htmlType=\"button\"\n translate={false}\n className={styles.sourceButton}\n testId={testId}\n onClick={openSource}\n >\n {escapePlainTextForText(footnoteSource.name)}\n </Button>\n );\n }\n const className = styles.sourceChip;\n const sourceChipContent = (\n <>\n <Icon pixelSize={12} color=\"var(--agents-fg-light)\" name=\"link\" />\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(footnoteSource.name)}\n </Text>\n </>\n );\n if (footnoteSource.url && !isEmailRender) {\n return (\n <a className={className} data-testid={testId} href={footnoteSource.url} target=\"_blank\" rel=\"noopener noreferrer\">\n {sourceChipContent}\n </a>\n );\n }\n return (\n <span className={className} data-testid={testId}>\n {sourceChipContent}\n </span>\n );\n};\n\n// Charts/tables keep chips (plain text in email). KPI footers show only valid page links and omit sources in email.\nexport const DataFootnote = (props: DataFootnoteProps) => {\n const { caption, source, isEmailRender, appearance = \"chip\", testId } = props;\n const captionText = readText(caption);\n const footnoteSources = readFootnoteSources(source)\n .map((footnoteSource, sourceIndex) => ({ footnoteSource, sourceIndex }))\n .filter(({ footnoteSource }) => appearance === \"chip\" || (!isEmailRender && readHostName(footnoteSource.url)));\n if (!captionText && footnoteSources.length === 0) return null;\n return (\n <div className={classNames(styles.footnote, appearance === \"quiet\" && styles.quiet)} data-testid={testId}>\n {captionText ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(captionText)}\n </Text>\n ) : null}\n {footnoteSources.map(({ footnoteSource, sourceIndex }) => (\n <SourceChip\n key={`${sourceIndex}-${footnoteSource.name}`}\n footnoteSource={footnoteSource}\n isEmailRender={isEmailRender}\n appearance={appearance}\n testId={testId && `${testId}-source-${sourceIndex}`}\n />\n ))}\n </div>\n );\n};\n","import { Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport { readText } from \"../data-value-format\";\n\nexport interface DataEmptyLineProps {\n /** The model's own empty line (`emptyText`); the kit's chrome sentence otherwise. */\n emptyText?: unknown;\n testId?: string;\n}\n\n/** The one muted line a data node shows when it has nothing to show (empty data). */\nexport const DataEmptyLine = (props: DataEmptyLineProps) => {\n const { emptyText, testId } = props;\n const modelText = readText(emptyText);\n return modelText ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false} testId={testId}>\n {escapePlainTextForText(modelText)}\n </Text>\n ) : (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={testId}>\n {\"No data to show.\"}\n </Text>\n );\n};\n","import { useEffect } from \"react\";\nimport type {\n WidgetRenderReportCode,\n WidgetRenderStatus,\n} from \"../../../renderer/render-report/widget-render-report\";\nimport type { ComposedViewRuntime } from \"../../composed-view-component-types\";\n\n/**\n * Reports a data node's status into the block's render report on every change — `mounted` included, so\n * a node that was `empty` or `pending` and then got its rows clears its earlier report instead of leaving it standing.\n */\nexport const useReportDataNodeStatus = (\n runtime: ComposedViewRuntime,\n status: WidgetRenderStatus,\n code?: WidgetRenderReportCode,\n detail?: string,\n): void => {\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n reportNodeStatus(status, code, detail);\n }, [reportNodeStatus, status, code, detail]);\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useCallback, useEffect, useState } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ApexChart } from \"./apex-chart-component\";\nimport {\n buildChartBarRowsModel,\n buildChartFunnelModel,\n buildChartModel,\n readChartDeltaField,\n readChartKind,\n} from \"./chart-model\";\nimport { ChartBarRows } from \"./ChartBarRows/ChartBarRows\";\nimport { ChartFunnelRows } from \"./ChartFunnelRows/ChartFunnelRows\";\nimport { readText } from \"./data-value-format\";\nimport { useChartPalette } from \"./use-chart-palette\";\nimport { useNumberLocale } from \"./use-number-locale\";\nimport { DataFootnote } from \"./DataFootnote/DataFootnote\";\nimport { DataEmptyLine } from \"./DataEmptyLine/DataEmptyLine\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./Chart.module.scss\";\n\n/** The light/dark scheme the page is in (`data-color-scheme` on `<html>`), so the palette is re-read on a switch. */\nconst useColorScheme = (): string | null => {\n const [colorScheme, setColorScheme] = useState<string | null>(() =>\n typeof document === \"undefined\" ? null : document.documentElement.getAttribute(\"data-color-scheme\"),\n );\n useEffect(() => {\n if (typeof MutationObserver === \"undefined\") return undefined;\n const observer = new MutationObserver(() =>\n setColorScheme(document.documentElement.getAttribute(\"data-color-scheme\")),\n );\n observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"data-color-scheme\"] });\n return () => observer.disconnect();\n }, []);\n return colorScheme;\n};\n\n/**\n * A remount key that changes when the chart's container width changes. ApexCharts measures its parent once and misses\n * the chat column narrowing when a canvas opens (an app widget that draws an ApexCharts chart keys it the same way).\n */\nconst useContainerWidthKey = () => {\n const [element, setElement] = useState<HTMLDivElement | null>(null);\n const [widthKey, setWidthKey] = useState(0);\n useEffect(() => {\n if (!element || typeof ResizeObserver === \"undefined\") return undefined;\n const observer = new ResizeObserver((entries) => {\n const measuredWidth = Math.round(entries[0]?.contentRect.width ?? 0);\n setWidthKey((previousWidth) => (previousWidth === measuredWidth ? previousWidth : measuredWidth));\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, [element]);\n const containerRef = useCallback((container: HTMLDivElement | null) => setElement(container), []);\n return { element, containerRef, widthKey };\n};\n\n/**\n * The `Chart` node: line, area, bar (horizontal for a ranking\n * or poll), pie, donut, scatter and heatmap through ApexCharts, in the theme's chart colours, with the legend under\n * the plot (a click on an entry hides its series), tooltips on hover and the values formatted like every data node. In a\n * compact slot (a table cell) it is a sparkline without axes, legend and title. A chart still waiting for its bound\n * rows shows a plot-shaped skeleton; no rows show one muted line and report `empty`; rows without any number in the\n * named series report `failed` (`INVALID_PROP`). The e-mail capture draws it without animation and tooltips.\n *\n * A bar chart with a `deltaField` (a measurement against an earlier one) draws its bars itself\n * ({@link ChartBarRows}): one horizontal bar per category with its value and the signed change at the right, coloured\n * by sign, and the `deltaLabel` line under the bars (\"Right: change in percentage points since January 2026\"; without\n * one, a `pp` change names its unit in the kit's own line). In a compact slot it stays a sparkline.\n *\n * A funnel (no ApexCharts funnel in the installed 3.35) draws its stages itself ({@link ChartFunnelRows}): centered\n * bars in the written order with each stage's value and its conversion from the stage before. A radar is ApexCharts'\n * radar: one axis per row, one polygon per series, the value axis hidden (the tooltip names the values).\n */\nconst ChartNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime, isPending, sizeClass, testId } = props;\n const locale = useNumberLocale();\n const colorScheme = useColorScheme();\n const { element, containerRef, widthKey } = useContainerWidthKey();\n const palette = useChartPalette(element, colorScheme);\n const isSparkline = sizeClass === \"compact\";\n const hasChangePerBar = readChartDeltaField(nodeProps) !== undefined && !isSparkline;\n const isFunnel = readChartKind(nodeProps.kind) === \"funnel\" && !isSparkline;\n const barRowsModelResult = hasChangePerBar ? buildChartBarRowsModel({ props: nodeProps, locale }) : undefined;\n const funnelModelResult = isFunnel ? buildChartFunnelModel({ props: nodeProps, locale }) : undefined;\n const chartModelResult =\n barRowsModelResult ??\n funnelModelResult ??\n buildChartModel({\n props: nodeProps,\n sizeClass,\n locale,\n palette,\n isEmailRender: runtime.isEmailRender,\n plotWidth: widthKey,\n });\n const drawsItsOwnRows = hasChangePerBar || isFunnel;\n const isWaiting = isPending && chartModelResult.status !== \"ok\";\n useReportDataNodeStatus(\n runtime,\n isWaiting\n ? \"pending\"\n : chartModelResult.status === \"ok\"\n ? \"mounted\"\n : chartModelResult.status === \"empty\"\n ? \"empty\"\n : \"failed\",\n isWaiting || chartModelResult.status === \"ok\"\n ? undefined\n : chartModelResult.status === \"empty\"\n ? \"NO_DATA\"\n : \"INVALID_PROP\",\n isWaiting || chartModelResult.status === \"ok\" ? undefined : chartModelResult.detail,\n );\n const title = readText(nodeProps.title);\n const kind = readChartKind(nodeProps.kind) ?? \"line\";\n const plottedSeriesLabels =\n barRowsModelResult?.status === \"ok\"\n ? [barRowsModelResult.model.seriesLabel]\n : funnelModelResult?.status === \"ok\"\n ? [funnelModelResult.model.seriesLabel]\n : chartModelResult.status === \"ok\" && \"seriesLabels\" in chartModelResult.model\n ? chartModelResult.model.seriesLabels\n : [];\n const accessibleLabel =\n chartModelResult.status === \"ok\" ? [title, plottedSeriesLabels.join(\", \")].filter(Boolean).join(\": \") : title;\n const deltaLabel = readText(nodeProps.deltaLabel);\n const deltaUnitLine =\n barRowsModelResult?.status === \"ok\" && barRowsModelResult.model.deltaUnit === \"pp\"\n ? \"Right: change in percentage points\"\n : barRowsModelResult?.status === \"ok\" && barRowsModelResult.model.deltaUnit === \"%\"\n ? \"Right: change in percent\"\n : undefined;\n return (\n <figure className={classNames(styles.chart, isSparkline && styles.sparkline)} data-testid={testId}>\n {title && !isSparkline ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n <div\n ref={containerRef}\n className={styles.plot}\n role={chartModelResult.status === \"ok\" && !drawsItsOwnRows ? \"img\" : undefined}\n aria-label={drawsItsOwnRows ? undefined : accessibleLabel}\n data-chart-kind={kind}\n >\n {isWaiting ? (\n <div className={styles.skeleton} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <SkeletonLine width=\"100%\" height={isSparkline ? 32 : 240} radius={12} />\n </div>\n ) : barRowsModelResult?.status === \"ok\" ? (\n <ChartBarRows model={barRowsModelResult.model} accessibleLabel={accessibleLabel} testId={`${testId}-rows`} />\n ) : funnelModelResult?.status === \"ok\" ? (\n <ChartFunnelRows\n model={funnelModelResult.model}\n accessibleLabel={accessibleLabel}\n testId={`${testId}-stages`}\n />\n ) : chartModelResult.status === \"ok\" && \"options\" in chartModelResult.model ? (\n <ApexChart\n key={`${widthKey}-${chartModelResult.model.apexType}`}\n type={chartModelResult.model.apexType}\n series={chartModelResult.model.series}\n options={chartModelResult.model.options}\n height={chartModelResult.model.height}\n width=\"100%\"\n />\n ) : isSparkline ? null : (\n <DataEmptyLine testId={`${testId}-empty`} />\n )}\n </div>\n {hasChangePerBar && chartModelResult.status === \"ok\" && deltaLabel ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(deltaLabel)}\n </Text>\n ) : hasChangePerBar && chartModelResult.status === \"ok\" && deltaUnitLine ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\">\n {deltaUnitLine}\n </Text>\n ) : null}\n {isSparkline ? null : (\n <DataFootnote caption={nodeProps.caption} source={nodeProps.source} isEmailRender={runtime.isEmailRender} />\n )}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Chart\", component: ChartNode };\n","import { Icon, isAgentsIconName, type AgentsIconName } from \"../../../provider/components\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readDataValueTone, readText } from \"./data-value-format\";\nimport { TONE_GRAPHIC_COLOR } from \"./data-tones\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./Icon.module.scss\";\n\nconst ICON_SIZE_PX: Record<string, number> = { small: 16, medium: 20, large: 24 };\n\n/** The icon a wire name stands for — the node's names are package icon names (`IconComposedViewNode::ICON_NAMES`). */\nconst readIconName = (value: unknown): AgentsIconName | undefined => (isAgentsIconName(value) ? value : undefined);\n\n/**\n * The `Icon` node (the check and cross of a majority column): one component-library icon in\n * its tone's graphic colour. A `label` makes it an image with a name for screen readers and a tooltip; without one it\n * is decoration. A bound name that is not an icon renders nothing and reports `failed`.\n */\nconst IconNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime, isPending } = props;\n const iconName = readIconName(nodeProps.name);\n const label = readText(nodeProps.label);\n const tone = readDataValueTone(nodeProps.tone);\n const sizePx = ICON_SIZE_PX[typeof nodeProps.size === \"string\" ? nodeProps.size : \"small\"] ?? ICON_SIZE_PX.small;\n const hasUnknownName = !isPending && iconName === undefined;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : hasUnknownName ? \"failed\" : \"mounted\",\n hasUnknownName ? \"INVALID_PROP\" : undefined,\n hasUnknownName ? `the Icon name \"${String(nodeProps.name)}\" is not an icon` : undefined,\n );\n if (iconName === undefined) return null;\n return (\n <span\n className={styles.icon}\n role={label ? \"img\" : undefined}\n aria-label={label}\n aria-hidden={label ? undefined : true}\n title={label}\n >\n <Icon pixelSize={sizePx} color={TONE_GRAPHIC_COLOR[tone]} name={iconName} />\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Icon\", component: IconNode };\n","import { createContext, useContext } from \"react\";\n\n/**\n * What a layout node needs to know about the layout nodes around it:\n *\n * - inside a `Surface` → a nested surface is a FLAT tile, never a second raised surface (two background levels, never\n * three);\n * - inside a `Pressable` → the content is already one button, so a nested `Pressable` or `Popover` renders without a\n * control of its own (no button inside a button).\n */\nexport interface LayoutNesting {\n isInsideSurface: boolean;\n isInsidePressable: boolean;\n}\n\nexport const LayoutNestingContext = createContext<LayoutNesting>({ isInsideSurface: false, isInsidePressable: false });\n\nexport const useLayoutNesting = () => useContext(LayoutNestingContext);\n","import styles from \"./KpiMeter.module.scss\";\nimport { SegmentBar } from \"../../../../provider/components\";\n\nexport interface KpiMeterProps {\n value: number;\n max: number;\n /** The fill colour (a tone's graphic colour). */\n color: string;\n testId?: string;\n}\n\n/**\n * The thin meter under a written score (\"61,4/100\", \"5/5\"): the `SegmentBar` component, filled part and track. It\n * repeats the figure the hero already states, so assistive technology skips it.\n */\nexport const KpiMeter = (props: KpiMeterProps) => {\n const { value, max, color, testId } = props;\n const segments = [\n { value, color },\n { value: max - value, color: \"var(--agents-kpi-meter-track)\" },\n ].filter((segment) => segment.value > 0);\n return (\n <div className={styles.meter} aria-hidden=\"true\" data-testid={testId}>\n <SegmentBar segments={segments} height={6} />\n </div>\n );\n};\n","import { Icon, type AgentsIconName } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport styles from \"./KpiToneAccent.module.scss\";\nimport { TONE_GRAPHIC_COLOR } from \"../data-tones\";\nimport type { DataValueTone } from \"../data-value-format\";\n\nconst TONE_ICON: Partial<Record<DataValueTone, AgentsIconName>> = {\n success: \"check\",\n warning: \"warning\",\n danger: \"exclamation\",\n info: \"info\",\n};\n\nconst TONE_CLASS: Partial<Record<DataValueTone, string>> = {\n success: styles.success,\n warning: styles.warning,\n danger: styles.danger,\n info: styles.info,\n};\n\nexport interface KpiToneAccentProps {\n tone: DataValueTone;\n testId?: string;\n}\n\n/**\n * The status accent of a judged KPI: a small tinted badge with the tone's glyph beside the label. The value carries the\n * same tone in its colour, so the badge is decoration. Neutral and muted values show none.\n */\nexport const KpiToneAccent = (props: KpiToneAccentProps) => {\n const { tone, testId } = props;\n const icon = TONE_ICON[tone];\n if (!icon) return null;\n return (\n <span className={classNames(styles.accent, TONE_CLASS[tone])} aria-hidden=\"true\" data-testid={testId}>\n <Icon pixelSize={14} color={TONE_GRAPHIC_COLOR[tone]} name={icon} />\n </span>\n );\n};\n","import type { DataValueFormat } from \"./data-value-format\";\nimport { readFiniteNumber } from \"./data-value-format\";\n\n// Only whole numeric values and scores use the hero; numerals in prose remain readable text.\nconst NUMBER_PATTERN = String.raw`[-+]?(?:\\d+(?:[   ]\\d{3})*(?:[.,]\\d+)?|[.,]\\d+)`;\nconst NUMERIC_SCORE = new RegExp(String.raw`^${NUMBER_PATTERN}(?:\\s*\\/\\s*${NUMBER_PATTERN}|\\s*%)?$`);\nconst RATIO = new RegExp(String.raw`^(${NUMBER_PATTERN})(\\s*\\/\\s*(${NUMBER_PATTERN}))$`);\n// A written value may join its headline figure and a remark with a middle dot (\"5/5 · 22 recenzii\").\nconst SEGMENT_SEPARATOR = /\\s+[·•]\\s+/;\n\nexport interface KpiValueParts {\n presentation: \"hero\" | \"text\";\n /** The headline: the whole value, or the numerator of a ratio. */\n lead: string;\n /** The denominator of a ratio exactly as written (\"/100\", \" / 5\"). */\n denominator?: string;\n /** The remark after a numeric headline, shown on the unit line. */\n secondary?: string;\n /** A ratio the meter can draw: 0 ≤ value ≤ max, max > 0. */\n ratio?: { value: number; max: number };\n}\n\n/** A written number as a JS number: grouping spaces dropped, a lone comma read as the decimal mark. */\nconst readWrittenNumber = (written: string): number => {\n const compact = written.replace(/[   ]/g, \"\");\n return Number(compact.includes(\".\") ? compact.replace(/,/g, \"\") : compact.replace(\",\", \".\"));\n};\n\nconst readHeroParts = (lead: string, secondary: string | undefined): KpiValueParts => {\n const ratioMatch = RATIO.exec(lead);\n if (!ratioMatch) return { presentation: \"hero\", lead, secondary };\n const value = readWrittenNumber(ratioMatch[1]);\n const max = readWrittenNumber(ratioMatch[3]);\n const ratio = max > 0 && value >= 0 && value <= max ? { value, max } : undefined;\n return { presentation: \"hero\", lead: ratioMatch[1], denominator: ratioMatch[2], secondary, ratio };\n};\n\n/**\n * How a KPI value is laid out, never what it says: a number or a written score takes the hero, a leading score with a\n * remark splits at its middle dot, any other text stays one headline. Every character of the value is kept.\n */\nexport const readKpiValueParts = (\n rawValue: unknown,\n formattedValue: string,\n format: DataValueFormat = \"number\",\n): KpiValueParts => {\n if (format === \"date\") return { presentation: \"text\", lead: formattedValue };\n if (typeof rawValue === \"number\") {\n return { presentation: Number.isFinite(rawValue) ? \"hero\" : \"text\", lead: formattedValue };\n }\n if (typeof rawValue !== \"string\" || rawValue === \"\" || readFiniteNumber(rawValue) !== undefined) {\n return { presentation: \"hero\", lead: formattedValue };\n }\n const written = formattedValue.trim();\n if (NUMERIC_SCORE.test(written)) return readHeroParts(written, undefined);\n const separator = SEGMENT_SEPARATOR.exec(written);\n if (separator && NUMERIC_SCORE.test(written.slice(0, separator.index))) {\n return readHeroParts(written.slice(0, separator.index), written.slice(separator.index + separator[0].length));\n }\n return { presentation: \"text\", lead: formattedValue };\n};\n\n/** The presentation alone of a raw value in its format. */\nexport const readKpiValuePresentation = (value: unknown, format: DataValueFormat = \"number\"): \"hero\" | \"text\" =>\n readKpiValueParts(value, typeof value === \"string\" ? value : String(value ?? \"\"), format).presentation;\n","import { TrendDelta } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport styles from \"./KpiTile.module.scss\";\nimport { WidgetKpiValue, WidgetSurface, WidgetText } from \"../../../widgets/_shared/modern\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport { useLayoutNesting } from \"../layout/layout-nesting-context\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataFootnote } from \"./DataFootnote/DataFootnote\";\nimport { TONE_GRAPHIC_COLOR, TONE_TEXT_CLASS } from \"./data-tones\";\nimport {\n formatDataValue,\n readDataValueFormat,\n readDataValueTone,\n readFiniteNumber,\n readText,\n} from \"./data-value-format\";\nimport { KpiMeter } from \"./KpiMeter/KpiMeter\";\nimport { KpiToneAccent } from \"./KpiToneAccent/KpiToneAccent\";\nimport { readKpiValueParts } from \"./kpi-value-parts\";\nimport { useNumberLocale } from \"./use-number-locale\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\n\n// A neutral score fills in the call-to-action colour; a judged one in its tone's graphic colour.\nconst readMeterColor = (tone: keyof typeof TONE_GRAPHIC_COLOR): string =>\n tone === \"neutral\" ? \"var(--agents-fg-cta)\" : TONE_GRAPHIC_COLOR[tone];\n\n/**\n * The `KpiTile` node: label → hero value → unit and change → detail → source,\n * the design's anatomy of a number tile, built on `WidgetKpiValue` (the ONE hero scale).\n * The change is the component library's `TrendDelta`: its arrow colour says whether the change is good (`higherIsBetter`), not its\n * direction; the number carries its sign (\"+12.4 %\"). On the chat (no `Surface` around it, the nesting context of the layout nodes) the tile is an elevated surface; inside a\n * `Surface` it is a flat tile on the nested background, so a grid of tiles in a card has two background levels, never\n * three. Outside the root slot it takes the compact padding. A value that is still\n * loading is the hero's skeleton; a value that resolved to nothing shows a dash and reports `empty`.\n */\nconst KpiTileNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime, isPending, sizeClass, testId } = props;\n const locale = useNumberLocale();\n const { isInsideSurface } = useLayoutNesting();\n const label = readText(nodeProps.label) ?? \"\";\n const format = readDataValueFormat(nodeProps.format);\n const currency = readText(nodeProps.currency);\n const decimals = readFiniteNumber(nodeProps.decimals);\n const formattedValue = formatDataValue(nodeProps.value, {\n format,\n currency,\n decimals,\n signed: nodeProps.signed === true,\n locale,\n });\n const hasValue = formattedValue !== \"\";\n const delta = readFiniteNumber(nodeProps.delta);\n const deltaFormat = readDataValueFormat(nodeProps.deltaFormat);\n const deltaLabel = readText(nodeProps.deltaLabel);\n const higherIsBetter = nodeProps.higherIsBetter !== false;\n const tone = readDataValueTone(nodeProps.tone);\n const unit = readText(nodeProps.unit);\n const detail = readText(nodeProps.detail);\n const valueParts = readKpiValueParts(nodeProps.value, formattedValue, format);\n const { ratio, secondary } = valueParts;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : hasValue ? \"mounted\" : \"empty\",\n !isPending && !hasValue ? \"NO_DATA\" : undefined,\n !isPending && !hasValue ? `the KpiTile \"${label}\" has no value` : undefined,\n );\n const deltaElement =\n delta === undefined ? undefined : (\n <span className={styles.delta} data-testid={`${testId}-delta`}>\n <TrendDelta\n current={delta}\n previous={0}\n higherIsBetter={higherIsBetter}\n // TrendDelta hands over the magnitude only; the change keeps its sign (\"+6\", \"+5 %\", \"-0.49\").\n format={(magnitude) =>\n formatDataValue(delta < 0 ? -magnitude : magnitude, { format: deltaFormat, currency, locale, signed: true })\n }\n />\n {deltaLabel ? (\n <WidgetText variant=\"caption\" tone=\"light\" translate={false} testId={`${testId}-delta-label`}>\n {escapePlainTextForText(deltaLabel)}\n </WidgetText>\n ) : null}\n </span>\n );\n return (\n <WidgetSurface\n level={isInsideSurface ? \"flat\" : \"elevated\"}\n compact={sizeClass !== \"full\"}\n className={styles.tile}\n testId={testId}\n >\n {isPending ? (\n // The primitive's own loading skeleton animates its style every frame — a capture never settles on it.\n <div className={styles.loading} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <WidgetText variant=\"caption\" tone=\"light\" translate={false} testId={`${testId}-label`}>\n {escapePlainTextForText(label)}\n </WidgetText>\n <SkeletonLine width=\"60%\" height={40} radius={8} />\n </div>\n ) : (\n <WidgetKpiValue\n testId={testId}\n valuePresentation={valueParts.presentation}\n label={escapePlainTextForText(label)}\n accent={\n tone === \"neutral\" || tone === \"muted\" ? undefined : (\n <KpiToneAccent tone={tone} testId={`${testId}-accent`} />\n )\n }\n value={\n <span className={TONE_TEXT_CLASS[tone]} data-testid={`${testId}-value`}>\n <WidgetText translate={false}>{hasValue ? escapePlainTextForText(valueParts.lead) : \"—\"}</WidgetText>\n {valueParts.denominator ? (\n <span className={styles.denominator}>\n <WidgetText translate={false}>{escapePlainTextForText(valueParts.denominator)}</WidgetText>\n </span>\n ) : null}\n </span>\n }\n meter={\n ratio ? (\n <KpiMeter value={ratio.value} max={ratio.max} color={readMeterColor(tone)} testId={`${testId}-meter`} />\n ) : undefined\n }\n unit={\n secondary ? (\n <span className={styles.unitParts}>\n <WidgetText variant=\"value\" translate={false} inline testId={`${testId}-value-secondary`}>\n {escapePlainTextForText(secondary)}\n </WidgetText>\n {unit ? <WidgetText translate={false}>{escapePlainTextForText(unit)}</WidgetText> : null}\n </span>\n ) : unit ? (\n escapePlainTextForText(unit)\n ) : undefined\n }\n delta={deltaElement}\n />\n )}\n {detail ? (\n <WidgetText variant=\"caption\" tone=\"light\" translate={false} testId={`${testId}-detail`}>\n {escapePlainTextForText(detail)}\n </WidgetText>\n ) : null}\n <DataFootnote\n source={nodeProps.source}\n isEmailRender={runtime.isEmailRender}\n appearance=\"quiet\"\n testId={`${testId}-footnote`}\n />\n </WidgetSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"KpiTile\", component: KpiTileNode };\n","import { createContext, useContext } from \"react\";\n/**\n * Where a data node sits: a `TableRow` must know it is inside a `Table` to render a `<tr>`,\n * a `TableCell` inside a header row to render a `<th>`, a `Repeat` inside a `Table` or `List` to repeat only the row\n * nodes those containers take. Outside its container each node renders a standalone fallback instead of invalid\n * markup — a model may put a `TableRow` at the root, the reader does not forbid it.\n */\n\nexport type DataContainerKind = \"table\" | \"list\" | null;\n\nexport const DataContainerContext = createContext<DataContainerKind>(null);\nexport const useDataContainer = () => useContext(DataContainerContext);\n\nexport interface TableRowContextValue {\n isHeader: boolean;\n isEmphasis: boolean;\n}\n\nexport const TableRowContext = createContext<TableRowContextValue | null>(null);\nexport const useTableRow = () => useContext(TableRowContext);\n\nexport interface ListContextValue {\n marker: \"none\" | \"bullet\" | \"number\" | \"check\";\n}\n\nexport const ListContext = createContext<ListContextValue>({ marker: \"none\" });\nexport const useListMarker = () => useContext(ListContext).marker;\n\n/** The node types a container takes from a `Repeat` inside it. */\nexport const REPEATABLE_NODE_TYPES_BY_CONTAINER: Record<Exclude<DataContainerKind, null>, string> = {\n table: \"TableRow\",\n list: \"ListItem\",\n};\n","import { Icon, Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport type { ListContextValue } from \"../data-containers\";\nimport styles from \"./ListEntry.module.scss\";\n\nexport interface ListEntryProps {\n marker: ListContextValue[\"marker\"];\n title?: string;\n description?: string;\n meta?: string;\n value?: string;\n /** Nodes under the title (a ListItem's slot). */\n children?: ReactNode;\n /** Nodes at the end of the entry (a ListItem's `trailing` slot). */\n trailing?: ReactNode;\n /** Render a `<div>` instead of an `<li>` — an entry outside a list. */\n isStandalone?: boolean;\n testId?: string;\n}\n\n/**\n * One list entry: marker | title over description\n * and muted meta, then the nodes under them | value and trailing nodes. All text is the model's (no translation).\n */\nexport const ListEntry = (props: ListEntryProps) => {\n const { marker, title, description, meta, value, children, trailing, isStandalone = false, testId } = props;\n const EntryElement = isStandalone ? \"div\" : \"li\";\n return (\n <EntryElement className={classNames(styles.entry, marker !== \"none\" && styles.withMarker)} data-testid={testId}>\n {marker === \"bullet\" ? <span className={styles.bullet} aria-hidden=\"true\" /> : null}\n {marker === \"number\" ? <span className={styles.number} aria-hidden=\"true\" /> : null}\n {marker === \"check\" ? (\n <span className={styles.check} aria-hidden=\"true\">\n <Icon pixelSize={16} color=\"var(--agents-success-500)\" name=\"check\" />\n </span>\n ) : null}\n <span className={styles.text}>\n {title ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n {description ? (\n <Text role=\"help\" translate={false}>\n {escapePlainTextForText(description)}\n </Text>\n ) : null}\n {meta ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(meta)}\n </Text>\n ) : null}\n {children}\n </span>\n {value || trailing ? (\n <span className={styles.trailing}>\n {value ? (\n <Text role=\"body\" weight=\"medium\" className={styles.value} translate={false}>\n {escapePlainTextForText(value)}\n </Text>\n ) : null}\n {trailing}\n </span>\n ) : null}\n </EntryElement>\n );\n};\n","import { classNames } from \"../../../provider/class-names\";\nimport { useMemo } from \"react\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, ListContext, ListContextValue } from \"./data-containers\";\nimport { readObject, readText } from \"./data-value-format\";\nimport { ListEntry } from \"./ListEntry/ListEntry\";\nimport { DataEmptyLine } from \"./DataEmptyLine/DataEmptyLine\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./List.module.scss\";\n\nconst MARKERS: ReadonlyArray<ListContextValue[\"marker\"]> = [\"none\", \"bullet\", \"number\", \"check\"];\n\ninterface ShortFormListEntry {\n title?: string;\n description?: string;\n meta?: string;\n value?: string;\n}\n\n/** One entry of the short form: a string is the title; an object gives title / description / meta / value. */\nconst readShortFormEntry = (itemValue: ExpressionValue): ShortFormListEntry | undefined => {\n const itemText = readText(itemValue);\n if (itemText !== undefined) return { title: itemText };\n const itemObject = readObject(itemValue);\n if (!itemObject) return undefined;\n const entry: ShortFormListEntry = {\n title: readText(itemObject.title) ?? readText(itemObject.label) ?? readText(itemObject.name),\n description: readText(itemObject.description) ?? readText(itemObject.text),\n meta: readText(itemObject.meta),\n value: readText(itemObject.value),\n };\n return entry.title || entry.description ? entry : undefined;\n};\n\n/**\n * The `List` node: entries divided by hairlines, an `<ol>` when\n * the marker is `number`, a `<ul>` otherwise. The short form `items` renders before the node form's `ListItem` /\n * `Repeat` children. The short form is capped at `maxRepeatRows` (reported); no entry at all shows one muted line and\n * reports `empty`.\n */\nconst ListNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, isPending, testId } = props;\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n const marker = MARKERS.find((knownMarker) => knownMarker === nodeProps.marker) ?? \"none\";\n const listContextValue = useMemo<ListContextValue>(() => ({ marker }), [marker]);\n const shortFormEntries = (Array.isArray(nodeProps.items) ? nodeProps.items : [])\n .map(readShortFormEntry)\n .filter((entry): entry is ShortFormListEntry => entry !== undefined);\n const shownEntries = shortFormEntries.slice(0, maxRepeatRows);\n const childEntries = slots.children ?? [];\n const isEmpty = !isPending && shortFormEntries.length === 0 && childEntries.length === 0;\n const isOverEntryBudget = shortFormEntries.length > maxRepeatRows;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : isOverEntryBudget ? \"failed\" : isEmpty ? \"empty\" : \"mounted\",\n isOverEntryBudget ? \"BUDGET_EXCEEDED\" : isEmpty ? \"NO_DATA\" : undefined,\n isOverEntryBudget\n ? `the List shows the first ${maxRepeatRows} of ${shortFormEntries.length} entries only`\n : isEmpty\n ? \"the List has no entries\"\n : undefined,\n );\n if (isEmpty) return <DataEmptyLine emptyText={nodeProps.emptyText} testId={`${testId}-empty`} />;\n const ListElement = marker === \"number\" ? \"ol\" : \"ul\";\n return (\n <ListElement className={classNames(styles.list, marker === \"number\" && styles.numbered)} data-testid={testId}>\n <ListContext.Provider value={listContextValue}>\n {shownEntries.map((entry, entryIndex) => (\n <ListEntry\n key={entryIndex}\n testId={`${testId}-entry-${entryIndex}`}\n marker={marker}\n title={entry.title}\n description={entry.description}\n meta={entry.meta}\n value={entry.value}\n />\n ))}\n <DataContainerContext.Provider value=\"list\">{childEntries}</DataContainerContext.Provider>\n </ListContext.Provider>\n </ListElement>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"List\", component: ListNode };\n","import type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, useDataContainer, useListMarker } from \"./data-containers\";\nimport { readText } from \"./data-value-format\";\nimport { ListEntry } from \"./ListEntry/ListEntry\";\n\n/**\n * The `ListItem` node: one `List` entry — title, description, meta, value — with the nodes of its\n * slot under the title and those of `trailing` at its end. The nodes inside are no longer \"in the list\", so a\n * `Repeat` in an entry repeats freely. Outside a `List` it renders the same entry as a standalone row.\n */\nconst ListItemNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, testId } = props;\n const container = useDataContainer();\n const marker = useListMarker();\n const isInList = container === \"list\";\n return (\n <ListEntry\n testId={testId}\n marker={isInList ? marker : \"none\"}\n title={readText(nodeProps.title)}\n description={readText(nodeProps.description)}\n meta={readText(nodeProps.meta)}\n value={readText(nodeProps.value)}\n trailing={\n slots.trailing && slots.trailing.length > 0 ? (\n <DataContainerContext.Provider value={null}>{slots.trailing}</DataContainerContext.Provider>\n ) : undefined\n }\n isStandalone={!isInList}\n >\n {slots.children && slots.children.length > 0 ? (\n <DataContainerContext.Provider value={null}>{slots.children}</DataContainerContext.Provider>\n ) : null}\n </ListEntry>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"ListItem\", component: ListItemNode };\n","import type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { REPEATABLE_NODE_TYPES_BY_CONTAINER, useDataContainer } from \"./data-containers\";\nimport { readFiniteNumber } from \"./data-value-format\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\n\n/**\n * The `Repeat` node: its children once per item, with `{\"$item\":…}` bound to the item. It\n * renders no element of its own, so the repeated nodes sit where it sits — table rows in a `Table`, entries in a\n * `List`, tiles in a `Grid`. Inside a `Table` it repeats only its `TableRow`s, inside a `List` only its `ListItem`s\n * (anything else would be invalid markup there) and reports the rest. The renderer caps the items at `maxRepeatRows`\n * (`renderSlotForItem`) and reports the overflow; `limit` cuts earlier. An empty list reports `empty`.\n */\nconst RepeatNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, runtime, isPending, renderSlotForItem } = props;\n const container = useDataContainer();\n const items = Array.isArray(nodeProps.items) ? nodeProps.items : undefined;\n const limit = readFiniteNumber(nodeProps.limit);\n const shownItems = items && limit !== undefined && limit >= 0 ? items.slice(0, Math.floor(limit)) : (items ?? []);\n const childNodeTypes = (node.nodesBySlotName.children ?? []).map((childNode) => childNode.type);\n const acceptedNodeType = container ? REPEATABLE_NODE_TYPES_BY_CONTAINER[container] : undefined;\n const droppedNodeTypes = acceptedNodeType\n ? childNodeTypes.filter((childNodeType) => childNodeType !== acceptedNodeType)\n : [];\n const hasNoList = !isPending && items === undefined;\n useReportDataNodeStatus(\n runtime,\n isPending\n ? \"pending\"\n : hasNoList || droppedNodeTypes.length > 0\n ? \"failed\"\n : shownItems.length === 0\n ? \"empty\"\n : \"mounted\",\n hasNoList\n ? \"UNRESOLVED_BINDING\"\n : droppedNodeTypes.length > 0\n ? \"INVALID_NODE\"\n : shownItems.length === 0 && !isPending\n ? \"NO_DATA\"\n : undefined,\n hasNoList\n ? \"the Repeat items are not a list\"\n : droppedNodeTypes.length > 0\n ? `a Repeat in a ${container} repeats ${acceptedNodeType} nodes only — ${droppedNodeTypes.join(\", \")} not shown`\n : shownItems.length === 0 && !isPending\n ? \"the Repeat has no items\"\n : undefined,\n );\n const repeatedNodes = shownItems.flatMap((item, itemIndex) =>\n renderSlotForItem(\"children\", item, itemIndex).filter(\n (renderedNode, childPosition) =>\n acceptedNodeType === undefined || childNodeTypes[childPosition] === acceptedNodeType,\n ),\n );\n return <>{repeatedNodes}</>;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Repeat\", component: RepeatNode };\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n DataValueAlign,\n DataValueFormat,\n isNumericValue,\n readDataValueAlign,\n readDataValueFormat,\n readFiniteNumber,\n readObject,\n readText,\n} from \"./data-value-format\";\n\n/** One column of a `Table`'s short form (`columns`): the row field, its header and how its cells are shown. */\nexport interface TableColumn {\n key: string;\n label: string;\n align: DataValueAlign;\n format: DataValueFormat;\n currency?: string;\n decimals?: number;\n unit?: string;\n}\n\n/**\n * The short form's columns from the resolved `columns` prop: every entry with a string `key` (alias `field`, which a\n * model writes because `Chart` series use it); the header falls back to the key; a column without an `align` aligns\n * at the end when every value in it is a number.\n */\nexport const readTableColumns = (\n columnsValue: ExpressionValue,\n rows: Record<string, ExpressionValue>[],\n): TableColumn[] => {\n if (!Array.isArray(columnsValue)) return [];\n const columns: TableColumn[] = [];\n for (const columnValue of columnsValue) {\n const column = readObject(columnValue);\n const key = readText(column?.key) ?? readText(column?.field);\n if (!column || !key) continue;\n const values = rows.map((row) => row[key]).filter((value) => value !== undefined && value !== null && value !== \"\");\n const isNumericColumn = values.length > 0 && values.every((value) => isNumericValue(value));\n columns.push({\n key,\n label: readText(column.label) ?? key,\n align: readDataValueAlign(column.align, isNumericColumn ? \"end\" : \"start\"),\n format: readDataValueFormat(column.format),\n currency: readText(column.currency),\n decimals: readFiniteNumber(column.decimals),\n unit: readText(column.unit),\n });\n }\n return columns;\n};\n","import { Icon, Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { DataValueFormat, DataValueTone, formatDataValue } from \"../data-value-format\";\nimport { TONE_GRAPHIC_COLOR, TONE_TEXT_COLOR } from \"../data-tones\";\nimport { useNumberLocale } from \"../use-number-locale\";\nimport { translateText } from \"../../../../provider/environment\";\nimport styles from \"./TableValue.module.scss\";\n\nexport interface TableValueProps {\n value: ExpressionValue;\n format: DataValueFormat;\n currency?: string;\n decimals?: number;\n unit?: string;\n signed?: boolean;\n tone?: DataValueTone;\n isBold?: boolean;\n}\n\n/**\n * One table value: a formatted number or text in the cell's tone, tabular figures; a boolean as a check (yes, green)\n * or a cross (no, red) with its meaning for screen readers — ChatGPT's majority column. Empty renders nothing.\n */\nexport const TableValue = (props: TableValueProps) => {\n const { value, format, currency, decimals, unit, signed = false, tone = \"neutral\", isBold = false } = props;\n const locale = useNumberLocale();\n if (typeof value === \"boolean\") {\n return (\n <span className={styles.booleanValue} role=\"img\" aria-label={translateText(value ? \"Yes\" : \"No\")}>\n <Icon pixelSize={16} color={TONE_GRAPHIC_COLOR[value ? \"success\" : \"danger\"]} name={value ? \"check\" : \"close\"} />\n </span>\n );\n }\n const formattedValue = formatDataValue(value, { format, currency, decimals, unit, signed, locale });\n if (formattedValue === \"\") return null;\n return (\n <Text\n role=\"help\"\n weight={isBold ? \"bold\" : \"regular\"}\n color={TONE_TEXT_COLOR[tone]}\n className={styles.value}\n translate={false}\n >\n {escapePlainTextForText(formattedValue)}\n </Text>\n );\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext } from \"./data-containers\";\nimport { readRows } from \"./data-value-format\";\nimport { readTableColumns } from \"./table-columns\";\nimport { TableValue } from \"./TableValue/TableValue\";\nimport { DataFootnote } from \"./DataFootnote/DataFootnote\";\nimport { DataEmptyLine } from \"./DataEmptyLine/DataEmptyLine\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./Table.module.scss\";\n\nconst SKELETON_ROW_COUNT = 3;\n\n/**\n * The `Table` node. The short form — `columns` + `rows` — writes the\n * header row and one row per data row, each cell formatted by its column (a boolean as a check or a cross). The node\n * form — `TableRow` / `Repeat` children — follows it in the same body, so a total row can close the data rows. Rows\n * are hairline-divided, never boxed; a table wider than the chat pane scrolls inside itself. A\n * table still waiting for bound rows shows row-shaped skeletons; one with nothing to show one muted line and reports\n * `empty`. The short form renders at most `maxRepeatRows` rows and reports the rest.\n */\nconst TableNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, isPending, testId } = props;\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n const rows = readRows(nodeProps.rows) ?? [];\n const columns = readTableColumns(nodeProps.columns, rows);\n const shownRows = rows.slice(0, maxRepeatRows);\n const childRows = slots.children ?? [];\n const isWaitingForRows = isPending && rows.length === 0;\n const isEmpty = !isPending && (columns.length === 0 || rows.length === 0) && childRows.length === 0;\n const isOverRowBudget = rows.length > maxRepeatRows;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : isOverRowBudget ? \"failed\" : isEmpty ? \"empty\" : \"mounted\",\n isOverRowBudget ? \"BUDGET_EXCEEDED\" : isEmpty && !isPending ? \"NO_DATA\" : undefined,\n isOverRowBudget\n ? `the Table shows the first ${maxRepeatRows} of ${rows.length} rows only`\n : isEmpty && !isPending\n ? \"the Table has no rows\"\n : undefined,\n );\n return (\n <div className={styles.table} data-testid={testId}>\n <div className={styles.scroller}>\n <table className={styles.grid}>\n {columns.length > 0 ? (\n <thead>\n <tr>\n {columns.map((column) => (\n <th key={column.key} scope=\"col\" className={classNames(styles.cell, styles[column.align])}>\n <Text role=\"help\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(column.label)}\n </Text>\n </th>\n ))}\n </tr>\n </thead>\n ) : null}\n <tbody>\n {shownRows.map((row, rowIndex) => (\n <tr key={rowIndex} className={styles.row} data-testid={`${testId}-row-${rowIndex}`}>\n {columns.map((column) => (\n <td key={column.key} className={classNames(styles.cell, styles[column.align])}>\n <TableValue\n value={row[column.key]}\n format={column.format}\n currency={column.currency}\n decimals={column.decimals}\n unit={column.unit}\n />\n </td>\n ))}\n </tr>\n ))}\n {isWaitingForRows && columns.length > 0\n ? Array.from({ length: SKELETON_ROW_COUNT }, (unused, skeletonIndex) => (\n <tr\n key={`skeleton-${skeletonIndex}`}\n className={styles.row}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton-${skeletonIndex}`}\n >\n {columns.map((column) => (\n <td key={column.key} className={classNames(styles.cell, styles[column.align])}>\n <SkeletonLine width=\"70%\" height={12} />\n </td>\n ))}\n </tr>\n ))\n : null}\n <DataContainerContext.Provider value=\"table\">{childRows}</DataContainerContext.Provider>\n </tbody>\n </table>\n </div>\n {isEmpty ? <DataEmptyLine emptyText={nodeProps.emptyText} testId={`${testId}-empty`} /> : null}\n <DataFootnote caption={nodeProps.caption} source={nodeProps.source} isEmailRender={runtime.isEmailRender} />\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Table\", component: TableNode };\n","import { classNames } from \"../../../provider/class-names\";\nimport { CSSProperties } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, useTableRow } from \"./data-containers\";\nimport {\n formatDataValue,\n isNumericValue,\n readDataValueAlign,\n readDataValueFormat,\n readDataValueTone,\n readFiniteNumber,\n readFraction,\n readText,\n} from \"./data-value-format\";\nimport { TableValue } from \"./TableValue/TableValue\";\nimport { useNumberLocale } from \"./use-number-locale\";\nimport tableStyles from \"./Table.module.scss\";\nimport styles from \"./TableCell.module.scss\";\n\n/**\n * The `TableCell` node (`Cell.content`): a formatted `value`, then the nodes of its compact slot\n * (an `Icon`, a `Badge`, a sparkline `Chart`) — the cell is the place where a table holds other nodes. `bar` draws a\n * share bar before the value, `heat` tints the whole cell by intensity with the value on top (no value = a muted dash on the untinted tile). In a header row the cell is a `<th>`; outside a row it is a plain\n * inline block. The bar and heat widths travel as CSS custom properties — the one dynamic value, no inline style.\n */\nconst TableCellNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots } = props;\n const tableRow = useTableRow();\n const locale = useNumberLocale();\n const isHeader = tableRow?.isHeader ?? false;\n const isBold = isHeader || (tableRow?.isEmphasis ?? false);\n const align = readDataValueAlign(nodeProps.align, isNumericValue(nodeProps.value) ? \"end\" : \"start\");\n const format = readDataValueFormat(nodeProps.format);\n const bar = readFraction(nodeProps.bar);\n const heat = readFraction(nodeProps.heat);\n // A heat cell is one whose node declares `heat`, even when its binding resolved to nothing (a missing cohort month).\n const isHeatCell = Object.prototype.hasOwnProperty.call(node.props, \"heat\");\n const hasValue = formatDataValue(nodeProps.value, { format, locale }) !== \"\" || typeof nodeProps.value === \"boolean\";\n const cellStyle = {\n ...(bar !== undefined ? { \"--agents-table-cell-bar\": `${Math.round(bar * 1000) / 10}%` } : {}),\n ...(heat !== undefined ? { \"--agents-table-cell-heat\": `${Math.round(10 + heat * 70)}%` } : {}),\n } as CSSProperties;\n const content = (\n <span\n className={classNames(\n styles.content,\n styles[align],\n bar !== undefined && styles.withBar,\n isHeatCell && styles.heat,\n isHeatCell && heat === undefined && styles.heatEmpty,\n )}\n >\n {bar !== undefined ? <span className={styles.bar} aria-hidden=\"true\" /> : null}\n {hasValue ? (\n <TableValue\n value={nodeProps.value}\n format={format}\n currency={readText(nodeProps.currency)}\n decimals={readFiniteNumber(nodeProps.decimals)}\n unit={readText(nodeProps.unit)}\n signed={nodeProps.signed === true}\n tone={readDataValueTone(nodeProps.tone)}\n isBold={isBold}\n />\n ) : isHeatCell ? (\n <span className={styles.dash}>{\"—\"}</span>\n ) : null}\n {slots.children && slots.children.length > 0 ? (\n <DataContainerContext.Provider value={null}>{slots.children}</DataContainerContext.Provider>\n ) : null}\n </span>\n );\n if (!tableRow) return <span style={cellStyle}>{content}</span>;\n const cellClassName = classNames(tableStyles.cell, tableStyles[align], isHeatCell && styles.heatCell);\n return isHeader ? (\n <th scope=\"col\" className={cellClassName} style={cellStyle}>\n {content}\n </th>\n ) : (\n <td className={cellClassName} style={cellStyle}>\n {content}\n </td>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"TableCell\",\n component: TableCellNode,\n};\n","import { classNames } from \"../../../provider/class-names\";\nimport { useMemo } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, TableRowContext, TableRowContextValue, useDataContainer } from \"./data-containers\";\nimport styles from \"./Table.module.scss\";\n\n/**\n * The `TableRow` node (`Row.cells`): a `<tr>` of its `TableCell`s; `header` makes the cells\n * column headers, `emphasis` a bold total row. Outside a `Table` (a row at the root, a `Repeat` of rows without a\n * table) it wraps itself in a one-row table, so the markup stays valid.\n */\nconst TableRowNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, testId } = props;\n const container = useDataContainer();\n const isHeader = nodeProps.header === true;\n const isEmphasis = nodeProps.emphasis === true;\n const tableRowContextValue = useMemo<TableRowContextValue>(() => ({ isHeader, isEmphasis }), [isHeader, isEmphasis]);\n const row = (\n <tr className={classNames(styles.row, isHeader && styles.headerRow)} data-testid={testId}>\n <TableRowContext.Provider value={tableRowContextValue}>{slots.children}</TableRowContext.Provider>\n </tr>\n );\n if (container === \"table\") return row;\n return (\n <div className={styles.scroller}>\n <table className={styles.grid}>\n <tbody>\n <DataContainerContext.Provider value=\"table\">{row}</DataContainerContext.Provider>\n </tbody>\n </table>\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"TableRow\", component: TableRowNode };\n","import React from \"react\";\nimport { reportWidgetCrash } from \"../provider/environment\";\n\ninterface Props {\n /** Canonical widget name, for the error log. */\n widgetName: string;\n /** Called once when the widget threw — the render report marks the block `failed`. */\n onCrash?: () => void;\n children: React.ReactNode;\n}\n\ninterface State {\n hasError: boolean;\n}\n\n/**\n * Per-widget error boundary. Widget props originate from LLM output, so a\n * malformed payload can throw anywhere in a widget's render/effects — without a\n * boundary one bad widget unmounts the entire chat message. On error the\n * widget renders nothing (the surrounding prose stays intact) and the failure\n * is logged with the widget name.\n */\nexport class ConversationWidgetErrorBoundary extends React.Component<Props, State> {\n state: State = { hasError: false };\n\n static getDerivedStateFromError(): State {\n return { hasError: true };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {\n console.error(`[ConversationMarkdown] widget \"${this.props.widgetName}\" crashed`, error, errorInfo);\n reportWidgetCrash(this.props.widgetName, error, errorInfo);\n this.props.onCrash?.();\n }\n\n render(): React.ReactNode {\n if (this.state.hasError) {\n return null;\n }\n\n return this.props.children;\n }\n}\n","import React from \"react\";\nimport { WidgetFeatureGate } from \"../../provider/components\";\n\n/** Shared prop contract for any widget upgrade offer (a widget's own `upsellTrigger`); the flag is the app's object. */\nexport interface ConversationWidgetUpsellProps {\n flag: unknown;\n}\n\ninterface ConversationWidgetFeatureGateProps {\n /** The requirement the widget declares in the registry (an app feature flag, opaque to the package). */\n featureFlag: string;\n /** Optional per-widget upgrade offer; falls back to the app gate's own. */\n UpsellTrigger?: React.ComponentType<ConversationWidgetUpsellProps>;\n /** The widget's raw agent space key attribute (renders for another agent space). */\n agentSpaceKeyAttribute?: string | number;\n children: React.ReactNode;\n}\n\n/**\n * Gates a widget on the requirement its registry entry declares, through the app's `WidgetFeatureGate` component (the\n * environment's): the widget, a placeholder while the requirements load, or an upgrade offer. Without an app gate\n * every widget renders.\n */\nexport const ConversationWidgetFeatureGate = (props: ConversationWidgetFeatureGateProps) => {\n const { featureFlag, UpsellTrigger, agentSpaceKeyAttribute, children } = props;\n return (\n <WidgetFeatureGate featureFlag={featureFlag} UpsellTrigger={UpsellTrigger} agentSpaceKeyAttribute={agentSpaceKeyAttribute}>\n {children}\n </WidgetFeatureGate>\n );\n};\n","import { useEffect, useMemo } from \"react\";\nimport { conversationWidgetRegistry } from \"../../../renderer/conversationWidgetRegistry\";\nimport { resolveWidgetName } from \"../../../renderer/widget-name-resolver\";\nimport { ConversationWidgetErrorBoundary } from \"../../../renderer/ConversationWidgetErrorBoundary\";\nimport {\n buildWidgetAgentSpaceKeyProps,\n readWidgetAgentSpaceKeyAttribute,\n} from \"../../../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport { ConversationWidgetFeatureGate } from \"../../../renderer/_access/ConversationWidgetFeatureGate\";\nimport {\n WidgetRenderReportCode,\n WidgetRenderReportContext,\n WidgetRenderReporter,\n WidgetRenderStatus,\n} from \"../../../renderer/render-report/widget-render-report\";\n\nexport interface EmbeddedConversationWidgetProps {\n /** The wire name as written (a legacy `…Directive` name resolves as everywhere). */\n widgetName: string;\n /** The widget's own fields — its `payload`, exactly as its own fence would carry them next to `type`. */\n fields: Record<string, unknown>;\n /** The key of the tree's agent space; the key in the fields wins. */\n agentSpaceKey?: string | number;\n interactive: boolean;\n messageId?: string | number;\n /**\n * Where the widget's own render report goes — the tree's report at the node's path, never the host block's reporter\n * (an embedded widget and the tree would otherwise overwrite each other's report).\n */\n reportStatus: (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) => void;\n}\n\n/**\n * A domain widget rendered inside a `ComposedView` — as a `Widget` node in the tree, or as a widget the readers LIFTED\n * out of it and show after the view. It renders the registered component with the tree's\n * context: `interactive` and `messageId` of the host message, the agent space, and `justDelivered = false`, so it never\n * auto-opens a canvas (the owner opens it by clicking). It gets its OWN render-report context, which forwards its\n * statuses into the tree's report, names the widget in the detail, and turns a crash (`RENDER_FAILED`) or an unknown\n * name (`INVALID_NODE`) into a report instead of a silent nothing. The registry's feature gate applies as it does to\n * the widget's own fence. The registry is read at render time, never at module load (the registry imports this kit).\n */\nexport const EmbeddedConversationWidget = (props: EmbeddedConversationWidgetProps) => {\n const { widgetName, fields, agentSpaceKey, interactive, messageId, reportStatus } = props;\n const resolvedWidgetName = resolveWidgetName(widgetName);\n const entry = resolvedWidgetName\n ? conversationWidgetRegistry.widgets.find((widget) => widget.name === resolvedWidgetName)\n : undefined;\n const reporter = useMemo<WidgetRenderReporter>(\n () => ({\n report: (reportEntry) =>\n reportStatus(\n reportEntry.status,\n reportEntry.code,\n reportEntry.detail ? `${resolvedWidgetName ?? widgetName}: ${reportEntry.detail}` : undefined,\n ),\n }),\n [reportStatus, resolvedWidgetName, widgetName],\n );\n const payload = useMemo(() => JSON.stringify(fields), [fields]);\n\n useEffect(() => {\n if (!entry) reportStatus(\"failed\", \"INVALID_NODE\", `no registered widget \"${widgetName}\"`);\n }, [entry, reportStatus, widgetName]);\n\n if (!entry) return null;\n const EmbeddedComponent = entry.component;\n const fieldAgentSpaceKey = readWidgetAgentSpaceKeyAttribute(fields) ?? agentSpaceKey;\n const embeddedAgentSpaceKey =\n typeof fieldAgentSpaceKey === \"string\" || typeof fieldAgentSpaceKey === \"number\"\n ? String(fieldAgentSpaceKey)\n : undefined;\n const embeddedWidget = (\n <WidgetRenderReportContext.Provider value={reporter}>\n <ConversationWidgetErrorBoundary\n widgetName={entry.name}\n onCrash={() => reportStatus(\"failed\", \"RENDER_FAILED\", `the embedded ${entry.name} threw`)}\n >\n <EmbeddedComponent\n payload={payload}\n {...buildWidgetAgentSpaceKeyProps(embeddedAgentSpaceKey)}\n interactive={interactive}\n fresh={interactive}\n justDelivered={false}\n messageId={messageId}\n />\n </ConversationWidgetErrorBoundary>\n </WidgetRenderReportContext.Provider>\n );\n // The registry's feature gate holds inside a tree exactly as for the widget's own fence.\n if (!entry.featureFlag) return embeddedWidget;\n return (\n <ConversationWidgetFeatureGate\n featureFlag={entry.featureFlag}\n UpsellTrigger={entry.upsellTrigger}\n agentSpaceKeyAttribute={embeddedAgentSpaceKey}\n >\n {embeddedWidget}\n </ConversationWidgetFeatureGate>\n );\n};\n","import { useMemo } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { EmbeddedConversationWidget } from \"./EmbeddedConversationWidget\";\n\n/**\n * The core `Widget` node (`WidgetComposedViewNode.php`): an existing domain widget inside the tree,\n * rendered through {@link EmbeddedConversationWidget} with the tree's per-slot context. The node's `fields` become the\n * widget's `payload`, exactly as its own fence would carry them next to `type`. The widget reports into the tree at this\n * node's path (`runtime.reportNodeStatus`), never into the host block's reporter.\n */\nconst WidgetNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime } = props;\n const fields = useMemo(\n () =>\n typeof nodeProps.fields === \"object\" && nodeProps.fields !== null && !Array.isArray(nodeProps.fields)\n ? (nodeProps.fields as Record<string, unknown>)\n : {},\n [nodeProps.fields],\n );\n return (\n <EmbeddedConversationWidget\n widgetName={typeof nodeProps.widget === \"string\" ? nodeProps.widget : \"\"}\n fields={fields}\n agentSpaceKey={runtime.agentSpaceKey}\n interactive={runtime.interactive}\n messageId={runtime.messageId}\n reportStatus={runtime.reportNodeStatus}\n />\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Widget\", component: WidgetNode };\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { readOpenEntityActionTarget } from \"../../../renderer/canvas/entity-detail-instance\";\nimport type { ComposedViewRuntime } from \"../../composed-view-component-types\";\n\n/**\n * Whether an `EntityLink`'s click opens a detail panel. Pure; never throws.\n *\n * - `missing` — no action name (`action` absent, empty or not text);\n * - `unresolved` — the tree's action of that name is gone (the persist pass dropped it), is not `openEntity`, or\n * carries no resolved `entity` — the reference did not resolve, a click would open nothing;\n * - `resolved` — an `openEntity` action with its resolved entity — for a row-bound action (`ref: {\"$item\":\"entityRef\"}`)\n * the `entity` of the row the link renders in (`runtime.currentRow`);\n * - `unchecked` — the runtime cannot look actions up (it has no `findAction`), so the name is trusted and the click\n * runs the action; the widget opens nothing for an unresolved one.\n */\nexport type EntityLinkTargetState = \"missing\" | \"unresolved\" | \"resolved\" | \"unchecked\";\n\nexport interface EntityLinkTarget {\n state: EntityLinkTargetState;\n actionName: string;\n}\n\n/**\n * The runtime's optional action lookup: the tree action by name, or undefined. Not on `ComposedViewRuntime` yet — the\n * renderer adds it; until then every link is `unchecked`.\n */\ntype RuntimeWithActionLookup = ComposedViewRuntime & {\n findAction?: (actionName: string) => Record<string, unknown> | undefined;\n};\n\nexport const readEntityLinkTarget = (actionProp: ExpressionValue, runtime: ComposedViewRuntime): EntityLinkTarget => {\n const actionName = typeof actionProp === \"string\" ? actionProp.trim() : \"\";\n if (actionName === \"\") return { state: \"missing\", actionName: \"\" };\n const { findAction } = runtime as RuntimeWithActionLookup;\n if (typeof findAction !== \"function\") return { state: \"unchecked\", actionName };\n const action = findAction(actionName);\n if (\n action === undefined ||\n action.type !== \"openEntity\" ||\n readOpenEntityActionTarget(action, runtime.currentRow) === undefined\n ) {\n return { state: \"unresolved\", actionName };\n }\n return { state: \"resolved\", actionName };\n};\n","import { Icon, InteractiveSurface, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type {\n ComposedViewComponentDefinition,\n ComposedViewComponentProps,\n} from \"../../composed-view-component-types\";\nimport {\n readAllowedValue,\n readTextNodeContent,\n} from \"../text/shared/text-node-values\";\nimport { readEntityLinkTarget, type EntityLinkTargetState } from \"./entity-link-target\";\nimport styles from \"./EntityLink.module.scss\";\n\nconst VARIANTS = [\"link\", \"title\", \"chip\"] as const;\n\n/**\n * The `EntityLink` node (`EntityLinkComposedViewNode.php`; ChatGPT's `Entity` — the dotted-underlined\n * business name that opens a detail panel): the name of an entity a tool returned. A\n * click runs the tree's `openEntity` action named by `action`; the widget opens the `entityDetail` canvas for the\n * entity the backend resolved the platform-minted reference to. `link` (default) sits in a sentence or a table cell,\n * `title` is the bold headline of a Surface (a business name), `chip` a small pill with the detail\n * glyph.\n *\n * Without a usable action — no `action`, an action that is not `openEntity`, a reference the backend did not resolve —\n * the name shows as plain text and the node reports `failed UNRESOLVED_REF`, so the model learns the panel does not\n * open. In the e-mail capture the name shows without a control. A link never sends a chat message.\n */\nconst EntityLinkNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const content = readTextNodeContent(nodeProps.text);\n const variant = readAllowedValue(nodeProps.variant, VARIANTS, \"link\");\n const target = readEntityLinkTarget(nodeProps.action, runtime);\n const targetState: EntityLinkTargetState = target.state;\n const contentKind = content.kind;\n\n useEffect(() => {\n if (isPending) reportNodeStatus(\"pending\");\n else if (contentKind === \"missing\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the EntityLink has no name to show\");\n else if (contentKind === \"invalid\")\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the EntityLink got a name that is not text\");\n else if (targetState === \"missing\") {\n reportNodeStatus(\n \"failed\",\n \"UNRESOLVED_REF\",\n \"the EntityLink names no openEntity action — its name shows without a link\",\n );\n } else if (targetState === \"unresolved\") {\n reportNodeStatus(\n \"failed\",\n \"UNRESOLVED_REF\",\n \"the EntityLink's openEntity action has no resolved entity reference — its name shows without a link\",\n );\n } else reportNodeStatus(\"mounted\");\n }, [isPending, contentKind, targetState, reportNodeStatus]);\n\n if (isPending) return <SkeletonLine width=\"7em\" height={12} radius={4} />;\n if (content.kind !== \"text\") return null;\n const name = escapePlainTextForText(content.text);\n const isClickable = target.state !== \"missing\" && target.state !== \"unresolved\" && !runtime.isEmailRender;\n\n const isTitle = variant === \"title\";\n const textType = isTitle ? \"intro\" : \"body\";\n const fontWeight = isTitle ? \"bold\" : undefined;\n if (!isClickable) {\n return (\n <Text\n role={textType}\n weight={fontWeight}\n translate={false}\n display=\"inline\"\n className={classNames(styles.plainName, variant === \"chip\" && styles.plainChip)}\n testId={`${testId}-name`}\n >\n {name}\n </Text>\n );\n }\n const openDetail = () => runtime.runEvent({ action: target.actionName });\n if (variant === \"chip\") {\n return (\n <InteractiveSurface hoverable className={styles.chip}>\n <button type=\"button\" className={styles.chipButton} onClick={openDetail} data-testid=\"composed-entity-link\">\n <Text\n role=\"help\"\n translate={false}\n display=\"inline\"\n className={styles.chipName}\n testId={`${testId}-name`}\n >\n {name}\n </Text>\n <Icon color=\"var(--agents-fg-light)\" className={styles.chipIcon} pixelSize={14} name=\"details\" />\n </button>\n </InteractiveSurface>\n );\n }\n return (\n <button type=\"button\" className={styles.link} onClick={openDetail} data-testid=\"composed-entity-link\">\n <Text\n role={textType}\n weight={fontWeight}\n translate={false}\n display=\"inline\"\n className={styles.linkName}\n testId={`${testId}-name`}\n >\n {name}\n </Text>\n </button>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"EntityLink\",\n component: EntityLinkNode,\n};\n","import type {\n ComposedViewNode,\n JsonValue,\n} from \"../../../renderer/widget-tree/composed-view-tree\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\n\n/**\n * The reaction sentences of a `ComposedView` `Form` node — the frontend half of\n * `composed-view-widget-contract.json`; the backend reader is `ComposedViewConversationWidget::readAnswer()`:\n *\n * ComposedView form \"<name>\" submitted:\n * - <field>: <value>\n *\n * or `ComposedView form \"<name>\" declined.` Posted as a FRONTEND_WIDGET_CLICK signal. A stored contract: never reword it.\n */\n\n/** `FormComposedViewNode::FORM_NAME_PATTERN` — a name the quoted span of the signal can carry. */\nexport const FORM_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** `AIConversationMessage::MAX_SIGNAL_TEXT_CHARS` — the backend cuts a longer signal, so the composer stays below it. */\nexport const MAX_FORM_SIGNAL_CHARS = 2000;\n\nconst ELLIPSIS = \"…\";\n\nexport const isFormNameAllowed = (formName: unknown): formName is string =>\n typeof formName === \"string\" && FORM_NAME_PATTERN.test(formName);\n\n/**\n * One value on its signal line: a boolean as `true` / `false`, an empty value as nothing; inside a text a backslash is\n * written `\\\\`, a line break `\\n`, any other control character becomes a space — so a value never leaves its line.\n */\nexport const formatFormFieldValue = (value: ExpressionValue | undefined): string => {\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return Number.isFinite(value) ? String(value) : \"\";\n if (typeof value !== \"string\") return \"\";\n return value\n .trim()\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\\r\\n|\\r|\\n/g, \"\\\\n\")\n .replace(/\\p{Cc}/gu, \" \");\n};\n\n/** Cuts an escaped value to `maxLength` characters without splitting an escape (`\\\\`, `\\n`) in two. */\nconst cutEscapedValue = (escapedValue: string, maxLength: number): string => {\n if (escapedValue.length <= maxLength) return escapedValue;\n let cutValue = escapedValue.slice(0, Math.max(0, maxLength - ELLIPSIS.length));\n const trailingBackslashCount = /\\\\+$/.exec(cutValue)?.[0].length ?? 0;\n if (trailingBackslashCount % 2 === 1) cutValue = cutValue.slice(0, -1);\n return cutValue + ELLIPSIS;\n};\n\nconst buildFieldLine = (fieldName: string, formattedValue: string) =>\n formattedValue === \"\" ? `- ${fieldName}:` : `- ${fieldName}: ${formattedValue}`;\n\nconst joinSignalLines = (headLine: string, formattedFieldValues: ReadonlyArray<readonly [string, string]>) =>\n [\n headLine,\n ...formattedFieldValues.map(([fieldName, formattedValue]) => buildFieldLine(fieldName, formattedValue)),\n ].join(\"\\n\");\n\n/**\n * The submit sentence: the head line, then one line per field in the given order. Over {@link MAX_FORM_SIGNAL_CHARS}\n * the values share what the head and the field names leave, each cut to its share with an ellipsis.\n */\nexport const composeFormSubmitSignal = (\n formName: string,\n fieldValues: ReadonlyArray<readonly [string, ExpressionValue | undefined]>,\n): string => {\n const headLine = `ComposedView form \"${formName}\" submitted:`;\n const formattedFieldValues = fieldValues.map(\n ([fieldName, value]) => [fieldName, formatFormFieldValue(value)] as const,\n );\n const fullSignal = joinSignalLines(headLine, formattedFieldValues);\n if (fullSignal.length <= MAX_FORM_SIGNAL_CHARS || formattedFieldValues.length === 0) return fullSignal;\n const lengthWithoutValues = joinSignalLines(\n headLine,\n formattedFieldValues.map(([fieldName]) => [fieldName, \"\"] as const),\n ).length;\n // A filled field line is one space plus its value longer than the empty one.\n const valueShare = Math.max(\n ELLIPSIS.length + 1,\n Math.floor((MAX_FORM_SIGNAL_CHARS - lengthWithoutValues) / formattedFieldValues.length) - 1,\n );\n return joinSignalLines(\n headLine,\n formattedFieldValues.map(\n ([fieldName, formattedValue]) => [fieldName, cutEscapedValue(formattedValue, valueShare)] as const,\n ),\n );\n};\n\nexport const composeFormDeclineSignal = (formName: string) => `ComposedView form \"${formName}\" declined.`;\n\n/** The state name a prop value reads or writes: a `{\"$state\": …}` binding or a `{\"set\": …}` event. */\nconst readBoundStateName = (propValue: JsonValue): string | undefined => {\n if (typeof propValue !== \"object\" || propValue === null || Array.isArray(propValue)) return undefined;\n if (typeof propValue.$state === \"string\") return propValue.$state;\n if (typeof propValue.set === \"string\") return propValue.set;\n return undefined;\n};\n\nconst collectBoundStateNamesOfNode = (node: ComposedViewNode, stateNames: string[]): void => {\n for (const propValue of Object.values(node.props)) {\n const stateName = readBoundStateName(propValue);\n if (stateName !== undefined && !stateNames.includes(stateName)) stateNames.push(stateName);\n }\n for (const slotNodes of Object.values(node.nodesBySlotName)) {\n for (const slotNode of slotNodes) collectBoundStateNamesOfNode(slotNode, stateNames);\n }\n};\n\n/**\n * The fields a form sends when its `fields` prop names none: every state name its body binds (`{\"$state\": …}` values,\n * `{\"set\": …}` events), tree order, each once.\n */\nexport const collectBoundStateNames = (formNode: ComposedViewNode): string[] => {\n const stateNames: string[] = [];\n for (const slotNodes of Object.values(formNode.nodesBySlotName)) {\n for (const slotNode of slotNodes) collectBoundStateNamesOfNode(slotNode, stateNames);\n }\n return stateNames;\n};\n\n/** The state names a list prop (`fields`, `requiredFields`) names, each once, kept only when the tree declares that state. */\nexport const readStateNameList = (propValue: JsonValue | undefined, state: Record<string, unknown>): string[] => {\n if (!Array.isArray(propValue)) return [];\n const stateNames: string[] = [];\n for (const stateName of propValue) {\n if (\n typeof stateName === \"string\" &&\n Object.prototype.hasOwnProperty.call(state, stateName) &&\n !stateNames.includes(stateName)\n ) {\n stateNames.push(stateName);\n }\n }\n return stateNames;\n};\n\n/** A required field is filled: not empty, not only spaces, and a checkbox ticked. */\nexport const isFormFieldFilled = (value: ExpressionValue | undefined): boolean => {\n if (value === undefined || value === null || value === false) return false;\n if (typeof value === \"string\") return value.trim() !== \"\";\n return true;\n};\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { createContext, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useConversationWidgetContext } from \"../../../renderer/ConversationWidgetCallbacksContext\";\nimport { ConversationWidgetButton } from \"../../../widgets/_shared/ConversationWidgetButton\";\nimport { DonePill } from \"../../../widgets/_shared/DonePill\";\nimport { WidgetSurface } from \"../../../widgets/_shared/modern\";\nimport { ModelText } from \"../../ModelText/ModelText\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n collectBoundStateNames,\n composeFormDeclineSignal,\n composeFormSubmitSignal,\n isFormFieldFilled,\n isFormNameAllowed,\n readStateNameList,\n} from \"./compose-form-signal\";\nimport styles from \"./Form.module.scss\";\n\n/** True inside a Form's body: a nested Form gives its body to the outer form instead of submitting on its own. */\nconst ComposedViewFormContext = createContext(false);\n\n/** Judgement text in the 900 tone, flipped for the dark scheme (no functional error token). */\nconst ERROR_TEXT_COLOR = \"light-dark(var(--agents-danger-900), var(--agents-danger-500))\";\n\ntype FormSubmissionStatus = \"idle\" | \"sending\" | \"sent\" | \"declined\" | \"failed\";\n\n/**\n * The `Form` node (`FormComposedViewNode.php`): the kit's inputs inside one surface with a submit\n * and an optional decline. The inputs write the tree's local state as everywhere; only the submit reaches the agent — as\n * ONE FRONTEND_WIDGET_CLICK signal through `injectSignal` (`ComposedView form \"<name>\" submitted:` + one `- <field>:\n * <value>` line per field, `compose-form-signal.ts`; the stored contract is `composed-view-widget-contract.json`). The\n * fields are the state names of `fields`, else every state name the body binds; `requiredFields` must be filled first.\n *\n * Answered only once the host accepted the signal: then a done pill replaces the buttons and the body is disabled;\n * an undelivered signal keeps the form and offers the retry. A replayed reply shows the body without buttons (its answer\n * belongs to its own turn), the e-mail capture shows the body frozen without any action row. A name the signal cannot\n * carry and a Form inside a Form render their body and report `failed`, so the model learns the form cannot submit.\n */\nconst FormNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots, sizeClass, runtime, testId } = props;\n const { state, interactive, isEmailRender, reportNodeStatus } = runtime;\n const isInsideForm = useContext(ComposedViewFormContext);\n const { injectSignal } = useConversationWidgetContext();\n const [submissionStatus, setSubmissionStatus] = useState<FormSubmissionStatus>(\"idle\");\n const [hasTriedWithMissingFields, setHasTriedWithMissingFields] = useState(false);\n const isSignalInFlightRef = useRef(false);\n\n const formName = isFormNameAllowed(nodeProps.name) ? nodeProps.name : undefined;\n const fieldNames = useMemo(\n () =>\n Array.isArray(node.props.fields)\n ? readStateNameList(node.props.fields, state)\n : collectBoundStateNames(node).filter((stateName) => Object.prototype.hasOwnProperty.call(state, stateName)),\n [node, state],\n );\n const requiredFieldNames = useMemo(() => readStateNameList(node.props.requiredFields, state), [node, state]);\n const hasMissingRequiredField = requiredFieldNames.some((stateName) => !isFormFieldFilled(state[stateName]));\n\n useEffect(() => {\n if (isInsideForm) {\n reportNodeStatus(\n \"failed\",\n \"INVALID_NODE\",\n \"a Form inside a Form has no submit of its own — its inputs belong to the outer form\",\n );\n } else if (formName === undefined) {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n 'a Form name is letters, digits, \"_\" or \"-\", at most 64 — this form renders but cannot submit',\n );\n }\n }, [isInsideForm, formName, reportNodeStatus]);\n\n if (isInsideForm)\n return (\n <div className={styles.nestedBody} data-testid={testId}>\n {slots.children}\n </div>\n );\n\n const canSend = formName !== undefined && interactive && !isEmailRender;\n const isAnswered = submissionStatus === \"sent\" || submissionStatus === \"declined\";\n\n /** One signal at a time; the form counts as answered only once the host accepted it. */\n const sendSignal = async (signalText: string, answeredStatus: \"sent\" | \"declined\") => {\n if (isSignalInFlightRef.current) return;\n isSignalInFlightRef.current = true;\n setSubmissionStatus(\"sending\");\n try {\n const accepted = await injectSignal(signalText);\n setSubmissionStatus(accepted === true ? answeredStatus : \"failed\");\n } catch {\n setSubmissionStatus(\"failed\");\n } finally {\n isSignalInFlightRef.current = false;\n }\n };\n\n const submit = () => {\n if (!canSend || formName === undefined || isAnswered) return;\n if (hasMissingRequiredField) {\n setHasTriedWithMissingFields(true);\n return;\n }\n void sendSignal(\n composeFormSubmitSignal(\n formName,\n fieldNames.map((fieldName) => [fieldName, state[fieldName]] as const),\n ),\n \"sent\",\n );\n };\n\n const decline = () => {\n if (!canSend || formName === undefined || isAnswered) return;\n void sendSignal(composeFormDeclineSignal(formName), \"declined\");\n };\n\n const title = typeof nodeProps.title === \"string\" && nodeProps.title.trim() !== \"\" ? nodeProps.title : undefined;\n const description =\n typeof nodeProps.description === \"string\" && nodeProps.description.trim() !== \"\"\n ? nodeProps.description\n : undefined;\n const submitLabel =\n typeof nodeProps.submitLabel === \"string\" && nodeProps.submitLabel.trim() !== \"\"\n ? nodeProps.submitLabel\n : undefined;\n const declineLabel =\n typeof nodeProps.declineLabel === \"string\" && nodeProps.declineLabel.trim() !== \"\"\n ? nodeProps.declineLabel\n : undefined;\n const isSending = submissionStatus === \"sending\";\n const headerItems = slots.header ?? [];\n const showsMissingFields = hasTriedWithMissingFields && hasMissingRequiredField;\n\n const renderActionRow = () => {\n if (isEmailRender || formName === undefined) return null;\n if (submissionStatus === \"sent\") return <DonePill testId={`${testId}-done`}>{\"Sent\"}</DonePill>;\n if (submissionStatus === \"declined\")\n return (\n <DonePill status=\"neutral\" testId={`${testId}-done`}>\n {\"Declined\"}\n </DonePill>\n );\n if (!interactive) {\n return (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" testId={`${testId}-replay-note`}>\n {\"This form can only be sent from the newest reply.\"}\n </Text>\n );\n }\n return (\n <div className={styles.actions}>\n <ConversationWidgetButton\n variant=\"primary\"\n size=\"medium\"\n isLoading={isSending}\n disabled={isSending}\n translate={submitLabel === undefined}\n onClick={submit}\n testId={`${testId}-submit`}\n >\n {submitLabel === undefined ? \"Send\" : escapePlainTextForText(submitLabel)}\n </ConversationWidgetButton>\n {declineLabel !== undefined ? (\n <ConversationWidgetButton\n variant=\"muted\"\n // Every type shares the muted size set, so submit and decline are both medium.\n size=\"medium\"\n disabled={isSending}\n translate={false}\n onClick={decline}\n testId={`${testId}-decline`}\n >\n {escapePlainTextForText(declineLabel)}\n </ConversationWidgetButton>\n ) : null}\n </div>\n );\n };\n\n return (\n <WidgetSurface level={sizeClass === \"full\" ? \"elevated\" : \"flat\"} testId={testId}>\n {/* The browser never submits: the component library buttons are submit buttons, the body's own buttons included — only the\n action row's onClick sends. */}\n <form className={styles.form} noValidate onSubmit={(submitEvent) => submitEvent.preventDefault()}>\n {title !== undefined || description !== undefined || headerItems.length > 0 ? (\n <div className={styles.headerRow}>\n <div className={styles.header}>\n {title !== undefined ? (\n <ModelText role=\"body\" weight=\"bold\">\n {title}\n </ModelText>\n ) : null}\n {description !== undefined ? (\n <ModelText role=\"help\" color=\"var(--agents-fg-light)\">\n {description}\n </ModelText>\n ) : null}\n </div>\n {headerItems.length > 0 ? <div className={styles.headerItems}>{headerItems}</div> : null}\n </div>\n ) : null}\n {/* Disabled while the answer is on its way and after it was given; the e-mail capture keeps the normal look\n (its page is inert and the renderer freezes the state). */}\n <ComposedViewFormContext.Provider value={true}>\n <fieldset className={styles.fields} disabled={isAnswered || isSending}>\n {slots.children}\n </fieldset>\n </ComposedViewFormContext.Provider>\n <div className={styles.footer} aria-live=\"polite\">\n {showsMissingFields ? (\n <Text role=\"caption\" color={ERROR_TEXT_COLOR} testId={`${testId}-error-required`}>\n {\"Please fill in the required fields.\"}\n </Text>\n ) : null}\n {submissionStatus === \"failed\" ? (\n <Text role=\"caption\" color={ERROR_TEXT_COLOR} testId={`${testId}-error`}>\n {\"Something went wrong. Please try again.\"}\n </Text>\n ) : null}\n {renderActionRow()}\n </div>\n </form>\n </WidgetSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Form\", component: FormNode };\n","/** The date pattern per locale — the same table the app's date picker reads (`DD.MM.YYYY` for `de_DE`). */\nconst DATE_PATTERNS_BY_LOCALE: Record<string, string> = {\n en_US: \"MM/DD/YYYY\",\n en_GB: \"DD/MM/YYYY\",\n de_DE: \"DD.MM.YYYY\",\n de_AT: \"DD.MM.YYYY\",\n fr_FR: \"DD/MM/YYYY\",\n nl_NL: \"DD-MM-YYYY\",\n es_ES: \"DD/MM/YYYY\",\n it_IT: \"DD/MM/YYYY\",\n pl_PL: \"YYYY-MM-DD\",\n pt_PT: \"DD/MM/YYYY\",\n ja_JP: \"YYYY/MM/DD\",\n id_ID: \"DD/MM/YYYY\",\n fi_FI: \"DD.MM.YYYY\",\n sk_SK: \"DD.MM.YYYY\",\n sv_SE: \"YYYY-MM-DD\",\n cs_CZ: \"DD.MM.YYYY\",\n el_GR: \"DD/MM/YYYY\",\n};\n\n/** The date pattern of a locale written with an underscore (`de_DE`); an unknown locale reads `DD.MM.YYYY`. */\nexport const getDatePatternFromLocale = (locale: string): string => {\n const datePattern = DATE_PATTERNS_BY_LOCALE[locale];\n if (!datePattern) {\n console.error(\"ERROR | getDatePatternFromLocale | Details: locale not found \", locale);\n return \"DD.MM.YYYY\";\n }\n return datePattern;\n};\n","import type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { getDatePatternFromLocale } from \"./date-pattern-of-locale\";\nimport type { ComposedViewRuntime } from \"../../../composed-view-component-types\";\n\n/**\n * The value readers the kit's input components share. Every reader is total: a value the model wrote\n * in another shape gives the documented default, never an exception — the readers on both sides already dropped what\n * the schema refuses, these readers only narrow what is left.\n */\n\n/** One choice of a `Tabs`, `Select` or `RadioGroup`: the id written to the state and the label the owner reads. */\nexport interface ComposedInputOption {\n id: string | number;\n label: string;\n description?: string;\n disabled: boolean;\n}\n\n/** Choices beyond this count are not shown (a drop-down with more is a list, not an input). */\nexport const MAX_INPUT_OPTIONS = 100;\n\nconst readOptionId = (optionObject: Record<string, unknown>): string | number | undefined => {\n // `id` is the documented key; `value` / `key` are what a model transcribing ChatGPT's `<Option value=…>` writes.\n for (const idKey of [\"id\", \"value\", \"key\"]) {\n const candidate = optionObject[idKey];\n if (typeof candidate === \"string\" && candidate !== \"\") return candidate;\n if (typeof candidate === \"number\" && Number.isFinite(candidate)) return candidate;\n }\n return undefined;\n};\n\nconst readOptionLabel = (optionObject: Record<string, unknown>): string | undefined => {\n for (const labelKey of [\"label\", \"title\", \"name\", \"text\"]) {\n const candidate = optionObject[labelKey];\n if (typeof candidate === \"string\" && candidate.trim() !== \"\") return candidate;\n if (typeof candidate === \"number\" && Number.isFinite(candidate)) return String(candidate);\n }\n return undefined;\n};\n\nconst readOption = (optionValue: unknown): ComposedInputOption | undefined => {\n if (typeof optionValue === \"string\") {\n return optionValue.trim() === \"\" ? undefined : { id: optionValue, label: optionValue, disabled: false };\n }\n if (typeof optionValue === \"number\") {\n return Number.isFinite(optionValue) ? { id: optionValue, label: String(optionValue), disabled: false } : undefined;\n }\n if (typeof optionValue !== \"object\" || optionValue === null || Array.isArray(optionValue)) return undefined;\n const optionObject = optionValue as Record<string, unknown>;\n const label = readOptionLabel(optionObject);\n const id = readOptionId(optionObject) ?? label;\n if (id === undefined || label === undefined) return undefined;\n const description = optionObject.description;\n return {\n id,\n label,\n description: typeof description === \"string\" && description.trim() !== \"\" ? description : undefined,\n disabled: optionObject.disabled === true,\n };\n};\n\n/**\n * The choices of an `options` prop: a label list (`[\"Bear\", \"Base\"]`, the label is the id) or objects with an `id` (or\n * `value` / `key`) and a `label`. An entry without a usable id and label is skipped, a repeated id keeps its first entry.\n */\nexport const readComposedInputOptions = (optionsValue: ExpressionValue | undefined): ComposedInputOption[] => {\n if (!Array.isArray(optionsValue)) return [];\n const options: ComposedInputOption[] = [];\n const seenIds = new Set<string>();\n for (const optionValue of optionsValue) {\n if (options.length >= MAX_INPUT_OPTIONS) break;\n const option = readOption(optionValue);\n if (!option || seenIds.has(String(option.id))) continue;\n seenIds.add(String(option.id));\n options.push(option);\n }\n return options;\n};\n\n/** The option whose id equals `value` (a number state matches a numeric-string id and the reverse). */\nexport const findComposedInputOption = (\n options: ComposedInputOption[],\n value: ExpressionValue | undefined,\n): ComposedInputOption | undefined =>\n value === undefined || value === null ? undefined : options.find((option) => String(option.id) === String(value));\n\n/** A text prop, or `undefined` when it is not a non-empty string (a number is shown as written). */\nexport const readComposedText = (value: ExpressionValue | undefined): string | undefined => {\n if (typeof value === \"string\") return value.trim() === \"\" ? undefined : value;\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return undefined;\n};\n\n/** A finite number prop, or `fallback`. */\nexport const readComposedNumber = (value: ExpressionValue | undefined, fallback: number): number =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n\n/** Whether the owner may use the control: a live (interactive) message, never a replay or the e-mail capture. */\nexport const isComposedInputUsable = (runtime: ComposedViewRuntime): boolean =>\n runtime.interactive && !runtime.isEmailRender;\n\n/** The decimals a number is written with (`0.1` → 1, `5` → 0, `0.25` → 2), capped at 6. */\nexport const countDecimals = (value: number): number => {\n if (!Number.isFinite(value)) return 0;\n const [, fraction = \"\"] = String(value).split(\".\");\n return Math.min(fraction.length, 6);\n};\n\n/** A number with `decimals` places in the owner's language, `unit` after it: `3` + \"%\" + 1 → \"3.0 %\". */\nexport const formatComposedNumber = (\n value: number,\n decimals: number,\n unit: string | undefined,\n languageCode: string,\n): string => {\n const fractionDigits = Math.max(0, Math.min(6, Math.round(decimals)));\n const formatOptions: Intl.NumberFormatOptions = {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n };\n let formattedNumber: string;\n try {\n formattedNumber = new Intl.NumberFormat(languageCode || \"en\", formatOptions).format(value);\n } catch {\n formattedNumber = new Intl.NumberFormat(\"en\", formatOptions).format(value);\n }\n if (!unit) return formattedNumber;\n // A scale written as \"/100\" joins the number (\"51/100\"); any other unit follows a no-break space, so \"3.0 %\" never\n // wraps between the number and its unit.\n return unit.startsWith(\"/\") ? `${formattedNumber}${unit}` : `${formattedNumber}\\u00a0${unit}`;\n};\n\n/** A value clamped into `[min, max]` and snapped onto the step grid that starts at `min`. */\nexport const snapToSliderStep = (value: number, min: number, max: number, step: number): number => {\n const clampedValue = Math.min(Math.max(value, min), max);\n if (!(step > 0)) return clampedValue;\n const snappedValue = min + Math.round((clampedValue - min) / step) * step;\n const decimals = Math.max(countDecimals(step), countDecimals(min));\n return Math.min(Number(snappedValue.toFixed(decimals)), max);\n};\n\nconst ISO_DAY_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** A `YYYY-MM-DD` day as its local midnight in milliseconds, or `undefined` for anything else (`2026-02-30` too). */\nexport const parseIsoDay = (value: ExpressionValue | undefined): number | undefined => {\n if (typeof value !== \"string\") return undefined;\n const dayMatch = ISO_DAY_PATTERN.exec(value.trim());\n if (!dayMatch) return undefined;\n const year = Number(dayMatch[1]);\n const monthIndex = Number(dayMatch[2]) - 1;\n const dayOfMonth = Number(dayMatch[3]);\n const localDate = new Date(year, monthIndex, dayOfMonth);\n if (localDate.getMonth() !== monthIndex || localDate.getDate() !== dayOfMonth) return undefined;\n return localDate.getTime();\n};\n\n/**\n * The locale as the date pattern table of the component library's `DatePicker` keys it (`de-DE` → `de_DE`): the owner settings\n * write a BCP 47 tag, the picker looks the pattern up by the underscore form and falls back to `DD.MM.YYYY`.\n */\nexport const toDatePatternLocale = (locale: string): string => locale.replace(\"-\", \"_\");\n\n/**\n * A `YYYY-MM-DD` day as the owner reads it in `locale` (\"25/10/2026\" for `en-GB`, \"25.10.2026\" for `de-DE`) — in the\n * same pattern the editable `DatePicker` shows (`getDatePatternFromLocale`, the table the component library's picker reads), so the\n * frozen value on a replay and in the e-mail matches the field the owner edited; `undefined` for no valid day.\n */\nexport const formatIsoDayForReading = (isoDay: string | undefined, locale: string): string | undefined => {\n const timestamp = parseIsoDay(isoDay);\n if (timestamp === undefined) return undefined;\n const localDate = new Date(timestamp);\n const twoDigits = (datePart: number) => String(datePart).padStart(2, \"0\");\n return getDatePatternFromLocale(toDatePatternLocale(locale))\n .replace(\"YYYY\", String(localDate.getFullYear()))\n .replace(\"MM\", twoDigits(localDate.getMonth() + 1))\n .replace(\"DD\", twoDigits(localDate.getDate()));\n};\n\n/** A timestamp in milliseconds as its local `YYYY-MM-DD` day. */\nexport const formatIsoDay = (timestamp: number): string => {\n const localDate = new Date(timestamp);\n const twoDigits = (datePart: number) => String(datePart).padStart(2, \"0\");\n return `${localDate.getFullYear()}-${twoDigits(localDate.getMonth() + 1)}-${twoDigits(localDate.getDate())}`;\n};\n","import { type AgentsIconName } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { ConversationWidgetButton } from \"../../../widgets/_shared/ConversationWidgetButton\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { isComposedInputUsable, readComposedText } from \"./shared/composed-input-values\";\nimport styles from \"./ComposedInputs.module.scss\";\n\n/** The closed glyph list of the node's `icon` prop → the component-library icon. */\nconst BUTTON_ICON_NAMES: Record<string, AgentsIconName> = {\n copy: \"duplicate\",\n reset: \"refresh\",\n link: \"link\",\n add: \"add\",\n check: \"check\",\n next: \"arrowRight\",\n calendar: \"calendar\",\n info: \"info\",\n};\n\n/** How long a copy button says \"Copied\" after the click (the confirmation ChatGPT's \"Copy result\" gives). */\nexport const COPIED_CONFIRMATION_MS = 2000;\n\n/** The name of the tree action a click runs (`onClick: {\"action\": \"<name>\"}`), or undefined for a `set` click. */\nconst readClickActionName = (onClick: unknown): string | undefined => {\n if (typeof onClick !== \"object\" || onClick === null || Array.isArray(onClick)) return undefined;\n const actionName = (onClick as Record<string, unknown>).action;\n return typeof actionName === \"string\" ? actionName : undefined;\n};\n\n/**\n * `Button` — runs one of the tree's own actions or writes a value to its state (`ButtonComposedViewNode.php`; ChatGPT's \"Copy result\" / \"Reset\" of the simulators): `onClick: {\"action\": \"<name>\"}`\n * runs `copy`, `resetState`, `openUrl` or `openEntity`; `onClick: {\"set\": \"<name>\"}` writes `value`. It never sends a\n * chat message. `primary` is the one main action (a square button, for real-effect\n * actions), `secondary` sits beside it. It is an affordance only, so a replayed message and the e-mail capture show no\n * button at all. The component library renders a `<button>` without a type — a submit button inside a `Form` would become the Enter\n * target and submit the form; this one is set to `type=\"button\"`. A button that runs a `copy` action confirms the copy\n * for {@link COPIED_CONFIRMATION_MS}: its label turns into \"Copied\" with a check glyph. A label longer than the chat column\n * wraps onto a second line (copy wraps, never cut) instead of pushing the button out of the widget.\n */\nconst ComposedButton = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, runtime, testId } = props;\n const wrapperRef = useRef<HTMLDivElement>(null);\n const label = readComposedText(nodeProps.label);\n const isUsable = isComposedInputUsable(runtime);\n const [isCopyConfirmed, setIsCopyConfirmed] = useState(false);\n const clickActionName = readClickActionName(node.props.onClick);\n const isCopyButton = clickActionName !== undefined && runtime.findAction?.(clickActionName)?.type === \"copy\";\n useEffect(() => {\n if (!isCopyConfirmed) return;\n const confirmationTimer = setTimeout(() => setIsCopyConfirmed(false), COPIED_CONFIRMATION_MS);\n return () => clearTimeout(confirmationTimer);\n }, [isCopyConfirmed]);\n useLayoutEffect(() => {\n wrapperRef.current?.querySelectorAll(\"button\").forEach((buttonElement) => {\n buttonElement.type = \"button\";\n });\n });\n if (!label || !isUsable) return null;\n const nodeIcon = typeof nodeProps.icon === \"string\" ? BUTTON_ICON_NAMES[nodeProps.icon] : undefined;\n const icon = isCopyConfirmed ? \"check\" : nodeIcon;\n const isFullWidth = nodeProps.fullWidth === true;\n const buttonType = nodeProps.variant === \"secondary\" ? \"muted\" : \"primary\";\n const click = () => {\n runtime.runEvent(node.props.onClick, nodeProps.value);\n if (isCopyButton) setIsCopyConfirmed(true);\n };\n return (\n <div ref={wrapperRef} className={isFullWidth ? styles.buttonFullWidth : styles.button}>\n <ConversationWidgetButton\n variant={buttonType}\n size=\"medium\"\n icon={icon}\n iconPosition=\"left\"\n wrapsLabel\n translate={isCopyConfirmed}\n fullWidth={isFullWidth}\n onClick={click}\n testId={testId}\n >\n {isCopyConfirmed ? \"Copied\" : escapePlainTextForText(label)}\n </ConversationWidgetButton>\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Button\", component: ComposedButton };\n","import { Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport { SkeletonLine } from \"../../../../widgets/_shared/skeleton-primitives\";\nimport styles from \"./ComposedInputField.module.scss\";\n\nexport interface ComposedInputFieldProps {\n /** The model's label above the control (business content, never translated). */\n label?: string;\n /** The id of the control the label names — a native `<label for>`; omit when the control labels itself. */\n controlId?: string;\n /** Shown at the end of the label row — the slider's formatted value. */\n labelRowValue?: string;\n /** One muted line under the control. */\n description?: string;\n /** False on a replay and in the e-mail capture: the control stays visible, but takes no pointer, key or focus. */\n isUsable: boolean;\n /** A bound value is still loading: the control's place is a skeleton of the same height. */\n isPending?: boolean;\n /** The height of that skeleton in px (the control's own height). */\n pendingHeight?: number;\n className?: string;\n testId?: string;\n children: ReactNode;\n}\n\n/**\n * The frame every kit input sits in: the label row (label left, a value right), the control, an\n * optional muted line. A control the owner may not use (a replayed message, the e-mail capture) keeps its look and its\n * current value but is `inert` — no click, no key, no focus — so a frozen tree never pretends to answer. Every model\n * string goes through `escapePlainTextForText`: the app's `Text` may parse a string child as markup.\n */\nexport const ComposedInputField = (props: ComposedInputFieldProps) => {\n const {\n label,\n controlId,\n labelRowValue,\n description,\n isUsable,\n isPending = false,\n pendingHeight = 40,\n className,\n testId,\n children,\n } = props;\n const labelText = label ? (\n <Text role=\"body\" weight=\"medium\" translate={false}>\n {escapePlainTextForText(label)}\n </Text>\n ) : null;\n return (\n <div\n className={classNames(styles.field, !isUsable && styles.frozen, className)}\n inert={!isUsable || undefined}\n data-usable={isUsable ? \"true\" : \"false\"}\n data-testid={testId ? `${testId}-field` : undefined}\n >\n {labelText || labelRowValue ? (\n <div className={styles.labelRow}>\n {labelText && controlId ? (\n <label htmlFor={controlId} className={styles.label}>\n {labelText}\n </label>\n ) : (\n <span className={styles.label}>{labelText}</span>\n )}\n {labelRowValue ? (\n <Text role=\"body\" weight=\"bold\" translate={false} className={styles.labelValue}>\n {escapePlainTextForText(labelRowValue)}\n </Text>\n ) : null}\n </div>\n ) : null}\n {isPending ? (\n <span aria-busy=\"true\" className={styles.pending} data-testid={testId ? `${testId}-skeleton` : undefined}>\n <SkeletonLine height={pendingHeight} radius={12} />\n </span>\n ) : (\n children\n )}\n {description ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false} className={styles.description}>\n {escapePlainTextForText(description)}\n </Text>\n ) : null}\n </div>\n );\n};\n","import { useState } from \"react\";\nimport type { ComposedViewNode } from \"../../../../renderer/widget-tree/composed-view-tree\";\nimport type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewRuntime } from \"../../../composed-view-component-types\";\nimport { isComposedInputUsable } from \"./composed-input-values\";\n\nexport interface ComposedInputValueOptions<ValueType> {\n node: ComposedViewNode;\n runtime: ComposedViewRuntime;\n /** The prop that carries the value (`value`, `checked`), resolved. */\n resolvedValue: ExpressionValue | undefined;\n /** Narrows the resolved value to the control's type; `undefined` for a value of another shape. */\n readValue: (resolvedValue: ExpressionValue | undefined) => ValueType | undefined;\n /** What the control shows when nothing is set. */\n fallbackValue: ValueType;\n valuePropName?: string;\n eventPropName?: string;\n /** What the event writes for a shown value (a number field shows text but writes a number); the value itself by default. */\n toEventValue?: (nextValue: ValueType) => unknown;\n}\n\nexport interface ComposedInputValue<ValueType> {\n /** The value the control shows. */\n value: ValueType;\n /** The owner changed the control: keep it and run the node's event (`{\"set\": …}` writes the tree state). */\n changeValue: (nextValue: ValueType) => void;\n}\n\n/**\n * The value of one kit input. A tree normally BINDS the control to its state (`value: {\"$state\":\n * \"period\"}` + `onChange: {\"set\": \"period\"}`): the state is the truth and every node bound to it follows. A control\n * written with no value but a `{\"set\": <name>}` event shows its own set target (the lenient state\n * rule — the readers declare an undeclared target with null). A control with a literal value, or with neither, still\n * works on its own — it keeps the owner's last choice, so a click never looks dead. The event is the node's RAW wire\n * value (`node.props[eventPropName]`), as the runtime expects it.\n */\nexport const useComposedInputValue = <ValueType>(\n options: ComposedInputValueOptions<ValueType>,\n): ComposedInputValue<ValueType> => {\n const {\n node,\n runtime,\n resolvedValue,\n readValue,\n fallbackValue,\n valuePropName = \"value\",\n eventPropName = \"onChange\",\n toEventValue,\n } = options;\n const [ownValue, setOwnValue] = useState<ValueType | undefined>(undefined);\n const wireValue = node.props[valuePropName];\n const eventWireValue = node.props[eventPropName];\n const ownSetTarget =\n wireValue === undefined &&\n typeof eventWireValue === \"object\" &&\n eventWireValue !== null &&\n !Array.isArray(eventWireValue) &&\n typeof eventWireValue.set === \"string\" &&\n Object.prototype.hasOwnProperty.call(runtime.state, eventWireValue.set)\n ? eventWireValue.set\n : undefined;\n const isBoundToTheTree =\n ownSetTarget !== undefined || (typeof wireValue === \"object\" && wireValue !== null && !Array.isArray(wireValue));\n const treeValue = readValue(ownSetTarget !== undefined ? runtime.state[ownSetTarget] : resolvedValue);\n const value = (isBoundToTheTree ? (treeValue ?? ownValue) : (ownValue ?? treeValue)) ?? fallbackValue;\n // A frozen control (a replay, the e-mail capture) is `inert` in the browser; this guard holds where inert does not.\n const changeValue = (nextValue: ValueType) => {\n if (!isComposedInputUsable(runtime)) return;\n setOwnValue(nextValue);\n runtime.runEvent(node.props[eventPropName], toEventValue ? toEventValue(nextValue) : nextValue);\n };\n return { value, changeValue };\n};\n","import { escapePlainTextForText } from \"../../../provider/environment\";\nimport { Checkbox } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { isComposedInputUsable, readComposedText } from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\n\nconst readChecked = (resolvedValue: ExpressionValue | undefined): boolean | undefined =>\n typeof resolvedValue === \"boolean\" ? resolvedValue : undefined;\n\n/**\n * `Checkbox` — one option on or off (`CheckboxComposedViewNode.php`; ChatGPT's \"show the comparison\n * values\" of the analytics studio): writes `true` / `false` to the tree state through `onChange`. The label is the\n * model's text, an optional muted line explains it. Frozen on a replay and in the e-mail capture.\n */\nconst ComposedCheckbox = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const label = readComposedText(nodeProps.label) ?? \"\";\n const description = readComposedText(nodeProps.description);\n const isUsable = isComposedInputUsable(runtime);\n const { value: isChecked, changeValue } = useComposedInputValue<boolean>({\n node,\n runtime,\n resolvedValue: nodeProps.checked,\n readValue: readChecked,\n fallbackValue: false,\n valuePropName: \"checked\",\n });\n return (\n <ComposedInputField\n description={description}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={24}\n testId={testId}\n >\n <Checkbox\n testId={testId}\n label={escapePlainTextForText(label)}\n translate={false}\n checked={isChecked}\n breaksLongWords\n onChange={() => changeValue(!isChecked)}\n />\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"Checkbox\",\n component: ComposedCheckbox,\n};\n","import { Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport styles from \"./ComposedInputFrozenValue.module.scss\";\n\nexport interface ComposedInputFrozenValueProps {\n /** The control's current value as the owner reads it; empty shows a muted dash. */\n shownValue: string | undefined;\n /** Keep the line breaks of a multi-line text. */\n isMultiline?: boolean;\n testId?: string;\n}\n\n/**\n * A text-like control (a select, a field, a date) on a replayed message or in the e-mail capture:\n * its value as plain readable text in the field's shape — normal text colour, no disabled grey, no caret, no chevron.\n * Only the affordance goes; what the owner had chosen stays legible.\n */\nexport const ComposedInputFrozenValue = (props: ComposedInputFrozenValueProps) => {\n const { shownValue, isMultiline = false, testId } = props;\n const hasValue = shownValue !== undefined && shownValue.trim() !== \"\";\n return (\n <div\n className={classNames(styles.frozenValue, isMultiline && styles.multiline)}\n data-frozen-value=\"true\"\n data-testid={testId}\n >\n {hasValue ? (\n <Text role=\"body\" translate={false} allowNewLines={isMultiline}>\n {escapePlainTextForText(shownValue)}\n </Text>\n ) : (\n <Text role=\"body\" translate={false} color=\"var(--agents-fg-lightest)\">\n {\"—\"}\n </Text>\n )}\n </div>\n );\n};\n","import { useAgentsOwnerSettings } from \"../../../../provider/AgentsProvider\";\n\n/** The date format when no owner date locale is loaded (a preview, a story, a spec): day/month/year. */\nconst FALLBACK_DATE_LOCALE = \"en-GB\";\n\nconst readBrowserLanguage = (): string => (typeof navigator === \"undefined\" ? \"en\" : navigator.language || \"en\");\n\n/**\n * The owner's language for number formatting, from the app (`useOwnerSettings`). Read defensively: the kit renders in\n * hosts that know no language (the widget preview, a spec, the e-mail capture) — there the browser's language formats\n * the numbers.\n */\nexport const useComposedInputLanguage = (): string => useAgentsOwnerSettings().languageCode || readBrowserLanguage();\n\n/** The owner's date locale, read as defensively as the language. */\nexport const useComposedInputDateLocale = (): string => useAgentsOwnerSettings().dateLocale || FALLBACK_DATE_LOCALE;\n","import { DateInput, Icon } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport {\n formatIsoDay,\n formatIsoDayForReading,\n isComposedInputUsable,\n parseIsoDay,\n readComposedText,\n toDatePatternLocale,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputDateLocale } from \"./shared/use-composed-input-language\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport styles from \"./ComposedInputs.module.scss\";\n\nconst readIsoDay = (resolvedValue: ExpressionValue | undefined): string | undefined =>\n parseIsoDay(resolvedValue) === undefined ? undefined : String(resolvedValue).trim();\n\n/**\n * `DatePicker` — one day from a calendar (`DatePickerComposedViewNode.php`; the reference date of\n * ChatGPT's analytics studio): shown in the owner's date format (the field and the frozen value in one pattern), written to the tree state as `YYYY-MM-DD` through\n * `onChange`; `min` / `max` (also `YYYY-MM-DD`) bound the calendar. A value that is no valid day shows an empty field.\n * On a replay and in the e-mail capture it shows its current day as plain text.\n */\nconst ComposedDatePicker = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const dateLocale = useComposedInputDateLocale();\n const label = readComposedText(nodeProps.label);\n const minDay = parseIsoDay(nodeProps.min);\n const maxDay = parseIsoDay(nodeProps.max);\n const isUsable = isComposedInputUsable(runtime);\n const { value, changeValue } = useComposedInputValue<string | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readIsoDay,\n fallbackValue: undefined,\n });\n const pickDay = (pickedTimestamp: number | null | undefined) => {\n if (typeof pickedTimestamp !== \"number\" || !Number.isFinite(pickedTimestamp)) return;\n changeValue(formatIsoDay(pickedTimestamp));\n };\n return (\n <ComposedInputField label={label} isUsable={isUsable} isPending={isPending} pendingHeight={48} testId={testId}>\n {isUsable ? (\n <div className={styles.datePicker} data-testid={testId}>\n <DateInput\n // A new day from the tree (a reset) remounts the picker: it keeps its own copy of the value otherwise.\n key={value ?? \"none\"}\n value={parseIsoDay(value)}\n minDate={minDay}\n maxDate={maxDay}\n locale={toDatePatternLocale(dateLocale)}\n onChange={pickDay}\n />\n {/* The field says what it opens (ChatGPT's date field carries the calendar glyph); the click stays the field's. */}\n <Icon className={styles.datePickerIcon} color=\"var(--agents-fg-light)\" pixelSize={18} name=\"calendar\" />\n </div>\n ) : (\n <ComposedInputFrozenValue shownValue={formatIsoDayForReading(value, dateLocale)} testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"DatePicker\",\n component: ComposedDatePicker,\n};\n","import { useId, useState } from \"react\";\nimport { TextInput } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport { isComposedInputUsable, readComposedNumber, readComposedText } from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\n\nconst readFieldText = (resolvedValue: ExpressionValue | undefined): string | undefined => {\n if (typeof resolvedValue === \"string\") return resolvedValue;\n if (typeof resolvedValue === \"number\" && Number.isFinite(resolvedValue)) return String(resolvedValue);\n if (resolvedValue === null) return \"\";\n return undefined;\n};\n\n/** The typed text as the state value: a number field writes a finite number, or null while it is empty or unparsable. */\nconst toStateValue = (typedText: string, isNumberField: boolean): string | number | null => {\n if (!isNumberField) return typedText;\n const trimmedText = typedText.trim().replace(\",\", \".\");\n if (trimmedText === \"\") return null;\n const typedNumber = Number(trimmedText);\n return Number.isFinite(typedNumber) ? typedNumber : null;\n};\n\n/**\n * `Input` — a one-line text or number field (`InputComposedViewNode.php`; ChatGPT's `Input`): what\n * the owner types is written to the tree state through `onChange` on every keystroke, so a computed result follows. A\n * `number` field writes a number (null while empty). The browser checks nothing beyond the type; the tree computes with\n * what it gets. On a replay and in the e-mail capture it shows its current text as plain text.\n */\nconst ComposedInput = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const controlId = useId();\n const inputType = nodeProps.inputType === \"number\" || nodeProps.inputType === \"email\" ? nodeProps.inputType : \"text\";\n const isNumberField = inputType === \"number\";\n const label = readComposedText(nodeProps.label);\n const placeholder = readComposedText(nodeProps.placeholder);\n const maxLength = readComposedNumber(nodeProps.maxLength, 0);\n const isUsable = isComposedInputUsable(runtime);\n const { value, changeValue } = useComposedInputValue<string>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readFieldText,\n fallbackValue: \"\",\n toEventValue: (typedText) => toStateValue(typedText, isNumberField),\n });\n // The text as typed survives a state that holds the same number (\"3.\" and \"3,0\" stay on screen while the state is 3).\n const [typedText, setTypedText] = useState<string | undefined>(undefined);\n const shownText =\n typedText !== undefined && toStateValue(typedText, isNumberField) === toStateValue(value, isNumberField)\n ? typedText\n : value;\n const typeText = (nextText: string) => {\n const limitedText = maxLength > 0 ? nextText.slice(0, maxLength) : nextText;\n setTypedText(limitedText);\n changeValue(limitedText);\n };\n return (\n <ComposedInputField\n label={label}\n controlId={controlId}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={48}\n testId={testId}\n >\n {isUsable ? (\n <TextInput\n id={controlId}\n testId={testId}\n type={inputType}\n value={shownText}\n placeholder={placeholder}\n maxLength={maxLength > 0 ? maxLength : undefined}\n onChange={typeText}\n />\n ) : (\n <ComposedInputFrozenValue shownValue={shownText} testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Input\", component: ComposedInput };\n","import { useEffect } from \"react\";\nimport type { ComposedViewRuntime } from \"../../../composed-view-component-types\";\n\n/**\n * A choice input with no usable option renders nothing — and says so in the block's render report, so\n * the model learns the control did not show and answers in prose instead of \"pick one above\".\n */\nexport const useReportMissingOptions = (\n optionCount: number,\n nodeType: string,\n isPending: boolean,\n runtime: ComposedViewRuntime,\n): void => {\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n if (isPending || optionCount > 0) return;\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `${nodeType} has no usable option — it is not shown`);\n }, [optionCount, nodeType, isPending, reportNodeStatus]);\n};\n","import { RadioGroup, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useId } from \"react\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport {\n findComposedInputOption,\n isComposedInputUsable,\n readComposedInputOptions,\n readComposedText,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport { useReportMissingOptions } from \"./shared/use-report-missing-options\";\nimport styles from \"./ComposedInputs.module.scss\";\n\nconst readChoiceId = (resolvedValue: ExpressionValue | undefined): string | undefined =>\n typeof resolvedValue === \"string\" || typeof resolvedValue === \"number\" ? String(resolvedValue) : undefined;\n\n/**\n * `RadioGroup` — radio buttons (`RadioGroupComposedViewNode.php`; ChatGPT's `RadioGroup`): one of a\n * few choices that each carry a visible explanation (`description` under the label), the picked one written to the\n * tree state through `onChange`. Under each other by default, side by side with `direction: \"row\"`. Frozen on a replay\n * and in the e-mail capture.\n */\nconst ComposedRadioGroup = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const groupName = useId();\n const options = readComposedInputOptions(nodeProps.options);\n const label = readComposedText(nodeProps.label);\n const direction = nodeProps.direction === \"row\" ? \"row\" : \"column\";\n const { value, changeValue } = useComposedInputValue<string | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readChoiceId,\n fallbackValue: undefined,\n });\n useReportMissingOptions(options.length, \"RadioGroup\", isPending, runtime);\n if (!isPending && options.length === 0) return null;\n const selectedOption = findComposedInputOption(options, value);\n const radioOptions = options.map((option) => ({\n // The label and its explanation as one node.\n label: (\n <span className={styles.radioOptionText} data-testid={`${testId}-option-${option.id}`}>\n <Text role=\"body\" translate={false}>\n {escapePlainTextForText(option.label)}\n </Text>\n {option.description ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(option.description)}\n </Text>\n ) : null}\n </span>\n ),\n value: String(option.id),\n disabled: option.disabled,\n }));\n const selectOption = (selectedRadioValue: unknown) => {\n const pickedOption = options.find((option) => String(option.id) === String(selectedRadioValue));\n if (pickedOption) changeValue(String(pickedOption.id));\n };\n return (\n <ComposedInputField\n label={label}\n isUsable={isComposedInputUsable(runtime)}\n isPending={isPending}\n pendingHeight={72}\n testId={testId}\n >\n <div role=\"radiogroup\" aria-label={label} data-testid={testId}>\n <RadioGroup\n name={groupName}\n value={selectedOption ? String(selectedOption.id) : \"\"}\n options={radioOptions}\n direction={direction}\n onChange={selectOption}\n />\n </div>\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"RadioGroup\",\n component: ComposedRadioGroup,\n};\n","import { useId } from \"react\";\nimport { Select } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport {\n findComposedInputOption,\n isComposedInputUsable,\n readComposedInputOptions,\n readComposedText,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport { useReportMissingOptions } from \"./shared/use-report-missing-options\";\n\nconst readChoiceId = (resolvedValue: ExpressionValue | undefined): string | number | undefined =>\n typeof resolvedValue === \"string\" || typeof resolvedValue === \"number\" ? resolvedValue : undefined;\n\n/**\n * `Select` — a drop-down (`SelectComposedViewNode.php`; ChatGPT's channel select of the analytics\n * studio): one of a longer list of choices, the picked one written to the tree state through `onChange`. The option\n * texts are the model's (not translated). On a replay and in the e-mail capture it shows its current choice as plain\n * text.\n */\nconst ComposedSelect = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const controlId = useId();\n const options = readComposedInputOptions(nodeProps.options);\n const label = readComposedText(nodeProps.label);\n const placeholder = readComposedText(nodeProps.placeholder);\n const { value, changeValue } = useComposedInputValue<string | number | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readChoiceId,\n fallbackValue: undefined,\n });\n useReportMissingOptions(options.length, \"Select\", isPending, runtime);\n if (!isPending && options.length === 0) return null;\n const selectedOption = findComposedInputOption(options, value);\n const isUsable = isComposedInputUsable(runtime);\n // The option texts are the model's, shown as written.\n const selectOptions = options.map((option) => ({\n value: String(option.id),\n label: option.label,\n description: option.description,\n disabled: option.disabled,\n }));\n const selectOption = (selectedKey: string) => {\n const pickedOption = options.find((option) => String(option.id) === selectedKey);\n if (pickedOption) changeValue(pickedOption.id);\n };\n return (\n <ComposedInputField\n label={label}\n controlId={controlId}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={48}\n testId={testId}\n >\n {isUsable ? (\n <Select\n id={controlId}\n testId={testId}\n options={selectOptions}\n value={selectedOption ? String(selectedOption.id) : \"\"}\n placeholder={placeholder}\n onChange={selectOption}\n />\n ) : (\n <ComposedInputFrozenValue shownValue={selectedOption?.label} testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Select\", component: ComposedSelect };\n","import { useEffect, useRef, useState } from \"react\";\nimport { RangeSlider } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport {\n countDecimals,\n formatComposedNumber,\n isComposedInputUsable,\n readComposedNumber,\n readComposedText,\n snapToSliderStep,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputLanguage } from \"./shared/use-composed-input-language\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport styles from \"./ComposedInputs.module.scss\";\n\n/** While dragging, the tree state is written at most this often (the state store caps inputs at 30 updates a second). */\nconst DRAG_STATE_WRITE_INTERVAL_MS = 60;\n\nconst readFiniteNumber = (resolvedValue: ExpressionValue | undefined): number | undefined =>\n typeof resolvedValue === \"number\" && Number.isFinite(resolvedValue) ? resolvedValue : undefined;\n\n/**\n * `Slider` — a number between `min` and `max` (`SliderComposedViewNode.php`; the sliders of ChatGPT's\n * revenue and MRR simulators): the label left, the formatted value right (\"35,000\", \"3.0 %\", \"70 €\" — `unit` and\n * `decimals`, in the owner's language), the track below. Dragging writes the tree state about 16 times a second so\n * computed KPIs follow the thumb; letting go always writes the final value. An invalid range (`max` not above `min`)\n * renders nothing and is reported. Frozen on a replay and in the e-mail capture.\n */\nconst ComposedSlider = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const languageCode = useComposedInputLanguage();\n const [dragValue, setDragValue] = useState<number | undefined>(undefined);\n const lastDragWriteAtRef = useRef(0);\n const min = readComposedNumber(nodeProps.min, 0);\n const max = readComposedNumber(nodeProps.max, 100);\n const rawStep = readComposedNumber(nodeProps.step, 1);\n const step = rawStep > 0 ? rawStep : 1;\n const unit = readComposedText(nodeProps.unit);\n const decimals = readComposedNumber(nodeProps.decimals, countDecimals(step));\n const label = readComposedText(nodeProps.label);\n const showsValue = nodeProps.showValue !== false;\n const isRangeValid = max > min;\n const { value, changeValue } = useComposedInputValue<number>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readFiniteNumber,\n fallbackValue: min,\n });\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n if (isRangeValid) return;\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `Slider max (${max}) must be above min (${min}) — it is not shown`);\n }, [isRangeValid, min, max, reportNodeStatus]);\n if (!isRangeValid) return null;\n const shownValue = snapToSliderStep(dragValue ?? value, min, max, step);\n const moveThumb = (movedValue: number) => {\n if (!isComposedInputUsable(runtime)) return;\n const snappedValue = snapToSliderStep(movedValue, min, max, step);\n setDragValue(snappedValue);\n const now = Date.now();\n if (now - lastDragWriteAtRef.current < DRAG_STATE_WRITE_INTERVAL_MS) return;\n lastDragWriteAtRef.current = now;\n runtime.runEvent(node.props.onChange, snappedValue);\n };\n const releaseThumb = (releasedValue: number) => {\n setDragValue(undefined);\n changeValue(snapToSliderStep(releasedValue, min, max, step));\n };\n const isUsable = isComposedInputUsable(runtime);\n return (\n <ComposedInputField\n label={label}\n labelRowValue={\n showsValue && !isPending ? formatComposedNumber(shownValue, decimals, unit, languageCode) : undefined\n }\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={28}\n testId={testId}\n >\n <div className={styles.sliderTrack} aria-label={label} data-testid={testId}>\n <RangeSlider\n value={shownValue}\n min={min}\n max={max}\n step={step}\n onMove={moveThumb}\n onRelease={releaseThumb}\n />\n </div>\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Slider\", component: ComposedSlider };\n","import { Tabs, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport {\n findComposedInputOption,\n isComposedInputUsable,\n readComposedInputOptions,\n readComposedText,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport { useReportMissingOptions } from \"./shared/use-report-missing-options\";\nimport styles from \"./ComposedInputs.module.scss\";\n\nconst readChoiceId = (resolvedValue: ExpressionValue | undefined): string | number | undefined =>\n typeof resolvedValue === \"string\" || typeof resolvedValue === \"number\" ? resolvedValue : undefined;\n\n/**\n * `Tabs` — the segmented control (`TabsComposedViewNode.php`; ChatGPT's 7/30-day toggle of the\n * analytics dashboard, the Bear/Base/Bull scenarios of the MRR simulator): a few short choices side by side, the picked\n * one written to the tree state through `onChange`. Labels are the model's text. A disabled choice is not shown. Frozen on a replay and in the e-mail capture.\n */\nconst ComposedTabs = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const options = readComposedInputOptions(nodeProps.options);\n const label = readComposedText(nodeProps.label);\n const { value, changeValue } = useComposedInputValue<string | number | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readChoiceId,\n fallbackValue: options[0]?.id,\n });\n useReportMissingOptions(options.length, \"Tabs\", isPending, runtime);\n if (!isPending && options.length === 0) return null;\n const selectedOption = findComposedInputOption(options, value) ?? options[0];\n const tabs = options.map((option) => ({\n value: String(option.id),\n disabled: option.disabled,\n testId: `${testId}-option-${option.id}`,\n label: <Text translate={false}>{escapePlainTextForText(option.label)}</Text>,\n }));\n const selectOption = (selectedTabValue: unknown) => {\n const pickedOption = options.find((option) => String(option.id) === String(selectedTabValue));\n if (pickedOption && String(pickedOption.id) !== String(selectedOption?.id)) changeValue(pickedOption.id);\n };\n return (\n <ComposedInputField\n label={label}\n isUsable={isComposedInputUsable(runtime)}\n isPending={isPending}\n pendingHeight={36}\n testId={testId}\n >\n <div className={styles.tabsBar} data-testid={testId}>\n <Tabs\n options={tabs}\n value={selectedOption ? String(selectedOption.id) : undefined}\n onChange={selectOption}\n ariaLabel={label}\n />\n </div>\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Tabs\", component: ComposedTabs };\n","import { useId } from \"react\";\nimport { TextArea } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport { isComposedInputUsable, readComposedNumber, readComposedText } from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\n\n/** The visible lines a textarea may ask for — beyond that it is a document, not a field. */\nconst MAX_TEXTAREA_ROWS = 12;\n\nconst readFieldText = (resolvedValue: ExpressionValue | undefined): string | undefined =>\n typeof resolvedValue === \"string\" ? resolvedValue : resolvedValue === null ? \"\" : undefined;\n\n/**\n * `Textarea` — a multi-line text field (`TextareaComposedViewNode.php`; ChatGPT's `Textarea`): what\n * the owner types is written to the tree state through `onChange`; with `maxLength` the field shows a counter and takes\n * no more. It starts at `rows` lines and grows with its text up to {@link MAX_TEXTAREA_ROWS}. The tree state caps a string at its own length budget, so a longer text is cut there. On a replay and in\n * the e-mail capture it shows its current text as plain text, line breaks kept.\n */\nconst ComposedTextarea = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const controlId = useId();\n const label = readComposedText(nodeProps.label);\n const placeholder = readComposedText(nodeProps.placeholder);\n const maxLength = readComposedNumber(nodeProps.maxLength, 0);\n const rows = Math.min(Math.max(Math.round(readComposedNumber(nodeProps.rows, 3)), 1), MAX_TEXTAREA_ROWS);\n const isUsable = isComposedInputUsable(runtime);\n const { value, changeValue } = useComposedInputValue<string>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readFieldText,\n fallbackValue: \"\",\n });\n const typeText = (nextText: string) => changeValue(maxLength > 0 ? nextText.slice(0, maxLength) : nextText);\n return (\n <ComposedInputField\n label={label}\n controlId={controlId}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={24 * rows + 24}\n testId={testId}\n >\n {isUsable ? (\n <TextArea\n id={controlId}\n testId={testId}\n value={value}\n placeholder={placeholder}\n // No fixed `rows`: the field starts at `rows` lines and grows with the text up to the cap, so a drafted\n // e-mail shows whole (ChatGPT's writing block) instead of scrolling inside a short box.\n minRows={rows}\n maxRows={Math.max(rows, MAX_TEXTAREA_ROWS)}\n maxLength={maxLength > 0 ? maxLength : undefined}\n showsCounter={maxLength > 0}\n onChange={typeText}\n />\n ) : (\n <ComposedInputFrozenValue shownValue={value} isMultiline testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"Textarea\",\n component: ComposedTextarea,\n};\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\n\n/**\n * Reads the resolved props of the layout nodes. A prop arrives as a JSON value after its binding was\n * resolved — or `undefined` when it was dropped or is still pending — so every reader falls back to the node's\n * default instead of trusting the type. The closed vocabularies mirror `ComposedViewLayoutSpacing.php`.\n */\n\nexport type LayoutGap = \"none\" | \"xsmall\" | \"small\" | \"medium\" | \"large\";\n\nconst LAYOUT_GAPS: readonly LayoutGap[] = [\"none\", \"xsmall\", \"small\", \"medium\", \"large\"];\n\n/** The value when it is one of `allowedValues`, else `fallback`. */\nexport const readEnumProp = <AllowedValue extends string | number>(\n value: ExpressionValue | undefined,\n allowedValues: readonly AllowedValue[],\n fallback: AllowedValue,\n): AllowedValue => (allowedValues.includes(value as AllowedValue) ? (value as AllowedValue) : fallback);\n\nexport const readGapProp = (value: ExpressionValue | undefined, fallback: LayoutGap = \"medium\"): LayoutGap =>\n readEnumProp(value, LAYOUT_GAPS, fallback);\n\n/** A non-empty text (a number is shown as written), else `undefined`. */\nexport const readTextProp = (value: ExpressionValue | undefined): string | undefined => {\n if (typeof value === \"string\") return value.trim() === \"\" ? undefined : value;\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return undefined;\n};\n\nexport const readBooleanProp = (value: ExpressionValue | undefined, fallback: boolean): boolean =>\n typeof value === \"boolean\" ? value : fallback;\n\nexport interface LayoutSourceLink {\n name?: string;\n url?: string;\n}\n\n/** A `{\"name\",\"url\"}` source; the url only when it is http(s). */\nexport const readSourceLinkProp = (value: ExpressionValue | undefined): LayoutSourceLink | undefined => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n const sourceObject = value as Record<string, ExpressionValue>;\n const name = readTextProp(sourceObject.name);\n const rawUrl = readTextProp(sourceObject.url);\n const url = rawUrl !== undefined && /^https?:\\/\\//i.test(rawUrl) ? rawUrl : undefined;\n if (name === undefined && url === undefined) return undefined;\n return { name, url };\n};\n","import { Icon, InteractiveSurface } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readBooleanProp, readEnumProp, readTextProp } from \"./layout-props\";\nimport styles from \"./Carousel.module.scss\";\n\nconst VISIBLE_ITEM_COUNTS = [1, 2, 3, 4] as const;\n\nconst VISIBLE_CLASS_NAMES: Record<(typeof VISIBLE_ITEM_COUNTS)[number], string> = {\n 1: styles.visible1,\n 2: styles.visible2,\n 3: styles.visible3,\n 4: styles.visible4,\n};\n\nconst SKELETON_SLIDE_COUNT = 3;\n\n/** Whether the track can scroll further back / forward (a pixel of rounding counts as the end). */\nconst readScrollEdges = (track: HTMLDivElement) => ({\n canScrollBack: track.scrollLeft > 1,\n canScrollForward: track.scrollLeft + track.clientWidth < track.scrollWidth - 1,\n});\n\n/**\n * `Carousel` (`CarouselComposedViewNode.php`): slides in one horizontal row the owner pages through —\n * by swipe, by the keyboard on the focused track, or by the previous / next buttons, which show only while there is\n * something to scroll to. Each child node is a slide; with `items` the children are one slide's template rendered per\n * item (`$item` bound; the renderer caps it at `maxRepeatRows`). The e-mail capture shows the first slides without\n * controls. No slides → `empty`; `items` still waiting for its data → skeleton slides.\n */\nconst Carousel = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, renderSlotForItem, runtime, isPending, testId } = props;\n const trackRef = useRef<HTMLDivElement>(null);\n const [scrollEdges, setScrollEdges] = useState({ canScrollBack: false, canScrollForward: false });\n const visibleItemCount = readEnumProp(nodeProps.visibleItems, VISIBLE_ITEM_COUNTS, 2);\n const isShowingArrows = readBooleanProp(nodeProps.showArrows, true) && !runtime.isEmailRender;\n const carouselLabel = readTextProp(nodeProps.label);\n // With `items` written, the slides come from the list only — a list that did not resolve shows no slides.\n const isRepeatingItems = node.props.items !== undefined;\n const items = Array.isArray(nodeProps.items) ? nodeProps.items : [];\n const isWaitingForItems = isRepeatingItems && isPending && !Array.isArray(nodeProps.items);\n\n // One slide per item (the template's nodes together), or one slide per child node when there are no items.\n const slides: ReactNode[][] = isWaitingForItems\n ? []\n : isRepeatingItems\n ? items\n .map((item, itemIndex) => renderSlotForItem(\"children\", item, itemIndex))\n .filter((slide) => slide.length > 0)\n : renderSlotForItem(\"children\", null, 0).map((slideNode) => [slideNode]);\n const slideCount = slides.length;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (isWaitingForItems) reportNodeStatus(\"pending\");\n else if (slideCount > 0) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Carousel has no slides to show\");\n }, [isWaitingForItems, slideCount, reportNodeStatus]);\n\n const updateScrollEdges = useCallback(() => {\n if (trackRef.current) setScrollEdges(readScrollEdges(trackRef.current));\n }, []);\n\n useEffect(() => {\n const track = trackRef.current;\n if (!track) return undefined;\n updateScrollEdges();\n track.addEventListener(\"scroll\", updateScrollEdges, { passive: true });\n const resizeObserver = typeof ResizeObserver === \"undefined\" ? undefined : new ResizeObserver(updateScrollEdges);\n resizeObserver?.observe(track);\n return () => {\n track.removeEventListener(\"scroll\", updateScrollEdges);\n resizeObserver?.disconnect();\n };\n }, [updateScrollEdges, slideCount]);\n\n const scrollBySlide = (direction: 1 | -1) => {\n const track = trackRef.current;\n if (!track) return;\n const firstSlide = track.firstElementChild as HTMLElement | null;\n const slideStep = firstSlide ? firstSlide.getBoundingClientRect().width : track.clientWidth;\n const prefersReducedMotion = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false;\n track.scrollBy?.({ left: direction * slideStep, behavior: prefersReducedMotion ? \"auto\" : \"smooth\" });\n };\n\n if (isWaitingForItems) {\n return (\n <div\n className={classNames(styles.carousel, VISIBLE_CLASS_NAMES[visibleItemCount])}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n <div className={classNames(styles.track, styles.frozenTrack)}>\n {Array.from({ length: SKELETON_SLIDE_COUNT }, (unused, skeletonIndex) => (\n <div key={skeletonIndex} className={styles.slide}>\n <div className={styles.skeletonSlide}>\n <SkeletonLine width=\"50%\" height={12} />\n <SkeletonLine width=\"70%\" height={24} />\n <SkeletonLine width=\"40%\" height={10} />\n </div>\n </div>\n ))}\n </div>\n </div>\n );\n }\n if (slideCount === 0) return null;\n\n return (\n <div className={classNames(styles.carousel, VISIBLE_CLASS_NAMES[visibleItemCount])} data-testid={testId}>\n <div className={styles.viewport}>\n <div\n ref={trackRef}\n data-testid={`${testId}-track`}\n className={classNames(styles.track, runtime.isEmailRender && styles.frozenTrack)}\n role=\"group\"\n aria-roledescription={translateText(\"carousel\")}\n aria-label={carouselLabel}\n tabIndex={runtime.isEmailRender ? undefined : 0}\n >\n {slides.map((slideNodes, slideIndex) => (\n <div\n key={slideIndex}\n className={styles.slide}\n data-testid={`${testId}-slide-${slideIndex}`}\n role=\"group\"\n aria-roledescription={translateText(\"slide\")}\n aria-label={\n translateText(\"%position% of %count%\", { position: slideIndex + 1, count: slideCount })\n }\n >\n {slideNodes}\n </div>\n ))}\n </div>\n {isShowingArrows && scrollEdges.canScrollBack ? (\n <InteractiveSurface hoverable className={classNames(styles.arrow, styles.arrowPrevious)}>\n <button\n type=\"button\"\n className={styles.arrowButton}\n data-testid={`${testId}-previous`}\n aria-label={translateText(\"Show the previous slides\")}\n onClick={() => scrollBySlide(-1)}\n >\n <Icon name=\"arrowLeft\" />\n </button>\n </InteractiveSurface>\n ) : null}\n {isShowingArrows && scrollEdges.canScrollForward ? (\n <InteractiveSurface hoverable className={classNames(styles.arrow, styles.arrowNext)}>\n <button\n type=\"button\"\n className={styles.arrowButton}\n data-testid={`${testId}-next`}\n aria-label={translateText(\"Show the next slides\")}\n onClick={() => scrollBySlide(1)}\n >\n <Icon name=\"arrowRight\" />\n </button>\n </InteractiveSurface>\n ) : null}\n </div>\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Carousel\", component: Carousel };\n","import type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp } from \"./layout-props\";\nimport styles from \"./Divider.module.scss\";\n\nconst ORIENTATIONS = [\"horizontal\", \"vertical\"] as const;\n\n/** `Divider` (`DividerComposedViewNode.php`): a hairline, horizontal in a column, vertical in a row. */\nconst Divider = (props: ComposedViewComponentProps) => {\n const { props: nodeProps } = props;\n const orientation = readEnumProp(nodeProps.orientation, ORIENTATIONS, \"horizontal\");\n return <div role=\"separator\" aria-orientation={orientation} className={styles[orientation]} />;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Divider\", component: Divider };\n","import type { LayoutGap } from \"./layout-props\";\n\n/** The CSS-module class of a gap step (`_layout-gaps.scss`): `medium` → `gapMedium`. */\nexport const layoutGapClassName = (styles: Record<string, string>, gap: LayoutGap): string | undefined =>\n styles[`gap${gap.charAt(0).toUpperCase()}${gap.slice(1)}`];\n","import { classNames } from \"../../../provider/class-names\";\nimport { useEffect } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readGapProp } from \"./layout-props\";\nimport { layoutGapClassName } from \"./layout-gap-class\";\nimport styles from \"./Flow.module.scss\";\n\nconst ALIGNMENTS = [\"start\", \"center\", \"end\"] as const;\n\nconst ALIGNMENT_CLASS_NAMES: Record<(typeof ALIGNMENTS)[number], string> = {\n start: styles.alignStart,\n center: styles.alignCenter,\n end: styles.alignEnd,\n};\n\n/**\n * `Flow` (`FlowComposedViewNode.php`): badges, labels, chips and small controls side by side,\n * wrapping onto as many lines as they need. Without items it shows nothing and reports `empty`.\n */\nconst Flow = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime } = props;\n const items = slots.children ?? [];\n const alignment = readEnumProp(nodeProps.align, ALIGNMENTS, \"center\");\n const hasItems = items.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasItems) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Flow has no items to show\");\n }, [hasItems, reportNodeStatus]);\n\n if (!hasItems) return null;\n return (\n <div\n className={classNames(\n styles.flow,\n ALIGNMENT_CLASS_NAMES[alignment],\n layoutGapClassName(styles, readGapProp(nodeProps.gap, \"small\")),\n )}\n >\n {items}\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Flow\", component: Flow };\n","import { classNames } from \"../../../provider/class-names\";\nimport { useEffect } from \"react\";\nimport { getComposedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readGapProp } from \"./layout-props\";\nimport { layoutGapClassName } from \"./layout-gap-class\";\nimport styles from \"./Grid.module.scss\";\n\nconst COLUMN_COUNTS = [1, 2, 3, 4] as const;\nconst MIN_COLUMN_WIDTHS = [\"compact\", \"regular\"] as const;\n\n/**\n * The cells a compact column fits: a number tile, a pressable tile, a status, a button. Any other cell — a surface with\n * a title and a description, a text, a chart — needs the regular minimum, or a phone shows two columns of four-word lines.\n */\nconst COMPACT_CELL_NODE_TYPES: ReadonlySet<string> = new Set([\n \"KpiTile\",\n \"Pressable\",\n \"Badge\",\n \"Icon\",\n \"Favicon\",\n \"Button\",\n]);\n\n/** A cell that fits a compact column: a compact node type, or an embedded widget whose size class is compact (a snapshot tile). */\nconst isCompactCell = (cellNode: ComposedViewComponentProps[\"node\"]): boolean => {\n if (COMPACT_CELL_NODE_TYPES.has(cellNode.type)) return true;\n const embeddedWidgetName = cellNode.type === \"Widget\" ? cellNode.props.widget : undefined;\n const embeddableWidgets = getComposedNodeSchema().embeddableWidgets;\n return (\n typeof embeddedWidgetName === \"string\" &&\n Object.prototype.hasOwnProperty.call(embeddableWidgets, embeddedWidgetName) &&\n embeddableWidgets[embeddedWidgetName].sizeClass === \"compact\"\n );\n};\n\n/** The written minimum wins; KPI-only grids use regular width, otherwise the existing compact-cell rules apply. */\nexport const readMinColumnWidth = (node: ComposedViewComponentProps[\"node\"], writtenMinColumnWidth: unknown) => {\n if (MIN_COLUMN_WIDTHS.includes(writtenMinColumnWidth as (typeof MIN_COLUMN_WIDTHS)[number])) {\n return writtenMinColumnWidth as (typeof MIN_COLUMN_WIDTHS)[number];\n }\n const cellNodes = node.nodesBySlotName.children ?? [];\n if (cellNodes.length > 0 && cellNodes.every((cell) => cell.type === \"KpiTile\")) return \"regular\";\n return cellNodes.every(isCompactCell) ? \"compact\" : \"regular\";\n};\n\nconst COLUMN_CLASS_NAMES: Record<(typeof COLUMN_COUNTS)[number], string> = {\n 1: styles.columns1,\n 2: styles.columns2,\n 3: styles.columns3,\n 4: styles.columns4,\n};\n\n/**\n * `Grid` (`GridComposedViewNode.php`): one cell per child, at most `columns` side by side, every\n * cell in a row as tall as the tallest. On a narrow pane it shows fewer columns (the cell keeps its minimum width). The\n * minimum is the written `minColumnWidth`; without one KPI-only grids take the regular minimum so textual KPI values\n * stay readable. Other grids keep their compact-cell default.\n * A grid without children shows nothing and reports `empty`.\n */\nconst Grid = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots, runtime, testId } = props;\n const cells = slots.children ?? [];\n const columnCount = readEnumProp(nodeProps.columns, COLUMN_COUNTS, 2);\n const minColumnWidth = readMinColumnWidth(node, nodeProps.minColumnWidth);\n const hasCells = cells.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasCells) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Grid has no cells to show\");\n }, [hasCells, reportNodeStatus]);\n\n if (!hasCells) return null;\n return (\n <div\n data-testid={testId}\n className={classNames(\n styles.grid,\n COLUMN_CLASS_NAMES[columnCount],\n minColumnWidth === \"regular\" ? styles.minColumnRegular : styles.minColumnCompact,\n layoutGapClassName(styles, readGapProp(nodeProps.gap)),\n )}\n >\n {cells}\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Grid\", component: Grid };\n","import { Icon, InteractiveSurface, Text, type AgentsIconName } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readTextProp } from \"./layout-props\";\nimport { useLayoutNesting } from \"./layout-nesting-context\";\nimport styles from \"./Popover.module.scss\";\n\nconst ICONS = [\"info\", \"help\", \"none\"] as const;\nconst PLACEMENTS = [\"start\", \"end\"] as const;\n\nconst ICON_NAMES: Record<Exclude<(typeof ICONS)[number], \"none\">, AgentsIconName> = {\n info: \"info\",\n help: \"help\",\n};\n\n/**\n * `Popover` (`PopoverComposedViewNode.php`; ChatGPT's \"ⓘ Methodik\"): a small text button that opens a\n * floating explanation — `text`, or the nodes of `content`. A click opens it, a second click, Escape or a click\n * elsewhere closes it; the button carries `aria-expanded` and names the panel. The component library's `Popover` is a hover tooltip,\n * which a phone cannot open, so the kit uses a disclosure button instead. Inside a `Pressable` (already one button) and\n * in the e-mail capture it shows its label only. A popover with nothing to explain → `empty`.\n */\nconst Popover = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, testId } = props;\n const { isInsidePressable } = useLayoutNesting();\n const [isOpen, setIsOpen] = useState(false);\n const popoverRef = useRef<HTMLSpanElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const panelId = useId();\n const label = readTextProp(nodeProps.label);\n const text = readTextProp(nodeProps.text);\n const contentNodes = slots.content ?? [];\n const icon = readEnumProp(nodeProps.icon, ICONS, \"info\");\n const placement = readEnumProp(nodeProps.placement, PLACEMENTS, \"end\");\n const hasExplanation = text !== undefined || contentNodes.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (label !== undefined && hasExplanation) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Popover has no label or nothing to explain\");\n }, [label, hasExplanation, reportNodeStatus]);\n\n // While open: a press outside the popover or Escape closes it (Escape returns the focus to the button).\n useEffect(() => {\n if (!isOpen) return undefined;\n const closeOnOutsidePress = (pointerEvent: PointerEvent) => {\n if (popoverRef.current && !popoverRef.current.contains(pointerEvent.target as Node)) setIsOpen(false);\n };\n const closeOnEscape = (keyboardEvent: KeyboardEvent) => {\n if (keyboardEvent.key !== \"Escape\") return;\n setIsOpen(false);\n triggerRef.current?.focus();\n };\n document.addEventListener(\"pointerdown\", closeOnOutsidePress);\n document.addEventListener(\"keydown\", closeOnEscape);\n return () => {\n document.removeEventListener(\"pointerdown\", closeOnOutsidePress);\n document.removeEventListener(\"keydown\", closeOnEscape);\n };\n }, [isOpen]);\n\n if (label === undefined || !hasExplanation) return null;\n const labelContent = (\n <>\n {icon !== \"none\" ? <Icon className={styles.icon} name={ICON_NAMES[icon]} /> : null}\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(label)}\n </Text>\n </>\n );\n if (isInsidePressable || runtime.isEmailRender)\n return (\n <span className={styles.staticLabel} data-testid={testId}>\n {labelContent}\n </span>\n );\n\n return (\n <span ref={popoverRef} className={styles.popover}>\n <InteractiveSurface hoverable className={styles.triggerWrapper}>\n <button\n ref={triggerRef}\n type=\"button\"\n className={styles.trigger}\n data-testid={testId}\n aria-expanded={isOpen}\n aria-controls={isOpen ? panelId : undefined}\n onClick={() => setIsOpen((wasOpen) => !wasOpen)}\n >\n {labelContent}\n </button>\n </InteractiveSurface>\n {isOpen ? (\n <span\n id={panelId}\n role=\"note\"\n data-testid={`${testId}-panel`}\n className={classNames(styles.panel, placement === \"start\" ? styles.placementStart : styles.placementEnd)}\n >\n {text !== undefined ? (\n <Text role=\"help\" translate={false}>\n {escapePlainTextForText(text)}\n </Text>\n ) : null}\n {contentNodes}\n </span>\n ) : null}\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Popover\", component: Popover };\n","import { InteractiveSurface } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useMemo } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readTextProp } from \"./layout-props\";\nimport { LayoutNestingContext, useLayoutNesting } from \"./layout-nesting-context\";\nimport styles from \"./Pressable.module.scss\";\n\n/**\n * `Pressable` (`PressableComposedViewNode.php`): its content as one clickable area. A click runs the\n * node's `onClick` — `{\"set\": <state>}` writes `value`, `{\"action\": <name>}` runs the tree's action — through the\n * renderer, so a frozen tree (the e-mail) writes nothing. `isSelected` draws the one selection ring of the design\n * (inset ring + 8 % tint) and sets `aria-pressed`. In the e-mail capture, and inside another pressable, the content\n * shows without a control. Nothing inside → `empty`.\n */\nconst Pressable = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots, runtime, testId } = props;\n const nesting = useLayoutNesting();\n const contentNodes = slots.children ?? [];\n const isSelected = typeof nodeProps.isSelected === \"boolean\" ? nodeProps.isSelected : undefined;\n const accessibleLabel = readTextProp(nodeProps.label);\n const hasContent = contentNodes.length > 0;\n const { reportNodeStatus } = runtime;\n const innerNesting = useMemo(() => ({ ...nesting, isInsidePressable: true }), [nesting]);\n\n useEffect(() => {\n if (hasContent) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Pressable has no content to click\");\n }, [hasContent, reportNodeStatus]);\n\n if (!hasContent) return null;\n if (runtime.isEmailRender || nesting.isInsidePressable) {\n return (\n <div className={classNames(styles.pressable, styles.content, isSelected && styles.selected)} data-testid={testId}>\n {contentNodes}\n </div>\n );\n }\n return (\n <InteractiveSurface hoverable className={classNames(styles.pressable, isSelected && styles.selected)}>\n <button\n type=\"button\"\n className={styles.button}\n data-testid={testId}\n aria-pressed={isSelected}\n aria-label={accessibleLabel}\n onClick={() => runtime.runEvent(node.props.onClick, nodeProps.value)}\n >\n <LayoutNestingContext.Provider value={innerNesting}>{contentNodes}</LayoutNestingContext.Provider>\n </button>\n </InteractiveSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Pressable\", component: Pressable };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readSourceLinkProp, readTextProp } from \"./layout-props\";\nimport styles from \"./Quote.module.scss\";\n\n/**\n * `Quote` (`QuoteComposedViewNode.php`): the quoted words (`text`, or the text nodes in the\n * children), then one caption line — who said it and where it was published, joined by a middle dot; the source opens\n * in a new tab. All of it is the model's business content (never translated). Nothing to quote → `empty`.\n */\nconst Quote = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, testId } = props;\n const text = readTextProp(nodeProps.text);\n const attribution = readTextProp(nodeProps.attribution);\n const source = readSourceLinkProp(nodeProps.source);\n const contentNodes = slots.children ?? [];\n const hasQuotedContent = text !== undefined || contentNodes.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasQuotedContent) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Quote has no quoted text\");\n }, [hasQuotedContent, reportNodeStatus]);\n\n if (!hasQuotedContent) return null;\n const sourceLabel = source?.name ?? source?.url;\n const canOpenSource = source?.url !== undefined && !runtime.isEmailRender;\n return (\n <figure className={styles.quote} data-testid={testId}>\n <blockquote className={styles.quotedContent} cite={source?.url}>\n {text !== undefined ? (\n <Text role=\"body\" translate={false}>\n {escapePlainTextForText(text)}\n </Text>\n ) : null}\n {contentNodes}\n </blockquote>\n {attribution !== undefined || sourceLabel !== undefined ? (\n <figcaption className={styles.caption}>\n {attribution !== undefined ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(attribution)}\n </Text>\n ) : null}\n {attribution !== undefined && sourceLabel !== undefined ? (\n <Text role=\"caption\" color=\"var(--agents-fg-lightest)\" translate={false} ariaHidden>\n {\"·\"}\n </Text>\n ) : null}\n {sourceLabel !== undefined && canOpenSource ? (\n <a\n className={styles.sourceLink}\n href={source?.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n data-testid={`${testId}-source`}\n >\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(sourceLabel)}\n </Text>\n </a>\n ) : null}\n {sourceLabel !== undefined && !canOpenSource ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(sourceLabel)}\n </Text>\n ) : null}\n </figcaption>\n ) : null}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Quote\", component: Quote };\n","import { classNames } from \"../../../provider/class-names\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readBooleanProp, readEnumProp } from \"./layout-props\";\nimport styles from \"./Spacer.module.scss\";\n\nconst SIZES = [\"small\", \"medium\", \"large\"] as const;\n\n/** `Spacer` (`SpacerComposedViewNode.php`): a fixed step of room, or all the free room (`grow`). */\nconst Spacer = (props: ComposedViewComponentProps) => {\n const { props: nodeProps } = props;\n const size = readEnumProp(nodeProps.size, SIZES, \"medium\");\n const isGrowing = readBooleanProp(nodeProps.grow, false);\n return <div aria-hidden=\"true\" className={classNames(styles.spacer, styles[size], isGrowing && styles.grow)} />;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Spacer\", component: Spacer };\n","import { classNames } from \"../../../provider/class-names\";\nimport { useEffect } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readBooleanProp, readEnumProp, readGapProp } from \"./layout-props\";\nimport { layoutGapClassName } from \"./layout-gap-class\";\nimport styles from \"./Stack.module.scss\";\n\nconst DIRECTIONS = [\"row\", \"column\"] as const;\nconst ALIGNMENTS = [\"start\", \"center\", \"end\", \"stretch\", \"baseline\"] as const;\nconst JUSTIFICATIONS = [\"start\", \"center\", \"end\", \"between\"] as const;\n\nconst ALIGNMENT_CLASS_NAMES: Record<(typeof ALIGNMENTS)[number], string> = {\n start: styles.alignStart,\n center: styles.alignCenter,\n end: styles.alignEnd,\n stretch: styles.alignStretch,\n baseline: styles.alignBaseline,\n};\n\nconst JUSTIFICATION_CLASS_NAMES: Record<(typeof JUSTIFICATIONS)[number], string> = {\n start: styles.justifyStart,\n center: styles.justifyCenter,\n end: styles.justifyEnd,\n between: styles.justifyBetween,\n};\n\n/**\n * `Stack` (`StackComposedViewNode.php`): the children in a row or a column with one gap step between\n * them. A row centres its items and wraps by default, so a title with a control at its end (`justify: \"between\"`)\n * stays readable on a phone. A stack without children shows nothing and reports `empty`.\n */\nconst Stack = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime } = props;\n const children = slots.children ?? [];\n const direction = readEnumProp(nodeProps.direction, DIRECTIONS, \"column\");\n const alignment = readEnumProp(nodeProps.align, ALIGNMENTS, direction === \"row\" ? \"center\" : \"stretch\");\n const justification = readEnumProp(nodeProps.justify, JUSTIFICATIONS, \"start\");\n const isWrapping = direction === \"row\" && readBooleanProp(nodeProps.wrap, true);\n const hasChildren = children.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasChildren) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Stack has no children to show\");\n }, [hasChildren, reportNodeStatus]);\n\n if (!hasChildren) return null;\n return (\n <div\n className={classNames(\n styles.stack,\n styles[direction],\n isWrapping && styles.wrap,\n ALIGNMENT_CLASS_NAMES[alignment],\n JUSTIFICATION_CLASS_NAMES[justification],\n layoutGapClassName(styles, readGapProp(nodeProps.gap)),\n )}\n >\n {children}\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Stack\", component: Stack };\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useMemo } from \"react\";\nimport { WidgetSurface } from \"../../../widgets/_shared/modern\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readTextProp } from \"./layout-props\";\nimport { LayoutNestingContext, useLayoutNesting } from \"./layout-nesting-context\";\nimport styles from \"./Surface.module.scss\";\n\nconst DENSITIES = [\"regular\", \"compact\"] as const;\n\n/**\n * `Surface` (`SurfaceComposedViewNode.php`; ChatGPT's `Card` — named Surface, the project's noun is\n * never \"card\"): a titled group of nodes. The outermost surface is raised on the chat (`WidgetSurface` elevated); a\n * surface inside another one is a flat tile, so a composition never stacks three background levels. The title is the\n * widget title (`textIntro` bold) on the outer surface and a tile title (`text` bold) inside; the subtitle is one muted\n * line. Slots: `media` flush at the top, `header` at the end of the title row, the body, `footer` at the foot. A\n * surface with nothing to show reports `empty`.\n */\nconst Surface = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, testId } = props;\n const nesting = useLayoutNesting();\n const title = readTextProp(nodeProps.title);\n const subtitle = readTextProp(nodeProps.subtitle);\n const isCompact = readEnumProp(nodeProps.density, DENSITIES, \"regular\") === \"compact\";\n const mediaNodes = slots.media ?? [];\n const headerNodes = slots.header ?? [];\n const bodyNodes = slots.children ?? [];\n const footerNodes = slots.footer ?? [];\n const hasContent =\n title !== undefined ||\n subtitle !== undefined ||\n mediaNodes.length + headerNodes.length + bodyNodes.length + footerNodes.length > 0;\n const { reportNodeStatus } = runtime;\n const innerNesting = useMemo(() => ({ ...nesting, isInsideSurface: true }), [nesting]);\n\n useEffect(() => {\n if (hasContent) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Surface has no title and no content\");\n }, [hasContent, reportNodeStatus]);\n\n if (!hasContent) return null;\n const isOutermost = !nesting.isInsideSurface;\n const hasHeader = title !== undefined || subtitle !== undefined || headerNodes.length > 0;\n return (\n <WidgetSurface\n level={isOutermost ? \"elevated\" : \"flat\"}\n compact={isCompact}\n testId={testId}\n className={classNames(styles.surface, isCompact && styles.compact)}\n >\n <LayoutNestingContext.Provider value={innerNesting}>\n {mediaNodes.length > 0 ? (\n <div className={classNames(styles.media, isCompact && styles.compactMedia)}>{mediaNodes}</div>\n ) : null}\n {hasHeader ? (\n <div className={styles.header}>\n {title !== undefined || subtitle !== undefined ? (\n <div className={styles.titles}>\n {title !== undefined ? (\n <Text\n role={isOutermost ? \"intro\" : \"body\"}\n weight=\"bold\"\n translate={false}\n >\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n {subtitle !== undefined ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(subtitle)}\n </Text>\n ) : null}\n </div>\n ) : null}\n {headerNodes.length > 0 ? <div className={styles.headerEnd}>{headerNodes}</div> : null}\n </div>\n ) : null}\n {bodyNodes.length > 0 ? <div className={styles.body}>{bodyNodes}</div> : null}\n {footerNodes.length > 0 ? <div className={styles.footer}>{footerNodes}</div> : null}\n </LayoutNestingContext.Provider>\n </WidgetSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Surface\", component: Surface };\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n type ComposedViewTone,\n readOptionalComposedViewTone,\n} from \"../../composed-view-tones\";\n\n/**\n * The `Map` node's props, read into one typed map view (`MapComposedViewNode.php`). The props arrive\n * with every binding resolved; the reader checked their JSON types, not the shape of a point, so this reading is\n * alias-tolerant (a model that writes `name` / `latitude` / `lon` still gets its point), caps the points at the\n * repeat budget and never throws: a point without valid coordinates is dropped and counted, so the component can\n * report it. Pure — no React, no Google SDK.\n */\n\nexport interface MapPoint {\n /** Stable within one map: the point's position in the written list. */\n key: string;\n label: string;\n lat: number;\n lng: number;\n /** 0–5, one decimal. */\n rating?: number;\n /** The category line (\"Café\", \"Restaurant\"). */\n subtitle?: string;\n /** A status line (\"Closed\", \"Open until 18:00\"). */\n detail?: string;\n /**\n * How the status line reads, a tone of the kit's list (`composed-view-tones.ts`): `success` (open), `danger`\n * (closed), `warning` (closes soon) — the older `positive` / `negative` read as `success` / `danger`; none = plain text.\n */\n detailTone?: MapPointDetailTone;\n /** An http(s) or data: image URL. */\n image?: string;\n /** The name of a tree action the point runs on click (an `openEntity` action opens the entity's detail panel). */\n actionName?: string;\n /**\n * The point as the props hand it — a row of a resolved `$from` list carries its own `entityRef` + `entity`. The click\n * runs the action in this row, so a row-bound `openEntity` action (`ref: {\"$item\":\"entityRef\"}`) opens its entity.\n */\n row: Record<string, unknown>;\n}\n\nexport type MapPointDetailTone = ComposedViewTone;\n\nexport interface MapLatLng {\n lat: number;\n lng: number;\n}\n\nexport interface MapView {\n title?: string;\n points: MapPoint[];\n showRoute: boolean;\n /** The route line: `routePath` when given, else the points in their order (only when `showRoute`). */\n routeLine: MapLatLng[];\n routeLabel?: string;\n showCarousel: boolean;\n heightPx: number;\n /** Points dropped for missing or invalid coordinates. */\n droppedPointCount: number;\n /** Points past the repeat budget, not shown. */\n cappedPointCount: number;\n}\n\nexport const MAP_DEFAULT_HEIGHT_PX = 330;\nexport const MAP_MIN_HEIGHT_PX = 240;\nexport const MAP_MAX_HEIGHT_PX = 560;\n\nconst LABEL_KEYS = [\"label\", \"name\", \"title\"];\nconst LAT_KEYS = [\"lat\", \"latitude\"];\nconst LNG_KEYS = [\"lng\", \"lon\", \"long\", \"longitude\"];\nconst SUBTITLE_KEYS = [\"subtitle\", \"category\", \"type\"];\nconst DETAIL_KEYS = [\"detail\", \"status\", \"caption\"];\nconst IMAGE_KEYS = [\"image\", \"imageUrl\", \"photo\", \"thumbnail\"];\nconst ACTION_KEYS = [\"action\", \"onClick\", \"onSelect\"];\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readFirst = (record: Record<string, unknown>, keys: string[]): unknown => {\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined && record[key] !== null) {\n return record[key];\n }\n }\n return undefined;\n};\n\nconst readText = (record: Record<string, unknown>, keys: string[]): string | undefined => {\n const value = readFirst(record, keys);\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed === \"\" ? undefined : trimmed;\n};\n\nconst readNumber = (value: unknown): number | undefined => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value.trim().replace(\",\", \".\"));\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n};\n\n/** A coordinate pair inside the valid range, or undefined. Also takes `{position: {lat, lng}}` / `{location: …}`. */\nexport const readLatLng = (record: Record<string, unknown>): MapLatLng | undefined => {\n const nested = readFirst(record, [\"position\", \"location\", \"coordinates\"]);\n const source = isPlainObject(nested) ? nested : record;\n const lat = readNumber(readFirst(source, LAT_KEYS));\n const lng = readNumber(readFirst(source, LNG_KEYS));\n if (lat === undefined || lng === undefined) return undefined;\n if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return undefined;\n return { lat, lng };\n};\n\n/** Only http(s) and inline `data:image/` URLs reach an `<img src>`. */\nconst readImageUrl = (record: Record<string, unknown>): string | undefined => {\n const value = readText(record, IMAGE_KEYS);\n if (!value) return undefined;\n return /^https?:\\/\\//i.test(value) || /^data:image\\//i.test(value) ? value : undefined;\n};\n\n/** The action name: a plain string, or the event form `{\"action\": \"<name>\"}`. */\nconst readActionName = (record: Record<string, unknown>): string | undefined => {\n const value = readFirst(record, ACTION_KEYS);\n if (typeof value === \"string\" && value.trim() !== \"\") return value.trim();\n if (isPlainObject(value) && typeof value.action === \"string\" && value.action.trim() !== \"\")\n return value.action.trim();\n return undefined;\n};\n\nconst readDetailTone = (record: Record<string, unknown>): MapPointDetailTone | undefined => {\n return readOptionalComposedViewTone(readText(record, [\"detailTone\", \"statusTone\", \"tone\"]));\n};\n\nconst readRating = (record: Record<string, unknown>): number | undefined => {\n const rating = readNumber(readFirst(record, [\"rating\", \"stars\", \"score\"]));\n if (rating === undefined || rating < 0 || rating > 5) return undefined;\n return Math.round(rating * 10) / 10;\n};\n\n/**\n * One point. `fallbackActionName` is the Map's `pointAction`: the action a point without its own `action` runs — over\n * points bound to a resolved `$from` list a row-bound `openEntity` action opens each row's `entity`, since such a row carries no `action` key.\n */\nconst readPoint = (pointValue: unknown, pointIndex: number, fallbackActionName?: string): MapPoint | undefined => {\n if (!isPlainObject(pointValue)) return undefined;\n const position = readLatLng(pointValue);\n if (!position) return undefined;\n return {\n key: `point-${pointIndex}`,\n label: readText(pointValue, LABEL_KEYS) ?? \"\",\n lat: position.lat,\n lng: position.lng,\n rating: readRating(pointValue),\n subtitle: readText(pointValue, SUBTITLE_KEYS),\n detail: readText(pointValue, DETAIL_KEYS),\n detailTone: readDetailTone(pointValue),\n image: readImageUrl(pointValue),\n actionName: readActionName(pointValue) ?? fallbackActionName,\n row: pointValue,\n };\n};\n\nconst readHeight = (value: ExpressionValue | undefined): number => {\n const height = readNumber(value);\n if (height === undefined) return MAP_DEFAULT_HEIGHT_PX;\n return Math.min(MAP_MAX_HEIGHT_PX, Math.max(MAP_MIN_HEIGHT_PX, Math.round(height)));\n};\n\nconst readRoutePath = (value: ExpressionValue | undefined, maxVertices: number): MapLatLng[] => {\n if (!Array.isArray(value)) return [];\n const routePath: MapLatLng[] = [];\n for (const pathValue of value.slice(0, maxVertices)) {\n const position = isPlainObject(pathValue) ? readLatLng(pathValue) : undefined;\n if (position) routePath.push(position);\n }\n return routePath;\n};\n\nconst readTrimmedString = (value: ExpressionValue | undefined): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\n/**\n * The map view of a `Map` node's resolved props. `maxPoints` is the schema's `maxRepeatRows`; `maxRouteVertices` the\n * collection cap (a real road path from a tool is long).\n */\nexport const readMapView = (\n props: Record<string, ExpressionValue>,\n maxPoints: number,\n maxRouteVertices: number,\n): MapView => {\n const pointValues = Array.isArray(props.points) ? props.points : [];\n const cappedPointCount = Math.max(0, pointValues.length - maxPoints);\n const points: MapPoint[] = [];\n let droppedPointCount = 0;\n const pointActionName = readTrimmedString(props.pointAction);\n pointValues.slice(0, maxPoints).forEach((pointValue, pointIndex) => {\n const point = readPoint(pointValue, pointIndex, pointActionName);\n if (point) points.push(point);\n else droppedPointCount += 1;\n });\n const showRoute = props.route === true;\n const routePath = readRoutePath(props.routePath, maxRouteVertices);\n let routeLine: MapLatLng[] = [];\n if (showRoute) {\n routeLine = routePath.length >= 2 ? routePath : points.map((point) => ({ lat: point.lat, lng: point.lng }));\n }\n return {\n title: readTrimmedString(props.title),\n points,\n showRoute,\n routeLine,\n routeLabel: showRoute ? readTrimmedString(props.routeLabel) : undefined,\n showCarousel: props.carousel !== \"hidden\" && points.length > 0,\n heightPx: readHeight(props.minHeight),\n droppedPointCount,\n cappedPointCount,\n };\n};\n\n/** The rating as the owner's locale writes it (one decimal: \"4,7\" in German, \"4.7\" in English). */\nexport const formatMapRating = (rating: number, languageCode?: string): string => {\n try {\n return new Intl.NumberFormat(languageCode || undefined, {\n minimumFractionDigits: 1,\n maximumFractionDigits: 1,\n }).format(rating);\n } catch {\n return rating.toFixed(1);\n }\n};\n","import { createContext, useContext } from \"react\";\n\n/**\n * Where a `Map` node renders: `inline` in the chat (the map card with its carousel and the expand\n * control), or `fullScreen` in the `mapFullScreen` canvas (the map filling the pane beside the list of points). The\n * canvas body renders the same node through the same renderer and provides `fullScreen`; nothing else changes.\n */\nexport type MapPresentation = \"inline\" | \"fullScreen\";\n\nexport const MapPresentationContext = createContext<MapPresentation>(\"inline\");\n\nexport const useMapPresentation = () => useContext(MapPresentationContext);\n","import { exceedsJsonContainerDepth } from \"./widget-tree/bounded-json\";\n\n/**\n * The JSON of a widget block as every frontend reader decodes it — the twin of the backend's\n * `WidgetBlocks::buildWidgetJsonWithoutSurplusClosers()`: a block whose JSON does not decode is read\n * once more without the surplus closing brackets a model wrote at its end (one `}` too many after a correct tree), up to\n * {@link MAX_SURPLUS_CLOSERS} trailing `}` / `]` dropped one by one. The parity fixture `composed-view-parity.json`\n * (`surplusCloserCases`) holds both readers equal.\n */\n\n/** The most trailing `}` / `]` a block read drops to decode a block (the backend's `WidgetBlocks::MAX_SURPLUS_CLOSERS`). */\nexport const MAX_SURPLUS_CLOSERS = 3;\n\n/** The decoded value of `jsonText` when it is a JSON object no deeper than the backend decodes; undefined otherwise. */\nconst decodeJsonObject = (jsonText: string): Record<string, unknown> | undefined => {\n let decoded: unknown;\n try {\n decoded = JSON.parse(jsonText);\n } catch {\n return undefined;\n }\n if (typeof decoded !== \"object\" || decoded === null || Array.isArray(decoded) || exceedsJsonContainerDepth(decoded)) {\n return undefined;\n }\n return decoded as Record<string, unknown>;\n};\n\n/**\n * The block JSON without its surplus trailing closers, or null when it decodes as written or when no shortened text\n * decodes to a JSON object — exactly the backend's answer.\n */\nexport const readWidgetJsonWithoutSurplusClosers = (widgetJson: string): string | null => {\n if (decodeJsonObject(widgetJson) !== undefined) return null;\n let candidateJson = widgetJson.trimEnd();\n for (let droppedCloserCount = 0; droppedCloserCount < MAX_SURPLUS_CLOSERS; droppedCloserCount++) {\n const lastCharacter = candidateJson.slice(-1);\n if (lastCharacter !== \"}\" && lastCharacter !== \"]\") return null;\n candidateJson = candidateJson.slice(0, -1).trimEnd();\n if (decodeJsonObject(candidateJson) !== undefined) return candidateJson;\n }\n return null;\n};\n\n/** The block's JSON object — as written, or without its surplus trailing closers; undefined for a malformed block. */\nexport const parseWidgetJsonObject = (widgetJson: string): Record<string, unknown> | undefined =>\n decodeJsonObject(widgetJson) ?? decodeJsonObject(readWidgetJsonWithoutSurplusClosers(widgetJson) ?? \"\");\n","import { visit } from \"unist-util-visit\";\nimport { BARE_WIDGET_PARAGRAPH, WIDGET_FENCE_LANG } from \"./widget-fence-syntax\";\nimport { resolveWidgetName } from \"./widget-name-resolver\";\nimport { parseWidgetJsonObject } from \"./widget-fence-json\";\nimport { buildWidgetAgentSpaceKeyProps, readWidgetAgentSpaceKeyAttribute } from \"./_agent-space/widget-agent-space-key-attribute\";\n\n/**\n * Render a widget the agent emitted in either form:\n *\n * 1. a ```widget fenced code block (the base-prompt convention):\n * ```widget\n * { \"type\": \"<WidgetName>\", ...fields }\n * ```\n * 2. a bare `widget { \"type\": \"<WidgetName>\", ...fields }` line (no fence) — the same intent when the model\n * drops the backticks, which happens in practice. Markdown parses this as a plain `paragraph`, so it never\n * reached the fence path and leaked as raw JSON to the customer (the block shown verbatim).\n *\n * Both are rewritten into the SAME `leafDirective` node that `::WidgetName{payload='…'}` produces, so the existing\n * pipeline (conversationWidgetAstPlugin → ConversationWidgetHost → feature-gate → hydration) renders it unchanged —\n * the non-`type` fields become the node's `payload` (a JSON string), exactly what the widgets parse.\n *\n * MUST run BEFORE conversationWidgetAstPlugin. The `type` is resolved through the ONE legacy rule\n * (`resolveWidgetName`): the canonical `ExampleWidget` matches exactly, the legacy `ExampleWidgetDirective` resolves\n * onto it. A block whose JSON decodes only without surplus trailing `}` / `]` renders like the backend reads it\n * (`widget-fence-json.ts`). A malformed JSON block or an unknown widget name is dropped (renders nothing) — the kill switch; never leak\n * raw JSON or a `:name` fallback to the user.\n */\nexport default function remarkWidgetFencePlugin() {\n // `resolveWidgetName` (widget-name-resolver) is the ONE source of truth for \"is this a real widget\", shared with\n // the unrendered-widget detector so a dropped block here and a reported block there always agree.\n return (tree: any) => {\n // In-place replacement only (no splice) so the visitor's indices stay valid: rewrite the node into a\n // `leafDirective`, or drop it to an empty text node (malformed JSON / unknown widget → render nothing).\n const rewrite = (parent: any, index: number, widgetJson: string) => {\n const drop = () => {\n parent.children[index] = { type: \"text\", value: \"\" };\n };\n\n // A JSON object as written or without the model's surplus trailing `}` / `]` (the backend reads it the same way);\n // deeper than the backend decodes (`json_decode(…, 32)`), not an object, or malformed → dropped.\n const parsed = parseWidgetJsonObject(widgetJson);\n if (parsed === undefined) {\n drop();\n return;\n }\n\n const { type, ...fields } = parsed as Record<string, unknown>;\n const widgetName = typeof type === \"string\" ? resolveWidgetName(type) : undefined;\n if (!widgetName) {\n drop(); // unknown / unsupported widget → render nothing\n return;\n }\n\n const agentSpaceKeyAttribute = readWidgetAgentSpaceKeyAttribute(fields);\n parent.children[index] = {\n // `\"leafDirective\"` is remark-directive's node type — its contract, not our vocabulary.\n type: \"leafDirective\",\n name: widgetName,\n // The fence's place in the message travels on: it is the block's identity in the render report (two blocks\n // of one type in one message are told apart by it) — without it every block sat at offset 0.\n ...(parent.children[index]?.position ? { position: parent.children[index].position } : {}),\n attributes: {\n payload: JSON.stringify(fields),\n // The agent space key is the one fence field the FRAMEWORK consumes rather than the widget: the block field\n // the app declares (`AgentsEnvironment.widgetSelfHydrationKeyFieldName`) is documented on every widget and\n // resolved centrally by `useResolvedConversationWidgetAgentSpaceKey`. Without lifting it here it stayed\n // buried in the payload string and never arrived as a prop, so a fence targeting another agent space\n // silently rendered the ACTIVE agent space's data — every widget except the ones that happened to parse\n // it back out themselves. Carried as a string under the declared field name, matching what the\n // `::Name{<field>=123}` attribute form delivers; the resolver normalizes both. It stays in the payload too,\n // so widgets that parse it keep working.\n ...buildWidgetAgentSpaceKeyProps(agentSpaceKeyAttribute === undefined ? undefined : String(agentSpaceKeyAttribute)),\n },\n children: [],\n data: {},\n };\n };\n\n // Concatenate a node's text (paragraph children are text nodes; the bare JSON carries no markdown syntax).\n const textOf = (node: any): string =>\n typeof node.value === \"string\"\n ? node.value\n : Array.isArray(node.children)\n ? node.children.map(textOf).join(\"\")\n : \"\";\n\n visit(tree, (node: any, index, parent) => {\n if (!parent || index === null || index === undefined) {\n return;\n }\n if (node.type === \"code\") {\n if (node.lang !== WIDGET_FENCE_LANG) {\n return;\n }\n rewrite(parent, index, node.value);\n return;\n }\n if (node.type === \"paragraph\") {\n const match = BARE_WIDGET_PARAGRAPH.exec(textOf(node));\n if (match) {\n rewrite(parent, index, match[1]);\n }\n }\n });\n };\n}\n","import { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport remarkDirective from \"remark-directive\";\nimport { visit } from \"unist-util-visit\";\nimport remarkWidgetFencePlugin from \"../remarkWidgetFencePlugin\";\nimport { resolveWidgetName } from \"../widget-name-resolver\";\nimport { readWidgetAgentSpaceKeyAttribute } from \"../_agent-space/widget-agent-space-key-attribute\";\nimport { shortStringHash } from \"./canvas-state\";\nimport { getComposedViewSubtreeNodes, parseComposedViewTree } from \"../widget-tree/composed-view-tree\";\n\n/** The wire name of the composable widget kit — its tree may embed domain widgets as `Widget` nodes. */\nconst COMPOSED_VIEW_WIDGET_NAME = \"ComposedView\";\n\n/** One widget the anchor message carries — what a canvas body parses its own payload from. */\nexport interface WidgetFenceInMessage {\n /** The CANONICAL wire name (a stored legacy `<Name>Directive` resolves onto it). */\n readonly name: string;\n /** The fence's non-`type` fields as the JSON string every widget parser takes (`payload`). */\n readonly payload: string;\n /** The agent space key the framework lifts out of the fence (the block field the app declares), when present. */\n readonly agentSpaceKey?: string;\n /** `shortStringHash(payload)` — what `canvasInstanceIdForMessagePayload` puts into the instance id. */\n readonly payloadHash: string;\n /** Every string attribute of the node (`target`, `mode`, … — widgets that do not use `payload`). */\n readonly attributes: Readonly<Record<string, string>>;\n}\n\n/**\n * Every widget in a message's markdown, in document order, through the SAME pipeline the message renders with\n * (`remarkDirective` for the stored `::Name{payload='…'}` form, `remarkWidgetFencePlugin` for the ```widget fence and\n * the bare `widget { … }` line) — so a canvas body re-reads exactly the payload its inline widget rendered from, in\n * both the canonical and the legacy wire form. Malformed or unknown widgets are dropped, as when rendering.\n *\n * A `ComposedView` block is followed by the domain widgets its tree embeds (`Widget` nodes), each as if\n * its own fence stood there — `payload` = the node's `fields` — so a canvas opened from a widget in a slot finds its\n * payload like any other canvas body, and the reload restore finds the widget that opens the canvas.\n *\n * Shell-side only (the pipeline imports the widget registry through the name resolver): imported by canvas bodies,\n * never by the slice or the canvas model modules.\n */\nexport const findWidgetFencesInMarkdown = (markdown: string): WidgetFenceInMessage[] => {\n if (!markdown) return [];\n const processor = unified().use(remarkParse).use(remarkDirective).use(remarkWidgetFencePlugin);\n const tree = processor.runSync(processor.parse(markdown));\n const fences: WidgetFenceInMessage[] = [];\n visit(tree, \"leafDirective\", (node: any) => {\n const name = typeof node.name === \"string\" ? resolveWidgetName(node.name) : undefined;\n if (!name) return;\n const attributes = (node.attributes ?? {}) as Record<string, unknown>;\n const payload = typeof attributes.payload === \"string\" ? attributes.payload : \"{}\";\n const stringAttributes = Object.fromEntries(\n Object.entries(attributes).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"),\n );\n const agentSpaceKey = readWidgetAgentSpaceKeyAttribute(attributes);\n fences.push({\n name,\n payload,\n ...(typeof agentSpaceKey === \"string\" ? { agentSpaceKey } : {}),\n payloadHash: shortStringHash(payload),\n attributes: stringAttributes,\n });\n if (name === COMPOSED_VIEW_WIDGET_NAME) fences.push(...findWidgetsEmbeddedInComposedView(payload));\n });\n return fences;\n};\n\n/**\n * The domain widgets a `ComposedView` payload embeds (its KEPT `Widget` nodes — only embeddable ones survive the\n * reader), in tree order, as fences. Total: a payload the reader cannot take gives none, it never throws (the canvas\n * restore and the anchor lookups call this outside any error boundary).\n */\nconst findWidgetsEmbeddedInComposedView = (composedViewPayload: string): WidgetFenceInMessage[] => {\n try {\n return readWidgetsEmbeddedInComposedView(composedViewPayload);\n } catch {\n return [];\n }\n};\n\nconst readWidgetsEmbeddedInComposedView = (composedViewPayload: string): WidgetFenceInMessage[] => {\n const tree = parseComposedViewTree(composedViewPayload);\n if (tree.view === null) return [];\n const embeddedFences: WidgetFenceInMessage[] = [];\n for (const node of getComposedViewSubtreeNodes(tree.view)) {\n if (node.type !== \"Widget\" || typeof node.props.widget !== \"string\") continue;\n const name = resolveWidgetName(node.props.widget);\n if (!name) continue;\n const fields = typeof node.props.fields === \"object\" && node.props.fields !== null ? node.props.fields : {};\n const payload = JSON.stringify(fields);\n const agentSpaceKey = readWidgetAgentSpaceKeyAttribute(fields);\n embeddedFences.push({\n name,\n payload,\n ...(agentSpaceKey !== undefined ? { agentSpaceKey: String(agentSpaceKey) } : {}),\n payloadHash: shortStringHash(payload),\n attributes: { payload },\n });\n }\n return embeddedFences;\n};\n\n/**\n * The fence a canvas is anchored on: the widget of `name` whose payload hash the canvas instance id carries\n * (`canvasInstanceIdForMessagePayload`). Two identical widgets in one message share one canvas by design.\n */\nexport const findWidgetFenceByPayloadHash = (\n markdown: string,\n name: string,\n payloadHash: string,\n): WidgetFenceInMessage | undefined =>\n findWidgetFencesInMarkdown(markdown).find((fence) => fence.name === name && fence.payloadHash === payloadHash);\n","import { shortStringHash } from \"../../../renderer/canvas/canvas-state\";\nimport { findWidgetFencesInMarkdown } from \"../../../renderer/canvas/find-widget-fences-in-markdown\";\nimport {\n getComposedViewSubtreeNodes,\n parseComposedViewTree,\n type ComposedViewNode,\n type ComposedViewTree,\n} from \"../../../renderer/widget-tree/composed-view-tree\";\n\n/**\n * Which `Map` node a `mapFullScreen` canvas shows. A canvas is a pointer to its anchor message, so the\n * instance id carries only the message and a short hash of the node — its id and its\n * wire props — and the body finds the node again in the message's `ComposedView` fences. Two identical maps in one\n * message are one canvas; a map whose message no longer carries it opens nothing.\n *\n * Format `mapFullScreen:message:<messageId>:map-<hash>` — the `map-` part keeps it apart from the payload-hash form\n * (`payloadHashOfInstanceId`), which the shared canvas helpers would otherwise read as a fence hash.\n */\n\nexport const MAP_NODE_TYPE = \"Map\";\nconst COMPOSED_VIEW_WIDGET_NAME = \"ComposedView\";\nconst MAP_FULL_SCREEN_INSTANCE_ID = /^mapFullScreen:message:(\\d+):map-([0-9a-z]+)$/;\n\n/** The short hash of a map node: its id and its props as written (bindings unresolved), so it is stable across renders. */\nexport const buildMapNodeKey = (mapNode: ComposedViewNode): string =>\n shortStringHash(JSON.stringify({ id: mapNode.id, props: mapNode.props }));\n\nexport const canvasInstanceIdForMapFullScreen = (messageId: number, mapNode: ComposedViewNode): string =>\n `mapFullScreen:message:${messageId}:map-${buildMapNodeKey(mapNode)}`;\n\n/** The map node key a `mapFullScreen` instance id carries, or undefined for another shape. */\nexport const readMapNodeKeyOfInstanceId = (instanceId: string): string | undefined =>\n MAP_FULL_SCREEN_INSTANCE_ID.exec(instanceId)?.[2];\n\nexport interface MapNodeInComposedView {\n /** The whole tree the map sits in — its state, data, computed values and actions resolve the map's bindings. */\n tree: ComposedViewTree;\n mapNode: ComposedViewNode;\n}\n\n/**\n * The `Map` node with this key among the `ComposedView` fences of a message, with its tree. Total: an unparsable\n * message or a missing map gives undefined, never a throw (a canvas body runs outside the message's error boundary).\n */\nexport const findMapNodeInMarkdown = (markdown: string, mapNodeKey: string): MapNodeInComposedView | undefined => {\n try {\n for (const fence of findWidgetFencesInMarkdown(markdown)) {\n if (fence.name !== COMPOSED_VIEW_WIDGET_NAME) continue;\n const tree = parseComposedViewTree(fence.payload);\n if (tree.view === null) continue;\n const mapNode = getComposedViewSubtreeNodes(tree.view).find(\n (node) => node.type === MAP_NODE_TYPE && buildMapNodeKey(node) === mapNodeKey,\n );\n if (mapNode) return { tree, mapNode };\n }\n } catch {\n return undefined;\n }\n return undefined;\n};\n","import { Button, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { formatMapRating, type MapPoint } from \"./map-points\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapPointMarkerProps {\n point: MapPoint;\n /** 1-based, shown instead of the rating when the map draws a route (the stops in their order). */\n routeStopNumber?: number;\n isSelected: boolean;\n languageCode?: string;\n /** Undefined → a static pin (the e-mail capture): no button, nothing to focus. */\n onClick?: () => void;\n}\n\n/**\n * One point on the map: a small dark pill — the rating with a star, the stop number on a route, or a\n * plain dot — over the point's label with a halo so it reads on any map tile. The pill is a component-library muted `onDark`\n * Button; only the pill takes clicks, never the label.\n */\nexport const MapPointMarker = (props: MapPointMarkerProps) => {\n const { point, routeStopNumber, isSelected, languageCode, onClick } = props;\n const hasRating = point.rating !== undefined && routeStopNumber === undefined;\n let pillText = \"•\";\n if (routeStopNumber !== undefined) pillText = String(routeStopNumber);\n else if (point.rating !== undefined) pillText = formatMapRating(point.rating, languageCode);\n\n return (\n <div\n className={classNames(styles.marker, isSelected && styles.markerSelected)}\n data-testid=\"map-point-marker\"\n data-point-key={point.key}\n >\n <span\n // The component library's Button takes no aria-label: the point's name goes onto its native button.\n ref={(node) => {\n if (point.label) node?.querySelector(\"button\")?.setAttribute(\"aria-label\", point.label);\n }}\n className={classNames(styles.markerPill, onClick && styles.markerPillInteractive)}\n inert={!onClick}\n aria-hidden={onClick ? undefined : \"true\"}\n >\n <Button\n variant=\"muted\"\n size=\"small\"\n rounded\n onDark\n pressed={onClick ? isSelected : undefined}\n icon={hasRating ? \"starActive\" : undefined}\n translate={false}\n onClick={onClick}\n testId={`map-point-marker-pill-${point.key}`}\n >\n {pillText}\n </Button>\n </span>\n {point.label ? (\n <span className={styles.markerLabel}>\n <Text role=\"caption\" weight=\"medium\" display=\"inline\" translate={false}>\n {escapePlainTextForText(point.label)}\n </Text>\n </span>\n ) : null}\n </div>\n );\n};\n","import { useCallback, useContext, useEffect, useState } from \"react\";\nimport { Map as AgentsMap, MapMarker } from \"../../../provider/components\";\nimport { WidgetImageReadinessContext } from \"../../../image-render/WidgetImageRenderContext\";\nimport type { MapPoint, MapView } from \"./map-points\";\nimport { MapPointMarker } from \"./MapPointMarker\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapGoogleMapProps {\n mapView: MapView;\n selectedPointKey?: string;\n languageCode?: string;\n /** The Google SDK is loaded (`useGoogleMapApiLoader`, the one loader of the app). */\n isJsApiLoaded: boolean;\n isEmailRender: boolean;\n /** Undefined → markers are static (the e-mail capture, a replay without interaction). */\n onPointClick?: (point: MapPoint) => void;\n /** Extra bottom room kept free of points when fitting — the carousel lies over the map's bottom edge. */\n bottomOverlayPx: number;\n className?: string;\n}\n\nconst FIT_PADDING_PX = 48;\nconst SINGLE_POINT_ZOOM = 15;\nconst ROUTE_STROKE_WEIGHT = 4;\nconst ROUTE_STROKE_OPACITY = 0.85;\n/** Used only when the theme token cannot be read (a host without the theme stylesheet). */\nconst ROUTE_STROKE_FALLBACK = \"#1f2329\";\n\n/** The route line's colour: the theme's foreground token, read once at draw time (the SDK takes a colour, not a var). */\nconst readRouteStrokeColor = (mapDiv: HTMLElement | null): string => {\n if (!mapDiv) return ROUTE_STROKE_FALLBACK;\n const tokenValue = getComputedStyle(mapDiv).getPropertyValue(\"--agents-fg\").trim();\n return tokenValue || ROUTE_STROKE_FALLBACK;\n};\n\n/**\n * The Google map of a `Map` node: the environment's map (the app supplies the key and the map id), one marker per point, the route polyline when the node asks\n * for one, the view fitted to every point and the route, and a pan to the selected point. In the e-mail capture the\n * map has no controls and no gestures, and it reports `MAP_SDK_LOAD_FAILED` to the capture readiness on a load error.\n */\nexport const MapGoogleMap = (props: MapGoogleMapProps) => {\n const {\n mapView,\n selectedPointKey,\n languageCode,\n isJsApiLoaded,\n isEmailRender,\n onPointClick,\n bottomOverlayPx,\n className,\n } = props;\n const readiness = useContext(WidgetImageReadinessContext);\n const [map, setMap] = useState<google.maps.Map>();\n const [hasTilesLoaded, setHasTilesLoaded] = useState(false);\n const handleOnLoad = useCallback((loadedMap: google.maps.Map) => setMap(loadedMap), []);\n // The first frame's centre only — a centre prop that changed on every render would undo every pan and fit.\n const [initialCenter] = useState(() =>\n mapView.points[0] ? { lat: mapView.points[0].lat, lng: mapView.points[0].lng } : undefined,\n );\n\n // The view: every point and the whole route; one point alone gets a street-level zoom instead of a fit.\n const fitKey = JSON.stringify([mapView.points.map((point) => [point.lat, point.lng]), mapView.routeLine.length]);\n useEffect(() => {\n if (!map || typeof google === \"undefined\") return;\n const positions = [...mapView.points, ...mapView.routeLine];\n if (positions.length === 0) return;\n if (positions.length === 1) {\n map.setCenter({ lat: positions[0].lat, lng: positions[0].lng });\n map.setZoom(SINGLE_POINT_ZOOM);\n return;\n }\n const bounds = new google.maps.LatLngBounds();\n positions.forEach((position) => bounds.extend({ lat: position.lat, lng: position.lng }));\n map.fitBounds(bounds, {\n top: FIT_PADDING_PX,\n right: FIT_PADDING_PX,\n bottom: FIT_PADDING_PX + bottomOverlayPx,\n left: FIT_PADDING_PX,\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map, fitKey, bottomOverlayPx]);\n\n // The route line through the stops (or the tool's path), removed with the map or a new route.\n useEffect(() => {\n if (!map || typeof google === \"undefined\" || mapView.routeLine.length < 2) return;\n const routePolyline = new google.maps.Polyline({\n path: mapView.routeLine,\n map,\n strokeColor: readRouteStrokeColor(map.getDiv()),\n strokeWeight: ROUTE_STROKE_WEIGHT,\n strokeOpacity: ROUTE_STROKE_OPACITY,\n clickable: false,\n });\n return () => routePolyline.setMap(null);\n }, [map, mapView.routeLine]);\n\n // A click on a card or a marker brings its point into view.\n useEffect(() => {\n const selectedPoint = mapView.points.find((point) => point.key === selectedPointKey);\n if (map && selectedPoint) map.panTo({ lat: selectedPoint.lat, lng: selectedPoint.lng });\n }, [map, selectedPointKey, mapView.points]);\n\n // The e-mail capture waits for the tiles; a map that cannot render fails the capture instead of a blank image.\n useEffect(() => {\n if (!map || !isEmailRender) return;\n const tilesListener = map.addListener(\"tilesloaded\", () => setHasTilesLoaded(true));\n return () => tilesListener.remove();\n }, [map, isEmailRender]);\n useEffect(() => {\n if (isEmailRender && isJsApiLoaded && mapView.points.length === 0) readiness?.fail(\"MAP_COORDINATES_MISSING\");\n }, [isEmailRender, isJsApiLoaded, mapView.points.length, readiness]);\n\n const staticOptions: google.maps.MapOptions = isEmailRender\n ? {\n disableDefaultUI: true,\n zoomControl: false,\n fullscreenControl: false,\n mapTypeControl: false,\n keyboardShortcuts: false,\n gestureHandling: \"none\",\n clickableIcons: false,\n }\n : { fullscreenControl: false, clickableIcons: false };\n\n return (\n <div className={className} aria-busy={isEmailRender ? !hasTilesLoaded : undefined}>\n <AgentsMap\n testId=\"ComposedViewMap-GoogleMaps\"\n isLoaded={isJsApiLoaded}\n languageCode={languageCode}\n onLoad={handleOnLoad}\n zoom={12}\n center={initialCenter}\n className={styles.mapContainer}\n options={{\n ...staticOptions,\n streetViewControl: false,\n mapTypeControlOptions: { mapTypeIds: [] },\n }}\n >\n {mapView.points.map((point, pointIndex) => (\n <MapMarker\n key={point.key}\n id={`composed-map-${point.key}`}\n isLoaded={isJsApiLoaded}\n position={{ lat: point.lat, lng: point.lng }}\n zIndex={point.key === selectedPointKey ? 20 : 10}\n title={point.label || undefined}\n >\n <MapPointMarker\n point={point}\n routeStopNumber={mapView.showRoute ? pointIndex + 1 : undefined}\n isSelected={point.key === selectedPointKey}\n languageCode={languageCode}\n onClick={onPointClick ? () => onPointClick(point) : undefined}\n />\n </MapMarker>\n ))}\n </AgentsMap>\n </div>\n );\n};\n","import { Icon, InteractiveSurface, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useState } from \"react\";\nimport { COMPOSED_VIEW_TONE_TEXT_COLOR } from \"../../composed-view-tones\";\nimport { formatMapRating, type MapPoint } from \"./map-points\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapPointCardProps {\n point: MapPoint;\n /** `carousel`: a card along the map's bottom edge (inline); `row`: a row of the full-screen list. */\n variant: \"carousel\" | \"row\";\n isSelected: boolean;\n languageCode?: string;\n /** 1-based stop number on a route. */\n routeStopNumber?: number;\n /** Undefined → a static card (the e-mail capture). */\n onClick?: () => void;\n}\n\n/**\n * One point as a card: the thumbnail, the label, the rating with its category, and the\n * status line. Clickable through the GlobalStateComponent hover layer around a native button; selected = the inner CTA\n * ring. A point without an image shows the pin glyph on a flat tile, never an empty box.\n */\nexport const MapPointCard = (props: MapPointCardProps) => {\n const { point, variant, isSelected, languageCode, routeStopNumber, onClick } = props;\n const [isImageBroken, setIsImageBroken] = useState(false);\n const showImage = point.image !== undefined && !isImageBroken;\n\n const ratingLine = [\n point.rating !== undefined ? formatMapRating(point.rating, languageCode) : undefined,\n point.subtitle,\n ].filter((part): part is string => part !== undefined);\n\n const content = (\n <>\n <span className={styles.cardThumbnail} aria-hidden=\"true\">\n {showImage ? (\n <img src={point.image} alt=\"\" loading=\"lazy\" onError={() => setIsImageBroken(true)} />\n ) : routeStopNumber !== undefined ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {String(routeStopNumber)}\n </Text>\n ) : (\n <Icon className={styles.cardThumbnailIcon} name=\"pinFilled\" />\n )}\n </span>\n <span className={styles.cardText}>\n {point.label ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(point.label)}\n </Text>\n ) : null}\n {ratingLine.length > 0 ? (\n <span className={styles.cardMeta}>\n {point.rating !== undefined ? (\n <Icon className={styles.cardStar} size=\"small\" name=\"starActive\" />\n ) : null}\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(ratingLine.join(\" · \"))}\n </Text>\n </span>\n ) : null}\n {point.detail ? (\n <Text\n role=\"caption\"\n weight={point.detailTone ? \"medium\" : undefined}\n color={point.detailTone ? COMPOSED_VIEW_TONE_TEXT_COLOR[point.detailTone] : \"var(--agents-fg-light)\"}\n translate={false}\n >\n {escapePlainTextForText(point.detail)}\n </Text>\n ) : null}\n </span>\n </>\n );\n\n const cardClassName = classNames(\n styles.card,\n variant === \"carousel\" ? styles.cardCarousel : styles.cardRow,\n isSelected && styles.cardSelected,\n );\n if (!onClick) {\n return (\n <div className={cardClassName} data-point-key={point.key}>\n <span className={styles.cardInner}>{content}</span>\n </div>\n );\n }\n return (\n <InteractiveSurface hoverable className={cardClassName}>\n <button\n type=\"button\"\n className={classNames(styles.cardInner, styles.cardButton)}\n onClick={onClick}\n aria-pressed={isSelected}\n data-point-key={point.key}\n data-testid=\"map-point-card\"\n >\n {content}\n </button>\n </InteractiveSurface>\n );\n};\n","import { Icon, InteractiveSurface } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport type { MapPoint } from \"./map-points\";\nimport { MapPointCard } from \"./MapPointCard\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapPointCarouselProps {\n points: MapPoint[];\n selectedPointKey?: string;\n languageCode?: string;\n /** Whether the points are the stops of a route — the cards then show their stop number. */\n isRoute: boolean;\n /** Undefined → static cards and no paging buttons (the e-mail capture). */\n onPointSelect?: (point: MapPoint) => void;\n}\n\n/** Whether the track can scroll further back / forward (a pixel of rounding counts as the end). */\nconst readScrollEdges = (track: HTMLDivElement) => ({\n canScrollBack: track.scrollLeft > 1,\n canScrollForward: track.scrollLeft + track.clientWidth < track.scrollWidth - 1,\n});\n\nconst prefersReducedMotion = (): boolean =>\n typeof window !== \"undefined\" && (window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false);\n\n/**\n * The point cards along the map's bottom edge: one horizontal, snapping row the owner pages through\n * by swipe, trackpad or the previous / next buttons, which show only while there is a card to scroll to — without\n * them a mouse could not reach the cards past the second one (the row hides its scrollbar so the map stays clean). A\n * selected point (a marker click) scrolls its card into view.\n */\nexport const MapPointCarousel = (props: MapPointCarouselProps) => {\n const { points, selectedPointKey, languageCode, isRoute, onPointSelect } = props;\n const trackRef = useRef<HTMLDivElement>(null);\n const [scrollEdges, setScrollEdges] = useState({ canScrollBack: false, canScrollForward: false });\n const isPageable = onPointSelect !== undefined;\n\n const updateScrollEdges = useCallback(() => {\n if (trackRef.current) setScrollEdges(readScrollEdges(trackRef.current));\n }, []);\n\n useEffect(() => {\n const track = trackRef.current;\n if (!track) return undefined;\n updateScrollEdges();\n track.addEventListener(\"scroll\", updateScrollEdges, { passive: true });\n const resizeObserver = typeof ResizeObserver === \"undefined\" ? undefined : new ResizeObserver(updateScrollEdges);\n resizeObserver?.observe(track);\n return () => {\n track.removeEventListener(\"scroll\", updateScrollEdges);\n resizeObserver?.disconnect();\n };\n }, [updateScrollEdges, points.length]);\n\n // A marker click selects a point whose card may sit outside the row's visible part: bring it in.\n useEffect(() => {\n const track = trackRef.current;\n if (!track || selectedPointKey === undefined) return;\n const selectedCard = Array.from(track.querySelectorAll<HTMLElement>(\"[data-point-key]\")).find(\n (cardElement) => cardElement.dataset.pointKey === selectedPointKey,\n );\n if (!selectedCard) return;\n const trackBox = track.getBoundingClientRect();\n const cardBox = selectedCard.getBoundingClientRect();\n if (cardBox.left >= trackBox.left && cardBox.right <= trackBox.right) return;\n track.scrollBy?.({\n left: cardBox.left < trackBox.left ? cardBox.left - trackBox.left : cardBox.right - trackBox.right,\n behavior: prefersReducedMotion() ? \"auto\" : \"smooth\",\n });\n }, [selectedPointKey]);\n\n const scrollByCard = (direction: 1 | -1) => {\n const track = trackRef.current;\n if (!track) return;\n const firstCard = track.firstElementChild as HTMLElement | null;\n const cardStep = firstCard ? firstCard.getBoundingClientRect().width : track.clientWidth;\n track.scrollBy?.({ left: direction * cardStep, behavior: prefersReducedMotion() ? \"auto\" : \"smooth\" });\n };\n\n return (\n <div className={styles.carouselViewport}>\n <div ref={trackRef} className={styles.carousel} role=\"list\" data-testid=\"map-carousel\">\n {points.map((point, pointIndex) => (\n <div\n role=\"listitem\"\n key={point.key}\n className={styles.carouselItem}\n data-testid={`map-carousel-item-${point.key}`}\n >\n <MapPointCard\n point={point}\n variant=\"carousel\"\n isSelected={point.key === selectedPointKey}\n languageCode={languageCode}\n routeStopNumber={isRoute ? pointIndex + 1 : undefined}\n onClick={onPointSelect ? () => onPointSelect(point) : undefined}\n />\n </div>\n ))}\n </div>\n {isPageable && scrollEdges.canScrollBack ? (\n <InteractiveSurface hoverable className={classNames(styles.carouselArrow, styles.carouselArrowPrevious)}>\n <button\n type=\"button\"\n className={styles.carouselArrowButton}\n aria-label={translateText(\"Show the previous slides\")}\n onClick={() => scrollByCard(-1)}\n data-testid=\"map-carousel-previous\"\n >\n <Icon name=\"arrowLeft\" />\n </button>\n </InteractiveSurface>\n ) : null}\n {isPageable && scrollEdges.canScrollForward ? (\n <InteractiveSurface hoverable className={classNames(styles.carouselArrow, styles.carouselArrowNext)}>\n <button\n type=\"button\"\n className={styles.carouselArrowButton}\n aria-label={translateText(\"Show the next slides\")}\n onClick={() => scrollByCard(1)}\n data-testid=\"map-carousel-next\"\n >\n <Icon name=\"arrowRight\" />\n </button>\n </InteractiveSurface>\n ) : null}\n </div>\n );\n};\n","import { Icon, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { translateText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { MapPoint, MapView } from \"./map-points\";\nimport type { MapPresentation } from \"./map-presentation-context\";\nimport { MapGoogleMap } from \"./MapGoogleMap\";\nimport { MapPointCard } from \"./MapPointCard\";\nimport { MapPointCarousel } from \"./MapPointCarousel\";\nimport styles from \"./Map.module.scss\";\n\nexport interface ComposedMapViewProps {\n mapView: MapView;\n presentation: MapPresentation;\n /** A bound `points` prop still waits for its data. */\n isPending: boolean;\n /** The Google SDK state from the app's one loader (`useGoogleMapApiLoader`). */\n isJsApiLoaded: boolean;\n hasLoadError: boolean;\n isEmailRender: boolean;\n languageCode?: string;\n selectedPointKey?: string;\n /** Undefined → points are static (the e-mail capture). */\n onPointSelect?: (point: MapPoint) => void;\n /** Undefined → no expand control (the e-mail capture, a reply still streaming, the full-screen canvas itself). */\n onExpand?: () => void;\n /** The `mapFullScreen` canvas shows this map now: the control closes it again. */\n isShownFullScreen?: boolean;\n}\n\n/** The bottom band the inline carousel covers, kept free of points when the map fits its view. */\nconst CAROUSEL_OVERLAY_PX = 112;\n\n/**\n * The look of a `Map` node. Inline: the map in a rounded frame, the\n * route line's label top left, the expand control top right, the point cards along the bottom edge. Full screen (the\n * `mapFullScreen` canvas): the map filling the pane beside the list of every point. Loading is a frame-shaped\n * skeleton; no points renders nothing; a map that cannot load keeps its cards with one muted line in the frame —\n * the component reports each.\n */\nexport const ComposedMapView = (props: ComposedMapViewProps) => {\n const {\n mapView,\n presentation,\n isPending,\n isJsApiLoaded,\n hasLoadError,\n isEmailRender,\n languageCode,\n selectedPointKey,\n onPointSelect,\n onExpand,\n isShownFullScreen = false,\n } = props;\n const isFullScreen = presentation === \"fullScreen\";\n const frameStyle = isFullScreen ? undefined : { height: mapView.heightPx };\n\n if (isPending) {\n return (\n <div className={styles.frame} style={frameStyle} aria-busy=\"true\" data-testid=\"map-skeleton\">\n <SkeletonLine width=\"100%\" height={mapView.heightPx} radius={0} />\n </div>\n );\n }\n // No points: nothing on screen (the prose answer stands); the node reports `empty` so the model knows.\n if (mapView.points.length === 0) return null;\n\n // Without the map the cards are the only place the points show, so they stay even when the node hid them.\n const showCarousel = mapView.showCarousel || hasLoadError;\n const routeStopNumberOf = (pointIndex: number) => (mapView.showRoute ? pointIndex + 1 : undefined);\n // A map that cannot load keeps its points: the frame shows one muted line where the map would be, the cards and the\n // full-screen list stay.\n const googleMap = hasLoadError ? (\n <div className={styles.mapUnavailable} data-testid=\"map-unavailable\">\n <Text role=\"help\" color=\"var(--agents-fg-light)\">\n {\"The map could not be loaded.\"}\n </Text>\n </div>\n ) : isJsApiLoaded ? (\n <MapGoogleMap\n className={styles.mapLayer}\n mapView={mapView}\n selectedPointKey={selectedPointKey}\n languageCode={languageCode}\n isJsApiLoaded={isJsApiLoaded}\n isEmailRender={isEmailRender}\n onPointClick={onPointSelect}\n bottomOverlayPx={!isFullScreen && showCarousel ? CAROUSEL_OVERLAY_PX : 0}\n />\n ) : (\n <div className={styles.mapLayer} aria-busy=\"true\">\n <SkeletonLine width=\"100%\" height={mapView.heightPx} radius={0} />\n </div>\n );\n const routeChip = mapView.routeLabel ? (\n <div className={styles.routeChip} data-testid=\"map-route-label\">\n <Icon className={styles.routeChipIcon} size=\"small\" name=\"clock\" />\n <Text role=\"caption\" weight=\"medium\" translate={false}>\n {escapePlainTextForText(mapView.routeLabel)}\n </Text>\n </div>\n ) : null;\n\n if (isFullScreen) {\n return (\n <div className={styles.fullScreen} data-testid=\"map-full-screen\">\n <div className={styles.fullScreenMap}>\n {googleMap}\n {routeChip}\n </div>\n <aside className={styles.fullScreenList}>\n <div className={styles.fullScreenHeader}>\n {mapView.title ? (\n <Text role=\"intro\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(mapView.title)}\n </Text>\n ) : null}\n <Text\n role=\"caption\"\n color=\"var(--agents-fg-light)\"\n replacements={{ count: mapView.points.length }}\n context={mapView.points.length === 1 ? \"one\" : \"other\"}\n >\n {\"%count% place\"}\n </Text>\n </div>\n <div className={styles.fullScreenRows} role=\"list\" data-testid=\"map-full-screen-list\">\n {mapView.points.map((point, pointIndex) => (\n <div role=\"listitem\" key={point.key} data-testid={`map-full-screen-row-${point.key}`}>\n <MapPointCard\n point={point}\n variant=\"row\"\n isSelected={point.key === selectedPointKey}\n languageCode={languageCode}\n routeStopNumber={routeStopNumberOf(pointIndex)}\n onClick={onPointSelect ? () => onPointSelect(point) : undefined}\n />\n </div>\n ))}\n </div>\n </aside>\n </div>\n );\n }\n\n return (\n <div className={styles.frame} style={frameStyle} data-testid=\"map-inline\">\n {googleMap}\n {routeChip}\n {onExpand ? (\n <button\n type=\"button\"\n className={styles.expandButton}\n onClick={onExpand}\n aria-pressed={isShownFullScreen}\n aria-label={\n translateText(isShownFullScreen ? \"Close the full-screen map\" : \"Open the map in full screen\")\n }\n data-testid=\"map-expand\"\n >\n <Icon name={isShownFullScreen ? \"minimize\" : \"maximize\"} />\n </button>\n ) : null}\n {showCarousel ? (\n <MapPointCarousel\n points={mapView.points}\n selectedPointKey={selectedPointKey}\n languageCode={languageCode}\n isRoute={mapView.showRoute}\n onPointSelect={onPointSelect}\n />\n ) : null}\n </div>\n );\n};\n","import { useSyncExternalStore } from \"react\";\n\n/**\n * Whether Google refused the Maps key for this page. The SDK reports a refused key — a referrer the\n * key does not allow, a disabled API — only through the global `window.gm_authFailure` callback; the script itself\n * loads fine, so `useGoogleMapApiLoader` sees no error. After a refusal every new map fails inside the SDK, so the\n * `Map` node stops creating Google maps, shows its points without the map and reports `failed`.\n *\n * One page-wide flag: the handler is installed once and keeps any handler that was there before.\n */\n\ndeclare global {\n interface Window {\n gm_authFailure?: () => void;\n }\n}\n\nlet hasGoogleMapsAuthFailed = false;\nconst authFailureListeners = new Set<() => void>();\nlet isHandlerInstalled = false;\n\nconst markGoogleMapsAuthFailed = () => {\n hasGoogleMapsAuthFailed = true;\n authFailureListeners.forEach((listener) => listener());\n};\n\nconst installAuthFailureHandler = () => {\n if (isHandlerInstalled || typeof window === \"undefined\") return;\n isHandlerInstalled = true;\n const previousHandler = window.gm_authFailure;\n window.gm_authFailure = () => {\n markGoogleMapsAuthFailed();\n previousHandler?.();\n };\n};\n\nconst subscribeToAuthFailure = (listener: () => void) => {\n installAuthFailureHandler();\n authFailureListeners.add(listener);\n return () => {\n authFailureListeners.delete(listener);\n };\n};\n\nconst readAuthFailure = () => hasGoogleMapsAuthFailed;\nconst readAuthFailureOnServer = () => false;\n\nexport const useGoogleMapsAuthFailure = (): boolean =>\n useSyncExternalStore(subscribeToAuthFailure, readAuthFailure, readAuthFailureOnServer);\n\n/** For specs: the flag back to its initial state. */\nexport const resetGoogleMapsAuthFailureForTests = () => {\n hasGoogleMapsAuthFailed = false;\n};\n\n/** For specs and stories: what the SDK's callback does. */\nexport const simulateGoogleMapsAuthFailure = () => markGoogleMapsAuthFailed();\n","import { useEffect, useMemo, useState } from \"react\";\nimport { useAgentsMapsLoader } from \"../../../provider/AgentsProvider\";\nimport { useConversationWidgetContext } from \"../../../renderer/ConversationWidgetCallbacksContext\";\nimport { messageAnchor } from \"../../../renderer/canvas/canvas-state\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { WidgetRenderReportEntry } from \"../../../renderer/render-report/widget-render-report\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readMapView, type MapPoint, type MapView } from \"./map-points\";\nimport { useMapPresentation } from \"./map-presentation-context\";\nimport { canvasInstanceIdForMapFullScreen, MAP_NODE_TYPE } from \"./map-full-screen-instance\";\nimport { ComposedMapView } from \"./ComposedMapView\";\nimport { useGoogleMapsAuthFailure } from \"./use-google-maps-auth-failure\";\n\ninterface MapLoadState {\n isPending: boolean;\n isJsApiLoaded: boolean;\n hasLoadError: boolean;\n /** Google refused the key (`gm_authFailure`): the script loaded, the map cannot render. */\n hasAuthFailed: boolean;\n}\n\n/** What the block reports for this map: never a silent nothing. */\nexport const buildMapRenderReport = (mapView: MapView, loadState: MapLoadState): WidgetRenderReportEntry => {\n if (loadState.isPending) return { status: \"pending\" };\n if (loadState.hasLoadError || loadState.hasAuthFailed) {\n const reason = loadState.hasAuthFailed ? \"Google refused the Maps key\" : \"the Google Maps script did not load\";\n return { status: \"failed\", code: \"RENDER_FAILED\", detail: `${reason} — the points show without the map` };\n }\n if (mapView.points.length === 0 && mapView.droppedPointCount > 0) {\n return {\n status: \"failed\",\n code: \"INVALID_PROP\",\n detail: `none of the ${mapView.droppedPointCount} Map points has valid \"lat\"/\"lng\" coordinates — no map shown`,\n };\n }\n if (mapView.points.length === 0) {\n return { status: \"empty\", code: \"NO_DATA\", detail: \"the Map has no points — no map shown\" };\n }\n if (!loadState.isJsApiLoaded) return { status: \"pending\" };\n if (mapView.droppedPointCount > 0) {\n return {\n status: \"failed\",\n code: \"INVALID_PROP\",\n detail: `${mapView.droppedPointCount} Map point(s) without valid \"lat\"/\"lng\" coordinates are not on the map`,\n };\n }\n if (mapView.cappedPointCount > 0) {\n return {\n status: \"failed\",\n code: \"BUDGET_EXCEEDED\",\n detail: `the Map shows the first ${mapView.points.length} points only`,\n };\n }\n return { status: \"mounted\" };\n};\n\n/**\n * The `Map` node (`MapComposedViewNode.php`): labelled points with rating badges, the view fitted to\n * them, a card carousel, an optional route line, and an expand control that opens the `mapFullScreen` canvas (anchored\n * on the host message; the body finds this node again by its key). A marker or card click selects the point and runs\n * the point's `action` — an `openEntity` action opens the entity's detail panel. The Google SDK comes from the app's one\n * loader (`AgentsEnvironment.useMapsLoader`), the key and map id from the app, as every map widget of the chat.\n */\nconst MapNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime } = props;\n const presentation = useMapPresentation();\n const { openCanvas, closeCanvas, canvas } = useConversationWidgetContext();\n const { isLoaded, loadError, languageCode } = useAgentsMapsLoader();\n const hasAuthFailed = useGoogleMapsAuthFailure();\n const hasLoadError = loadError !== undefined || hasAuthFailed;\n const [selectedPointKey, setSelectedPointKey] = useState<string>();\n const { maxRepeatRows, maxCollectionItems } = composedNodeSchema.budgets;\n\n // The resolved props are a new object on every render; the view is rebuilt only when their content changes.\n const nodePropsKey = JSON.stringify(nodeProps);\n const mapView = useMemo(\n () => readMapView(nodeProps, maxRepeatRows, maxCollectionItems),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [nodePropsKey, maxRepeatRows, maxCollectionItems],\n );\n\n const report = buildMapRenderReport(mapView, {\n isPending,\n isJsApiLoaded: isLoaded,\n hasLoadError: loadError !== undefined,\n hasAuthFailed,\n });\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n reportNodeStatus(report.status, report.code, report.detail);\n }, [reportNodeStatus, report.status, report.code, report.detail]);\n\n const selectPoint = (point: MapPoint) => {\n setSelectedPointKey(point.key);\n if (point.actionName) runtime.runEvent({ action: point.actionName }, undefined, point.row as ExpressionValue);\n };\n\n const numericMessageId = runtime.messageId === undefined ? Number.NaN : Number(runtime.messageId);\n const canExpand = presentation === \"inline\" && !runtime.isEmailRender && Number.isFinite(numericMessageId);\n const fullScreenInstanceId = canExpand ? canvasInstanceIdForMapFullScreen(numericMessageId, node) : undefined;\n const isShownFullScreen =\n fullScreenInstanceId !== undefined &&\n canvas?.canvasId === \"mapFullScreen\" &&\n canvas.instanceId === fullScreenInstanceId;\n // The control toggles: it opens this map full screen, and closes the canvas again while it shows this map.\n const toggleFullScreen = () => {\n if (fullScreenInstanceId === undefined) return;\n if (isShownFullScreen) {\n closeCanvas(true);\n return;\n }\n openCanvas({\n canvasId: \"mapFullScreen\",\n instanceId: fullScreenInstanceId,\n anchor: messageAnchor(numericMessageId),\n origin: \"cardClick\",\n justDelivered: false,\n });\n };\n\n return (\n <ComposedMapView\n mapView={mapView}\n presentation={presentation}\n isPending={isPending}\n isJsApiLoaded={isLoaded}\n hasLoadError={hasLoadError}\n isEmailRender={runtime.isEmailRender}\n languageCode={languageCode}\n selectedPointKey={selectedPointKey}\n onPointSelect={runtime.isEmailRender ? undefined : selectPoint}\n onExpand={canExpand ? toggleFullScreen : undefined}\n isShownFullScreen={isShownFullScreen}\n />\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: MAP_NODE_TYPE, component: MapNode };\n","import { ModelText } from \"../../ModelText/ModelText\";\nimport styles from \"./MediaCaption.module.scss\";\n\nexport interface MediaCaptionProps {\n title?: string;\n caption?: string;\n}\n\n/** The lines under a picture or a video: the title (card title, bold) over a muted caption; nothing when both are empty. */\nexport const MediaCaption = (props: MediaCaptionProps) => {\n const { title, caption } = props;\n if (!title && !caption) return null;\n return (\n <span className={styles.caption}>\n {title ? (\n <ModelText role=\"body\" weight=\"bold\" className={styles.wrap}>\n {title}\n </ModelText>\n ) : null}\n {caption ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-light)\" className={styles.wrap}>\n {caption}\n </ModelText>\n ) : null}\n </span>\n );\n};\n","import { useCallback, useState } from \"react\";\n\nexport type ImageLoadState = \"loading\" | \"loaded\" | \"failed\";\n\ninterface ImageLoadRecord {\n src: string | undefined;\n state: ImageLoadState;\n}\n\n/**\n * The load state of one `<img>`, bound to its `src`: a new source reads as `loading` without an effect (an effect that\n * resets after the commit would undo the `onLoad` of a cached picture that already fired), and the ref marks a picture\n * that is already complete when it mounts — a cached or lazily loaded one fires no `onLoad` React could still see.\n */\nexport const useImageLoadState = (src: string | undefined) => {\n const [loadRecord, setLoadRecord] = useState<ImageLoadRecord>({ src, state: \"loading\" });\n const loadState: ImageLoadState = loadRecord.src === src ? loadRecord.state : \"loading\";\n const markLoaded = useCallback(() => setLoadRecord({ src, state: \"loaded\" }), [src]);\n const markFailed = useCallback(() => setLoadRecord({ src, state: \"failed\" }), [src]);\n const imageRef = useCallback(\n (imageElement: HTMLImageElement | null) => {\n if (imageElement?.complete && imageElement.naturalWidth > 0) setLoadRecord({ src, state: \"loaded\" });\n },\n [src],\n );\n return { loadState, imageRef, markLoaded, markFailed };\n};\n","import { Icon, InteractiveSurface, Skeleton, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { translateText } from \"../../../provider/environment\";\nimport { ModelText } from \"../../ModelText/ModelText\";\nimport type { MediaAspectRatio, MediaImage, MediaImageFit } from \"./media-values\";\nimport styles from \"./MediaImageTile.module.scss\";\nimport { useImageLoadState } from \"./use-image-load-state\";\n\nexport interface MediaImageTileProps {\n image: MediaImage;\n aspectRatio: MediaAspectRatio;\n fit?: MediaImageFit;\n /** Load at once instead of lazily — the e-mail capture, which shoots the whole widget. */\n isEager?: boolean;\n /** Opens the lightbox at this picture; without it the tile is a plain picture (the e-mail capture). */\n onOpen?: () => void;\n /** The pictures the gallery does not show — counted on this tile as \"+N\". */\n hiddenImageCount?: number;\n /** The compact radius and no source chip — a thumbnail in a compact slot or a dense grid. */\n isCompact?: boolean;\n /** Called once when the picture fails to load; the tile then shows its alt text instead. */\n onLoadFailed?: () => void;\n testId?: string;\n}\n\nconst ASPECT_RATIO_CLASS_NAMES: Readonly<Record<MediaAspectRatio, string>> = {\n \"1:1\": styles.ratioSquare,\n \"4:3\": styles.ratioFourByThree,\n \"3:2\": styles.ratioThreeByTwo,\n \"5:4\": styles.ratioFiveByFour,\n \"16:9\": styles.ratioSixteenByNine,\n \"3:4\": styles.ratioThreeByFour,\n};\n\n/**\n * One picture of the media kit: a frame in the picture's aspect ratio on `--agents-bg-disabled`, a\n * skeleton in the frame's shape until the picture painted, the picture lazily loaded (`object-fit` cover or contain),\n * the source as a dark chip over its corner and, on the last visible tile of a gallery, the count of the hidden rest.\n * A picture that fails to load is replaced by its alt text — no broken image, and the e-mail capture never waits on a\n * missing asset. A tile that opens the lightbox is a native button inside the hoverable surface.\n */\nexport const MediaImageTile = (props: MediaImageTileProps) => {\n const {\n image,\n aspectRatio,\n fit = \"cover\",\n isEager = false,\n onOpen,\n hiddenImageCount = 0,\n isCompact = false,\n onLoadFailed,\n testId,\n } = props;\n const { loadState, imageRef, markLoaded, markFailed: markImageFailed } = useImageLoadState(image.src);\n\n const markFailed = () => {\n markImageFailed();\n onLoadFailed?.();\n };\n\n const frameClassName = classNames(\n styles.frame,\n ASPECT_RATIO_CLASS_NAMES[aspectRatio],\n isCompact && styles.frameCompact,\n );\n\n const frameContent = (\n <>\n {loadState === \"failed\" ? (\n <span className={styles.fallback}>\n <Icon color=\"var(--agents-fg-light)\" name=\"image\" />\n <ModelText role=\"caption\" color=\"var(--agents-fg)\" className={styles.fallbackText}>\n {image.alt}\n </ModelText>\n </span>\n ) : (\n <img\n ref={imageRef}\n className={classNames(styles.image, fit === \"contain\" && styles.imageContain)}\n src={image.src}\n alt={image.alt}\n loading={isEager ? \"eager\" : \"lazy\"}\n decoding=\"async\"\n onLoad={markLoaded}\n onError={markFailed}\n />\n )}\n {loadState === \"loading\" ? <Skeleton className={styles.skeleton} /> : null}\n {image.source && !isCompact ? (\n <span className={styles.sourceChip}>\n <ModelText role=\"caption\" color=\"var(--agents-fg-on-dark)\" ellipsis>\n {image.source.name}\n </ModelText>\n </span>\n ) : null}\n {hiddenImageCount > 0 ? (\n <span className={styles.hiddenCountChip}>\n <Icon color=\"var(--agents-fg-on-dark)\" name=\"photo\" />\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {`+${hiddenImageCount}`}\n </Text>\n </span>\n ) : null}\n </>\n );\n\n if (!onOpen) {\n return (\n <span className={frameClassName} data-testid={testId}>\n {frameContent}\n </span>\n );\n }\n const openLabel =\n hiddenImageCount > 0\n ? translateText(\n \"Open the gallery at %alt%, %count% more picture\",\n { alt: image.alt, count: hiddenImageCount },\n hiddenImageCount === 1 ? \"one\" : \"other\",\n )\n : translateText(\"Open the picture %alt% full size\", { alt: image.alt });\n return (\n <InteractiveSurface hoverable className={frameClassName}>\n {frameContent}\n <button\n type=\"button\"\n className={styles.openButton}\n aria-label={openLabel}\n onClick={onOpen}\n data-testid={testId ? `${testId}-open` : undefined}\n />\n </InteractiveSurface>\n );\n};\n","import { openImageGallery } from \"../../../provider/environment\";\n\n/**\n * The values the media kit components (`Image`, `ImageGroup`, `Video`) read from their resolved props.\n * Every reader is total: a value that does not fit is `undefined` (or dropped from a list and counted), never a throw —\n * the component reports what it lost and renders the rest.\n */\n\n/** Where a picture or a video was found — the chip over an image, the source line under a video. */\nexport interface MediaSource {\n name: string;\n url?: string;\n}\n\n/** One picture of an `Image` node or of an `ImageGroup` list. */\nexport interface MediaImage {\n src: string;\n alt: string;\n title?: string;\n caption?: string;\n source?: MediaSource;\n}\n\n/** The pictures of a list prop: the usable ones, how many were dropped (no `src` / `alt`) and how many past the row cap. */\nexport interface MediaImageList {\n images: MediaImage[];\n droppedCount: number;\n cappedCount: number;\n}\n\nconst readText = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** An `http(s)` URL, unchanged; anything else (a `javascript:` link, a relative path, a typo) is `undefined`. */\nexport const readHttpUrl = (value: unknown): string | undefined => {\n const text = readText(value);\n if (!text) return undefined;\n try {\n const url = new URL(text);\n return url.protocol === \"https:\" || url.protocol === \"http:\" ? text : undefined;\n } catch {\n return undefined;\n }\n};\n\n/** An image address: an `http(s)` URL or an inline `data:image/…` URI (the fixtures, a generated picture). */\nexport const readImageUrl = (value: unknown): string | undefined => {\n const text = readText(value);\n if (text && /^data:image\\/[a-z0-9.+-]+[;,]/i.test(text)) return text;\n return readHttpUrl(value);\n};\n\n/** `{\"name\",\"url\"}`; a source with only a URL is named by its host. */\nexport const readMediaSource = (value: unknown): MediaSource | undefined => {\n if (!isRecord(value)) return undefined;\n const url = readHttpUrl(value.url);\n const name = readText(value.name) ?? (url ? new URL(url).hostname.replace(/^www\\./, \"\") : undefined);\n if (!name) return undefined;\n return url ? { name, url } : { name };\n};\n\n/** One picture from a record carrying `src` and `alt` (an `Image` node's props or one entry of an `ImageGroup`). */\nexport const readMediaImage = (value: unknown): MediaImage | undefined => {\n if (!isRecord(value)) return undefined;\n const src = readImageUrl(value.src);\n const alt = readText(value.alt);\n if (!src || !alt) return undefined;\n const title = readText(value.title);\n const caption = readText(value.caption);\n const source = readMediaSource(value.source);\n return {\n src,\n alt,\n ...(title ? { title } : {}),\n ...(caption ? { caption } : {}),\n ...(source ? { source } : {}),\n };\n};\n\n/** The pictures of a list prop, at most `maxImages` (the schema's `maxRepeatRows`). Not a list = no pictures. */\nexport const readMediaImageList = (value: unknown, maxImages: number): MediaImageList => {\n const entries = Array.isArray(value) ? value : [];\n const usableImages = entries.map(readMediaImage).filter((image): image is MediaImage => image !== undefined);\n const images = usableImages.slice(0, maxImages);\n return {\n images,\n droppedCount: entries.length - usableImages.length,\n cappedCount: usableImages.length - images.length,\n };\n};\n\n/** The frames of the node schema (`ImageComposedViewNode::ASPECT_RATIOS`); each has its class in `MediaImageTile.module.scss`. */\nexport const MEDIA_ASPECT_RATIOS = [\"1:1\", \"4:3\", \"3:2\", \"5:4\", \"16:9\", \"3:4\"] as const;\n\nexport type MediaAspectRatio = (typeof MEDIA_ASPECT_RATIOS)[number];\n\n/** The frame a prop names, or `fallbackAspectRatio` when it names none of the schema's frames. */\nexport const readAspectRatio = (value: unknown, fallbackAspectRatio: MediaAspectRatio): MediaAspectRatio =>\n MEDIA_ASPECT_RATIOS.find((aspectRatio) => aspectRatio === value) ?? fallbackAspectRatio;\n\n/** How a picture fills its frame: `cover` crops a photo, `contain` shows a logo whole. */\nexport type MediaImageFit = \"cover\" | \"contain\";\n\nexport const readImageFit = (value: unknown): MediaImageFit => (value === \"contain\" ? \"contain\" : \"cover\");\n\n/** A positive whole number prop (`maxVisible`), or the fallback. */\nexport const readPositiveCount = (value: unknown, fallbackCount: number): number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallbackCount;\n\n/**\n * Opens the app's image lightbox over `images`, starting at `startIndex` — the same lightbox the chat's image and logo\n * galleries open. Every entry carries its position as its id.\n */\nexport const openMediaImagesLightbox = (images: MediaImage[], startIndex: number): void => {\n if (images.length === 0) return;\n const gallery = images.map((image, imageIndex) => ({\n id: `composed-view-image-${imageIndex}`,\n url: image.src,\n name: image.title ?? image.alt,\n }));\n openImageGallery(gallery, Math.min(Math.max(startIndex, 0), gallery.length - 1));\n};\n\n/** `1418` → `23:38`, `3725` → `1:02:05`; no length for a missing, negative or non-finite value. */\nexport const formatVideoDuration = (durationSeconds: unknown): string | undefined => {\n if (typeof durationSeconds !== \"number\" || !Number.isFinite(durationSeconds) || durationSeconds < 0) return undefined;\n const wholeSeconds = Math.floor(durationSeconds);\n const hours = Math.floor(wholeSeconds / 3600);\n const minutes = Math.floor((wholeSeconds % 3600) / 60);\n const paddedSeconds = String(wholeSeconds % 60).padStart(2, \"0\");\n return hours > 0 ? `${hours}:${String(minutes).padStart(2, \"0\")}:${paddedSeconds}` : `${minutes}:${paddedSeconds}`;\n};\n\n/**\n * A video id of the video connector (YouTube): letters, digits, `-` and `_` only — so it goes into the embed,\n * watch and thumbnail URLs without escaping.\n */\nexport const readVideoId = (value: unknown): string | undefined => {\n const text = readText(value);\n return text && /^[A-Za-z0-9_-]{6,32}$/.test(text) ? text : undefined;\n};\n\nconst YOUTUBE_WATCH_HOSTS = [\"youtube.com\", \"www.youtube.com\", \"m.youtube.com\", \"music.youtube.com\"];\n\n/**\n * The video id of a YouTube link the model wrote as `url` (`youtube.com/watch?v=…`, `youtu.be/…`, `/shorts/…`,\n * `/embed/…`), so such a video plays in place like a connector video; any other link is `undefined`.\n */\nexport const readYouTubeVideoIdFromUrl = (url: string | undefined): string | undefined => {\n if (!url) return undefined;\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch {\n return undefined;\n }\n const host = parsedUrl.hostname.toLowerCase();\n if (host === \"youtu.be\") return readVideoId(parsedUrl.pathname.split(\"/\")[1]);\n if (!YOUTUBE_WATCH_HOSTS.includes(host)) return undefined;\n if (parsedUrl.pathname === \"/watch\") return readVideoId(parsedUrl.searchParams.get(\"v\"));\n const pathMatch = parsedUrl.pathname.match(/^\\/(?:shorts|embed|live)\\/([^/]+)/);\n return pathMatch ? readVideoId(pathMatch[1]) : undefined;\n};\n\n/** The privacy-enhanced embed of a connector video; it autoplays, because the owner pressed play to load it. */\nexport const buildVideoEmbedUrl = (videoId: string): string =>\n `https://www.youtube-nocookie.com/embed/${videoId}?autoplay=1&rel=0`;\n\nexport const buildVideoWatchUrl = (videoId: string): string => `https://www.youtube.com/watch?v=${videoId}`;\n\nexport const buildVideoThumbnailUrl = (videoId: string): string => `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`;\n","import { Skeleton } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { MediaCaption } from \"./MediaCaption\";\nimport { MediaImageTile } from \"./MediaImageTile\";\nimport { openMediaImagesLightbox, readAspectRatio, readImageFit, readMediaImage } from \"./media-values\";\nimport styles from \"./Image.module.scss\";\n\n/**\n * The `Image` node (`ImageComposedViewNode.php`): one picture with its\n * title and caption under it and its source as a chip over it, lazily loaded, opening the component library's lightbox on click. In\n * a compact slot (a table cell) it is a 4:3 thumbnail without text. A picture whose `src` is no http(s) or data:image\n * address reports `failed` and renders nothing; a picture that does not load shows its alt text and reports `failed`.\n */\nconst ImageNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const image = useMemo(() => readMediaImage(nodeProps), [nodeProps]);\n const aspectRatio = readAspectRatio(nodeProps.aspectRatio, \"4:3\");\n const isCompact = sizeClass === \"compact\";\n const [hasLoadFailed, setHasLoadFailed] = useState(false);\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n setHasLoadFailed(false);\n }, [image?.src]);\n\n useEffect(() => {\n if (isPending) return;\n if (!image) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the Image has no http(s) or data:image src, or no alt text\");\n return;\n }\n if (hasLoadFailed) {\n reportNodeStatus(\"failed\", \"RENDER_FAILED\", `the picture \"${image.alt}\" did not load`);\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, image, hasLoadFailed, reportNodeStatus]);\n\n if (isPending) {\n return (\n <span\n className={classNames(styles.pendingFrame, isCompact && styles.pendingFrameCompact)}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n <Skeleton className={styles.pendingSkeleton} />\n </span>\n );\n }\n if (!image) return null;\n const openLightbox = runtime.isEmailRender ? undefined : () => openMediaImagesLightbox([image], 0);\n return (\n <figure className={classNames(styles.image, isCompact && styles.imageCompact)} data-testid={testId}>\n <MediaImageTile\n testId={`${testId}-tile`}\n image={image}\n aspectRatio={isCompact ? \"4:3\" : aspectRatio}\n fit={readImageFit(nodeProps.fit)}\n isEager={runtime.isEmailRender}\n isCompact={isCompact}\n onOpen={openLightbox}\n onLoadFailed={() => setHasLoadFailed(true)}\n />\n {isCompact ? null : <MediaCaption title={image.title} caption={image.caption} />}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Image\", component: ImageNode };\n","import { Icon, InteractiveSurface, Skeleton, Text, type AgentsIconName } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { KeyboardEvent, useEffect, useMemo, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { MediaCaption } from \"./MediaCaption\";\nimport { MediaImageTile } from \"./MediaImageTile\";\nimport {\n MediaAspectRatio,\n MediaImage,\n openMediaImagesLightbox,\n readAspectRatio,\n readMediaImageList,\n readPositiveCount,\n} from \"./media-values\";\nimport styles from \"./ImageGroup.module.scss\";\n\n/** Tiles a grid shows before its last tile counts the hidden rest (`maxVisible`); a compact strip shows three. */\nconst DEFAULT_MAX_VISIBLE_TILES = 4;\nconst COMPACT_MAX_VISIBLE_TILES = 3;\n/** Skeleton tiles while the bound pictures are pending. */\nconst PENDING_TILE_COUNT = 4;\n\ntype ImageGroupLayout = \"grid\" | \"carousel\" | \"magazine\";\n\nconst readImageGroupLayout = (value: unknown): ImageGroupLayout =>\n value === \"carousel\" || value === \"magazine\" ? value : \"grid\";\n\ninterface ImageGroupLayoutProps {\n images: MediaImage[];\n aspectRatio: MediaAspectRatio;\n isEmailRender: boolean;\n onImageLoadFailed: (imageIndex: number) => void;\n testId: string;\n}\n\nconst buildOpenImageHandler = (images: MediaImage[], imageIndex: number, isEmailRender: boolean) =>\n isEmailRender ? undefined : () => openMediaImagesLightbox(images, imageIndex);\n\n/** The grid (ChatGPT 44): up to `maxVisible` tiles, the last one counting the hidden rest; every tile opens the lightbox. */\nconst ImageGroupGrid = (props: ImageGroupLayoutProps & { maxVisibleTiles: number; isCompact: boolean }) => {\n const { images, aspectRatio, isEmailRender, onImageLoadFailed, maxVisibleTiles, isCompact, testId } = props;\n const visibleImages = images.slice(0, maxVisibleTiles);\n const hiddenImageCount = images.length - visibleImages.length;\n return (\n <div className={classNames(styles.grid, isCompact && styles.gridCompact)} data-testid={testId}>\n {visibleImages.map((image, imageIndex) => (\n <figure key={`${imageIndex}:${image.src}`} className={styles.tile}>\n <MediaImageTile\n testId={`${testId}-tile-${imageIndex}`}\n image={image}\n aspectRatio={aspectRatio}\n isEager={isEmailRender}\n isCompact={isCompact}\n hiddenImageCount={imageIndex === visibleImages.length - 1 ? hiddenImageCount : 0}\n onOpen={buildOpenImageHandler(images, imageIndex, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(imageIndex)}\n />\n {isCompact ? null : <MediaCaption title={image.title} caption={image.caption} />}\n </figure>\n ))}\n </div>\n );\n};\n\n/** The magazine (ChatGPT 15): the first picture as a 16:9 hero, the others as tiles under it, each with its text. */\nconst ImageGroupMagazine = (props: ImageGroupLayoutProps & { heroAspectRatio: MediaAspectRatio }) => {\n const { images, aspectRatio, heroAspectRatio, isEmailRender, onImageLoadFailed, testId } = props;\n const [heroImage, ...tileImages] = images;\n return (\n <div className={styles.magazine} data-testid={testId}>\n <figure className={styles.tile}>\n <MediaImageTile\n testId={`${testId}-tile-0`}\n image={heroImage}\n aspectRatio={heroAspectRatio}\n isEager={isEmailRender}\n onOpen={buildOpenImageHandler(images, 0, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(0)}\n />\n <MediaCaption title={heroImage.title} caption={heroImage.caption} />\n </figure>\n {tileImages.length > 0 ? (\n <div className={styles.grid}>\n {tileImages.map((image, tileIndex) => (\n <figure key={`${tileIndex}:${image.src}`} className={styles.tile}>\n <MediaImageTile\n testId={`${testId}-tile-${tileIndex + 1}`}\n image={image}\n aspectRatio={aspectRatio}\n isEager={isEmailRender}\n onOpen={buildOpenImageHandler(images, tileIndex + 1, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(tileIndex + 1)}\n />\n <MediaCaption title={image.title} caption={image.caption} />\n </figure>\n ))}\n </div>\n ) : null}\n </div>\n );\n};\n\ninterface CarouselStepButtonProps {\n label: string;\n icon: AgentsIconName;\n className: string;\n isDisabled: boolean;\n onStep: () => void;\n testId: string;\n}\n\n/** Previous / next of the carousel: a round dark control over the picture, the hover layer from GlobalStateComponent. */\nconst CarouselStepButton = (props: CarouselStepButtonProps) => {\n const { label, icon, className, isDisabled, onStep, testId } = props;\n return (\n <InteractiveSurface\n hoverable={!isDisabled}\n className={classNames(styles.carouselButton, className, isDisabled && styles.carouselButtonDisabled)}\n >\n <button\n type=\"button\"\n className={styles.carouselButtonTarget}\n aria-label={label}\n data-testid={testId}\n disabled={isDisabled}\n onClick={onStep}\n >\n <Icon color=\"var(--agents-fg-on-dark)\" name={icon} />\n </button>\n </InteractiveSurface>\n );\n};\n\n/**\n * The carousel (ChatGPT 09): one large picture at a time with its text, previous / next over its sides, the position\n * as \"2 / 5\" and the arrow keys. The e-mail capture shows the first picture without the controls.\n */\nconst ImageGroupCarousel = (props: ImageGroupLayoutProps) => {\n const { images, aspectRatio, isEmailRender, onImageLoadFailed, testId } = props;\n const [shownImageIndex, setShownImageIndex] = useState(0);\n const lastImageIndex = images.length - 1;\n const currentImageIndex = Math.min(shownImageIndex, lastImageIndex);\n const currentImage = images[currentImageIndex];\n const hasControls = !isEmailRender && images.length > 1;\n const showImage = (imageIndex: number) => setShownImageIndex(Math.min(Math.max(imageIndex, 0), lastImageIndex));\n const showImageForKey = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"ArrowLeft\") showImage(currentImageIndex - 1);\n if (event.key === \"ArrowRight\") showImage(currentImageIndex + 1);\n };\n return (\n <div\n className={styles.carousel}\n data-testid={testId}\n role=\"group\"\n aria-roledescription=\"carousel\"\n tabIndex={hasControls ? 0 : undefined}\n onKeyDown={hasControls ? showImageForKey : undefined}\n >\n <div className={styles.carouselStage}>\n <MediaImageTile\n key={`${currentImageIndex}:${currentImage.src}`}\n testId={`${testId}-tile-${currentImageIndex}`}\n image={currentImage}\n aspectRatio={aspectRatio}\n isEager\n onOpen={buildOpenImageHandler(images, currentImageIndex, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(currentImageIndex)}\n />\n {hasControls ? (\n <>\n <CarouselStepButton\n label={translateText(\"Previous picture\")}\n icon=\"arrowLeft\"\n className={styles.carouselButtonPrevious}\n isDisabled={currentImageIndex === 0}\n onStep={() => showImage(currentImageIndex - 1)}\n testId={`${testId}-previous`}\n />\n <CarouselStepButton\n label={translateText(\"Next picture\")}\n icon=\"arrowRight\"\n className={styles.carouselButtonNext}\n isDisabled={currentImageIndex === lastImageIndex}\n onStep={() => showImage(currentImageIndex + 1)}\n testId={`${testId}-next`}\n />\n <span className={styles.carouselPosition} aria-live=\"polite\" data-testid={`${testId}-position`}>\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {`${currentImageIndex + 1} / ${images.length}`}\n </Text>\n </span>\n </>\n ) : null}\n </div>\n <MediaCaption title={currentImage.title} caption={currentImage.caption} />\n </div>\n );\n};\n\n/**\n * The `ImageGroup` node (`ImageGroupComposedViewNode.php`): a gallery as a grid, a carousel or a\n * magazine; every picture opens the component library's lightbox over the whole gallery at its place. The pictures are capped at the\n * schema's `maxRepeatRows`; an entry without an http(s) / data:image `src` or an `alt` is dropped. It reports `failed`\n * for dropped, capped or unloadable pictures (the rest still shows), `empty` for a gallery with no picture (one muted\n * line), and nothing while its bound pictures are pending (the renderer reports the pending dataset; skeleton tiles).\n */\nconst ImageGroupNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n const { images, droppedCount, cappedCount } = useMemo(\n () => readMediaImageList(nodeProps.images, maxRepeatRows),\n [nodeProps.images, maxRepeatRows],\n );\n const layout = readImageGroupLayout(nodeProps.layout);\n const isCompact = sizeClass === \"compact\";\n const [failedImageIndexes, setFailedImageIndexes] = useState<number[]>([]);\n const { reportNodeStatus } = runtime;\n const imageSourcesKey = images.map((image) => image.src).join(\"\\n\");\n\n useEffect(() => {\n setFailedImageIndexes([]);\n }, [imageSourcesKey]);\n\n useEffect(() => {\n if (isPending) return;\n if (droppedCount > 0) {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n `${droppedCount} of ${droppedCount + images.length + cappedCount} pictures dropped: each needs an http(s) or data:image src and an alt text`,\n );\n return;\n }\n if (cappedCount > 0) {\n reportNodeStatus(\"failed\", \"BUDGET_EXCEEDED\", `ImageGroup shows the first ${maxRepeatRows} pictures only`);\n return;\n }\n if (images.length === 0) {\n reportNodeStatus(\"empty\", \"NO_DATA\", \"the ImageGroup has no pictures\");\n return;\n }\n if (failedImageIndexes.length > 0) {\n reportNodeStatus(\n \"failed\",\n \"RENDER_FAILED\",\n `${failedImageIndexes.length} of ${images.length} pictures did not load`,\n );\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, droppedCount, cappedCount, images.length, failedImageIndexes.length, maxRepeatRows, reportNodeStatus]);\n\n const markImageLoadFailed = (imageIndex: number) =>\n setFailedImageIndexes((currentIndexes) =>\n currentIndexes.includes(imageIndex) ? currentIndexes : [...currentIndexes, imageIndex],\n );\n\n if (isPending) {\n return (\n <div\n className={classNames(styles.grid, isCompact && styles.gridCompact)}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n {Array.from({ length: isCompact ? COMPACT_MAX_VISIBLE_TILES : PENDING_TILE_COUNT }, (unused, tileIndex) => (\n <span key={tileIndex} className={classNames(styles.pendingTile, isCompact && styles.pendingTileCompact)}>\n <Skeleton className={styles.pendingSkeleton} />\n </span>\n ))}\n </div>\n );\n }\n if (images.length === 0) {\n return (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={`${testId}-empty`}>\n {\"No pictures to show.\"}\n </Text>\n );\n }\n const layoutProps: ImageGroupLayoutProps = {\n images,\n aspectRatio: readAspectRatio(nodeProps.aspectRatio, layout === \"magazine\" ? \"1:1\" : \"4:3\"),\n isEmailRender: runtime.isEmailRender,\n onImageLoadFailed: markImageLoadFailed,\n testId,\n };\n // A compact slot has no room for a carousel or a hero: every layout becomes the thumbnail strip there.\n if (isCompact) {\n return <ImageGroupGrid {...layoutProps} aspectRatio=\"4:3\" maxVisibleTiles={COMPACT_MAX_VISIBLE_TILES} isCompact />;\n }\n if (layout === \"carousel\") {\n return <ImageGroupCarousel {...layoutProps} aspectRatio={readAspectRatio(nodeProps.aspectRatio, \"16:9\")} />;\n }\n if (layout === \"magazine\") {\n return <ImageGroupMagazine {...layoutProps} heroAspectRatio=\"16:9\" />;\n }\n return (\n <ImageGroupGrid\n {...layoutProps}\n maxVisibleTiles={readPositiveCount(nodeProps.maxVisible, DEFAULT_MAX_VISIBLE_TILES)}\n isCompact={false}\n />\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"ImageGroup\",\n component: ImageGroupNode,\n};\n","import { Icon, InteractiveSurface, Skeleton, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport { ModelText } from \"../../ModelText/ModelText\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n buildVideoEmbedUrl,\n buildVideoThumbnailUrl,\n buildVideoWatchUrl,\n formatVideoDuration,\n readHttpUrl,\n readImageUrl,\n readMediaSource,\n readVideoId,\n readYouTubeVideoIdFromUrl,\n} from \"./media-values\";\nimport styles from \"./Video.module.scss\";\nimport { useImageLoadState } from \"./use-image-load-state\";\n\nconst readTitle = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\n/**\n * The `Video` node (`VideoComposedViewNode.php`): one video\n * as a card — the 16:9 thumbnail with its length, the title, the channel and the source, and \"Open video\" to the watch\n * page. A connector video (`videoId`) plays in place: the play button swaps the thumbnail for the\n * privacy-enhanced embed, and so does a YouTube watch link written as `url`; any other `url` opens in a new tab. Without a thumbnail a connector video takes its id's\n * thumbnail; a thumbnail that fails falls back to the play glyph on the empty frame. The e-mail capture shows the card\n * without play button and link. A video with neither a `videoId` nor an http(s) `url` reports `failed` and shows its\n * text only.\n */\nconst VideoNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const title = readTitle(nodeProps.title);\n const url = readHttpUrl(nodeProps.url);\n const videoId = readVideoId(nodeProps.videoId) ?? readYouTubeVideoIdFromUrl(url);\n const watchUrl = url ?? (videoId ? buildVideoWatchUrl(videoId) : undefined);\n const thumbnailUrl = readImageUrl(nodeProps.thumbnail) ?? (videoId ? buildVideoThumbnailUrl(videoId) : undefined);\n const duration = formatVideoDuration(nodeProps.durationSeconds);\n const channel = readTitle(nodeProps.channel);\n const source = useMemo(() => readMediaSource(nodeProps.source), [nodeProps.source]);\n const isCompact = sizeClass === \"compact\";\n const [isPlaying, setIsPlaying] = useState(false);\n const {\n loadState: thumbnailLoadState,\n imageRef: thumbnailRef,\n markLoaded: markThumbnailLoaded,\n markFailed: markThumbnailFailed,\n } = useImageLoadState(thumbnailUrl);\n\n useEffect(() => {\n if (isPending) return;\n if (!title) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the Video has no title\");\n return;\n }\n if (!watchUrl) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `the video \"${title}\" has neither a videoId nor an http(s) url`);\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, title, watchUrl, reportNodeStatus]);\n\n if (isPending) {\n return (\n <span\n className={classNames(styles.video, isCompact && styles.videoCompact)}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n <span className={styles.frame}>\n <Skeleton className={styles.frameSkeleton} />\n </span>\n </span>\n );\n }\n if (!title) return null;\n\n const canPlayInPlace = videoId !== undefined && !isEmailRender && !isCompact;\n const canOpen = watchUrl !== undefined && !isEmailRender;\n const showThumbnail = thumbnailUrl !== undefined && thumbnailLoadState !== \"failed\";\n const playVideo = () => {\n if (canPlayInPlace) {\n setIsPlaying(true);\n return;\n }\n if (watchUrl) window.open(watchUrl, \"_blank\", \"noopener,noreferrer\");\n };\n const metaLine = [channel, duration].filter((metaPart): metaPart is string => metaPart !== undefined).join(\" · \");\n const sourceName = source && source.name !== channel ? source.name : undefined;\n\n const frame =\n isPlaying && videoId ? (\n <span className={styles.frame}>\n <iframe\n className={styles.player}\n data-testid={`${testId}-player`}\n src={buildVideoEmbedUrl(videoId)}\n title={title}\n allow=\"autoplay; encrypted-media; picture-in-picture; fullscreen\"\n allowFullScreen\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n </span>\n ) : (\n <InteractiveSurface hoverable={canOpen} className={styles.frame}>\n {showThumbnail ? (\n <img\n ref={thumbnailRef}\n className={styles.thumbnail}\n src={thumbnailUrl}\n alt=\"\"\n loading={isEmailRender ? \"eager\" : \"lazy\"}\n decoding=\"async\"\n onLoad={markThumbnailLoaded}\n onError={markThumbnailFailed}\n />\n ) : null}\n {showThumbnail && thumbnailLoadState === \"loading\" ? <Skeleton className={styles.frameSkeleton} /> : null}\n <span className={classNames(styles.playBadge, isCompact && styles.playBadgeCompact)} aria-hidden=\"true\">\n <Icon color=\"var(--agents-fg-on-dark)\" name=\"play\" />\n </span>\n {duration ? (\n <span className={styles.durationChip}>\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {duration}\n </Text>\n </span>\n ) : null}\n {canOpen ? (\n <button\n type=\"button\"\n className={styles.playButton}\n data-testid={`${testId}-play`}\n aria-label={translateText(\"Play the video %title%\", { title })}\n onClick={playVideo}\n />\n ) : null}\n </InteractiveSurface>\n );\n\n if (isCompact) {\n return (\n <span className={classNames(styles.video, styles.videoCompact)} data-testid={testId}>\n {frame}\n <ModelText role=\"caption\" ellipsis>\n {title}\n </ModelText>\n </span>\n );\n }\n return (\n <figure className={styles.video} data-testid={testId}>\n {frame}\n <span className={styles.text}>\n <ModelText role=\"body\" weight=\"bold\" className={styles.wrap}>\n {title}\n </ModelText>\n {metaLine ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-light)\">\n {metaLine}\n </ModelText>\n ) : null}\n {sourceName ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-lightest)\">\n {sourceName}\n </ModelText>\n ) : null}\n </span>\n {canOpen && watchUrl ? (\n <a\n className={styles.openLink}\n href={watchUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n data-testid={`${testId}-open-link`}\n >\n <Text role=\"help\" weight=\"medium\" color=\"var(--agents-fg-cta)\">\n {\"Open video\"}\n </Text>\n <Icon color=\"var(--agents-fg-cta)\" name=\"arrowRight\" />\n </a>\n ) : null}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Video\", component: VideoNode };\n","/**\n * The values the `VideoCard` node reads from its resolved props, each reader total: a value that\n * does not fit is `undefined`, never a throw.\n */\n\n/** A view count: a finite whole number of zero or more. */\nexport const readViewCount = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined;\n\n/** A view count in the locale's compact notation: `18234` → `18K` (en), `18.234` (de), `1.2M` (en). */\nexport const formatViewCount = (viewCount: number, locale: string): string =>\n new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }).format(viewCount);\n\nconst PUBLISHED_DAY = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** A `Y-m-d` publish day in the locale's short form (`Feb 8, 2025`, `8. Feb. 2025`); anything else is `undefined`. */\nexport const formatPublishedDay = (value: unknown, locale: string): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n const dayParts = PUBLISHED_DAY.exec(value.trim());\n if (!dayParts) return undefined;\n const monthIndex = Number(dayParts[2]) - 1;\n const publishedDay = new Date(Number(dayParts[1]), monthIndex, Number(dayParts[3]));\n if (Number.isNaN(publishedDay.getTime()) || publishedDay.getMonth() !== monthIndex) return undefined;\n return new Intl.DateTimeFormat(locale, { day: \"numeric\", month: \"short\", year: \"numeric\" }).format(publishedDay);\n};\n","import { Icon, InteractiveSurface, Skeleton, Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { useEffect, useState } from \"react\";\nimport { translateText } from \"../../../../provider/environment\";\nimport { ModelText } from \"../../../ModelText/ModelText\";\nimport type {\n ComposedViewComponentDefinition,\n ComposedViewComponentProps,\n} from \"../../../composed-view-component-types\";\nimport {\n buildVideoEmbedUrl,\n buildVideoThumbnailUrl,\n buildVideoWatchUrl,\n formatVideoDuration,\n readImageUrl,\n readVideoId,\n} from \"../media-values\";\nimport { useNumberLocale } from \"../../data/use-number-locale\";\nimport { useLayoutNesting } from \"../../layout/layout-nesting-context\";\nimport { formatPublishedDay, formatViewCount, readViewCount } from \"./video-card-values\";\nimport styles from \"./VideoCard.module.scss\";\nimport { useImageLoadState } from \"../use-image-load-state\";\n\nconst readTitle = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\n/**\n * The `VideoCard` node (backend `VideoCardComposedViewNode.php`): one YouTube\n * search result as a card — the 16:9 thumbnail with the length on a dark chip and the play glyph, the title, and\n * \"channel · views · date\" under it. Play swaps the thumbnail for the privacy-enhanced embed in place; \"Open on YouTube\"\n * opens the watch page in a new tab. A thumbnail that does not load leaves the play glyph on the empty frame. The\n * e-mail capture shows the card without play button and link. Without a title or a valid videoId the node reports\n * `failed` and shows its title only.\n */\nconst VideoCardNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const { isInsideSurface, isInsidePressable } = useLayoutNesting();\n const numberLocale = useNumberLocale();\n const title = readTitle(nodeProps.title);\n const videoId = readVideoId(nodeProps.videoId);\n const thumbnailUrl = readImageUrl(nodeProps.thumbnail) ?? (videoId ? buildVideoThumbnailUrl(videoId) : undefined);\n const duration = formatVideoDuration(nodeProps.durationSeconds);\n const channel = readTitle(nodeProps.channel);\n const viewCount = readViewCount(nodeProps.viewCount);\n const publishedDay = formatPublishedDay(nodeProps.publishedAt, numberLocale);\n const isCompact = sizeClass === \"compact\";\n const [isPlaying, setIsPlaying] = useState(false);\n const {\n loadState: thumbnailLoadState,\n imageRef: thumbnailRef,\n markLoaded: markThumbnailLoaded,\n markFailed: markThumbnailFailed,\n } = useImageLoadState(thumbnailUrl);\n\n useEffect(() => {\n if (isPending) return;\n if (!title) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the VideoCard has no title\");\n return;\n }\n if (!videoId) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `the VideoCard \"${title}\" has no valid YouTube videoId`);\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, title, videoId, reportNodeStatus]);\n\n const cardClassName = classNames(\n styles.card,\n isInsideSurface ? styles.cardFlat : styles.cardElevated,\n isCompact && styles.cardCompact,\n );\n\n if (isPending) {\n return (\n <span className={cardClassName} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <span className={styles.frame}>\n <Skeleton className={styles.frameSkeleton} />\n </span>\n <span className={styles.text}>\n <Skeleton className={styles.titleSkeleton} />\n <Skeleton className={styles.metaSkeleton} />\n </span>\n </span>\n );\n }\n if (!title) return null;\n if (!videoId) {\n return (\n <span className={cardClassName} data-testid={testId}>\n <ModelText role=\"body\" weight=\"bold\" className={styles.wrap}>\n {title}\n </ModelText>\n </span>\n );\n }\n\n const watchUrl = videoId ? buildVideoWatchUrl(videoId) : undefined;\n const hasControls = videoId !== undefined && !isEmailRender && !isInsidePressable;\n const canPlayInPlace = hasControls && !isCompact;\n const showThumbnail = thumbnailUrl !== undefined && thumbnailLoadState !== \"failed\";\n const playVideo = () => {\n if (canPlayInPlace) {\n setIsPlaying(true);\n return;\n }\n if (watchUrl) window.open(watchUrl, \"_blank\", \"noopener,noreferrer\");\n };\n\n const frame =\n isPlaying && videoId ? (\n <span className={styles.frame}>\n <iframe\n className={styles.player}\n data-testid={`${testId}-player`}\n src={buildVideoEmbedUrl(videoId)}\n title={title}\n allow=\"autoplay; encrypted-media; picture-in-picture; fullscreen\"\n allowFullScreen\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n </span>\n ) : (\n <InteractiveSurface hoverable={hasControls} className={styles.frame}>\n {showThumbnail ? (\n <img\n ref={thumbnailRef}\n className={styles.thumbnail}\n src={thumbnailUrl}\n alt=\"\"\n loading={isEmailRender ? \"eager\" : \"lazy\"}\n decoding=\"async\"\n onLoad={markThumbnailLoaded}\n onError={markThumbnailFailed}\n />\n ) : null}\n {showThumbnail && thumbnailLoadState === \"loading\" ? <Skeleton className={styles.frameSkeleton} /> : null}\n <span className={classNames(styles.playBadge, isCompact && styles.playBadgeCompact)} aria-hidden=\"true\">\n <Icon color=\"var(--agents-fg-on-dark)\" name=\"play\" />\n </span>\n {duration ? (\n <span className={styles.durationChip}>\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {duration}\n </Text>\n </span>\n ) : null}\n {hasControls ? (\n <button\n type=\"button\"\n className={styles.playButton}\n data-testid={`${testId}-play`}\n aria-label={translateText(\"Play the video %title%\", { title })}\n onClick={playVideo}\n />\n ) : null}\n </InteractiveSurface>\n );\n\n if (isCompact) {\n return (\n <span className={cardClassName} data-testid={testId}>\n {frame}\n <ModelText role=\"caption\" weight=\"medium\" className={styles.compactTitle}>\n {title}\n </ModelText>\n </span>\n );\n }\n\n // YouTube's own card layout: the channel on its line, \"views · date\" under it — a wrapped line never starts with a dot.\n const statisticPhrases = [\n viewCount !== undefined ? (\n <Text\n key=\"views\"\n role=\"caption\"\n color=\"var(--agents-fg-light)\"\n replacements={{ count: formatViewCount(viewCount, numberLocale) }}\n context={viewCount === 1 ? \"one\" : \"other\"}\n >\n {\"%count% view\"}\n </Text>\n ) : null,\n publishedDay ? (\n <Text key=\"published\" role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {publishedDay}\n </Text>\n ) : null,\n ].filter((statisticPhrase) => statisticPhrase !== null);\n\n return (\n <article className={cardClassName} data-testid={testId}>\n {frame}\n <span className={styles.text}>\n <span className={styles.title} title={title}>\n <ModelText role=\"body\" weight=\"bold\" className={styles.titleText}>\n {title}\n </ModelText>\n </span>\n {channel ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-light)\" className={styles.wrap}>\n {channel}\n </ModelText>\n ) : null}\n {statisticPhrases.length > 0 ? (\n <span className={styles.metaLine}>\n {statisticPhrases.map((statisticPhrase, phraseIndex) => (\n <span key={phraseIndex} className={styles.metaPhrase}>\n {phraseIndex > 0 ? (\n <Text role=\"caption\" color=\"var(--agents-fg-lightest)\" translate={false}>\n {\"·\"}\n </Text>\n ) : null}\n {statisticPhrase}\n </span>\n ))}\n </span>\n ) : null}\n </span>\n {hasControls && watchUrl ? (\n <a\n className={styles.openLink}\n href={watchUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n data-testid={`${testId}-open-link`}\n >\n <Text role=\"help\" weight=\"medium\" color=\"var(--agents-fg-cta)\">\n {\"Open on YouTube\"}\n </Text>\n <Icon color=\"var(--agents-fg-cta)\" name=\"arrowRight\" />\n </a>\n ) : null}\n </article>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"VideoCard\",\n component: VideoCardNode,\n};\n","import type { HLJSApi, LanguageFn } from \"highlight.js\";\nimport type KatexModule from \"katex\";\nimport type { Mermaid } from \"mermaid\";\nimport type { DOMPurify } from \"dompurify\";\n\n/**\n * The renderer libraries of the rich kit components, each behind a dynamic `import()`: the kit's\n * component files are imported eagerly by the folder registry, so a static import here would put KaTeX, highlight.js,\n * Mermaid and DOMPurify into the chat bundle. Each library loads once per page, on the first node that needs it, as\n * its own chunk; a failed load is forgotten so the next node retries.\n */\n\ntype Katex = typeof KatexModule;\n\nlet katexPromise: Promise<Katex> | undefined;\nlet highlighterPromise: Promise<HLJSApi> | undefined;\nlet mermaidPromise: Promise<Mermaid> | undefined;\nlet domPurifyPromise: Promise<DOMPurify> | undefined;\nconst highlightLanguagePromises: Record<string, Promise<boolean>> = {};\n\n/** KaTeX with its stylesheet (the stylesheet loads the fonts it needs on demand). */\nexport const loadKatex = (): Promise<Katex> => {\n katexPromise ??= Promise.all([import(\"katex\"), import(\"katex/dist/katex.min.css\")])\n .then(([katexModule]) => katexModule.default)\n .catch((error: unknown) => {\n katexPromise = undefined;\n throw error;\n });\n return katexPromise;\n};\n\n/** Mermaid (its diagram-type chunks load inside it, per diagram type). */\nexport const loadMermaid = (): Promise<Mermaid> => {\n mermaidPromise ??= import(\"mermaid\")\n .then((mermaidModule) => mermaidModule.default)\n .catch((error: unknown) => {\n mermaidPromise = undefined;\n throw error;\n });\n return mermaidPromise;\n};\n\n/** DOMPurify as a factory: each caller builds its own instance, so hooks never leak from one caller to another. */\nexport const loadDomPurify = (): Promise<DOMPurify> => {\n domPurifyPromise ??= import(\"dompurify\")\n .then((domPurifyModule) => domPurifyModule.default)\n .catch((error: unknown) => {\n domPurifyPromise = undefined;\n throw error;\n });\n return domPurifyPromise;\n};\n\n/**\n * The highlight.js grammars the `Code` node can load, by grammar name. A closed list of static imports: each grammar\n * is its own chunk, and no name outside the list can be requested.\n */\nconst HIGHLIGHT_LANGUAGE_LOADERS: Record<string, () => Promise<{ default: LanguageFn }>> = {\n bash: () => import(\"highlight.js/lib/languages/bash\"),\n c: () => import(\"highlight.js/lib/languages/c\"),\n cpp: () => import(\"highlight.js/lib/languages/cpp\"),\n csharp: () => import(\"highlight.js/lib/languages/csharp\"),\n css: () => import(\"highlight.js/lib/languages/css\"),\n diff: () => import(\"highlight.js/lib/languages/diff\"),\n dockerfile: () => import(\"highlight.js/lib/languages/dockerfile\"),\n go: () => import(\"highlight.js/lib/languages/go\"),\n graphql: () => import(\"highlight.js/lib/languages/graphql\"),\n ini: () => import(\"highlight.js/lib/languages/ini\"),\n java: () => import(\"highlight.js/lib/languages/java\"),\n javascript: () => import(\"highlight.js/lib/languages/javascript\"),\n json: () => import(\"highlight.js/lib/languages/json\"),\n kotlin: () => import(\"highlight.js/lib/languages/kotlin\"),\n markdown: () => import(\"highlight.js/lib/languages/markdown\"),\n php: () => import(\"highlight.js/lib/languages/php\"),\n plaintext: () => import(\"highlight.js/lib/languages/plaintext\"),\n python: () => import(\"highlight.js/lib/languages/python\"),\n ruby: () => import(\"highlight.js/lib/languages/ruby\"),\n rust: () => import(\"highlight.js/lib/languages/rust\"),\n scss: () => import(\"highlight.js/lib/languages/scss\"),\n shell: () => import(\"highlight.js/lib/languages/shell\"),\n sql: () => import(\"highlight.js/lib/languages/sql\"),\n swift: () => import(\"highlight.js/lib/languages/swift\"),\n typescript: () => import(\"highlight.js/lib/languages/typescript\"),\n xml: () => import(\"highlight.js/lib/languages/xml\"),\n yaml: () => import(\"highlight.js/lib/languages/yaml\"),\n};\n\n/** The names a model writes for a language, mapped to the grammar name. */\nconst HIGHLIGHT_LANGUAGE_ALIASES: Record<string, string> = {\n \"c++\": \"cpp\",\n \"c#\": \"csharp\",\n cs: \"csharp\",\n docker: \"dockerfile\",\n html: \"xml\",\n js: \"javascript\",\n jsx: \"javascript\",\n md: \"markdown\",\n py: \"python\",\n rb: \"ruby\",\n rs: \"rust\",\n sh: \"bash\",\n svg: \"xml\",\n text: \"plaintext\",\n toml: \"ini\",\n ts: \"typescript\",\n tsx: \"typescript\",\n txt: \"plaintext\",\n yml: \"yaml\",\n zsh: \"bash\",\n};\n\n/** The grammar name for what the model wrote (`\"PHP\"`, `\"ts\"`, `\"html\"`), or undefined when no grammar fits. */\nexport const resolveHighlightLanguage = (language: unknown): string | undefined => {\n if (typeof language !== \"string\") return undefined;\n const lowercasedLanguage = language.trim().toLowerCase();\n const grammarName = Object.prototype.hasOwnProperty.call(HIGHLIGHT_LANGUAGE_ALIASES, lowercasedLanguage)\n ? HIGHLIGHT_LANGUAGE_ALIASES[lowercasedLanguage]\n : lowercasedLanguage;\n return Object.prototype.hasOwnProperty.call(HIGHLIGHT_LANGUAGE_LOADERS, grammarName) ? grammarName : undefined;\n};\n\n/** The highlight.js core, without any grammar. */\nconst loadHighlighter = (): Promise<HLJSApi> => {\n highlighterPromise ??= import(\"highlight.js/lib/core\")\n .then((highlighterModule) => highlighterModule.default)\n .catch((error: unknown) => {\n highlighterPromise = undefined;\n throw error;\n });\n return highlighterPromise;\n};\n\n/** The highlight.js core with the grammar `grammarName` registered (a name {@link resolveHighlightLanguage} returned). */\nexport const loadHighlighterWithLanguage = async (grammarName: string): Promise<HLJSApi> => {\n const highlighter = await loadHighlighter();\n if (!Object.prototype.hasOwnProperty.call(highlightLanguagePromises, grammarName)) {\n highlightLanguagePromises[grammarName] = HIGHLIGHT_LANGUAGE_LOADERS[grammarName]()\n .then((grammarModule) => {\n highlighter.registerLanguage(grammarName, grammarModule.default);\n return true;\n })\n .catch((error: unknown) => {\n delete highlightLanguagePromises[grammarName];\n throw error;\n });\n }\n await highlightLanguagePromises[grammarName];\n return highlighter;\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport type { ComposedSizeClass } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport { WidgetSurface } from \"../../../widgets/_shared/modern\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport styles from \"./RichNodeFrame.module.scss\";\n\nexport interface RichNodeFrameProps {\n /** The room the node has: at the root (`full`) the node is the widget and sits on its own elevated surface. */\n sizeClass: ComposedSizeClass;\n /** The model-written heading (business content, never translated). */\n title?: string;\n /** The model-written line under the heading. */\n caption?: string;\n /** A short technical label on the right of the header (\"LaTeX\", \"PHP\"), shown as written. */\n badge?: ReactNode;\n /** The header's controls (copy, wrap), right-aligned. */\n actions?: ReactNode;\n /** A node that is a tile wherever it sits (a code block); otherwise a nested node renders without a surface. */\n isTileWhenNested?: boolean;\n /** The muted line under the content (Math's example line), divided by a hairline. */\n footer?: ReactNode;\n children: ReactNode;\n testId?: string;\n}\n\n/**\n * The frame every rich kit node shares: on the chat (the tree's root) an elevated card with the\n * heading, the caption and the header controls; nested in another node, the same parts without a surface of their own\n * (the parent is the card) — a code block keeps a tile there, flat inside a surface and elevated outside one. The title is `textIntro` bold at the root and\n * `text` bold inside a parent.\n */\nexport const RichNodeFrame = (props: RichNodeFrameProps) => {\n const { sizeClass, title, caption, badge, actions, isTileWhenNested = false, footer, children, testId } = props;\n const isRoot = sizeClass === \"full\";\n const hasHeader = Boolean(title) || badge !== undefined || actions !== undefined;\n const content = (\n <>\n {hasHeader ? (\n <div className={styles.header}>\n <div className={styles.heading}>\n {title ? (\n <Text\n role={isRoot ? \"intro\" : \"body\"}\n weight=\"bold\"\n translate={false}\n className={styles.wrappingText}\n >\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n {caption ? (\n <Text\n role=\"help\"\n color=\"var(--agents-fg-light)\"\n translate={false}\n className={styles.wrappingText}\n >\n {escapePlainTextForText(caption)}\n </Text>\n ) : null}\n </div>\n {badge !== undefined || actions !== undefined ? (\n <div className={styles.headerEnd}>\n {badge}\n {actions}\n </div>\n ) : null}\n </div>\n ) : null}\n {children}\n {footer ? <div className={styles.footer}>{footer}</div> : null}\n </>\n );\n if (isRoot)\n return (\n <WidgetSurface level=\"elevated\" testId={testId}>\n {content}\n </WidgetSurface>\n );\n // A code block keeps a tile of its own: elevated when its parents draw no surface (a Stack on the chat), flat inside\n // a surface — the stylesheet reads WidgetSurface's `data-surface-level` on an ancestor.\n if (isTileWhenNested)\n return (\n <div className={styles.tile} data-testid={testId}>\n {content}\n </div>\n );\n return (\n <div className={classNames(styles.nested, sizeClass === \"compact\" && styles.compact)} data-testid={testId}>\n {content}\n </div>\n );\n};\n\nexport interface RichNodeContentSkeletonProps {\n /** The height of the content block it stands for, in CSS pixels. */\n height: number;\n testId?: string;\n}\n\n/** The loading block of a rich node: the content's own shape (the heading stays real text), marked busy. */\nexport const RichNodeContentSkeleton = (props: RichNodeContentSkeletonProps) => {\n const { height, testId } = props;\n return (\n <div className={styles.skeleton} aria-busy=\"true\" data-testid={testId}>\n <SkeletonLine width=\"100%\" height={height} radius={12} />\n </div>\n );\n};\n\nexport interface RichNodeBadgeProps {\n /** A technical name shown as written (\"LaTeX\", \"PHP\", \"Mermaid\"). */\n children: string;\n}\n\n/** The quiet label in a rich node's header that names the notation (ChatGPT's \"LaTeX\" badge). */\nexport const RichNodeBadge = (props: RichNodeBadgeProps) => {\n const { children } = props;\n return (\n <span className={styles.badge}>\n <Text role=\"caption\" weight=\"medium\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(children)}\n </Text>\n </span>\n );\n};\n","import { Button } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useState } from \"react\";\nimport { ConversationWidgetActions } from \"../../../renderer/ConversationWidgetActions/ConversationWidgetActions\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadHighlighterWithLanguage, resolveHighlightLanguage } from \"./rich-libraries\";\nimport { RichNodeBadge, RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport styles from \"./Code.module.scss\";\n\n/** Lines shown before \"Show all lines\"; the rest stays one click away. */\nexport const CODE_COLLAPSED_LINE_COUNT = 24;\n\nconst COPIED_CONFIRMATION_MS = 2000;\n\n/** How a language name reads in the header — the common names in their usual spelling, the rest as written. */\nconst LANGUAGE_DISPLAY_NAMES: Record<string, string> = {\n bash: \"Bash\",\n cpp: \"C++\",\n csharp: \"C#\",\n css: \"CSS\",\n dockerfile: \"Dockerfile\",\n graphql: \"GraphQL\",\n html: \"HTML\",\n javascript: \"JavaScript\",\n js: \"JavaScript\",\n json: \"JSON\",\n kotlin: \"Kotlin\",\n markdown: \"Markdown\",\n php: \"PHP\",\n python: \"Python\",\n scss: \"SCSS\",\n sql: \"SQL\",\n ts: \"TypeScript\",\n typescript: \"TypeScript\",\n xml: \"XML\",\n yaml: \"YAML\",\n};\n\nconst readLanguageDisplayName = (language: unknown): string | undefined => {\n if (typeof language !== \"string\" || language.trim() === \"\") return undefined;\n const writtenLanguage = language.trim();\n const lowercasedLanguage = writtenLanguage.toLowerCase();\n return Object.prototype.hasOwnProperty.call(LANGUAGE_DISPLAY_NAMES, lowercasedLanguage)\n ? LANGUAGE_DISPLAY_NAMES[lowercasedLanguage]\n : writtenLanguage;\n};\n\ntype CodeHighlighting = { status: \"plain\" } | { status: \"highlighted\"; html: string };\n\n/**\n * The `Code` node (`CodeComposedViewNode.php`): source code in a tile with the\n * language (or the title) in its header, a copy button and a line-wrap toggle. The plain code shows at once; the\n * highlight.js grammar of the language loads on first use and colours it (highlight.js escapes the source, so the\n * coloured markup holds no markup of the code's own). An unknown language stays plain text. Long code shows its first\n * {@link CODE_COLLAPSED_LINE_COUNT} lines with \"Show all lines\". The e-mail capture shows no controls and wraps lines.\n */\nconst CodeNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const code = typeof nodeProps.code === \"string\" ? nodeProps.code.replace(/\\n+$/, \"\") : \"\";\n const grammarName = resolveHighlightLanguage(nodeProps.language);\n const languageDisplayName = readLanguageDisplayName(nodeProps.language);\n const title = typeof nodeProps.title === \"string\" && nodeProps.title.trim() !== \"\" ? nodeProps.title : undefined;\n const [highlighting, setHighlighting] = useState<CodeHighlighting>({ status: \"plain\" });\n const [isWrapped, setIsWrapped] = useState(nodeProps.wrap === true);\n const [isExpanded, setIsExpanded] = useState(false);\n const [isCopied, setIsCopied] = useState(false);\n const lineCount = code === \"\" ? 0 : code.split(\"\\n\").length;\n const isCollapsible = lineCount > CODE_COLLAPSED_LINE_COUNT;\n\n useEffect(() => {\n setHighlighting({ status: \"plain\" });\n if (grammarName === undefined || code === \"\") return;\n let isCurrent = true;\n loadHighlighterWithLanguage(grammarName)\n .then((highlighter) => {\n if (!isCurrent) return;\n const highlightedHtml = highlighter.highlight(code, { language: grammarName, ignoreIllegals: true }).value;\n setHighlighting({ status: \"highlighted\", html: highlightedHtml });\n })\n // A grammar that does not load leaves the plain code, which is complete — nothing is lost but the colours.\n .catch(() => undefined);\n return () => {\n isCurrent = false;\n };\n }, [code, grammarName]);\n\n useEffect(() => {\n if (isPending) reportNodeStatus(\"pending\");\n else if (code === \"\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the code block is empty\");\n else reportNodeStatus(\"mounted\");\n }, [code, isPending, reportNodeStatus]);\n\n useEffect(() => {\n if (!isCopied) return;\n const confirmationTimer = setTimeout(() => setIsCopied(false), COPIED_CONFIRMATION_MS);\n return () => clearTimeout(confirmationTimer);\n }, [isCopied]);\n\n const copyCode = () => {\n void navigator.clipboard\n ?.writeText(code)\n .then(() => setIsCopied(true))\n .catch(() => undefined);\n };\n\n // The code is bound to data that has not arrived yet: the tile with its header and a code-shaped skeleton.\n if (isPending) {\n return (\n <RichNodeFrame sizeClass={sizeClass} title={title ?? languageDisplayName} isTileWhenNested testId={testId}>\n <RichNodeContentSkeleton height={160} testId={`${testId}-skeleton`} />\n </RichNodeFrame>\n );\n }\n // No code: the node renders nothing and reports `empty` (one muted line or nothing).\n if (code === \"\") return null;\n\n const linesWrap = isWrapped || isEmailRender;\n const isClipped = isCollapsible && !isExpanded;\n const actions = isEmailRender ? undefined : (\n <ConversationWidgetActions>\n <div className={styles.actions}>\n <Button\n variant=\"muted\"\n size=\"small\"\n icon=\"text\"\n pressed={isWrapped}\n testId={`${testId}-wrap`}\n onClick={() => setIsWrapped((wasWrapped) => !wasWrapped)}\n >\n {\"Wrap lines\"}\n </Button>\n <Button\n variant=\"muted\"\n size=\"small\"\n icon={isCopied ? \"check\" : \"duplicate\"}\n onClick={copyCode}\n testId={`${testId}-copy`}\n >\n {isCopied ? \"Copied\" : \"Copy\"}\n </Button>\n </div>\n </ConversationWidgetActions>\n );\n\n return (\n <RichNodeFrame\n sizeClass={sizeClass}\n title={title ?? languageDisplayName ?? undefined}\n badge={title && languageDisplayName ? <RichNodeBadge>{languageDisplayName}</RichNodeBadge> : undefined}\n actions={actions}\n isTileWhenNested\n testId={testId}\n >\n <div className={classNames(styles.codeArea, isClipped && styles.clipped)}>\n {highlighting.status === \"highlighted\" ? (\n <pre className={classNames(styles.code, linesWrap && styles.wrapped)}>\n <code className=\"hljs\" dangerouslySetInnerHTML={{ __html: highlighting.html }} />\n </pre>\n ) : (\n <pre className={classNames(styles.code, linesWrap && styles.wrapped)}>\n <code>{code}</code>\n </pre>\n )}\n </div>\n {isCollapsible && !isEmailRender ? (\n <div className={styles.expandRow}>\n <Button\n variant=\"muted\"\n size=\"small\"\n rounded\n icon={isExpanded ? \"caretUp\" : \"caretDown\"}\n replacements={{ lineCount }}\n testId={`${testId}-expand`}\n onClick={() => setIsExpanded((wasExpanded) => !wasExpanded)}\n >\n {isExpanded ? \"Show fewer lines\" : \"Show all %lineCount% lines\"}\n </Button>\n </div>\n ) : null}\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Code\", component: CodeNode };\n","import type { DOMPurify } from \"dompurify\";\n\n/**\n * Sanitises SVG markup for the rich kit components: the `Svg` node's model-written graphic and the\n * SVG Mermaid draws for a `Diagram`. DOMPurify's SVG profile, plus:\n *\n * - no `script`, `foreignObject`, link (`a`), `image` / `feImage`, `use`, animation (`animate`, `set`, …) or embedding\n * element (DOMPurify's SVG profile leaves out `use` itself);\n * - no `style` element for a model-written graphic (Mermaid's own scoped stylesheet stays, its CSS is Mermaid's);\n * - a reference (`href`, `xlink:href`) only to an element of the same graphic (`#id`), a paint `url(…)` only as\n * `url(#id)` — nothing that loads from outside the graphic;\n * - exactly one `<svg>` element at the root; a root without a `viewBox` gets one from its `width` / `height`, and the\n * fixed size is dropped so the graphic scales with its box.\n *\n * Each call builds its own DOMPurify instance, so the hooks never reach another caller of the library.\n */\n\nexport interface SanitizedSvgMarkup {\n /** The safe markup of the one `<svg>` element, or null when nothing safe is left to draw. */\n markup: string | null;\n /** The names of the elements and attributes that were removed (`script`, `onload`, `href`, …), deduplicated. */\n removedPartNames: string[];\n}\n\nexport interface SanitizeSvgMarkupOptions {\n /** Keep a `<style>` element (Mermaid's scoped stylesheet); false for a model-written graphic. */\n keepStyleElement: boolean;\n /** The accessible name of the graphic (`role=\"img\"` + `aria-label`); without one the graphic keeps its own. */\n label?: string;\n}\n\nconst FORBIDDEN_ELEMENT_NAMES = [\n \"a\",\n \"animate\",\n \"animateColor\",\n \"animateMotion\",\n \"animateTransform\",\n \"discard\",\n \"embed\",\n \"feImage\",\n \"foreignObject\",\n \"iframe\",\n \"image\",\n \"object\",\n \"script\",\n \"set\",\n];\n\nconst REFERENCE_ATTRIBUTE_NAMES = new Set([\"href\", \"xlink:href\"]);\n\nconst DOCUMENT_WRAPPER_ELEMENT_NAMES = new Set([\"html\", \"head\", \"body\"]);\n\n/** Every `url(…)` in the value points into the graphic (`url(#id)`). */\nconst usesOnlyInternalUrls = (attributeValue: string): boolean => {\n const urlPattern = /url\\s*\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/gi;\n let urlMatch = urlPattern.exec(attributeValue);\n while (urlMatch !== null) {\n if (!urlMatch[2].trim().startsWith(\"#\")) return false;\n urlMatch = urlPattern.exec(attributeValue);\n }\n return true;\n};\n\nconst readNumericLength = (lengthValue: string | null): number | null => {\n if (lengthValue === null) return null;\n const length = Number.parseFloat(lengthValue);\n return Number.isFinite(length) && length > 0 && /^\\s*[\\d.]+(px)?\\s*$/.test(lengthValue) ? length : null;\n};\n\nexport const sanitizeSvgMarkup = (\n domPurifyFactory: DOMPurify,\n svgMarkup: string,\n options: SanitizeSvgMarkupOptions,\n): SanitizedSvgMarkup => {\n const domPurify = domPurifyFactory(window);\n const hookRemovedPartNames: string[] = [];\n domPurify.addHook(\"uponSanitizeAttribute\", (attributeOwner, hookEvent) => {\n const attributeName = hookEvent.attrName.toLowerCase();\n const attributeValue = hookEvent.attrValue ?? \"\";\n const isExternalReference = REFERENCE_ATTRIBUTE_NAMES.has(attributeName) && !attributeValue.trim().startsWith(\"#\");\n const loadsFromOutside = /url\\s*\\(/i.test(attributeValue) && !usesOnlyInternalUrls(attributeValue);\n const isStyleExpression = attributeName === \"style\" && /@import|expression\\s*\\(|javascript:/i.test(attributeValue);\n if (isExternalReference || loadsFromOutside || isStyleExpression) {\n hookEvent.keepAttr = false;\n hookRemovedPartNames.push(attributeName);\n }\n });\n const sanitizedFragment = domPurify.sanitize(svgMarkup, {\n USE_PROFILES: { svg: true, svgFilters: true },\n // `role` is an accessibility attribute, not a script or a reference: Mermaid writes `role=\"graphics-document\n // document\"` on every drawing, and removing it reported every valid diagram as unsafe.\n ADD_ATTR: [\"role\"],\n FORBID_TAGS: options.keepStyleElement ? FORBIDDEN_ELEMENT_NAMES : [...FORBIDDEN_ELEMENT_NAMES, \"style\"],\n RETURN_DOM_FRAGMENT: true,\n });\n const removedPartNames = new Set<string>(hookRemovedPartNames);\n for (const removedPart of domPurify.removed) {\n if (\"element\" in removedPart && removedPart.element) {\n const removedElementName = removedPart.element.nodeName.toLowerCase();\n // The document wrapper DOMPurify parses into is listed as removed when it returns a fragment — not a part.\n if (!DOCUMENT_WRAPPER_ELEMENT_NAMES.has(removedElementName)) removedPartNames.add(removedElementName);\n } else if (\"attribute\" in removedPart && removedPart.attribute) {\n removedPartNames.add(removedPart.attribute.name.toLowerCase());\n }\n }\n domPurify.removeAllHooks();\n\n const rootElements = Array.from(sanitizedFragment.children);\n const svgElement =\n rootElements.length === 1 && rootElements[0].nodeName.toLowerCase() === \"svg\" ? rootElements[0] : null;\n if (svgElement === null) return { markup: null, removedPartNames: [...removedPartNames] };\n\n if (!svgElement.hasAttribute(\"viewBox\")) {\n const width = readNumericLength(svgElement.getAttribute(\"width\"));\n const height = readNumericLength(svgElement.getAttribute(\"height\"));\n if (width !== null && height !== null) svgElement.setAttribute(\"viewBox\", `0 0 ${width} ${height}`);\n }\n if (svgElement.hasAttribute(\"viewBox\")) {\n svgElement.removeAttribute(\"width\");\n svgElement.removeAttribute(\"height\");\n }\n svgElement.setAttribute(\"focusable\", \"false\");\n if (options.label) {\n svgElement.setAttribute(\"role\", \"img\");\n svgElement.setAttribute(\"aria-label\", options.label);\n }\n if (!svgElement.hasChildNodes()) return { markup: null, removedPartNames: [...removedPartNames] };\n return { markup: svgElement.outerHTML, removedPartNames: [...removedPartNames] };\n};\n","import { useEffect, useState } from \"react\";\n\n/**\n * The colours a Mermaid diagram is drawn in: the theme's functional tokens, resolved to concrete\n * colours on the diagram's own element at draw time — Mermaid computes shades from them, so it needs real colours, not\n * `var(…)` references — and the revision that changes when the colour scheme or theme switches, so the diagram is\n * redrawn in the new colours.\n */\n\nconst resolveTokenColor = (probeParent: HTMLElement, cssColorValue: string): string => {\n const colorProbe = document.createElement(\"span\");\n colorProbe.style.color = cssColorValue;\n colorProbe.style.display = \"none\";\n probeParent.appendChild(colorProbe);\n const resolvedColor = getComputedStyle(colorProbe).color;\n colorProbe.remove();\n return resolvedColor;\n};\n\n/** Relative luminance (0 dark … 1 light) of an `rgb(…)` colour, or 1 when it cannot be read. */\nconst readLuminance = (rgbColor: string): number => {\n const channelMatch = rgbColor.match(/\\d+(\\.\\d+)?/g);\n if (!channelMatch || channelMatch.length < 3) return 1;\n const [red, green, blue] = channelMatch.slice(0, 3).map((channel) => Number(channel) / 255);\n return 0.2126 * red + 0.7152 * green + 0.0722 * blue;\n};\n\n/** Mermaid's `base` theme variables from the theme tokens around `probeParent`. */\nexport const readDiagramThemeVariables = (probeParent: HTMLElement): Record<string, string | boolean> => {\n const surfaceColor = resolveTokenColor(probeParent, \"var(--agents-bg-surface)\");\n const nodeColor = resolveTokenColor(probeParent, \"var(--agents-bg-var)\");\n const textColor = resolveTokenColor(probeParent, \"var(--agents-fg)\");\n const lineColor = resolveTokenColor(probeParent, \"var(--agents-fg-lightest)\");\n const borderColor = resolveTokenColor(probeParent, \"var(--agents-divider-gl)\");\n const fontFamily = getComputedStyle(probeParent).fontFamily;\n return {\n darkMode: readLuminance(surfaceColor) < 0.5,\n background: surfaceColor,\n fontFamily,\n primaryColor: nodeColor,\n primaryTextColor: textColor,\n primaryBorderColor: borderColor,\n secondaryColor: nodeColor,\n secondaryTextColor: textColor,\n secondaryBorderColor: borderColor,\n tertiaryColor: surfaceColor,\n tertiaryTextColor: textColor,\n tertiaryBorderColor: borderColor,\n mainBkg: nodeColor,\n nodeBorder: borderColor,\n clusterBkg: surfaceColor,\n clusterBorder: borderColor,\n lineColor,\n textColor,\n titleColor: textColor,\n edgeLabelBackground: nodeColor,\n noteBkgColor: nodeColor,\n noteTextColor: textColor,\n noteBorderColor: borderColor,\n actorBkg: nodeColor,\n actorBorder: borderColor,\n actorTextColor: textColor,\n signalColor: lineColor,\n signalTextColor: textColor,\n };\n};\n\nconst COLOR_SCHEME_ATTRIBUTES = [\"data-color-scheme\", \"data-theme\", \"class\", \"style\"];\n\n/** A number that grows whenever the page's colour scheme or theme may have changed. */\nexport const useColorSchemeRevision = (): number => {\n const [colorSchemeRevision, setColorSchemeRevision] = useState(0);\n useEffect(() => {\n const bumpRevision = () => setColorSchemeRevision((revision) => revision + 1);\n const attributeObserver = new MutationObserver(bumpRevision);\n attributeObserver.observe(document.documentElement, { attributes: true, attributeFilter: COLOR_SCHEME_ATTRIBUTES });\n const darkSchemeQuery = window.matchMedia?.(\"(prefers-color-scheme: dark)\");\n darkSchemeQuery?.addEventListener?.(\"change\", bumpRevision);\n return () => {\n attributeObserver.disconnect();\n darkSchemeQuery?.removeEventListener?.(\"change\", bumpRevision);\n };\n }, []);\n return colorSchemeRevision;\n};\n","import { Text } from \"../../../provider/components\";\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadDomPurify, loadMermaid } from \"./rich-libraries\";\nimport { sanitizeSvgMarkup } from \"./sanitize-svg-markup\";\nimport { RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport { readDiagramThemeVariables, useColorSchemeRevision } from \"./diagram-theme\";\nimport styles from \"./Diagram.module.scss\";\n\ntype DiagramRendering =\n | { status: \"loading\" }\n | { status: \"empty\" }\n | { status: \"rendered\"; svgMarkup: string; removedPartNames: string[] }\n | { status: \"failed\"; detail: string };\n\n/** The longest Mermaid parse message the report carries. */\nconst MAX_ERROR_DETAIL_LENGTH = 300;\n\nconst readMermaidErrorMessage = (error: unknown): string => {\n const message = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"unknown error\";\n return message.replace(/\\s+/g, \" \").trim().slice(0, MAX_ERROR_DETAIL_LENGTH);\n};\n\n/**\n * The `Diagram` node (`DiagramComposedViewNode.php`): a Mermaid diagram,\n * Mermaid loaded on first use as its own chunk. Mermaid runs at `securityLevel: \"strict\"` with SVG labels (no HTML in\n * labels, no click handlers), its colours are the theme's tokens resolved at draw time (redrawn when the colour scheme\n * changes), and the drawn SVG is sanitised again before it is shown. Source Mermaid cannot read renders one muted line\n * and is reported `failed` with Mermaid's message.\n */\nconst DiagramNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const source = typeof nodeProps.source === \"string\" ? nodeProps.source : \"\";\n const title = typeof nodeProps.title === \"string\" ? nodeProps.title : undefined;\n const caption = typeof nodeProps.caption === \"string\" ? nodeProps.caption : undefined;\n const [rendering, setRendering] = useState<DiagramRendering>({ status: \"loading\" });\n const themeProbeRef = useRef<HTMLDivElement>(null);\n const colorSchemeRevision = useColorSchemeRevision();\n // Mermaid needs a document-unique element id per drawing; React's id carries colons, which a CSS id selector refuses.\n const renderIdBase = `composed-diagram-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n\n useEffect(() => {\n if (isPending) {\n setRendering({ status: \"loading\" });\n return;\n }\n if (source.trim() === \"\") {\n setRendering({ status: \"empty\" });\n return;\n }\n let isCurrent = true;\n const themeProbe = themeProbeRef.current;\n setRendering({ status: \"loading\" });\n const drawDiagram = async (): Promise<DiagramRendering> => {\n const [mermaid, domPurifyFactory] = await Promise.all([loadMermaid(), loadDomPurify()]);\n const themeVariables = themeProbe ? readDiagramThemeVariables(themeProbe) : {};\n mermaid.initialize({\n startOnLoad: false,\n securityLevel: \"strict\",\n theme: \"base\",\n themeVariables,\n htmlLabels: false,\n // A short step name stays on one line (\"Widget auswählen\"); only a long one wraps.\n flowchart: { htmlLabels: false, useMaxWidth: true, wrappingWidth: 260 },\n maxTextSize: 4000,\n suppressErrorRendering: true,\n });\n try {\n await mermaid.parse(source);\n } catch (parseError) {\n return {\n status: \"failed\",\n detail: `Mermaid could not read the diagram — ${readMermaidErrorMessage(parseError)}`,\n };\n }\n const { svg } = await mermaid.render(`${renderIdBase}-${colorSchemeRevision}`, source);\n const sanitizedSvg = sanitizeSvgMarkup(domPurifyFactory, svg, { keepStyleElement: true, label: title });\n if (sanitizedSvg.markup === null)\n return { status: \"failed\", detail: \"the drawn diagram held nothing safe to show\" };\n return { status: \"rendered\", svgMarkup: sanitizedSvg.markup, removedPartNames: sanitizedSvg.removedPartNames };\n };\n drawDiagram()\n .then((diagramRendering) => {\n if (isCurrent) setRendering(diagramRendering);\n })\n .catch((drawError: unknown) => {\n if (isCurrent)\n setRendering({\n status: \"failed\",\n detail: `the diagram could not be drawn — ${readMermaidErrorMessage(drawError)}`,\n });\n });\n return () => {\n isCurrent = false;\n };\n }, [source, title, isPending, renderIdBase, colorSchemeRevision]);\n\n useEffect(() => {\n if (rendering.status === \"loading\") reportNodeStatus(\"pending\");\n if (rendering.status === \"empty\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the diagram source is empty\");\n if (rendering.status === \"failed\") reportNodeStatus(\"failed\", \"RENDER_FAILED\", rendering.detail);\n if (rendering.status === \"rendered\") {\n if (rendering.removedPartNames.length === 0) reportNodeStatus(\"mounted\");\n else {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n `unsafe parts of the drawn diagram were removed (${rendering.removedPartNames.join(\", \")}) — the rest is shown`,\n );\n }\n }\n }, [rendering, reportNodeStatus]);\n\n // No source: the node renders nothing and reports `empty` (one muted line or nothing).\n if (rendering.status === \"empty\") return null;\n return (\n <RichNodeFrame sizeClass={sizeClass} title={title} caption={caption} testId={testId}>\n <div ref={themeProbeRef} className={styles.diagramArea}>\n {rendering.status === \"rendered\" ? (\n <div className={styles.diagram} dangerouslySetInnerHTML={{ __html: rendering.svgMarkup }} />\n ) : null}\n {rendering.status === \"loading\" ? <RichNodeContentSkeleton height={240} testId={`${testId}-skeleton`} /> : null}\n {rendering.status === \"failed\" ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={`${testId}-error`}>\n {\"This diagram could not be drawn.\"}\n </Text>\n ) : null}\n </div>\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Diagram\", component: DiagramNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadKatex } from \"./rich-libraries\";\nimport { RichNodeBadge, RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport styles from \"./Math.module.scss\";\n\ntype MathRendering =\n | { status: \"loading\" }\n | { status: \"empty\" }\n | { status: \"rendered\"; html: string }\n | { status: \"failed\"; detail: string };\n\n/** KaTeX's own safety and size limits: no `\\href` / `\\url` / `\\includegraphics` / HTML extensions, bounded macros. */\nconst KATEX_OPTIONS = {\n throwOnError: false,\n trust: false,\n strict: \"ignore\",\n output: \"htmlAndMathml\",\n maxSize: 20,\n maxExpand: 500,\n} as const;\n\n/** The parse message KaTeX writes into its error element when `throwOnError` is off, or null for a valid formula. */\nconst readKatexErrorMessage = (renderedHtml: string): string | null => {\n if (!renderedHtml.includes(\"katex-error\")) return null;\n const template = document.createElement(\"template\");\n template.innerHTML = renderedHtml;\n return template.content.querySelector(\".katex-error\")?.getAttribute(\"title\") ?? \"KaTeX could not read the formula\";\n};\n\n/**\n * The `Math` node (`MathComposedViewNode.php`): a LaTeX formula typeset by\n * KaTeX, loaded on first use. A block formula sits centred under an optional heading with the \"LaTeX\" badge and an\n * optional caption line under a hairline; an inline formula flows in its line. A formula KaTeX cannot read shows its\n * source and one muted line, and is reported `failed` with KaTeX's parse message.\n */\nconst MathNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const latex = typeof nodeProps.latex === \"string\" ? nodeProps.latex : \"\";\n const isInline = nodeProps.display === \"inline\";\n const title = typeof nodeProps.title === \"string\" ? nodeProps.title : undefined;\n const caption = typeof nodeProps.caption === \"string\" ? nodeProps.caption : undefined;\n const [rendering, setRendering] = useState<MathRendering>({ status: \"loading\" });\n\n useEffect(() => {\n if (isPending) {\n setRendering({ status: \"loading\" });\n return;\n }\n if (latex.trim() === \"\") {\n setRendering({ status: \"empty\" });\n return;\n }\n let isCurrent = true;\n setRendering({ status: \"loading\" });\n loadKatex()\n .then((katex) => {\n if (!isCurrent) return;\n const renderedHtml = katex.renderToString(latex, { ...KATEX_OPTIONS, displayMode: !isInline });\n const errorMessage = readKatexErrorMessage(renderedHtml);\n setRendering(\n errorMessage === null\n ? { status: \"rendered\", html: renderedHtml }\n : { status: \"failed\", detail: `the formula is not valid LaTeX — ${errorMessage}` },\n );\n })\n .catch(() => {\n if (isCurrent) setRendering({ status: \"failed\", detail: \"the formula renderer could not be loaded\" });\n });\n return () => {\n isCurrent = false;\n };\n }, [latex, isInline, isPending]);\n\n useEffect(() => {\n if (rendering.status === \"loading\") reportNodeStatus(\"pending\");\n if (rendering.status === \"empty\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the formula is empty\");\n if (rendering.status === \"rendered\") reportNodeStatus(\"mounted\");\n if (rendering.status === \"failed\") reportNodeStatus(\"failed\", \"RENDER_FAILED\", rendering.detail);\n }, [rendering, reportNodeStatus]);\n\n // Nothing to typeset: the node renders nothing and reports `empty` (one muted line or nothing).\n if (rendering.status === \"empty\") return null;\n if (isInline) {\n if (rendering.status === \"rendered\") {\n return (\n <span\n className={styles.inlineFormula}\n data-testid={testId}\n dangerouslySetInnerHTML={{ __html: rendering.html }}\n />\n );\n }\n if (rendering.status === \"loading\") {\n return (\n <span className={styles.inlineSkeleton} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <SkeletonLine width={64} height={14} radius={4} />\n </span>\n );\n }\n return (\n <Text role=\"body\" translate={false} className={styles.source} testId={`${testId}-error`}>\n {escapePlainTextForText(latex)}\n </Text>\n );\n }\n\n const footer = caption ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false} className={styles.caption}>\n {escapePlainTextForText(caption)}\n </Text>\n ) : undefined;\n return (\n <RichNodeFrame\n sizeClass={sizeClass}\n title={title}\n badge={title ? <RichNodeBadge>LaTeX</RichNodeBadge> : undefined}\n footer={footer}\n testId={testId}\n >\n {rendering.status === \"rendered\" ? (\n <div className={styles.blockFormula} dangerouslySetInnerHTML={{ __html: rendering.html }} />\n ) : null}\n {rendering.status === \"loading\" ? <RichNodeContentSkeleton height={48} testId={`${testId}-skeleton`} /> : null}\n {rendering.status === \"failed\" ? (\n <div className={styles.failure} data-testid={`${testId}-error`}>\n <Text role=\"help\" color=\"var(--agents-fg-light)\">\n {\"This formula could not be rendered.\"}\n </Text>\n <Text role=\"help\" translate={false} className={styles.source}>\n {escapePlainTextForText(latex)}\n </Text>\n </div>\n ) : null}\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Math\", component: MathNode };\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadDomPurify } from \"./rich-libraries\";\nimport { sanitizeSvgMarkup } from \"./sanitize-svg-markup\";\nimport { RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport styles from \"./Svg.module.scss\";\n\ntype SvgRendering =\n | { status: \"loading\" }\n | { status: \"empty\" }\n | { status: \"rendered\"; svgMarkup: string; removedPartNames: string[] }\n | { status: \"failed\"; detail: string; removedPartNames: string[] };\n\n/**\n * The `Svg` node (`SvgComposedViewNode.php`): a vector graphic the model drew,\n * shown only after DOMPurify (loaded on first use) reduced it to safe SVG — no scripts, no event attributes, no\n * `foreignObject`, no `style` element, no link and no reference outside the graphic ({@link sanitizeSvgMarkup}). The\n * markup may be a computed text over the tree's state, so the drawing follows the inputs (the radar whose shape moves\n * with its sliders); each change is sanitised again. Removed parts are reported `failed` with their names while the\n * rest is drawn; markup with nothing safe left renders one muted line.\n */\nconst SvgNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const markup = typeof nodeProps.markup === \"string\" ? nodeProps.markup : \"\";\n const label = typeof nodeProps.label === \"string\" && nodeProps.label.trim() !== \"\" ? nodeProps.label : undefined;\n const title = typeof nodeProps.title === \"string\" ? nodeProps.title : undefined;\n const caption = typeof nodeProps.caption === \"string\" ? nodeProps.caption : undefined;\n const [rendering, setRendering] = useState<SvgRendering>({ status: \"loading\" });\n\n useEffect(() => {\n if (isPending) {\n setRendering({ status: \"loading\" });\n return;\n }\n if (markup.trim() === \"\") {\n setRendering({ status: \"empty\" });\n return;\n }\n let isCurrent = true;\n loadDomPurify()\n .then((domPurifyFactory) => {\n if (!isCurrent) return;\n const sanitizedSvg = sanitizeSvgMarkup(domPurifyFactory, markup, {\n keepStyleElement: false,\n label: label ?? title,\n });\n setRendering(\n sanitizedSvg.markup === null\n ? {\n status: \"failed\",\n detail: \"the markup holds no single <svg> element with safe content\",\n removedPartNames: sanitizedSvg.removedPartNames,\n }\n : { status: \"rendered\", svgMarkup: sanitizedSvg.markup, removedPartNames: sanitizedSvg.removedPartNames },\n );\n })\n .catch(() => {\n if (isCurrent)\n setRendering({ status: \"failed\", detail: \"the SVG sanitiser could not be loaded\", removedPartNames: [] });\n });\n return () => {\n isCurrent = false;\n };\n }, [markup, label, title, isPending]);\n\n useEffect(() => {\n if (rendering.status === \"loading\") reportNodeStatus(\"pending\");\n if (rendering.status === \"empty\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the SVG markup is empty\");\n if (rendering.status === \"failed\") {\n const removedPartsDetail =\n rendering.removedPartNames.length > 0 ? ` (removed: ${rendering.removedPartNames.join(\", \")})` : \"\";\n reportNodeStatus(\"failed\", \"RENDER_FAILED\", `${rendering.detail}${removedPartsDetail}`);\n }\n if (rendering.status === \"rendered\") {\n if (rendering.removedPartNames.length === 0) reportNodeStatus(\"mounted\");\n else {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n `unsafe SVG parts were removed (${rendering.removedPartNames.join(\", \")}) — the rest is drawn`,\n );\n }\n }\n }, [rendering, reportNodeStatus]);\n\n // No markup: the node renders nothing and reports `empty` (one muted line or nothing).\n if (rendering.status === \"empty\") return null;\n const graphic =\n rendering.status === \"rendered\" ? (\n <div\n className={classNames(styles.graphic, sizeClass === \"compact\" && styles.compactGraphic)}\n dangerouslySetInnerHTML={{ __html: rendering.svgMarkup }}\n />\n ) : rendering.status === \"loading\" ? (\n <RichNodeContentSkeleton height={sizeClass === \"compact\" ? 48 : 200} testId={`${testId}-skeleton`} />\n ) : (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={`${testId}-error`}>\n {\"This graphic could not be shown.\"}\n </Text>\n );\n\n return (\n <RichNodeFrame sizeClass={sizeClass} title={title} caption={caption} testId={testId}>\n {graphic}\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Svg\", component: SvgNode };\n","import { escapePlainTextForText } from \"../../../provider/environment\";\nimport { StatusBadge, type AgentsStatusBadgeStatus } from \"../../../provider/components\";\nimport { SkeletonPill } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n ComposedViewTone,\n readComposedViewTone,\n} from \"../../composed-view-tones\";\nimport { readTextNodeContent, readTextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\nimport styles from \"./Badge.module.scss\";\n\n/** The status colour of a tone: `muted` has no status of its own and reads as the neutral badge. */\nconst STATUS_OF_TONE: Readonly<Record<ComposedViewTone, AgentsStatusBadgeStatus>> = {\n neutral: \"neutral\",\n muted: \"neutral\",\n success: \"success\",\n warning: \"warning\",\n danger: \"danger\",\n info: \"info\",\n};\n\n/**\n * The `Badge` node (`BadgeComposedViewNode.php`): a short status with a judgement tone, as the design's\n * small status badge (the component library's `StatusBadge variant=\"small\"`, no icon). The status text\n * is the model's, so the badge is told not to translate it and the text is escaped (`model-text.ts`).\n */\nconst BadgeNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const tone = readComposedViewTone(nodeProps.tone);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Badge\");\n if (isPending) return <SkeletonPill width={72} height={20} />;\n if (content.kind !== \"text\") return null;\n return (\n <span className={styles.badge} data-tone={tone} data-testid={testId}>\n <StatusBadge\n status={STATUS_OF_TONE[tone]}\n text={escapePlainTextForText(content.text)}\n translate={false}\n size=\"small\"\n hideIcon\n />\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Badge\", component: BadgeNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readTextNodeContent, readTextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\nimport styles from \"./Caption.module.scss\";\n\n/**\n * The `Caption` node (`CaptionComposedViewNode.php`): muted secondary text — the sub-line under a title, a\n * unit, a date, a method note (`textCaption` in `--agents-fg-light`). A block of its own, or inline in a compact slot.\n */\nconst CaptionNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Caption\");\n if (isPending) return <SkeletonLine width=\"30%\" height={10} radius={4} />;\n if (content.kind !== \"text\") return null;\n return (\n <Text\n role=\"caption\"\n translate={false}\n color=\"--agents-fg-light\"\n display={sizeClass === \"compact\" ? \"inline\" : \"block\"}\n className={styles.caption}\n testId={testId}\n >\n {escapePlainTextForText(content.text)}\n </Text>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Caption\", component: CaptionNode };\n","import { Icon } from \"../../../../provider/components\";\nimport { useState } from \"react\";\nimport { buildFaviconUrl } from \"./text-node-values\";\nimport styles from \"./SiteFavicon.module.scss\";\n\nexport interface SiteFaviconProps {\n /** The site, or null when the value named none (the link glyph shows). */\n hostname: string | null;\n /** The site's name for the accessible label and the hover; the host name when absent. */\n siteName?: string;\n /** The e-mail capture fails on a broken image, and a favicon is an outside request: the capture shows the glyph. */\n isEmailRender: boolean;\n}\n\n/**\n * A site's favicon for the kit's text components (`Favicon`, `SourceRef`): the Google favicon service by host name, the\n * generic link glyph when there is no site, the image fails to load, or the e-mail capture renders — never a broken image.\n */\nexport const SiteFavicon = (props: SiteFaviconProps) => {\n const { hostname, siteName, isEmailRender } = props;\n const [hasFailedToLoad, setHasFailedToLoad] = useState(false);\n const accessibleName = siteName ?? hostname ?? undefined;\n if (hostname === null || hasFailedToLoad || isEmailRender) {\n return (\n <span\n className={styles.favicon}\n role={accessibleName ? \"img\" : undefined}\n aria-label={accessibleName}\n title={accessibleName}\n >\n <Icon color=\"var(--agents-fg-light)\" pixelSize={14} name=\"link\" />\n </span>\n );\n }\n return (\n <img\n className={styles.favicon}\n src={buildFaviconUrl(hostname)}\n alt={accessibleName ?? \"\"}\n title={accessibleName}\n loading=\"lazy\"\n onError={() => setHasFailedToLoad(true)}\n />\n );\n};\n","import { SiteFavicon } from \"./shared/SiteFavicon\";\nimport { SkeletonCircle } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readSiteHostname, TextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\n\n/**\n * The `Favicon` node (`FaviconComposedViewNode.php`): the small icon of the site of `url` (a page address or\n * a bare domain). A url that names no site shows the generic link glyph and reports `failed INVALID_PROP`.\n */\nconst FaviconNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime } = props;\n const hostname = readSiteHostname(nodeProps.url);\n const siteName = typeof nodeProps.name === \"string\" && nodeProps.name.trim() !== \"\" ? nodeProps.name : undefined;\n let renderState: TextNodeRenderState = \"shown\";\n if (isPending) renderState = \"pending\";\n else if (hostname === null) renderState = \"invalid\";\n useReportTextNodeRenderState(runtime, renderState, \"Favicon\", \"the Favicon url names no http(s) site\");\n if (isPending) return <SkeletonCircle size={16} />;\n return <SiteFavicon hostname={hostname} siteName={siteName} isEmailRender={runtime.isEmailRender} />;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Favicon\", component: FaviconNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readTextNodeContent, readTextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\nimport styles from \"./Label.module.scss\";\n\n/**\n * The `Label` node (`LabelComposedViewNode.php`): the short name above a value, an input or a group — the\n * design's section label (muted, medium, uppercase, letter-spaced; the look of `widgets/_shared/WidgetLabel`, whose copy\n * is a translation key, while a label here is the model's words and stays untranslated).\n */\nconst LabelNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Label\");\n if (isPending) return <SkeletonLine width={120} height={10} radius={4} />;\n if (content.kind !== \"text\") return null;\n return (\n <Text\n role=\"help\"\n weight=\"medium\"\n translate={false}\n color=\"--agents-fg-light\"\n className={styles.label}\n testId={testId}\n >\n {escapePlainTextForText(content.text)}\n </Text>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Label\", component: LabelNode };\n","import { Icon, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n readSafeHttpUrl,\n readTextNodeContent,\n TextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Link.module.scss\";\n\n/**\n * The `Link` node (`LinkComposedViewNode.php`): the model's text that opens an http(s) page in a new tab\n * (`target=\"_blank\" rel=\"noopener noreferrer\"`), with the new-tab glyph. A url with another scheme\n * (`javascript:`, `data:`, `mailto:`, a relative path) is no link: the text shows alone and the node reports\n * `failed INVALID_PROP`. A link never sends a chat message.\n */\nconst LinkNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const safeUrl = readSafeHttpUrl(nodeProps.url);\n let renderState: TextNodeRenderState = \"shown\";\n if (isPending) renderState = \"pending\";\n else if (content.kind === \"invalid\" || (content.kind === \"text\" && safeUrl === null)) renderState = \"invalid\";\n else if (content.kind === \"missing\") renderState = \"empty\";\n useReportTextNodeRenderState(\n runtime,\n renderState,\n \"Link\",\n content.kind === \"invalid\" ? undefined : \"the Link has no http(s) url — its text is shown without a link\",\n );\n if (isPending) return <SkeletonLine width=\"8em\" height={12} radius={4} />;\n if (content.kind !== \"text\") return null;\n if (safeUrl === null) {\n return (\n <Text role=\"body\" translate={false} display=\"inline\" className={styles.unlinked} testId={testId}>\n {escapePlainTextForText(content.text)}\n </Text>\n );\n }\n return (\n <a className={styles.link} href={safeUrl} target=\"_blank\" rel=\"noopener noreferrer\" data-testid={testId}>\n <Text role=\"body\" translate={false} display=\"inline\" className={styles.linkText}>\n {escapePlainTextForText(content.text)}\n </Text>\n <Icon color=\"var(--agents-fg-light)\" className={styles.newTabIcon} pixelSize={14} name=\"newTab\" />\n </a>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Link\", component: LinkNode };\n","import { Markdown, Text, type AgentsMarkdownProps } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n readSafeHttpUrl,\n readTextNodeContent,\n readTextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Markdown.module.scss\";\n\ninterface MarkdownElementProps {\n children?: ReactNode;\n /** The hast element react-markdown renders (its text is what a heading shows). */\n node?: MarkdownHastNode;\n}\n\ninterface MarkdownHastNode {\n type: string;\n value?: string;\n children?: MarkdownHastNode[];\n}\n\n/** The plain text of a hast element — a heading's inline formatting is not kept (see the heading renderer). */\nconst readHastText = (node: MarkdownHastNode | undefined): string => {\n if (!node) return \"\";\n if (node.type === \"text\") return node.value ?? \"\";\n return (node.children ?? []).map(readHastText).join(\"\");\n};\n\n/**\n * Every heading level as a section title (`text` bold). The component library's `Text` re-parses element children (a link inside\n * would lose its `href`), so a heading shows its plain text.\n */\nconst renderHeading = (props: MarkdownElementProps) => (\n <Text\n role=\"body\"\n weight=\"bold\"\n translate={false}\n display=\"block\"\n className={styles.heading}\n headingLevel={4}\n >\n {escapePlainTextForText(readHastText(props.node))}\n </Text>\n);\n\n/**\n * The safe subset: no images (an outside request, and a tracking pixel in a model's text), headings no\n * larger than a section title, links only to http(s) pages in a new tab — another scheme renders its text alone. Raw\n * HTML never reaches the DOM: the shared renderer has no raw-HTML plugin, so react-markdown drops it.\n */\nconst SAFE_MARKDOWN_COMPONENTS = {\n img: () => null,\n h1: renderHeading,\n h2: renderHeading,\n h3: renderHeading,\n h4: renderHeading,\n h5: renderHeading,\n h6: renderHeading,\n a: (props: MarkdownElementProps & { href?: string }) => {\n const safeUrl = readSafeHttpUrl(props.href);\n if (safeUrl === null) return <span>{props.children}</span>;\n return (\n <a className={styles.link} href={safeUrl} target=\"_blank\" rel=\"noopener noreferrer\">\n {props.children}\n </a>\n );\n },\n} as NonNullable<AgentsMarkdownProps[\"components\"]>;\n\n/**\n * The `Markdown` node (`MarkdownComposedViewNode.php`): the model's formatted text — paragraphs, emphasis,\n * lists, quotes, tables, headings — through the shared conversation Markdown renderer, held to the safe subset above\n * and never translated.\n */\nconst MarkdownNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.markdown);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Markdown\");\n if (isPending) {\n return (\n <div className={styles.skeleton} data-testid={`${testId}-skeleton`}>\n <SkeletonLine width=\"90%\" height={14} radius={4} />\n <SkeletonLine width=\"70%\" height={14} radius={4} />\n </div>\n );\n }\n if (content.kind !== \"text\") return null;\n return (\n <div className={styles.markdown} data-testid={testId}>\n <Markdown markdown={content.text} translate={false} components={SAFE_MARKDOWN_COMPONENTS} />\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Markdown\", component: MarkdownNode };\n","import type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { readSafeHttpUrl, readSiteHostname, readTextNodeContent } from \"./text-node-values\";\n\n/** One source of a `SourceRef`, read from its wire object: a name always, the rest only when it can be shown safely. */\nexport interface SourceRefEntry {\n /** The publisher or site (\"WDR\", \"Wikimedia Commons\"). */\n name: string;\n /** The http(s) page; null = the source is shown without a link. */\n url: string | null;\n /** The site of `url`, for its favicon; null = the link glyph. */\n hostname: string | null;\n /** The work's title (an image, an article), for the attribution line. */\n title: string | null;\n author: string | null;\n /** The licence name (\"CC BY-SA 4.0\"). */\n license: string | null;\n /** The licence's http(s) page; null = the licence is shown as text. */\n licenseUrl: string | null;\n}\n\nexport interface SourceRefEntries {\n /** The sources that can be shown, at most `maxEntries`. */\n entries: SourceRefEntry[];\n /** Wire items left out because they have no name (or are no object). */\n skippedCount: number;\n /** Items past `maxEntries` (the kit's `maxRepeatRows`). */\n cutCount: number;\n /** Whether `sources` was a list at all. */\n isList: boolean;\n}\n\nconst readOptionalText = (value: ExpressionValue): string | null => {\n const content = readTextNodeContent(value);\n return content.kind === \"text\" ? content.text : null;\n};\n\n/** The `sources` prop read into entries — never throws: what cannot be shown is counted, the rest is kept in order. */\nexport const readSourceRefEntries = (sourcesValue: ExpressionValue, maxEntries: number): SourceRefEntries => {\n // Nothing bound yet (a dataset still loading, an unset state) is an empty list, not a wrong one.\n if (sourcesValue === undefined || sourcesValue === null)\n return { entries: [], skippedCount: 0, cutCount: 0, isList: true };\n if (!Array.isArray(sourcesValue)) return { entries: [], skippedCount: 0, cutCount: 0, isList: false };\n const entries: SourceRefEntry[] = [];\n let skippedCount = 0;\n let cutCount = 0;\n for (const sourceValue of sourcesValue) {\n if (typeof sourceValue !== \"object\" || sourceValue === null || Array.isArray(sourceValue)) {\n skippedCount += 1;\n continue;\n }\n const name = readOptionalText(sourceValue.name);\n if (name === null) {\n skippedCount += 1;\n continue;\n }\n if (entries.length >= maxEntries) {\n cutCount += 1;\n continue;\n }\n const url = readSafeHttpUrl(sourceValue.url);\n entries.push({\n name,\n url,\n hostname: url === null ? null : readSiteHostname(url),\n title: readOptionalText(sourceValue.title),\n author: readOptionalText(sourceValue.author),\n license: readOptionalText(sourceValue.license),\n licenseUrl: readSafeHttpUrl(sourceValue.licenseUrl),\n });\n }\n return { entries, skippedCount, cutCount, isList: true };\n};\n\n/** Whether the entry carries an attribution beyond its name (an image licence, an author). */\nexport const hasAttribution = (entry: SourceRefEntry): boolean => entry.license !== null || entry.author !== null;\n","import { Icon, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { Fragment, useEffect, useId, useState } from \"react\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport { SkeletonPill } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { SiteFavicon } from \"./shared/SiteFavicon\";\nimport { hasAttribution, readSourceRefEntries, SourceRefEntry } from \"./shared/source-ref-entries\";\nimport styles from \"./SourceRef.module.scss\";\n\ninterface SourceChipProps {\n entry: SourceRefEntry;\n isEmailRender: boolean;\n testId: string;\n}\n\n/** One source as a chip: its favicon and name, a link to its page when it has one (new tab). */\nconst SourceChip = (props: SourceChipProps) => {\n const { entry, isEmailRender, testId } = props;\n const chipContent = (\n <>\n <SiteFavicon hostname={entry.hostname} siteName={entry.name} isEmailRender={isEmailRender} />\n <Text role=\"caption\" weight=\"medium\" translate={false} className={styles.chipName}>\n {escapePlainTextForText(entry.name)}\n </Text>\n </>\n );\n if (entry.url === null)\n return (\n <span className={styles.chip} data-testid={testId}>\n {chipContent}\n </span>\n );\n return (\n <a\n className={classNames(styles.chip, styles.linkedChip)}\n href={entry.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n title={entry.title ?? entry.name}\n data-testid={testId}\n >\n {chipContent}\n </a>\n );\n};\n\ninterface AttributionPart {\n text: string;\n /** The http(s) page of this part (the licence); null = plain text. */\n url: string | null;\n}\n\n/**\n * The attribution of one source: title · author · licence (linked when it has a page) · source name. Each part is its\n * own `Text` and the licence link sits outside it — the component library's `Text` re-parses element children and drops a link's\n * `href`, `target` and `rel`.\n */\nconst SourceAttribution = (props: { entry: SourceRefEntry }) => {\n const { entry } = props;\n const parts: AttributionPart[] = [];\n if (entry.title !== null) parts.push({ text: entry.title, url: null });\n if (entry.author !== null) parts.push({ text: entry.author, url: null });\n if (entry.license !== null) parts.push({ text: entry.license, url: entry.licenseUrl });\n parts.push({ text: entry.name, url: null });\n return (\n <span className={styles.attribution}>\n {parts.map((part, partIndex) => {\n const partText = (\n <Text\n role=\"caption\"\n translate={false}\n display=\"inline\"\n color=\"--agents-fg-light\"\n className={styles.attributionText}\n >\n {escapePlainTextForText(part.text)}\n </Text>\n );\n return (\n <Fragment key={partIndex}>\n {partIndex > 0 ? (\n <Text\n role=\"caption\"\n translate={false}\n display=\"inline\"\n color=\"--agents-fg-light\"\n className={styles.attributionText}\n >\n {\"·\"}\n </Text>\n ) : null}\n {part.url === null ? (\n partText\n ) : (\n <a className={styles.licenseLink} href={part.url} target=\"_blank\" rel=\"noopener noreferrer\">\n {partText}\n </a>\n )}\n </Fragment>\n );\n })}\n </span>\n );\n};\n\ninterface SourceListProps {\n entries: SourceRefEntry[];\n isEmailRender: boolean;\n testId: string;\n}\n\n/** The full source line (\"Sources\" + one chip per source) and one attribution line per licensed source. */\nconst SourceList = (props: SourceListProps) => {\n const { entries, isEmailRender, testId } = props;\n const attributedEntries = entries.filter(hasAttribution);\n return (\n <span className={styles.sourceList}>\n <span className={styles.sourceLine}>\n <Text\n role=\"caption\"\n color=\"--agents-fg-light\"\n className={styles.sourceLabel}\n context={entries.length === 1 ? \"one\" : \"other\"}\n >\n {\"Source\"}\n </Text>\n <span role=\"list\" className={styles.chips}>\n {entries.map((entry, entryIndex) => (\n <span role=\"listitem\" key={`${entryIndex}-${entry.name}`} className={styles.chipItem}>\n <SourceChip entry={entry} isEmailRender={isEmailRender} testId={`${testId}-chip-${entryIndex}`} />\n </span>\n ))}\n </span>\n </span>\n {attributedEntries.map((entry, entryIndex) => (\n <SourceAttribution key={`${entryIndex}-${entry.name}`} entry={entry} />\n ))}\n </span>\n );\n};\n\n/**\n * The `SourceRef` node (`SourceRefComposedViewNode.php`): where the shown values come from. In a\n * regular slot one line \"Sources\" with a chip per source (favicon, name, link to its page in a new tab) and, per source\n * with a licence or an author (an image from Wikimedia Commons), an attribution line. In a compact slot\n * (inside a `Text`, a table cell) one chip \"WDR +2\" that unfolds the full list — an effect-free toggle. Sources\n * without a name are left out and reported; at most `maxRepeatRows` sources are shown.\n */\nconst SourceRefNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const maxEntries = composedNodeSchema.budgets.maxRepeatRows;\n const { entries, skippedCount, cutCount, isList } = readSourceRefEntries(nodeProps.sources, maxEntries);\n const [isExpanded, setIsExpanded] = useState(false);\n const expandedListId = useId();\n\n useEffect(() => {\n if (isPending) reportNodeStatus(\"pending\");\n else if (!isList) reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the SourceRef sources are not a list\");\n else if (cutCount > 0) {\n reportNodeStatus(\"failed\", \"BUDGET_EXCEEDED\", `the SourceRef shows the first ${maxEntries} sources only`);\n } else if (skippedCount > 0) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `${skippedCount} source(s) without a name were left out`);\n } else if (entries.length === 0) reportNodeStatus(\"empty\", \"NO_DATA\", \"the SourceRef has no source to show\");\n else reportNodeStatus(\"mounted\");\n }, [reportNodeStatus, isPending, isList, cutCount, skippedCount, entries.length, maxEntries]);\n\n if (isPending) return <SkeletonPill width={120} height={24} />;\n if (entries.length === 0) return null;\n if (sizeClass !== \"compact\") {\n return (\n <span className={styles.sourceRef} data-testid={testId}>\n <SourceList entries={entries} isEmailRender={isEmailRender} testId={testId} />\n </span>\n );\n }\n const [firstEntry] = entries;\n const otherSourcesCount = entries.length - 1;\n if (otherSourcesCount === 0 && !hasAttribution(firstEntry)) {\n return (\n <span className={styles.sourceRef} data-testid={testId}>\n <SourceChip entry={firstEntry} isEmailRender={isEmailRender} testId={`${testId}-chip-0`} />\n </span>\n );\n }\n return (\n <span className={styles.sourceRef} data-testid={testId}>\n <button\n type=\"button\"\n className={classNames(styles.chip, styles.toggleChip)}\n aria-expanded={isExpanded}\n aria-controls={expandedListId}\n disabled={isEmailRender}\n data-testid={`${testId}-toggle`}\n onClick={() => setIsExpanded((wasExpanded) => !wasExpanded)}\n >\n <SiteFavicon hostname={firstEntry.hostname} siteName={firstEntry.name} isEmailRender={isEmailRender} />\n <Text\n role=\"caption\"\n weight=\"medium\"\n translate={false}\n className={styles.chipName}\n >\n {escapePlainTextForText(firstEntry.name)}\n </Text>\n {otherSourcesCount > 0 ? (\n <Text role=\"caption\" translate={false} color=\"--agents-fg-light\" className={styles.moreCount}>\n {`+${otherSourcesCount}`}\n </Text>\n ) : null}\n <Icon color=\"var(--agents-fg-light)\" pixelSize={12} name={isExpanded ? \"caretUp\" : \"caretDown\"} />\n </button>\n {isExpanded ? (\n <span id={expandedListId} className={styles.expandedList} data-testid={`${testId}-expanded`}>\n <SourceList entries={entries} isEmailRender={isEmailRender} testId={`${testId}-expanded`} />\n </span>\n ) : null}\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"SourceRef\",\n component: SourceRefNode,\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readComposedViewTone } from \"../../composed-view-tones\";\nimport {\n readAllowedValue,\n readTextNodeContent,\n TextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Text.module.scss\";\n\nconst TEXT_WEIGHTS = [\"regular\", \"medium\", \"bold\"] as const;\nconst FONT_WEIGHT_BY_TEXT_WEIGHT = {\n regular: \"regular\",\n medium: \"medium\",\n bold: \"bold\",\n} as const;\nconst MAX_CLAMPED_LINES = 10;\n\n/** `maxLines` within 1–10, else no clamp. */\nconst readMaxLines = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 1\n ? Math.min(Math.floor(value), MAX_CLAMPED_LINES)\n : undefined;\n\n/**\n * Whether the clamped run cuts its text off — measured on the element, again whenever its width changes (a narrower pane\n * clamps a text that fit before).\n */\nconst useIsTextCutOff = (isClamped: boolean, clampedText: string | null) => {\n const clampedRunRef = useRef<HTMLSpanElement>(null);\n const [isCutOff, setIsCutOff] = useState(false);\n useEffect(() => {\n const clampedRun = clampedRunRef.current;\n if (!isClamped || clampedText === null || !clampedRun) {\n setIsCutOff(false);\n return undefined;\n }\n const measureCutOff = () => setIsCutOff(clampedRun.scrollHeight > clampedRun.clientHeight + 1);\n measureCutOff();\n if (typeof ResizeObserver === \"undefined\") return undefined;\n const resizeObserver = new ResizeObserver(measureCutOff);\n resizeObserver.observe(clampedRun);\n return () => resizeObserver.disconnect();\n }, [isClamped, clampedText]);\n return { clampedRunRef, isCutOff };\n};\n\n/**\n * The `Text` node (`TextComposedViewNode.php`): plain text — a paragraph, or an inline run when it sits in\n * a compact slot (inside another `Text`, a table cell). Its children are inline nodes that follow the text on the same\n * line (a `Badge`, a `Link`, a `SourceRef` chip). `tone` picks the muted or a judgement colour, `maxLines` clamps a\n * long text, keeps the whole of it on hover and — when the clamp cut something off — offers \"Show more\" / \"Show less\"\n * below the paragraph, so a touch screen reaches the whole text too (the e-mail capture shows the clamp alone). The model's words are never translated and never parsed as markup.\n */\nconst TextNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, slots, sizeClass, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const childNodes = slots.children ?? [];\n const weight = readAllowedValue(nodeProps.weight, TEXT_WEIGHTS, \"regular\");\n const tone = readComposedViewTone(nodeProps.tone);\n const maxLines = readMaxLines(nodeProps.maxLines);\n const isInline = sizeClass === \"compact\";\n const [isExpanded, setIsExpanded] = useState(false);\n const isClamped = maxLines !== undefined && !isExpanded;\n const { clampedRunRef, isCutOff } = useIsTextCutOff(\n isClamped,\n content.kind === \"text\" && !isPending ? content.text : null,\n );\n const isShowingClampToggle =\n !isInline && !runtime.isEmailRender && maxLines !== undefined && (isCutOff || isExpanded);\n let renderState: TextNodeRenderState = \"shown\";\n if (isPending) renderState = \"pending\";\n else if (content.kind === \"invalid\") renderState = \"invalid\";\n else if (content.kind === \"missing\" && childNodes.length === 0) renderState = \"empty\";\n useReportTextNodeRenderState(runtime, renderState, \"Text\");\n\n if (isPending) {\n return isInline ? (\n <span className={styles.inlineSkeleton}>\n <SkeletonLine width=\"6em\" height={12} radius={4} />\n </span>\n ) : (\n <SkeletonLine width=\"80%\" height={14} radius={4} />\n );\n }\n if (renderState !== \"shown\") return null;\n const Wrapper = isInline ? \"span\" : \"div\";\n return (\n <Wrapper\n className={classNames(styles.text, isInline ? styles.inline : styles.paragraph, styles[tone])}\n data-testid={testId}\n >\n {content.kind === \"text\" ? (\n <span\n ref={clampedRunRef}\n className={isClamped ? classNames(styles.clamped, styles[`clampedAt${maxLines}Lines`]) : undefined}\n title={isClamped ? content.text : undefined}\n >\n <Text\n role=\"body\"\n weight={FONT_WEIGHT_BY_TEXT_WEIGHT[weight]}\n translate={false}\n display=\"inline\"\n color=\"--agents-text-node-tone-color\"\n >\n {escapePlainTextForText(content.text)}\n </Text>\n </span>\n ) : null}\n {childNodes.map((childNode, childIndex) => (\n <span key={childIndex} className={styles.inlineChild}>\n {childNode}\n </span>\n ))}\n {isShowingClampToggle ? (\n <button\n type=\"button\"\n className={styles.clampToggle}\n data-testid={`${testId}-toggle`}\n aria-expanded={isExpanded}\n onClick={() => setIsExpanded((wasExpanded) => !wasExpanded)}\n >\n <Text role=\"caption\" weight=\"medium\" color=\"var(--agents-fg-light)\">\n {isExpanded ? \"Show less\" : \"Show more\"}\n </Text>\n </button>\n ) : null}\n </Wrapper>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Text\", component: TextNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n readAllowedValue,\n readTextNodeContent,\n readTextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Title.module.scss\";\n\nconst TITLE_LEVELS = [\"widget\", \"section\"] as const;\n\n/**\n * The `Title` node (`TitleComposedViewNode.php`): the heading of the view (`widget`, the card title —\n * `textIntro` bold) or of one part of it (`section`, `text` bold). The model's words, never\n * translated; a skeleton while a bound text waits for its data.\n */\nconst TitleNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const level = readAllowedValue(nodeProps.level, TITLE_LEVELS, \"widget\");\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Title\");\n if (isPending) return <SkeletonLine width=\"40%\" height={level === \"widget\" ? 20 : 16} radius={4} />;\n if (content.kind !== \"text\") return null;\n return (\n <Text\n role={level === \"widget\" ? \"intro\" : \"body\"}\n weight=\"bold\"\n translate={false}\n className={styles.title}\n testId={testId}\n headingLevel={level === \"widget\" ? 3 : 4}\n >\n {escapePlainTextForText(content.text)}\n </Text>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Title\", component: TitleNode };\n","import { createContext, useContext } from \"react\";\nimport type { ComposedViewComponentDefinition } from \"./composed-view-component-types\";\n\n/**\n * The kit's component registry: every `components/**\\/*.composed.tsx` that exports\n * `composedViewComponent` registers itself by folder glob — a component is added with one new file and edits no list.\n * A second component for one node type is a build error (thrown at module load, caught by the spec).\n */\nconst componentModules = import.meta.glob<{ composedViewComponent?: ComposedViewComponentDefinition }>(\n \"./components/**/*.composed.tsx\",\n { eager: true },\n);\n\nexport const buildComposedViewComponentRegistry = (\n definitions: ComposedViewComponentDefinition[],\n): Readonly<Record<string, ComposedViewComponentDefinition>> => {\n const registry: Record<string, ComposedViewComponentDefinition> = {};\n for (const definition of definitions) {\n if (Object.prototype.hasOwnProperty.call(registry, definition.nodeType)) {\n throw new Error(`Two ComposedView components register the node type \"${definition.nodeType}\".`);\n }\n registry[definition.nodeType] = definition;\n }\n return registry;\n};\n\n/** Node type → component, from the folder. */\nexport const composedViewComponents = buildComposedViewComponentRegistry(\n Object.values(componentModules)\n .map((componentModule) => componentModule.composedViewComponent)\n .filter((definition): definition is ComposedViewComponentDefinition => definition !== undefined),\n);\n\n/** The registry the renderer uses — the folder's by default; a story or a spec may provide its own stub components. */\nexport const ComposedViewComponentsContext =\n createContext<Readonly<Record<string, ComposedViewComponentDefinition>>>(composedViewComponents);\n\nexport const useComposedViewComponents = () => useContext(ComposedViewComponentsContext);\n","import React from \"react\";\n\ninterface ComposedViewSlotErrorBoundaryProps {\n /** Where the node sits in the tree (`view.children[2]`), for the report. */\n nodePath: string;\n nodeType: string;\n onRenderFailed: (nodePath: string, nodeType: string) => void;\n children: React.ReactNode;\n}\n\ninterface ComposedViewSlotErrorBoundaryState {\n hasFailed: boolean;\n}\n\n/**\n * One node of a `ComposedView` tree inside its own error boundary (per-slot context): a node that throws\n * renders nothing and is reported `failed` (`RENDER_FAILED`), the rest of the tree stays. React error boundaries\n * require a class.\n */\nexport class ComposedViewSlotErrorBoundary extends React.Component<\n ComposedViewSlotErrorBoundaryProps,\n ComposedViewSlotErrorBoundaryState\n> {\n state: ComposedViewSlotErrorBoundaryState = { hasFailed: false };\n\n static getDerivedStateFromError(): ComposedViewSlotErrorBoundaryState {\n return { hasFailed: true };\n }\n\n componentDidCatch(error: Error): void {\n console.error(`[ComposedView] node ${this.props.nodeType} at ${this.props.nodePath} crashed`, error);\n this.props.onRenderFailed(this.props.nodePath, this.props.nodeType);\n }\n\n render(): React.ReactNode {\n return this.state.hasFailed ? null : this.props.children;\n }\n}\n","import { useEffect, useState } from \"react\";\n\n/** The value as it was `delayMs` after its last change. */\nexport const useDebouncedValue = <T>(value: T, delayMs: number): T => {\n const [debouncedValue, setDebouncedValue] = useState(value);\n useEffect(() => {\n const timer = setTimeout(() => setDebouncedValue(value), delayMs);\n return () => clearTimeout(timer);\n }, [value, delayMs]);\n return debouncedValue;\n};\n","import { useEffect, useMemo, useState } from \"react\";\nimport { useDebouncedValue } from \"./hooks/use-debounced-value\";\nimport { useWidgetHydration } from \"../renderer/widget-hydration\";\nimport {\n composedViewDataSourceHydrationType,\n ComposedViewDataSourcePayload,\n ComposedViewSourceBinding,\n hasComposedViewDataSourceFetcher,\n resolveComposedViewSourceParams,\n} from \"../renderer/widget-tree/composed-view-data-sources\";\nimport type { ExpressionValue } from \"../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewSourceValue } from \"../renderer/widget-tree/resolve-composed-view-values\";\n\n/** State-bound parameters settle for this long before the source is read again (a dragged slider reads once). */\nconst PARAM_DEBOUNCE_MS = 300;\n\ninterface ComposedViewDataSourceLoaderProps {\n sourceBinding: ComposedViewSourceBinding;\n state: Record<string, ExpressionValue>;\n agentSpaceKey: number | undefined;\n /** Whether this tree may start another read (the per-tree budget); a refused change keeps the last parameters. */\n mayRead: () => boolean;\n onValue: (bindingKey: string, sourceValue: ComposedViewSourceValue) => void;\n}\n\n/**\n * Reads ONE `$source` binding of a tree through the widget-hydration mechanism and hands the rows up.\n * Renders nothing; one component per binding, so the number of hooks never depends on the tree. The hydration reads\n * again whenever the payload changes, so a parameter change is first debounced, then counted against the tree's budget\n * (`maxSourceRequestsPerTreePerMinute`); a refused change keeps the rows of the last accepted parameters. A source\n * without a registered frontend fetcher fails at once (`UNRESOLVED_BINDING` in the report).\n */\nexport const ComposedViewDataSourceLoader = (props: ComposedViewDataSourceLoaderProps) => {\n const { sourceBinding, state, agentSpaceKey, mayRead, onValue } = props;\n const resolvedParams = useMemo(\n () => resolveComposedViewSourceParams(sourceBinding.writtenParams, state),\n [sourceBinding.writtenParams, state],\n );\n const debouncedParams = useDebouncedValue(resolvedParams, PARAM_DEBOUNCE_MS);\n const debouncedParamsJson = JSON.stringify(debouncedParams);\n const [acceptedPayload, setAcceptedPayload] = useState<ComposedViewDataSourcePayload>(() => ({\n params: resolvedParams,\n agentSpaceKey,\n }));\n\n useEffect(() => {\n const isUnchanged =\n JSON.stringify(acceptedPayload.params) === debouncedParamsJson && acceptedPayload.agentSpaceKey === agentSpaceKey;\n if (isUnchanged || !mayRead()) return;\n setAcceptedPayload({ params: JSON.parse(debouncedParamsJson) as Record<string, ExpressionValue>, agentSpaceKey });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- reacts to the settled parameters only\n }, [debouncedParamsJson, agentSpaceKey]);\n\n const isRegistered = hasComposedViewDataSourceFetcher(sourceBinding.dataSourceName);\n const hydration = useWidgetHydration<ExpressionValue[], ComposedViewDataSourcePayload>(\n composedViewDataSourceHydrationType(isRegistered ? sourceBinding.dataSourceName : \"unregistered\"),\n acceptedPayload,\n { showLastDataWhileRefreshing: true },\n );\n\n useEffect(() => {\n if (!isRegistered || hydration.isError) {\n onValue(sourceBinding.bindingKey, { status: \"failed\", value: undefined });\n } else if (hydration.data !== null) {\n onValue(sourceBinding.bindingKey, { status: \"resolved\", value: hydration.data });\n } else {\n onValue(sourceBinding.bindingKey, { status: \"pending\", value: undefined });\n }\n }, [isRegistered, hydration.isError, hydration.data, sourceBinding.bindingKey, onValue]);\n\n return null;\n};\n","import {\n ComposedViewTree,\n getComposedViewSubtreeNodes,\n readComposedViewBinding,\n} from \"../renderer/widget-tree/composed-view-tree\";\n\n/**\n * Which data paths of a `ComposedView` tree carry a time the report e-mail must state: the turn-time\n * `$from` snapshots (the tool results the backend wrote into the block when the report message was stored) and the\n * mail-time reads (a `$source` binding or an embedded domain widget, both read live while the e-mail is captured).\n * Inline data carries its own source line and no time.\n */\nexport interface ComposedViewDataTimes {\n /** The tree binds at least one `$from` tool result. */\n hasTurnTimeSnapshot: boolean;\n /**\n * The newest `resolvedAt` (ISO 8601) the persist-time resolution wrote into a resolved `$from` snapshot, when it\n * wrote one; otherwise undefined and the caption names the report time without a clock time.\n */\n turnTimeResolvedAt: string | undefined;\n /** The tree reads at least one `$source` or embeds a self-hydrating domain widget. */\n hasMailTimeRead: boolean;\n}\n\ninterface DataTimesCollection {\n hasTurnTimeSnapshot: boolean;\n newestResolvedAtMs: number | undefined;\n hasMailTimeRead: boolean;\n}\n\n/** The moment of a resolved `$from` snapshot, or undefined (no `resolvedAt`, or not a readable ISO moment). */\nconst readSnapshotResolvedAtMs = (fromBindingObject: unknown): number | undefined => {\n if (typeof fromBindingObject !== \"object\" || fromBindingObject === null || Array.isArray(fromBindingObject)) {\n return undefined;\n }\n const snapshot = fromBindingObject as Record<string, unknown>;\n if (snapshot.state !== \"resolved\" || typeof snapshot.resolvedAt !== \"string\") return undefined;\n const resolvedAtMs = Date.parse(snapshot.resolvedAt);\n return Number.isFinite(resolvedAtMs) ? resolvedAtMs : undefined;\n};\n\nconst collectDataTimesFromValue = (value: unknown, collection: DataTimesCollection): void => {\n const binding = readComposedViewBinding(value);\n if (binding !== null) {\n if (binding.kind === \"from\") {\n collection.hasTurnTimeSnapshot = true;\n const resolvedAtMs = readSnapshotResolvedAtMs(binding.wireValue.$from);\n if (resolvedAtMs !== undefined) {\n collection.newestResolvedAtMs = Math.max(collection.newestResolvedAtMs ?? resolvedAtMs, resolvedAtMs);\n }\n }\n if (binding.kind === \"source\") collection.hasMailTimeRead = true;\n return;\n }\n if (Array.isArray(value)) value.forEach((element) => collectDataTimesFromValue(element, collection));\n else if (typeof value === \"object\" && value !== null) {\n Object.values(value).forEach((nested) => collectDataTimesFromValue(nested, collection));\n }\n};\n\n/** The data paths with a time of a checked tree: its datasets and every node's props, embedded widgets included. */\nexport const readComposedViewDataTimes = (tree: ComposedViewTree): ComposedViewDataTimes => {\n const collection: DataTimesCollection = {\n hasTurnTimeSnapshot: false,\n newestResolvedAtMs: undefined,\n hasMailTimeRead: false,\n };\n collectDataTimesFromValue(tree.data, collection);\n const nodes = tree.view ? getComposedViewSubtreeNodes(tree.view) : [];\n for (const node of nodes) {\n if (node.type === \"Widget\") collection.hasMailTimeRead = true;\n collectDataTimesFromValue(node.props, collection);\n }\n return {\n hasTurnTimeSnapshot: collection.hasTurnTimeSnapshot,\n turnTimeResolvedAt:\n collection.newestResolvedAtMs === undefined ? undefined : new Date(collection.newestResolvedAtMs).toISOString(),\n hasMailTimeRead: collection.hasMailTimeRead,\n };\n};\n","import { Text } from \"../../provider/components\";\nimport { useMemo, useState } from \"react\";\nimport { useAgentsOwnerSettings } from \"../../provider/AgentsProvider\";\nimport { translateText } from \"../../provider/environment\";\nimport type { ComposedViewTree } from \"../../renderer/widget-tree/composed-view-tree\";\nimport { readComposedViewDataTimes } from \"../composed-view-data-times\";\nimport styles from \"./ComposedViewEmailDataTimes.module.scss\";\n\nconst FALLBACK_DATE_LOCALE = \"en-GB\";\n\n/** A moment in the owner's date locale and zone (`25.10.2026, 08:00`); without a usable zone, the capture's own. */\nexport const formatDataTime = (moment: Date, dateLocale: string, timeZone: string | null | undefined): string => {\n const formatOptions: Intl.DateTimeFormatOptions = { dateStyle: \"medium\", timeStyle: \"short\" };\n try {\n return new Intl.DateTimeFormat(dateLocale, timeZone ? { ...formatOptions, timeZone } : formatOptions).format(\n moment,\n );\n } catch {\n return new Intl.DateTimeFormat(FALLBACK_DATE_LOCALE, formatOptions).format(moment);\n }\n};\n\nexport interface ComposedViewEmailDataTimesProps {\n tree: ComposedViewTree;\n}\n\n/**\n * The time of each data path of an e-mailed `ComposedView`, as ONE caption line under the tree: a report\n * mail mixes the tool results written into the block at turn time (`$from`) with data read live while the mail is\n * captured (`$source`, embedded domain widgets) — the reader must know which numbers are from when. The turn time is\n * the `resolvedAt` the resolution wrote into the snapshot; the mail time is the capture moment, fixed at the first\n * render. Each phrase is its own translation key; the phrases are joined by a middle dot. A tree with inline data only\n * shows no line.\n */\nexport const ComposedViewEmailDataTimes = (props: ComposedViewEmailDataTimesProps) => {\n const { tree } = props;\n const dataTimes = useMemo(() => readComposedViewDataTimes(tree), [tree]);\n const [captureMoment] = useState(() => new Date());\n // The owner's settings come from the app, read defensively: the capture store is a partial copy of the app's.\n const { dateLocale: ownerDateLocale, locale: ownerLocale, timeZone } = useAgentsOwnerSettings();\n const dateLocale = ownerDateLocale || ownerLocale || FALLBACK_DATE_LOCALE;\n\n const phrases: string[] = [];\n if (dataTimes.hasTurnTimeSnapshot) {\n phrases.push(\n dataTimes.turnTimeResolvedAt === undefined\n ? translateText(\"Conversation data as of the time of the report\")\n : translateText(\"Conversation data as of %dataTime%\", {\n dataTime: formatDataTime(new Date(dataTimes.turnTimeResolvedAt), dateLocale, timeZone),\n }),\n );\n }\n if (dataTimes.hasMailTimeRead) {\n phrases.push(\n translateText(\"Live data as of %dataTime%\", {\n dataTime: formatDataTime(captureMoment, dateLocale, timeZone),\n }),\n );\n }\n if (phrases.length === 0) return null;\n return (\n <div className={styles.dataTimes} data-testid=\"composed-view-email-data-times\">\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {phrases.join(\" · \")}\n </Text>\n </div>\n );\n};\n","import { Text } from \"../provider/components\";\nimport React, { useCallback, useEffect, useMemo, useReducer, useRef } from \"react\";\nimport { stringifyWithinLimit } from \"../renderer/widget-tree/bounded-json\";\nimport {\n composedNodeSchema,\n ComposedSizeClass,\n getComposedNodeSchema,\n resolveComposedSlotForNodeProps,\n} from \"../renderer/widget-tree/composed-node-schema\";\nimport {\n ComposedViewAction,\n ComposedViewLiftedWidget,\n ComposedViewNode,\n ComposedViewTree,\n isComposedViewWithoutContent,\n} from \"../renderer/widget-tree/composed-view-tree\";\nimport {\n isRowBoundOpenEntityAction,\n readOpenEntityActionTarget,\n} from \"../renderer/canvas/entity-detail-instance\";\nimport {\n computeComposedViewValues,\n ExpressionValue,\n} from \"../renderer/widget-tree/expression/evaluate-expression\";\nimport { useComposedViewState } from \"../renderer/widget-tree/use-composed-view-state\";\nimport { collectComposedViewSourceBindings } from \"../renderer/widget-tree/composed-view-data-sources\";\nimport {\n ComposedViewSourceValue,\n ComposedViewValueScope,\n resolveComposedViewDatasets,\n resolveComposedViewValue,\n ResolvedBindingStatus,\n} from \"../renderer/widget-tree/resolve-composed-view-values\";\nimport type {\n WidgetRenderReportCode,\n WidgetRenderReportEntry,\n WidgetRenderStatus,\n} from \"../renderer/render-report/widget-render-report\";\nimport type { ComposedViewRuntime } from \"./composed-view-component-types\";\nimport { useComposedViewComponents } from \"./composed-view-components\";\nimport { ComposedViewSlotErrorBoundary } from \"./ComposedViewSlotErrorBoundary\";\nimport { ComposedViewDataSourceLoader } from \"./ComposedViewDataSourceLoader\";\nimport { EmbeddedConversationWidget } from \"./components/embedding/EmbeddedConversationWidget\";\nimport { ModelText } from \"./ModelText/ModelText\";\nimport { ComposedViewEmailDataTimes } from \"../image-render/ComposedViewEmailDataTimes/ComposedViewEmailDataTimes\";\nimport styles from \"./ComposedViewConversationWidget.module.scss\";\n\n/**\n * Renders a checked `ComposedView` tree: one state store per instance, the datasets and computed\n * values for the current state, then the node tree — each node through its registered component, each slot node in its\n * own error boundary, the slot's size class handed down. The renderer folds the tree's findings, the expression\n * errors, the nodes' own reports and the pending bindings into ONE block status for the render report. A finding that\n * drops nothing (the schema's `noteFindingCodes`: figures without a source, a choice state outside its choices, a set\n * state nothing reads, an `$item` field the rows lack, a slot under its minimum) never fails the block: a block that rendered reports `mounted`\n * with that code as a note, which the chat tells the model.\n */\n\nexport interface ComposedViewRendererProps {\n tree: ComposedViewTree;\n interactive: boolean;\n isEmailRender: boolean;\n messageId?: string | number;\n agentSpaceKey?: string | number;\n /** The block status, whenever it changes. */\n onReport: (entry: WidgetRenderReportEntry) => void;\n /**\n * Runs an `openEntity` action — the `entityDetail` canvas. A platform-minted reference carries the entity the backend\n * resolved it to; a row-bound action (`ref: {\"$item\":\"entityRef\"}`) comes with `currentRow`, the row it fired in,\n * whose `entity` it opens (`readOpenEntityActionTarget(action, currentRow)`).\n */\n onOpenEntity?: (action: ComposedViewAction, currentRow?: ExpressionValue) => void;\n testId?: string;\n}\n\ntype NodeReportAction = {\n nodePath: string;\n status: WidgetRenderStatus;\n code?: WidgetRenderReportCode;\n detail?: string;\n};\ntype NodeReports = Record<string, Omit<NodeReportAction, \"nodePath\">>;\n\nconst nodeReportsReducer = (nodeReports: NodeReports, action: NodeReportAction): NodeReports => {\n const current = nodeReports[action.nodePath];\n if (current && current.status === action.status && current.code === action.code && current.detail === action.detail) {\n return nodeReports;\n }\n return { ...nodeReports, [action.nodePath]: { status: action.status, code: action.code, detail: action.detail } };\n};\n\ntype SourceValueAction = { bindingKey: string; sourceValue: ComposedViewSourceValue };\ntype SourceValues = Record<string, ComposedViewSourceValue>;\n\nconst sourceValuesReducer = (sourceValues: SourceValues, action: SourceValueAction): SourceValues => {\n const current = sourceValues[action.bindingKey];\n if (current && current.status === action.sourceValue.status && current.value === action.sourceValue.value) {\n return sourceValues;\n }\n return { ...sourceValues, [action.bindingKey]: action.sourceValue };\n};\n\nconst SOURCE_BUDGET_WINDOW_MS = 60_000;\n\nconst MAX_DETAIL_FINDINGS = 5;\n\n/**\n * The first node report of `status`, its detail prefixed with the node's path (`view.children[1]: ExampleWidget: …`)\n * unless the detail names it already — the model learns WHICH cell of a dashboard failed or showed nothing.\n */\nconst findNodeReportWithItsPath = (\n nodeReports: NodeReports,\n status: WidgetRenderStatus,\n): WidgetRenderReportEntry | undefined => {\n const nodeReportEntry = Object.entries(nodeReports).find(([, nodeReport]) => nodeReport.status === status);\n if (!nodeReportEntry) return undefined;\n const [nodePath, nodeReport] = nodeReportEntry;\n const detail = nodeReport.detail ?? \"\";\n return { ...nodeReport, detail: detail.includes(nodePath) ? detail : `${nodePath}: ${detail}`.replace(/: $/, \"\") };\n};\n\n/** The finding codes that drop nothing (`ComposedViewValidationFinding::NOTE_CODES`): the block mounts with a note. */\nconst NOTE_FINDING_CODES: readonly string[] = composedNodeSchema.noteFindingCodes ?? [\"INLINE_VALUE_WITHOUT_SOURCE\"];\n\n/**\n * The rendered-node budget of ONE render pass (`maxRenderedNodes`): every node view counts itself; past the budget a\n * node renders nothing and the renderer reports `BUDGET_EXCEEDED` once the pass is committed. A `Repeat` multiplies its\n * template, so this — not the node count of the tree — is what bounds the DOM.\n */\ninterface RenderedNodeBudget {\n renderedNodeCount: number;\n isExceeded: boolean;\n}\n\ninterface ComposedViewNodeViewProps {\n node: ComposedViewNode;\n nodePath: string;\n sizeClass: ComposedSizeClass;\n scope: ComposedViewValueScope;\n runtime: ComposedViewRuntime;\n reportNodeStatus: (\n nodePath: string,\n status: WidgetRenderStatus,\n code?: WidgetRenderReportCode,\n detail?: string,\n ) => void;\n /** Reports a node that threw (from its slot boundary). */\n onRenderFailed: (nodePath: string, nodeType: string) => void;\n renderedNodeBudget: RenderedNodeBudget;\n testId: string;\n}\n\nconst toTestIdSegment = (rawSegment: string) => rawSegment.replace(/[^a-zA-Z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n\nconst ComposedViewNodeView = (props: ComposedViewNodeViewProps) => {\n const { node, nodePath, sizeClass, scope, runtime, reportNodeStatus, onRenderFailed, renderedNodeBudget, testId } =\n props;\n const components = useComposedViewComponents();\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n let isOverRepeatRows = false;\n renderedNodeBudget.renderedNodeCount += 1;\n const isOverRenderedNodes = renderedNodeBudget.renderedNodeCount > composedNodeSchema.budgets.maxRenderedNodes;\n if (isOverRenderedNodes) renderedNodeBudget.isExceeded = true;\n const definition = Object.prototype.hasOwnProperty.call(components, node.type) ? components[node.type] : undefined;\n const nodeTypeSchema = getComposedNodeSchema().nodeTypes[node.type];\n\n useEffect(() => {\n if (!definition)\n reportNodeStatus(nodePath, \"failed\", \"INVALID_NODE\", `no component renders the node type ${node.type}`);\n }, [definition, node.type, nodePath, reportNodeStatus]);\n // Runs after the component rendered its items, so it sees whether it asked for more than `maxRepeatRows`.\n useEffect(() => {\n if (isOverRepeatRows) {\n reportNodeStatus(\n nodePath,\n \"failed\",\n \"BUDGET_EXCEEDED\",\n `${node.type} shows the first ${maxRepeatRows} rows only`,\n );\n }\n });\n\n const currentRow = scope.item;\n const nodeRuntime = useMemo<ComposedViewRuntime>(\n () => ({\n ...runtime,\n currentRow,\n // An event of a node in an item scope fires in that scope's row, unless the node names the row itself (a Map point).\n runEvent: (eventWireValue: unknown, eventValue?: unknown, eventRow?: ExpressionValue) =>\n runtime.runEvent(eventWireValue, eventValue, eventRow !== undefined ? eventRow : currentRow),\n reportNodeStatus: (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n reportNodeStatus(nodePath, status, code, detail),\n }),\n [runtime, currentRow, reportNodeStatus, nodePath],\n );\n\n let isPending = false;\n const markBindingStatus = (status: ResolvedBindingStatus) => {\n if (status === \"pending\") isPending = true;\n };\n const resolvedProps: Record<string, ExpressionValue> = {};\n for (const [propName, propValue] of Object.entries(node.props)) {\n resolvedProps[propName] = resolveComposedViewValue(propValue, scope, markBindingStatus);\n }\n\n const renderSlotNodes = (slotName: string, slotScope: ComposedViewValueScope, keySuffix = \"\"): React.ReactNode[] => {\n // The slot of this node: a Grid's cells narrow with its `columns` (1 full, 2 regular, 3–4 compact).\n const declaredSlot = nodeTypeSchema?.slots.find((slot) => slot.name === slotName);\n const slotSizeClass = (\n declaredSlot ? resolveComposedSlotForNodeProps(declaredSlot, node.props).sizeClass : \"regular\"\n ) as ComposedSizeClass;\n const slotPathSegment = slotName === \"children\" ? \"children\" : `slots.${slotName}`;\n return (node.nodesBySlotName[slotName] ?? []).map((slotNode, slotPosition) => {\n const slotNodePath = `${nodePath}.${slotPathSegment}[${slotPosition}]${keySuffix}`;\n return (\n <ComposedViewSlotErrorBoundary\n key={slotNodePath}\n nodePath={slotNodePath}\n nodeType={slotNode.type}\n onRenderFailed={onRenderFailed}\n >\n <ComposedViewNodeView\n node={slotNode}\n nodePath={slotNodePath}\n sizeClass={slotSizeClass}\n scope={slotScope}\n runtime={runtime}\n reportNodeStatus={reportNodeStatus}\n onRenderFailed={onRenderFailed}\n renderedNodeBudget={renderedNodeBudget}\n testId={testId}\n />\n </ComposedViewSlotErrorBoundary>\n );\n });\n };\n\n if (!definition || isOverRenderedNodes) return null;\n const providesItemScope = nodeTypeSchema?.providesItemScope ?? false;\n const slots: Record<string, React.ReactNode[]> = {};\n if (!providesItemScope) {\n for (const slotName of Object.keys(node.nodesBySlotName)) slots[slotName] = renderSlotNodes(slotName, scope);\n }\n // A repeating node renders at most `maxRepeatRows` items, whatever its component asks for (enforced here, not per component).\n const renderSlotForItem = (slotName: string, item: ExpressionValue, itemIndex: number) => {\n if (itemIndex >= maxRepeatRows) {\n isOverRepeatRows = true;\n return [];\n }\n return renderSlotNodes(slotName, { ...scope, item }, `#${itemIndex}`);\n };\n const Component = definition.component;\n return (\n <Component\n node={node}\n props={resolvedProps}\n isPending={isPending}\n slots={slots}\n sizeClass={sizeClass}\n renderSlotForItem={renderSlotForItem}\n runtime={nodeRuntime}\n testId={`${testId}-${toTestIdSegment(node.type).toLowerCase()}-${toTestIdSegment(node.id ?? nodePath).toLowerCase()}`}\n />\n );\n};\n\ninterface ComposedViewLiftedWidgetViewProps {\n liftedWidget: ComposedViewLiftedWidget;\n interactive: boolean;\n messageId?: string | number;\n agentSpaceKey?: string | number;\n reportNodeStatus: ComposedViewNodeViewProps[\"reportNodeStatus\"];\n}\n\n/**\n * A widget the reader LIFTED out of the tree: shown after the view as its own widget, at full\n * width, reporting into the block at `lifted <path>`. A stored row lifts nothing — the backend rewrites the row before\n * it is stored — so this renders the trees of rows stored before the lift and of a reply still on its way.\n */\nconst ComposedViewLiftedWidgetView = (props: ComposedViewLiftedWidgetViewProps) => {\n const { liftedWidget, interactive, messageId, agentSpaceKey, reportNodeStatus } = props;\n const liftedPath = `lifted ${liftedWidget.path}`;\n const reportStatus = useCallback(\n (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n reportNodeStatus(liftedPath, status, code, detail),\n [reportNodeStatus, liftedPath],\n );\n return (\n <EmbeddedConversationWidget\n widgetName={liftedWidget.widget}\n fields={liftedWidget.fields}\n agentSpaceKey={agentSpaceKey}\n interactive={interactive}\n messageId={messageId}\n reportStatus={reportStatus}\n />\n );\n};\n\n/** The one muted line of a view left with nothing to show — never a title over an empty Grid. */\nconst ComposedViewNothingToShow = () => (\n <Text role=\"help\" color=\"var(--agents-fg-light)\">\n This view has nothing to show right now.\n </Text>\n);\n\n/** The `ComposedView` tree, rendered. */\nexport const ComposedViewRenderer = (props: ComposedViewRendererProps) => {\n const {\n tree,\n interactive,\n isEmailRender,\n messageId,\n agentSpaceKey,\n onReport,\n onOpenEntity,\n testId = \"composed-view-widget\",\n } = props;\n const budgets = composedNodeSchema.budgets;\n const { state, setStateValue, resetState } = useComposedViewState(tree, budgets);\n const [nodeReports, dispatchNodeReport] = useReducer(nodeReportsReducer, {});\n const [sourceValues, dispatchSourceValue] = useReducer(sourceValuesReducer, {});\n const renderedNodeBudget: RenderedNodeBudget = { renderedNodeCount: 0, isExceeded: false };\n useEffect(() => {\n if (renderedNodeBudget.isExceeded) {\n dispatchNodeReport({\n nodePath: \"view\",\n status: \"failed\",\n code: \"BUDGET_EXCEEDED\",\n detail: `more than ${budgets.maxRenderedNodes} rendered nodes — the rest is not shown`,\n });\n }\n });\n const sourceBindings = useMemo(() => collectComposedViewSourceBindings(tree), [tree]);\n const sourceReadTimesRef = useRef<number[]>([]);\n\n /** The per-tree read budget: every source read after the first one of each binding counts against it. */\n const mayReadSource = useCallback(() => {\n const now = Date.now();\n sourceReadTimesRef.current = sourceReadTimesRef.current.filter(\n (readTime) => now - readTime < SOURCE_BUDGET_WINDOW_MS,\n );\n if (sourceReadTimesRef.current.length >= budgets.maxSourceRequestsPerTreePerMinute) return false;\n sourceReadTimesRef.current.push(now);\n return true;\n }, [budgets.maxSourceRequestsPerTreePerMinute]);\n const onSourceValue = useCallback(\n (bindingKey: string, sourceValue: ComposedViewSourceValue) => dispatchSourceValue({ bindingKey, sourceValue }),\n [],\n );\n const sourceAgentSpaceKey = agentSpaceKey === undefined || agentSpaceKey === \"\" ? undefined : Number(agentSpaceKey);\n\n const resolvedDatasets = useMemo(\n () => resolveComposedViewDatasets(tree.data, sourceValues),\n [tree.data, sourceValues],\n );\n const computedValues = useMemo(\n () => computeComposedViewValues(tree.computed, state, resolvedDatasets.datasets, budgets),\n [tree.computed, state, resolvedDatasets.datasets, budgets],\n );\n\n const writeStateValue = useCallback(\n (stateName: string, value: unknown) => {\n if (!isEmailRender) setStateValue(stateName, value);\n },\n [isEmailRender, setStateValue],\n );\n\n const runAction = useCallback(\n (actionName: string, eventRow?: ExpressionValue) => {\n const action = Object.prototype.hasOwnProperty.call(tree.actions, actionName)\n ? tree.actions[actionName]\n : undefined;\n if (!action || isEmailRender) return;\n if (action.type === \"resetState\") resetState();\n if (action.type === \"openUrl\" && typeof action.url === \"string\") {\n window.open(action.url, \"_blank\", \"noopener,noreferrer\");\n }\n if (action.type === \"openEntity\" && isRowBoundOpenEntityAction(action)) {\n // The entity is the row's own — never one written on the action; a row without one opens nothing.\n if (readOpenEntityActionTarget(action, eventRow) === undefined) {\n dispatchNodeReport({\n nodePath: `actions.${actionName}`,\n status: \"failed\",\n code: \"UNRESOLVED_REF\",\n detail: `the openEntity action \"${actionName}\" fired in a row without a resolved entity — nothing opened`,\n });\n return;\n }\n onOpenEntity?.(action, eventRow);\n } else if (action.type === \"openEntity\" && typeof action.ref === \"string\") onOpenEntity?.(action);\n if (action.type === \"copy\") {\n const copiedValue = resolveComposedViewValue(action.value, {\n state,\n computed: computedValues.values,\n datasets: resolvedDatasets.datasets,\n datasetStatuses: resolvedDatasets.statusByDatasetName,\n sources: sourceValues,\n });\n // Bounded BEFORE it is built: a value shared many times over can be far larger as text than as a structure.\n const copiedText =\n typeof copiedValue === \"string\" ? copiedValue : stringifyWithinLimit(copiedValue, budgets.maxSourceBytes);\n if (copiedText === undefined) {\n dispatchNodeReport({\n nodePath: `actions.${actionName}`,\n status: \"failed\",\n code: \"BUDGET_EXCEEDED\",\n detail: `the value to copy is larger than ${budgets.maxSourceBytes} characters`,\n });\n return;\n }\n void navigator.clipboard?.writeText(copiedText);\n }\n },\n [\n tree.actions,\n isEmailRender,\n resetState,\n onOpenEntity,\n state,\n computedValues.values,\n resolvedDatasets.datasets,\n resolvedDatasets.statusByDatasetName,\n sourceValues,\n budgets.maxSourceBytes,\n ],\n );\n\n const reportNodeStatus = useCallback(\n (nodePath: string, status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n dispatchNodeReport({ nodePath, status, code, detail }),\n [],\n );\n const onRenderFailed = useCallback(\n (nodePath: string, nodeType: string) =>\n dispatchNodeReport({\n nodePath,\n status: \"failed\",\n code: \"RENDER_FAILED\",\n detail: `the ${nodeType} at ${nodePath} threw`,\n }),\n [],\n );\n\n const runtime = useMemo<ComposedViewRuntime>(\n () => ({\n state,\n setStateValue: writeStateValue,\n runEvent: (eventWireValue: unknown, eventValue?: unknown, eventRow?: ExpressionValue) => {\n if (typeof eventWireValue !== \"object\" || eventWireValue === null) return;\n const event = eventWireValue as { set?: unknown; action?: unknown };\n if (typeof event.set === \"string\") writeStateValue(event.set, eventValue);\n if (typeof event.action === \"string\") runAction(event.action, eventRow);\n },\n interactive,\n isEmailRender,\n messageId,\n agentSpaceKey,\n findAction: (actionName: string) =>\n Object.prototype.hasOwnProperty.call(tree.actions, actionName)\n ? (tree.actions[actionName] as Record<string, unknown>)\n : undefined,\n reportNodeStatus: (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n reportNodeStatus(\"view\", status, code, detail),\n }),\n [\n state,\n writeStateValue,\n runAction,\n interactive,\n isEmailRender,\n messageId,\n agentSpaceKey,\n tree.actions,\n reportNodeStatus,\n ],\n );\n\n const blockReport = useMemo<WidgetRenderReportEntry>(() => {\n const droppingFindings = tree.findings.filter((finding) => !NOTE_FINDING_CODES.includes(finding.code));\n // a view the lift took entirely leaves its lifted widgets: the block reports their notes, not \"no view\"\n if (tree.view === null && tree.liftedWidgets.length === 0) {\n return {\n status: \"failed\",\n code: droppingFindings[0]?.code ?? \"INVALID_NODE\",\n detail: \"the tree has no view to render\",\n };\n }\n if (droppingFindings.length > 0) {\n const findingLines = droppingFindings\n .slice(0, MAX_DETAIL_FINDINGS)\n .map((finding) => `${finding.code} at ${finding.path}: ${finding.message}`);\n return {\n status: \"failed\",\n code: droppingFindings[0].code,\n detail: `${droppingFindings.length} part(s) dropped, the rest rendered — ${findingLines.join(\"; \")}`,\n };\n }\n const expressionErrors = Object.entries(computedValues.errors);\n if (expressionErrors.length > 0) {\n const [computedName, expressionError] = expressionErrors[0];\n return {\n status: \"failed\",\n code: expressionError.errorCode,\n detail: `computed \"${computedName}\": ${expressionError.message}`,\n };\n }\n const failedNodeReport = findNodeReportWithItsPath(nodeReports, \"failed\");\n if (failedNodeReport) return failedNodeReport;\n const failedDataset = Object.entries(resolvedDatasets.statusByDatasetName).find(\n ([, status]) => status === \"failed\",\n );\n if (failedDataset) {\n return {\n status: \"failed\",\n code: \"UNRESOLVED_BINDING\",\n detail: `the dataset \"${failedDataset[0]}\" did not resolve`,\n };\n }\n const isPending =\n Object.values(resolvedDatasets.statusByDatasetName).includes(\"pending\") ||\n Object.values(nodeReports).some((nodeReport) => nodeReport.status === \"pending\");\n if (isPending) return { status: \"pending\" };\n const emptyNodeReport = findNodeReportWithItsPath(nodeReports, \"empty\");\n if (emptyNodeReport) return emptyNodeReport;\n // Rendered — but figures without a source are a NOTE the model reads, so its next tree names them.\n const unsourcedFindings = tree.findings.filter((finding) => finding.code === \"INLINE_VALUE_WITHOUT_SOURCE\");\n if (unsourcedFindings.length > 0) {\n return {\n status: \"mounted\",\n code: \"INLINE_VALUE_WITHOUT_SOURCE\",\n detail: `rendered, but ${unsourcedFindings.length} part(s) show figures without a source — ${unsourcedFindings\n .slice(0, MAX_DETAIL_FINDINGS)\n .map((finding) => `${finding.path}: ${finding.message}`)\n .join(\"; \")}`,\n };\n }\n // The other notes (a choice state outside its choices, a set state nothing reads, an `$item` field the rows lack).\n const noteFindings = tree.findings.filter((finding) => NOTE_FINDING_CODES.includes(finding.code));\n if (noteFindings.length > 0) {\n return {\n status: \"mounted\",\n code: noteFindings[0].code,\n detail: `rendered, but ${noteFindings.length} part(s) do not work as written — ${noteFindings\n .slice(0, MAX_DETAIL_FINDINGS)\n .map((finding) => `${finding.code} at ${finding.path}: ${finding.message}`)\n .join(\"; \")}`,\n };\n }\n return { status: \"mounted\" };\n }, [\n tree.findings,\n tree.view,\n tree.liftedWidgets.length,\n computedValues.errors,\n nodeReports,\n resolvedDatasets.statusByDatasetName,\n ]);\n\n useEffect(() => {\n onReport(blockReport);\n }, [blockReport, onReport]);\n\n const sourceLoaders = sourceBindings.map((sourceBinding) => (\n <ComposedViewDataSourceLoader\n key={sourceBinding.bindingKey}\n sourceBinding={sourceBinding}\n state={state}\n agentSpaceKey={sourceAgentSpaceKey}\n mayRead={mayReadSource}\n onValue={onSourceValue}\n />\n ));\n const liftedWidgetViews = tree.liftedWidgets.map((liftedWidget) => (\n <ComposedViewLiftedWidgetView\n key={liftedWidget.path}\n liftedWidget={liftedWidget}\n interactive={interactive}\n messageId={messageId}\n agentSpaceKey={agentSpaceKey}\n reportNodeStatus={reportNodeStatus}\n />\n ));\n if (tree.view === null) {\n // the lift took the whole view: only its widgets stand; nothing at all: one explicit line, never a blank block\n return (\n <div className={styles.root}>\n {sourceLoaders}\n {liftedWidgetViews.length > 0 ? liftedWidgetViews : <ComposedViewNothingToShow />}\n </div>\n );\n }\n // a layout that LOST all its content to the reader (a dropped or lifted node) shows the explicit line, never an\n // empty Grid; a layout written empty on purpose renders and reports `empty` itself\n const lostAllItsContent =\n isComposedViewWithoutContent(tree.view) &&\n tree.findings.some((finding) => !NOTE_FINDING_CODES.includes(finding.code) || finding.code === \"WIDGET_LIFTED\");\n const rootScope: ComposedViewValueScope = {\n state,\n computed: computedValues.values,\n datasets: resolvedDatasets.datasets,\n datasetStatuses: resolvedDatasets.statusByDatasetName,\n sources: sourceValues,\n };\n return (\n <div className={styles.root} data-testid={testId}>\n {sourceLoaders}\n {tree.title ? (\n <ModelText role=\"intro\" weight=\"bold\">\n {tree.title}\n </ModelText>\n ) : null}\n {lostAllItsContent ? (\n <ComposedViewNothingToShow />\n ) : (\n <ComposedViewSlotErrorBoundary nodePath=\"view\" nodeType={tree.view.type} onRenderFailed={onRenderFailed}>\n <ComposedViewNodeView\n node={tree.view}\n nodePath=\"view\"\n sizeClass=\"full\"\n scope={rootScope}\n runtime={runtime}\n reportNodeStatus={reportNodeStatus}\n onRenderFailed={onRenderFailed}\n renderedNodeBudget={renderedNodeBudget}\n testId={testId}\n />\n </ComposedViewSlotErrorBoundary>\n )}\n {liftedWidgetViews}\n {/* The e-mail states when each data path was read: turn-time `$from` vs mail-time `$source`. */}\n {isEmailRender ? <ComposedViewEmailDataTimes tree={tree} /> : null}\n </div>\n );\n};\n","import { useCallback, useMemo, useState } from \"react\";\nimport type { PayloadConversationWidgetProps } from \"../renderer/conversation-widget-props\";\nimport { useIsEmailWidgetRender } from \"../renderer/ConversationWidgetRenderContext\";\nimport { useConversationWidgetContext } from \"../renderer/ConversationWidgetCallbacksContext\";\nimport { readWidgetAgentSpaceKeyAttribute } from \"../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport { messageAnchor } from \"../renderer/canvas/canvas-state\";\nimport {\n canvasInstanceIdForEntityDetail,\n readOpenEntityActionTarget,\n} from \"../renderer/canvas/entity-detail-instance\";\nimport {\n ComposedViewAction,\n parseComposedViewTree,\n} from \"../renderer/widget-tree/composed-view-tree\";\nimport {\n useReportWidgetRenderStatus,\n WidgetRenderReportEntry,\n} from \"../renderer/render-report/widget-render-report\";\nimport type { ExpressionValue } from \"../renderer/widget-tree/expression/evaluate-expression\";\nimport { ComposedViewRenderer } from \"./ComposedViewRenderer\";\n\n/**\n * The composable widget kit: the model composes a TREE of kit components — layout, text, data,\n * media, inputs — with local state, computed values and a closed list of actions, in one ```widget fence of type\n * `ComposedView`. The payload is read into typed objects and checked against the generated node schema\n * (`widget-tree/composed-view-tree.ts`, the twin of the backend reader); what is invalid is dropped and reported, the\n * rest renders. Inputs change local state only (no chat turn, no write), so a replay stays usable; the e-mail capture\n * freezes them at their initial state.\n *\n * The kit's components register themselves by folder (`components/**\\/*.composed.tsx`); this widget only parses,\n * renders, reports and opens the `entityDetail` canvas for an `openEntity` action whose reference the backend resolved\n * (a reference still unresolved opens nothing; without a message id — a streaming reply — nothing opens either).\n */\nexport const ComposedViewConversationWidget = (props: PayloadConversationWidgetProps) => {\n const { payload, interactive = false, messageId } = props;\n const agentSpaceKey = readWidgetAgentSpaceKeyAttribute(props);\n const isEmailRender = useIsEmailWidgetRender();\n const tree = useMemo(() => parseComposedViewTree(payload), [payload]);\n const [blockReport, setBlockReport] = useState<WidgetRenderReportEntry>({ status: \"pending\" });\n const onReport = useCallback((entry: WidgetRenderReportEntry) => setBlockReport(entry), []);\n const { openCanvas } = useConversationWidgetContext();\n const numericMessageId = messageId === undefined ? Number.NaN : Number(messageId);\n const onOpenEntity = useCallback(\n (action: ComposedViewAction, currentRow?: ExpressionValue) => {\n const target = readOpenEntityActionTarget(action, currentRow);\n if (target === undefined || !Number.isFinite(numericMessageId)) return;\n openCanvas({\n canvasId: \"entityDetail\",\n instanceId: canvasInstanceIdForEntityDetail(target),\n anchor: messageAnchor(numericMessageId),\n origin: \"cardClick\",\n justDelivered: false,\n });\n },\n [openCanvas, numericMessageId],\n );\n\n useReportWidgetRenderStatus(blockReport.status, blockReport.code, blockReport.detail);\n\n return (\n <ComposedViewRenderer\n tree={tree}\n interactive={interactive}\n isEmailRender={isEmailRender}\n messageId={messageId}\n agentSpaceKey={agentSpaceKey}\n onReport={onReport}\n onOpenEntity={onOpenEntity}\n />\n );\n};\n","import type { ConversationWidgetEntry } from \"../renderer/conversationWidgetRegistry\";\nimport { ComposedViewConversationWidget } from \"./ComposedViewConversationWidget\";\n\n/**\n * The composable widget kit: a component tree the model composes; deliberately UNGATED — the data\n * it shows carries its own gates (the tools and data sources behind its bindings, an embedded widget's own feature\n * gate). It opens the `entityDetail` canvas (an `openEntity` action) and the `mapFullScreen` canvas (a `Map` node's\n * full-screen control). A canvas an embedded widget opens on a click is that widget's own: the embedded widget lists it\n * in its registry entry, and `findWidgetFencesInMarkdown` reads every embedded widget as a fence of its own, so the\n * reload restore finds it there.\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"ComposedView\",\n component: ComposedViewConversationWidget,\n opensCanvases: [\"entityDetail\", \"mapFullScreen\"],\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { ClockConversationWidget } from \"./ClockConversationWidget\";\n\n/**\n * The live clock / world clock — deliberately UNGATED: it shows no business data and needs no\n * capability (the time is computed in the browser).\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"Clock\",\n component: ClockConversationWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { ConceptExplainerConversationWidget } from \"./ConceptExplainerConversationWidget\";\n\n/**\n * The interactive explainer — deliberately UNGATED: the frame serves the explainer types an app\n * declares in several of its domains; a domain flag would hide every type for an owner missing that one domain, and\n * an explainer shows no data a feature flag protects. Opens no canvas.\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"ConceptExplainer\",\n component: ConceptExplainerConversationWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { CurrencyConverterConversationWidget } from \"./CurrencyConverterConversationWidget\";\n\n/** The currency converter: ungated — currency conversion belongs to no feature domain. */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"CurrencyConverter\",\n component: CurrencyConverterConversationWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { CustomVisualizationConversationWidget } from \"./CustomVisualizationConversationWidget\";\n\n/**\n * The sandboxed custom visualization — deliberately UNGATED: it shows no product data of one\n * domain, only what the block itself carries. Opens no canvas.\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"CustomVisualization\",\n component: CustomVisualizationConversationWidget,\n};\n","import { Button, Icon, Text } from \"../../../provider/components\";\nimport { ModelText } from \"../../../kit/ModelText/ModelText\";\nimport type { EntityMentionFields } from \"../shared/entity-mention\";\nimport styles from \"./EntityMentionChip.module.scss\";\n\nexport interface EntityMentionChipProps {\n mention: EntityMentionFields;\n /** The composer's ✕; omitted → no remove button. */\n onRemove?: () => void;\n testId?: string;\n}\n\n/**\n * ONE mentioned entity as a chip — in the chat input ({@link EntityMentionComposerWidget}): the detail glyph, the label \"About:\" and the name.\n * The name is what the panel showed — business content through `ModelText` (never translated, never parsed as\n * markup; a `replacements` value is parsed by the component library, so it is not used for it); without one the chip says \"About\n * this entry\".\n */\nexport const EntityMentionChip = (props: EntityMentionChipProps) => {\n const { mention, onRemove, testId = \"entity-mention-chip\" } = props;\n return (\n <span className={styles.chip} data-testid={testId}>\n <Icon color=\"var(--agents-fg-light)\" className={styles.icon} pixelSize={14} name=\"details\" />\n {mention.label !== null ? (\n <>\n <Text className={styles.prefix} role=\"help\" color=\"var(--agents-fg-light)\" textWrap=\"nowrap\">\n {\"About:\"}\n </Text>\n <ModelText className={styles.label} role=\"help\" textWrap=\"nowrap\">\n {mention.label}\n </ModelText>\n </>\n ) : (\n <Text className={styles.label} role=\"help\" textWrap=\"nowrap\">\n {\"About this entry\"}\n </Text>\n )}\n {onRemove && (\n <Button\n className={styles.remove}\n variant=\"muted\"\n size=\"small\"\n icon=\"close\"\n onClick={onRemove}\n testId={`${testId}-remove`}\n rounded\n />\n )}\n </span>\n );\n};\n","import { useMemo } from \"react\";\nimport type { ComposerConversationWidgetProps } from \"../../renderer/conversation-widget-props\";\nimport { EntityMentionChip } from \"./EntityMentionChip/EntityMentionChip\";\nimport { normalizeEntityMentionFields } from \"./shared/entity-mention\";\n\n/**\n * The registry `composerComponent` of `EntityMention`: the entity chip in the chat input until the owner\n * sends — its ✕ (or Backspace on an empty input) takes the mention out. Fields that name no entity render nothing.\n */\nexport const EntityMentionComposerWidget = (props: ComposerConversationWidgetProps) => {\n const { fields, remove, testId = \"entity-mention\" } = props;\n const mention = useMemo(() => normalizeEntityMentionFields(fields), [fields]);\n if (mention === null) return null;\n return <EntityMentionChip mention={mention} onRemove={remove} testId={`${testId}-chip`} />;\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { EntityMentionConversationWidget } from \"./EntityMentionConversationWidget\";\nimport { EntityMentionComposerWidget } from \"./EntityMentionComposerWidget\";\n\n/**\n * `EntityMention`: composed by the OWNER — the detail panel's \"Ask about this\" puts it into the chat\n * input (`composerComponent`), it travels in the owner's message as a fence and echoes read-only above its prose\n * (`component`). Ungated: it names an entity the owner could already open. Backspace removes the whole chip (one\n * entity per widget, so no `removeLastPartFromComposerWidgetFields`).\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"EntityMention\",\n component: EntityMentionConversationWidget,\n composerComponent: EntityMentionComposerWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { WritingDraftConversationWidget } from \"./WritingDraftConversationWidget\";\n\n/**\n * The editable text draft — deliberately UNGATED: it carries only the text the model wrote, reads no\n * business data and needs no capability; every action stays in the browser (copy, the owner's own mail program).\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"WritingDraft\",\n component: WritingDraftConversationWidget,\n};\n","import type React from \"react\";\nimport type { ConversationWidgetUpsellProps } from \"./_access/ConversationWidgetFeatureGate\";\nimport type { CanvasId } from \"./canvas/canvas-behaviours\";\nimport type { ComposerConversationWidgetProps } from \"./conversation-widget-props\";\nimport { SuggestedActions } from \"../widgets/SuggestedActions/SuggestedActions\";\nimport { MultiChoiceConversationWidget } from \"../widgets/MultiChoiceConversationWidget/MultiChoiceConversationWidget\";\nimport { QuickRepliesConversationWidget } from \"../widgets/QuickRepliesConversationWidget/QuickRepliesConversationWidget\";\nimport { ToolTraceConversationWidget } from \"../widgets/ToolTraceConversationWidget/ToolTraceConversationWidget\";\nimport { ConversationSearchResultsConversationWidget } from \"../widgets/ConversationSearchResultsConversationWidget/ConversationSearchResultsConversationWidget\";\nimport { WebSearchResultsConversationWidget } from \"../widgets/WebSearchResultsConversationWidget/WebSearchResultsConversationWidget\";\n\nexport interface ConversationWidgetEntry {\n /**\n * The CANONICAL wire name — short, never ending in `Directive` (that suffix is reserved as the legacy marker; see\n * `widget-name-resolver.ts`). Stored messages that carry the old `<Name>Directive` form resolve onto this one.\n */\n name: string;\n component: React.ComponentType<any>;\n /**\n * The app's requirement name (a feature flag) that gates this widget — opaque to the package, checked by the app's\n * `WidgetFeatureGate`. Omit to render unconditionally (default).\n */\n featureFlag?: string;\n /**\n * May this widget be mounted by NAME from outside a conversation — the `?agentWidget=<name>` deep-link a page uses to\n * open the chat with this widget's canvas already up, and the restore of a pinned canvas after a reload\n * (`resolve-deep-linkable-widget.ts`). Opt-in per widget because a URL is untrusted input: everything else is mounted\n * only from a message the agent wrote. Default false.\n */\n deepLinkable?: boolean;\n /**\n * The canvases (by canvas id, `canvas/canvas-behaviours.ts`) this widget may open. Documentation and the restore's\n * validation: a stored canvas pointer is re-opened only when its anchor message carries a widget that lists the\n * canvas. `_registry-wire-names.spec.ts` asserts every listed id is a declared canvas.\n */\n opensCanvases?: readonly CanvasId[];\n /** Optional custom upgrade offer for the gated widget; defaults to the app gate's own. */\n upsellTrigger?: React.ComponentType<ConversationWidgetUpsellProps>;\n /**\n * Renders this widget INSIDE the chat input (editable: per-part ✕ etc.). Present = the widget may be composed by\n * the customer (see `ConversationComposerWidget`). An entry declaring this MUST also declare `component` (asserted\n * in `_registry-wire-names.spec.ts`) — the message rendering.\n */\n composerComponent?: React.ComponentType<ComposerConversationWidgetProps>;\n /**\n * Backspace on an empty input removes the LAST removable part of the last composer widget. Returns the fields\n * without that part, or `null` when nothing is left (the widget is then removed entirely). Omitted → Backspace\n * removes the whole widget.\n */\n removeLastPartFromComposerWidgetFields?: (fields: Record<string, unknown>) => Record<string, unknown> | null;\n}\n\n/**\n * The package's widgets that register themselves by FILE: every `*.widget-registration.ts` below the\n * package's `widgets/` and `kit/` that exports `conversationWidgetRegistration` joins the list. An app registers its\n * own widgets with `registerConversationWidgets` (its folder globs stay in its own code).\n */\nconst widgetRegistrationModules = import.meta.glob<{ conversationWidgetRegistration?: ConversationWidgetEntry }>(\n [\"../widgets/**/*.widget-registration.ts\", \"../kit/**/*.widget-registration.ts\"],\n { eager: true },\n);\n\n/** The entries of a set of registration modules (`*.widget-registration.ts` files an app or the package globbed). */\nexport const readConversationWidgetRegistrations = (\n registrationModules: Record<string, { conversationWidgetRegistration?: ConversationWidgetEntry }>,\n): ConversationWidgetEntry[] =>\n Object.values(registrationModules)\n .map((registrationModule) => registrationModule.conversationWidgetRegistration)\n .filter((entry): entry is ConversationWidgetEntry => entry !== undefined);\n\n/** The package's own widgets registered by file. */\nexport const readFolderRegisteredConversationWidgets = (): ConversationWidgetEntry[] =>\n readConversationWidgetRegistrations(widgetRegistrationModules);\n\n/** Throws on a wire name registered twice — the written list and the registration files together. */\nexport const assertUniqueConversationWidgetNames = (widgets: readonly ConversationWidgetEntry[]): void => {\n const seenNames = new Set<string>();\n for (const widget of widgets) {\n if (seenNames.has(widget.name)) throw new Error(`The conversation widget \"${widget.name}\" is registered twice.`);\n seenNames.add(widget.name);\n }\n};\n\n/** The package's own widgets: the written entries and every package widget registered by file. */\nexport const packageConversationWidgets: readonly ConversationWidgetEntry[] = [\n { name: \"SuggestedActions\", component: SuggestedActions },\n { name: \"MultiChoice\", component: MultiChoiceConversationWidget },\n { name: \"QuickReplies\", component: QuickRepliesConversationWidget },\n { name: \"ToolTrace\", component: ToolTraceConversationWidget },\n {\n name: \"ConversationSearchResults\",\n component: ConversationSearchResultsConversationWidget,\n opensCanvases: [\"conversationSearchResults\"],\n },\n { name: \"WebSearchResults\", component: WebSearchResultsConversationWidget, opensCanvases: [\"webSearchResults\"] },\n // Every package widget with a `<Name>ConversationWidget.widget-registration.ts` file joins below.\n ...readFolderRegisteredConversationWidgets(),\n];\n\n/**\n * ONE list — every registered widget, in no particular order. There are no kinds of widget here: inline vs canvas vs\n * mount-time is the component's own choice, not a registry bucket. A widget that opens a canvas lists the canvas ids\n * (`opensCanvases`); the canvas's behaviour lives in `canvas/canvas-behaviours.ts`, its body in `canvas/canvasBodies.tsx`.\n * It starts with the package's own widgets; an app adds its widgets with `registerConversationWidgets` before the\n * first render (outside React). The array is filled in place, so a reader that holds it sees every registration.\n */\nexport const conversationWidgetRegistry: {\n widgets: ConversationWidgetEntry[];\n} = {\n widgets: [...packageConversationWidgets],\n};\n\nassertUniqueConversationWidgetNames(conversationWidgetRegistry.widgets);\n\nlet registryRevision = 0;\n\n/**\n * Counts the registrations: a reader that caches something derived from the registry (a name set, a component map)\n * rebuilds it when the revision moved.\n */\nexport const getConversationWidgetRegistryRevision = (): number => registryRevision;\n\n/**\n * Adds an app's widgets to the registry. Runs outside React, before the first render; throws when a wire name is\n * registered twice (with the package's own or an earlier registration).\n */\nexport const registerConversationWidgets = (widgets: readonly ConversationWidgetEntry[]): void => {\n assertUniqueConversationWidgetNames([...conversationWidgetRegistry.widgets, ...widgets]);\n conversationWidgetRegistry.widgets.push(...widgets);\n registryRevision += 1;\n};\n\n/**\n * Puts `widgets` in place of every registered entry and returns the entries the registry held, so a spec renders\n * against widgets of its own and puts the registry back afterwards (`installTestConversationWidgets`, the\n * `client/testing` subpath). Fills the same array in place, so a reader that holds it sees the swap; moves the revision.\n */\nexport const replaceConversationWidgetRegistryEntries = (\n widgets: readonly ConversationWidgetEntry[],\n): ConversationWidgetEntry[] => {\n assertUniqueConversationWidgetNames(widgets);\n const previousWidgets = conversationWidgetRegistry.widgets.splice(0, conversationWidgetRegistry.widgets.length, ...widgets);\n registryRevision += 1;\n return previousWidgets;\n};\n","import { conversationWidgetRegistry, getConversationWidgetRegistryRevision } from \"./conversationWidgetRegistry\";\n\n/**\n * WIRE LAYER — this file owns the ONE rule that maps a name off the wire onto a registered widget.\n *\n * CANONICAL names are SHORT: `QuickReplies`, `MultiChoice`, `WebSearchResults`. That is what the registry holds, what the\n * agent emits in a ```widget fence `type`, and what every doc and FE-generated message writes today.\n *\n * LEGACY names carry a trailing `Directive`: stored conversation messages in the database contain\n * `::QuickRepliesDirective{payload='…'}` and ```widget fences with `\"type\": \"QuickRepliesDirective\"`. Those rows are\n * permanent — the database is not rewritten.\n *\n * THE RULE (in `resolveCanonicalWidgetName`, and nowhere else):\n * 1. exact match against the canonical names;\n * 2. ONLY if the requested name ends in `Directive` — strip that suffix ONCE and retry the exact match;\n * 3. otherwise undefined (unknown widget).\n *\n * Consequence: the `Directive` suffix is RESERVED as the legacy marker. Never register a new widget under a name\n * ending in `Directive` — `_registry-wire-names.spec.ts` asserts no canonical name does, and asserts that every legacy\n * long name still resolves to the canonical one, so old conversations keep rendering forever.\n */\n\n/** The suffix every pre-canonicalization wire name carried. Reserved as the legacy marker — see the file header. */\nconst LEGACY_NAME_SUFFIX = \"Directive\";\n\nlet widgetNameSet: ReadonlySet<string> | undefined;\nlet widgetNameSetRevision = -1;\n\n/**\n * Every registered widget name, canonical (short) — the runtime source of truth for what renders. Read LAZILY: the\n * registry imports every widget, and a widget can import AgentChat, which imports this file — a module-scope read\n * would run before the registry finished initializing whenever a widget is the first module loaded (a story). Rebuilt\n * when an app registered more widgets since (`registerConversationWidgets`).\n */\nconst getWidgetNameSet = (): ReadonlySet<string> => {\n if (widgetNameSet === undefined || widgetNameSetRevision !== getConversationWidgetRegistryRevision()) {\n widgetNameSet = new Set(conversationWidgetRegistry.widgets.map((widget) => widget.name));\n widgetNameSetRevision = getConversationWidgetRegistryRevision();\n }\n return widgetNameSet;\n};\n\n/**\n * THE resolution rule (see the file header): exact canonical match, else — only for a name ending in `Directive` —\n * strip that legacy suffix once and match again. Undefined = no such widget. Every lookup in the pipeline goes through\n * this function (the fence plugin, the AST plugin, the drawer-reset scan, the unrendered-widget detector), so a name\n * that renders in one place renders in all of them.\n */\nexport const resolveCanonicalWidgetName = (\n requestedName: string,\n canonicalNames: ReadonlySet<string>,\n): string | undefined => {\n if (canonicalNames.has(requestedName)) return requestedName;\n if (!requestedName.endsWith(LEGACY_NAME_SUFFIX)) return undefined;\n const withoutLegacySuffix = requestedName.slice(0, -LEGACY_NAME_SUFFIX.length);\n return canonicalNames.has(withoutLegacySuffix) ? withoutLegacySuffix : undefined;\n};\n\n/**\n * Resolve a model-supplied ```widget `type` — or the name on a stored message's `::<Name>` node — to a registered\n * widget name. `QuickReplies` matches exactly; the legacy `QuickRepliesDirective` resolves to the same canonical\n * `QuickReplies`. Shared by the render plugin (which DROPS an unresolved block) and the unrendered-widget detector\n * (which REPORTS it), so both agree exactly on what counts as a valid widget.\n */\nexport const resolveWidgetName = (type: string): string | undefined =>\n resolveCanonicalWidgetName(type, getWidgetNameSet());\n\n/** Normalize a widget name / type for fuzzy comparison: lowercase, drop a trailing `Directive`. */\nconst normalizeWidgetName = (value: string): string => value.toLowerCase().replace(/directive$/, \"\");\n\n/** Split a PascalCase / camelCase widget name into lowercase word tokens (`WebSearchResults` → [web, search, results]). */\nconst wordTokens = (value: string): string[] =>\n value\n .replace(/directive$/i, \"\")\n .split(/(?=[A-Z])/)\n .map((token) => token.toLowerCase())\n .filter(Boolean);\n\n/** Levenshtein edit distance — the fine tiebreaker for the closest-widget shortlist (dependency-free). */\nconst editDistance = (a: string, b: string): number => {\n const rows = a.length + 1;\n const cols = b.length + 1;\n const dist: number[][] = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));\n for (let i = 0; i < rows; i++) dist[i][0] = i;\n for (let j = 0; j < cols; j++) dist[0][j] = j;\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n dist[i][j] = Math.min(\n dist[i - 1][j] + 1,\n dist[i][j - 1] + 1,\n dist[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),\n );\n }\n }\n return dist[rows - 1][cols - 1];\n};\n\n/**\n * The closest VALID widget names to an unknown `type` the model emitted — a deterministic similarity shortlist (no\n * LLM): substring containment + shared PascalCase tokens + edit-distance proximity as the tiebreaker. A candidate is\n * kept only when it genuinely resembles the type (containment, a shared word, or a very close spelling) — proximity\n * alone is too loose across ~60 widget names. Returned as the canonical (short) names, which is what a corrected\n * emission should use; empty when nothing is close.\n */\nexport const closestWidgetNames = (type: string, limit = 3): string[] => {\n const target = normalizeWidgetName(type);\n if (target === \"\") return [];\n const targetTokens = new Set(wordTokens(type));\n return [...getWidgetNameSet()]\n .map((name) => {\n const candidate = normalizeWidgetName(name);\n const candidateTokens = wordTokens(name);\n const contains = candidate.includes(target) || target.includes(candidate) ? 3 : 0;\n const overlap = candidateTokens.filter((token) => targetTokens.has(token)).length;\n // Proximity against the WHOLE name and against each word token (so a single-word typo like `conections` still\n // matches the `connections` token of a multi-word widget), best of the two.\n const nameProximity = 1 - editDistance(target, candidate) / Math.max(target.length, candidate.length);\n const tokenProximity = Math.max(\n 0,\n ...candidateTokens.map((token) => 1 - editDistance(target, token) / Math.max(target.length, token.length)),\n );\n const proximity = Math.max(nameProximity, tokenProximity);\n return {\n name,\n keep: contains > 0 || overlap > 0 || proximity >= 0.6,\n score: contains + overlap + proximity,\n };\n })\n .filter((entry) => entry.keep)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map((entry) => entry.name);\n};\n"],"names":["value","pending","nested","text","hasOwn","isPlainObject","entry","row","code","fields","categories","source","arrow","budgets","left","list","toStateValue","rows","fallback","readFiniteNumber","readText","delta","field","heatCell","styles","stage","readHttpUrl","SourceChip","caption","title","composedViewComponent","label","icon","compact","marker","description","trailing","column","bar","heat","content","tableStyles","headerItems","COPIED_CONFIRMATION_MS","labelText","FALLBACK_DATE_LOCALE","readFieldText","typedText","readChoiceId","readScrollEdges","track","slide","prefersReducedMotion","ALIGNMENTS","ALIGNMENT_CLASS_NAMES","embeddableWidgets","cell","attribution","sourceLabel","readImageUrl","COMPOSED_VIEW_WIDGET_NAME","markdown","AgentsMap","routeChip","image","readTitle","metaLine","frame","badge","actions","footer","graphic","Fragment","__vite_glob_0_0","__vite_glob_0_1","__vite_glob_0_2","__vite_glob_0_3","__vite_glob_0_4","__vite_glob_0_5","__vite_glob_0_6","dataTimes","nodeReport","conversationWidgetRegistration","remove"],"mappings":";;;;;;;;;;;AAgBO,MAAM,oBAAoB;AAQ1B,MAAM,wBAAwB;AAG9B,MAAM,0BAA0B;ACTvC,MAAM,sBAAsB;AAE5B,MAAM,oBAAoB;AAC1B,MAAM,4BAA4B;AAE3B,MAAM,kCAAkC,CAAC,WAC9C,gBAAgB,OAAO,UAAU,IAAI,OAAO,QAAQ;AAG/C,MAAM,6BAA6B,CAAC,eAAuD;AAChG,QAAM,QAAQ,0BAA0B,KAAK,UAAU;AACvD,SAAO,QAAQ,EAAE,YAAY,MAAM,CAAC,GAAG,UAAU,MAAM,CAAC,EAAA,IAAM;AAChE;AAGO,MAAM,iCAAiC;AAE9C,MAAM,gBAAgB,CAACA,WACrB,OAAOA,WAAU,YAAYA,WAAU,QAAQ,CAAC,MAAM,QAAQA,MAAK;AAO9D,MAAM,6BAA6B,CAAC,WAA6C;AACtF,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OAAO,SAAS,SAAS,IAAI,IAAI;AAChF,UAAM,UAAU,gBAAgB,OAAO,CAAC,UAAU,aAAa,IAAI,KAAK,CAAC,EAAE;AAG3E,UAAM,gBAAgB,IAAI,aAAa,QAAQ,SAAS,IAAI,KAAK,IAAI,OAAO,QAAQ,UAAU,MAAM;AACpG,UAAM,iBAAiB,KAAK;AAAA,MAC1B;AAAA,MACA,GAAG,gBAAgB,IAAI,CAAC,UAAU,IAAI,aAAa,QAAQ,KAAK,IAAI,KAAK,IAAI,OAAO,QAAQ,MAAM,MAAM,CAAC;AAAA,IAAA;AAE3G,UAAM,YAAY,KAAK,IAAI,eAAe,cAAc;AACxD,WAAO;AAAA,MACL;AAAA,MACA,MAAM,WAAW,KAAK,UAAU,KAAK,aAAa;AAAA,MAClD,OAAO,WAAW,UAAU;AAAA,IAAA;AAAA,EAEhC,CAAC,EACA,OAAO,CAACX,WAAUA,OAAM,IAAI,EAC5B,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK,EAChC,MAAM,GAAG,KAAK,EACd,IAAI,CAACA,WAAUA,OAAM,IAAI;AAC9B;"}
1
+ {"version":3,"file":"widget-name-resolver-BaxKaRa3.js","sources":["../../src/renderer/widget-fence-syntax.ts","../../src/renderer/canvas/entity-detail-instance.ts","../../src/renderer/widget-tree/composed-node-schema.ts","../../src/renderer/widget-tree/bounded-json.ts","../../src/renderer/widget-tree/composed-view-tree.ts","../../src/renderer/widget-tree/expression/parse-expression.ts","../../src/renderer/widget-tree/expression/evaluate-expression.ts","../../src/renderer/widget-tree/use-composed-view-state.ts","../../src/renderer/widget-tree/resolve-composed-view-values.ts","../../src/renderer/widget-tree/composed-view-data-sources.ts","../../src/kit/components/data/apex-chart-component.ts","../../src/kit/composed-view-tones.ts","../../src/kit/components/data/data-value-format.ts","../../src/kit/components/data/chart-model.ts","../../src/kit/components/data/data-tones.ts","../../src/kit/components/data/ChartBarRows/ChartBarRows.tsx","../../src/kit/components/data/ChartFunnelRows/ChartFunnelRows.tsx","../../src/kit/components/data/use-chart-palette.ts","../../src/kit/components/data/use-number-locale.ts","../../src/kit/components/data/DataFootnote/DataFootnote.tsx","../../src/kit/components/data/DataEmptyLine/DataEmptyLine.tsx","../../src/kit/components/data/use-report-data-node-status.ts","../../src/kit/components/data/Chart.composed.tsx","../../src/kit/components/data/Icon.composed.tsx","../../src/kit/components/layout/layout-nesting-context.ts","../../src/kit/components/data/KpiMeter/KpiMeter.tsx","../../src/kit/components/data/KpiToneAccent/KpiToneAccent.tsx","../../src/kit/components/data/kpi-value-parts.ts","../../src/kit/components/data/KpiTile.composed.tsx","../../src/kit/components/data/data-containers.ts","../../src/kit/components/data/ListEntry/ListEntry.tsx","../../src/kit/components/data/List.composed.tsx","../../src/kit/components/data/ListItem.composed.tsx","../../src/kit/components/data/Repeat.composed.tsx","../../src/kit/components/data/table-columns.ts","../../src/kit/components/data/TableValue/TableValue.tsx","../../src/kit/components/data/Table.composed.tsx","../../src/kit/components/data/TableCell.composed.tsx","../../src/kit/components/data/TableRow.composed.tsx","../../src/renderer/ConversationWidgetErrorBoundary.tsx","../../src/renderer/_access/ConversationWidgetFeatureGate.tsx","../../src/kit/components/embedding/EmbeddedConversationWidget.tsx","../../src/kit/components/embedding/WidgetNode.composed.tsx","../../src/kit/components/entity/entity-link-target.ts","../../src/kit/components/entity/EntityLink.composed.tsx","../../src/kit/components/form/compose-form-signal.ts","../../src/kit/components/form/Form.composed.tsx","../../src/kit/components/inputs/shared/date-pattern-of-locale.ts","../../src/kit/components/inputs/shared/composed-input-values.ts","../../src/kit/components/inputs/Button.composed.tsx","../../src/kit/components/inputs/shared/ComposedInputField.tsx","../../src/kit/components/inputs/shared/use-composed-input-value.ts","../../src/kit/components/inputs/Checkbox.composed.tsx","../../src/kit/components/inputs/shared/ComposedInputFrozenValue.tsx","../../src/kit/components/inputs/shared/use-composed-input-language.ts","../../src/kit/components/inputs/DatePicker.composed.tsx","../../src/kit/components/inputs/Input.composed.tsx","../../src/kit/components/inputs/shared/use-report-missing-options.ts","../../src/kit/components/inputs/RadioGroup.composed.tsx","../../src/kit/components/inputs/Select.composed.tsx","../../src/kit/components/inputs/Slider.composed.tsx","../../src/kit/components/inputs/Tabs.composed.tsx","../../src/kit/components/inputs/Textarea.composed.tsx","../../src/kit/components/layout/layout-props.ts","../../src/kit/components/layout/Carousel.composed.tsx","../../src/kit/components/layout/Divider.composed.tsx","../../src/kit/components/layout/layout-gap-class.ts","../../src/kit/components/layout/Flow.composed.tsx","../../src/kit/components/layout/Grid.composed.tsx","../../src/kit/components/layout/Popover.composed.tsx","../../src/kit/components/layout/Pressable.composed.tsx","../../src/kit/components/layout/Quote.composed.tsx","../../src/kit/components/layout/Spacer.composed.tsx","../../src/kit/components/layout/Stack.composed.tsx","../../src/kit/components/layout/Surface.composed.tsx","../../src/kit/components/map/map-points.ts","../../src/kit/components/map/map-presentation-context.ts","../../src/renderer/widget-fence-json.ts","../../src/renderer/remarkWidgetFencePlugin.ts","../../src/renderer/canvas/find-widget-fences-in-markdown.ts","../../src/kit/components/map/map-full-screen-instance.ts","../../src/kit/components/map/MapPointMarker.tsx","../../src/kit/components/map/MapGoogleMap.tsx","../../src/kit/components/map/MapPointCard.tsx","../../src/kit/components/map/MapPointCarousel.tsx","../../src/kit/components/map/ComposedMapView.tsx","../../src/kit/components/map/use-google-maps-auth-failure.ts","../../src/kit/components/map/Map.composed.tsx","../../src/kit/components/media/MediaCaption.tsx","../../src/kit/components/media/use-image-load-state.ts","../../src/kit/components/media/MediaImageTile.tsx","../../src/kit/components/media/media-values.ts","../../src/kit/components/media/Image.composed.tsx","../../src/kit/components/media/ImageGroup.composed.tsx","../../src/kit/components/media/Video.composed.tsx","../../src/kit/components/media/video-card/video-card-values.ts","../../src/kit/components/media/video-card/VideoCard.composed.tsx","../../src/kit/components/rich/rich-libraries.ts","../../src/kit/components/rich/RichNodeFrame.tsx","../../src/kit/components/rich/Code.composed.tsx","../../src/kit/components/rich/sanitize-svg-markup.ts","../../src/kit/components/rich/diagram-theme.ts","../../src/kit/components/rich/Diagram.composed.tsx","../../src/kit/components/rich/Math.composed.tsx","../../src/kit/components/rich/Svg.composed.tsx","../../src/kit/components/text/Badge.composed.tsx","../../src/kit/components/text/Caption.composed.tsx","../../src/kit/components/text/shared/SiteFavicon.tsx","../../src/kit/components/text/Favicon.composed.tsx","../../src/kit/components/text/Label.composed.tsx","../../src/kit/components/text/Link.composed.tsx","../../src/kit/components/text/Markdown.composed.tsx","../../src/kit/components/text/shared/source-ref-entries.ts","../../src/kit/components/text/SourceRef.composed.tsx","../../src/kit/components/text/Text.composed.tsx","../../src/kit/components/text/Title.composed.tsx","../../src/kit/composed-view-components.ts","../../src/kit/ComposedViewSlotErrorBoundary.tsx","../../src/kit/hooks/use-debounced-value.ts","../../src/kit/ComposedViewDataSourceLoader.tsx","../../src/image-render/composed-view-data-times.ts","../../src/image-render/ComposedViewEmailDataTimes/ComposedViewEmailDataTimes.tsx","../../src/kit/ComposedViewRenderer.tsx","../../src/kit/ComposedViewConversationWidget.tsx","../../src/kit/ComposedViewConversationWidget.widget-registration.ts","../../src/widgets/ClockConversationWidget/ClockConversationWidget.widget-registration.ts","../../src/widgets/ConceptExplainerConversationWidget/ConceptExplainerConversationWidget.widget-registration.ts","../../src/widgets/CurrencyConverterConversationWidget/CurrencyConverterConversationWidget.widget-registration.ts","../../src/widgets/CustomVisualizationConversationWidget/CustomVisualizationConversationWidget.widget-registration.ts","../../src/widgets/EntityMentionConversationWidget/EntityMentionChip/EntityMentionChip.tsx","../../src/widgets/EntityMentionConversationWidget/EntityMentionComposerWidget.tsx","../../src/widgets/EntityMentionConversationWidget/EntityMentionConversationWidget.widget-registration.ts","../../src/widgets/WritingDraftConversationWidget/WritingDraftConversationWidget.widget-registration.ts","../../src/renderer/conversationWidgetRegistry.ts","../../src/renderer/widget-name-resolver.ts"],"sourcesContent":["/**\n * WIRE SYNTAX — the ```widget fence and bare `widget { … }` forms, as import-free constants.\n *\n * Deliberately a leaf module (no imports): `widget-name-resolver.ts` reads the registry at module scope, and the\n * registry pulls in every widget → AgentChat → the unrendered-widget detector, which builds a RegExp from\n * WIDGET_FENCE_LANG at ITS module scope. When a story loads a widget before anything has evaluated the resolver, that\n * chain reaches the detector while the resolver is still in its temporal dead zone (\"Cannot access 'WIDGET_FENCE_LANG'\n * before initialization\"). Keeping the syntax here, outside the registry cycle, makes evaluation order irrelevant.\n */\n\n/**\n * The ```widget fence's info-string language — the ONE definition every fence regex in the pipeline (the render\n * plugin's `node.lang` check, the malformed-fence repairer, the drawer-reset scan, the unrendered-widget detector)\n * is built from, so \"``` widget\" (a space before the lang — remark accepts it, the model sometimes writes it) is\n * recognized identically everywhere.\n */\nexport const WIDGET_FENCE_LANG = \"widget\";\n\n/**\n * A bare `widget { …json… }` line (no ```widget fence) that IS the whole paragraph — the fallback form the model\n * emits when it drops the backticks. Capture group 1 is the JSON object. Anchored to the whole paragraph text so a\n * prose mention (\"the widget shows…\") never matches. Shared by the render plugin (rewrites it) so there is one\n * definition of the bare form. The detector uses {@link BARE_WIDGET_LINE_GLOBAL} to scan a raw message the same way.\n */\nexport const BARE_WIDGET_PARAGRAPH = /^\\s*widget\\s*(\\{[\\s\\S]*\\})\\s*$/;\n\n/** The bare `widget { … }` form scanned line-by-line across a raw message string (detector side of {@link BARE_WIDGET_PARAGRAPH}). */\nexport const BARE_WIDGET_LINE_GLOBAL = /^[ \\t]*widget[ \\t]*(\\{.*\\})[ \\t]*$/gm;\n","/**\n * The instance id of the `entityDetail` canvas: one instance per entity — `entityDetail:<entityType>:<id>`.\n * The entity type is the backend resolver's `ENTITY_TYPE` (a lowercase-first name like `review`, `keyword`); the id is\n * the one the backend resolved the platform-minted reference to when it stored the row (`openEntity` action) — a string, as `EntityReferenceRow::$entityId` is (a row id, or an external id such as a place's). A\n * module that imports only the environment accessor, safe for every layer.\n */\nimport { getWidgetSelfHydrationKeyFieldName } from \"../../provider/environment\";\n\nexport interface EntityDetailTarget {\n entityType: string;\n entityId: string;\n}\n\n/** The entity an `openEntity` action opens: its type, its id and the key of its agent space when the entity names one. */\nexport interface OpenEntityActionTarget extends EntityDetailTarget {\n agentSpaceKey?: number;\n}\n\nconst ENTITY_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9]*$/;\n/** An entity id: letters, digits, `_`, `-`, `.` — a row id or an external id, never a path or markup. */\nconst ENTITY_ID_PATTERN = /^[A-Za-z0-9_.-]{1,256}$/;\nconst ENTITY_DETAIL_INSTANCE_ID = /^entityDetail:([a-zA-Z][a-zA-Z0-9]*):([A-Za-z0-9_.-]{1,256})$/;\n\nexport const canvasInstanceIdForEntityDetail = (target: EntityDetailTarget): string =>\n `entityDetail:${target.entityType}:${target.entityId}`;\n\n/** The entity an `entityDetail` instance id names, or undefined for another instance id. */\nexport const readEntityDetailInstanceId = (instanceId: string): EntityDetailTarget | undefined => {\n const match = ENTITY_DETAIL_INSTANCE_ID.exec(instanceId);\n return match ? { entityType: match[1], entityId: match[2] } : undefined;\n};\n\n/** The `refState` the backend writes on an `openEntity` action whose `ref` is bound to the current row. */\nexport const OPEN_ENTITY_REF_STATE_FROM_ROW = \"row\";\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Whether an `openEntity` action opens the entity of the row it fires in — its `ref` is a `{\"$item\": \"<key>\"}`\n * binding (`{\"$item\":\"entityRef\"}` inside a `Repeat`, a `Map` point, a list row), or the backend marked it\n * `refState: \"row\"` (`ComposedViewBindingResolution::STATE_FROM_ROW`). Such an action carries no entity of its own.\n */\nexport const isRowBoundOpenEntityAction = (action: Record<string, unknown>): boolean => {\n if (action.refState === OPEN_ENTITY_REF_STATE_FROM_ROW) return true;\n const reference = action.ref;\n if (!isPlainRecord(reference)) return false;\n const referenceKeys = Object.keys(reference);\n return (\n referenceKeys.length === 1 &&\n referenceKeys[0] === \"$item\" &&\n typeof reference.$item === \"string\" &&\n reference.$item !== \"\"\n );\n};\n\n/**\n * The entity of an `{entityType, entityId, <agent space key field>}` object (`EntityReferenceRow::toWireArray()`), or\n * undefined. The key sits under the block field the app declares (`AgentsEnvironment.widgetSelfHydrationKeyFieldName`).\n */\nconst readEntityDetailTargetOfEntity = (\n entity: unknown,\n): OpenEntityActionTarget | undefined => {\n if (!isPlainRecord(entity)) return undefined;\n const { entityType, entityId } = entity;\n const agentSpaceKey = entity[getWidgetSelfHydrationKeyFieldName()];\n if (typeof entityType !== \"string\" || !ENTITY_TYPE_PATTERN.test(entityType)) return undefined;\n const entityIdText = typeof entityId === \"number\" && Number.isInteger(entityId) ? String(entityId) : entityId;\n if (typeof entityIdText !== \"string\" || !ENTITY_ID_PATTERN.test(entityIdText)) return undefined;\n return {\n entityType,\n entityId: entityIdText,\n agentSpaceKey: typeof agentSpaceKey === \"number\" ? agentSpaceKey : undefined,\n };\n};\n\n/**\n * The entity an `openEntity` action opens, or undefined (the action then does nothing):\n * - an action with a platform-minted reference — `{\"type\":\"openEntity\", \"ref\":\"<toolCallId>:<entityType>:<index>\",\n * \"entity\":{\"entityType\",\"entityId\",<agent space key field>}}` — opens the `entity` the backend resolved it to; undefined while\n * the reference is unresolved;\n * - a row-bound action ({@link isRowBoundOpenEntityAction}) opens the `entity` of `currentRow`, the row of the item\n * scope the event fires in (each row of a resolved `$from` list carries its own `entityRef` + `entity`) — NEVER an\n * `entity` written on the action; undefined without a row or for a row without an entity.\n */\nexport const readOpenEntityActionTarget = (\n action: Record<string, unknown>,\n currentRow?: unknown,\n): OpenEntityActionTarget | undefined => {\n if (isRowBoundOpenEntityAction(action)) {\n return isPlainRecord(currentRow) ? readEntityDetailTargetOfEntity(currentRow.entity) : undefined;\n }\n return readEntityDetailTargetOfEntity(action.entity);\n};\n","import { getAgentsEnvironment } from \"../../provider/environment\";\nimport generatedComposedNodeSchema from \"./composed-node-schema.json\";\n\n/**\n * THE schema of the `ComposedView` kit, GENERATED by the backend from its classes (`ComposedViewNodeSchema.php`) —\n * never edited by hand. The committed file holds the types the package's own classes declare; an app adds the node\n * types, widgets, data sources and entity types its classes declare as its part (`AgentsEnvironment.composedNodeSchemaApplicationPart`,\n * generated by the app's backend the same way), and `getComposedNodeSchema()` reads both. The frontend parser, the\n * renderer and the evaluator read the node types, slots, props, size classes and budgets from here, so both sides apply\n * the same contract. `kit/_ComposedViewRenderer.spec.tsx` checks that every node type has a registered component and\n * every component a node type.\n */\n\nexport type ComposedNodeCategory = \"inline\" | \"block\" | \"data\" | \"media\" | \"input\" | \"layout\" | \"heavy\";\nexport type ComposedSizeClass = \"compact\" | \"regular\" | \"full\";\nexport type ComposedPropType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\" | \"event\";\n\nexport interface ComposedNodeSlotSchema {\n name: string;\n acceptsCategories: ComposedNodeCategory[];\n acceptsNodeTypes: string[];\n minChildren: number;\n maxChildren: number | null;\n sizeClass: ComposedSizeClass;\n description: string;\n /** The node prop the slot's size class follows (a Grid's `columns`); absent = the size class is fixed. */\n sizeClassFromProp?: string;\n /** Prop value (as text) → size class; a value not listed keeps `sizeClass`. */\n sizeClassesByPropValue?: Record<string, ComposedSizeClass>;\n /** A heavy node (a map, an embedded widget) may sit in the slot while it is compact. */\n acceptsHeavyWhenCompact?: boolean;\n}\n\nexport interface ComposedNodePropSchema {\n name: string;\n types: ComposedPropType[];\n isRequired: boolean;\n isBindable: boolean;\n allowedValues: Array<string | number | boolean> | null;\n description: string;\n}\n\n/**\n * The type's part in the source rule (`ComposedViewNode::buildSourcingSchemaArray()`): a data node that `needsSource`\n * and holds inline figures in its subtree — written rows in a `rowsProps` prop, a written figure in a `figureProps`\n * prop — needs its `source`, a source on a data node around it, or a node that `namesSources` in the tree.\n */\nexport interface ComposedNodeSourcingSchema {\n needsSource: boolean;\n namesSources: boolean;\n rowsProps: string[];\n figureProps: string[];\n}\n\nexport interface ComposedNodeTypeSchema {\n categories: ComposedNodeCategory[];\n providesItemScope: boolean;\n summary: string;\n props: ComposedNodePropSchema[];\n slots: ComposedNodeSlotSchema[];\n /** Absent for a type that takes no part in the source rule. */\n sourcing?: ComposedNodeSourcingSchema;\n /** The prop that lists the node's choices (`ComposedViewNode::OPTIONS_PROP_NAME`); absent without choices. */\n optionsProp?: string;\n /** The prop a node that repeats its children repeats over (`ComposedViewNode::ITEMS_PROP_NAME`). */\n itemsProp?: string;\n /** The node sends the state of the inputs inside it (`Form`); absent otherwise. */\n submitsInputs?: boolean;\n}\n\nexport interface ComposedViewBudgets {\n maxSourceBytes: number;\n maxNodes: number;\n maxDepth: number;\n maxStateKeys: number;\n maxStateStringLength: number;\n maxComputedExpressions: number;\n maxExpressionSourceLength: number;\n maxExpressionAstNodes: number;\n maxComputedDependencyDepth: number;\n maxOperationsPerUpdate: number;\n maxCollectionItems: number;\n maxAllocatedItemsPerEvaluation: number;\n maxRepeatRows: number;\n maxRenderedNodes: number;\n maxInlineArrayItems: number;\n maxInlineCells: number;\n maxTextLength: number;\n maxActions: number;\n maxInputUpdatesPerSecond: number;\n maxSourceRequestsPerTreePerMinute: number;\n}\n\nexport interface ComposedDataSourceSchema {\n summary: string;\n /** The client endpoint, method and path with `{param}` placeholders. */\n clientEndpoint: string;\n /** Where the rows sit in the response (`$` or `$.field`). */\n rowsPath: string;\n freshnessSeconds: number;\n params: Array<{ name: string; type: string; isRequired: boolean; description: string }>;\n columns: Array<{ name: string; type: string; description: string }>;\n}\n\nexport interface ComposedNodeSchema {\n version: number;\n budgets: ComposedViewBudgets;\n categories: ComposedNodeCategory[];\n sizeClasses: ComposedSizeClass[];\n actionTypes: string[];\n bindingKinds: string[];\n findingCodes: string[];\n /** The codes of findings that drop nothing — the block mounts with the code as a note. */\n noteFindingCodes: string[];\n nodeTypes: Record<string, ComposedNodeTypeSchema>;\n embeddableWidgets: Record<string, { sizeClass: ComposedSizeClass }>;\n /** Every registered widget type: a `Widget` node naming one its slot refuses is lifted out of the tree. */\n widgetTypes?: string[];\n dataSources: Record<string, ComposedDataSourceSchema>;\n entityTypes: string[];\n}\n\n/** The sections of the schema an app adds for the types its own classes declare; every section is optional. */\nexport type ComposedNodeSchemaApplicationPart = Partial<\n Pick<ComposedNodeSchema, \"nodeTypes\" | \"embeddableWidgets\" | \"widgetTypes\" | \"dataSources\" | \"entityTypes\">\n>;\n\n/**\n * The package's committed schema, typed: its budgets and rules and the types the package itself declares. A reader of\n * types an app may add (node types, widgets, data sources, entity types) reads `getComposedNodeSchema()`.\n */\nexport const composedNodeSchema = generatedComposedNodeSchema as unknown as ComposedNodeSchema;\n\n/** Byte order of the type names, as the backend sorts them. */\nconst compareTypeNames = (first: string, second: string): number => (first < second ? -1 : first > second ? 1 : 0);\n\nconst mergeSortedByTypeName = <Entry>(\n packageEntries: Record<string, Entry> | undefined,\n applicationEntries: Record<string, Entry> | undefined,\n): Record<string, Entry> =>\n Object.fromEntries(\n Object.entries({ ...packageEntries, ...applicationEntries }).sort(([firstType], [secondType]) =>\n compareTypeNames(firstType, secondType),\n ),\n );\n\nconst mergeTypeNames = (packageTypeNames: string[] | undefined, applicationTypeNames: string[] | undefined): string[] =>\n [...new Set([...(packageTypeNames ?? []), ...(applicationTypeNames ?? [])])].sort(compareTypeNames);\n\n/** A schema with an app's part added: every section holds both sides' types, sorted by type name. */\nexport const addComposedNodeSchemaApplicationPart = (\n schema: ComposedNodeSchema,\n applicationPart: ComposedNodeSchemaApplicationPart,\n): ComposedNodeSchema => ({\n ...schema,\n nodeTypes: mergeSortedByTypeName(schema.nodeTypes, applicationPart.nodeTypes),\n embeddableWidgets: mergeSortedByTypeName(schema.embeddableWidgets, applicationPart.embeddableWidgets),\n widgetTypes: mergeTypeNames(schema.widgetTypes, applicationPart.widgetTypes),\n dataSources: mergeSortedByTypeName(schema.dataSources, applicationPart.dataSources),\n entityTypes: mergeTypeNames(schema.entityTypes, applicationPart.entityTypes),\n});\n\nlet schemaWithApplicationPart:\n | { applicationPart: ComposedNodeSchemaApplicationPart; schema: ComposedNodeSchema }\n | undefined;\n\n/**\n * The schema the readers apply: the package's schema with the part the app declares\n * (`AgentsEnvironment.composedNodeSchemaApplicationPart`); the package's schema alone when the app declares none.\n * Read at call time — an app installs its environment after this module is loaded. The same object while the part is.\n */\nexport const getComposedNodeSchema = (): ComposedNodeSchema => {\n const applicationPart = getAgentsEnvironment().composedNodeSchemaApplicationPart;\n if (!applicationPart) return composedNodeSchema;\n if (schemaWithApplicationPart?.applicationPart !== applicationPart) {\n schemaWithApplicationPart = {\n applicationPart,\n schema: addComposedNodeSchemaApplicationPart(composedNodeSchema, applicationPart),\n };\n }\n return schemaWithApplicationPart.schema;\n};\n\n/**\n * The slot of one node — `ComposedViewNodeSlot::buildForNodeProps()`: its size class read from the node's\n * `sizeClassFromProp` (a Grid with `columns: 3` gives compact cells); the declaration itself otherwise.\n */\nexport const resolveComposedSlotForNodeProps = (\n slot: ComposedNodeSlotSchema,\n nodeProps: Record<string, unknown>,\n): ComposedNodeSlotSchema => {\n if (!slot.sizeClassFromProp || !slot.sizeClassesByPropValue) return slot;\n const propValue = Object.prototype.hasOwnProperty.call(nodeProps, slot.sizeClassFromProp)\n ? nodeProps[slot.sizeClassFromProp]\n : undefined;\n if (typeof propValue !== \"number\" && typeof propValue !== \"string\") return slot;\n const propValueKey = String(propValue);\n const sizeClassOfPropValue = Object.prototype.hasOwnProperty.call(slot.sizeClassesByPropValue, propValueKey)\n ? slot.sizeClassesByPropValue[propValueKey]\n : undefined;\n return sizeClassOfPropValue === undefined || sizeClassOfPropValue === slot.sizeClass\n ? slot\n : { ...slot, sizeClass: sizeClassOfPropValue };\n};\n\n/** Whether a size class fits a slot's size class (compact ≤ regular ≤ full). */\nexport const sizeClassFitsSlot = (sizeClass: ComposedSizeClass, slotSizeClass: ComposedSizeClass): boolean => {\n const order: ComposedSizeClass[] = [\"compact\", \"regular\", \"full\"];\n return order.indexOf(sizeClass) !== -1 && order.indexOf(sizeClass) <= order.indexOf(slotSizeClass);\n};\n","/**\n * Bounded walks over decoded JSON: the widget payloads come from the model, so no\n * walk may recurse without a bound, run in the size of a shared sub-structure, or throw. The depth rule is the\n * backend's: a block is decoded with `json_decode(…, depth: 32)` (`WidgetBlocks.php`), which admits 31 nested\n * containers — a deeper block is MALFORMED there and is dropped here the same way.\n */\n\n/** The deepest container nesting `json_decode(…, 32)` admits (the top-level object counts as 1). */\nexport const MAX_JSON_CONTAINER_DEPTH = 31;\n\n/** Whether `value` nests containers deeper than `maxDepth` — iterative, never throws. */\nexport const exceedsJsonContainerDepth = (value: unknown, maxDepth: number = MAX_JSON_CONTAINER_DEPTH): boolean => {\n const pending: Array<[unknown, number]> = [[value, 1]];\n while (pending.length > 0) {\n const [current, depth] = pending.pop() as [unknown, number];\n if (typeof current !== \"object\" || current === null) continue;\n if (depth > maxDepth) return true;\n for (const nested of Object.values(current)) {\n if (typeof nested === \"object\" && nested !== null) pending.push([nested, depth + 1]);\n }\n }\n return false;\n};\n\nconst isSequentialIndexObject = (value: Record<string, unknown>): boolean => {\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((key, position) => key === String(position));\n};\n\n/**\n * The value as `json_decode(…, true)` sees it: an object whose keys are `\"0\"`, `\"1\"`, … in order is a LIST there\n * (`array_is_list`), so it becomes an array here. Bounded by the depth rule (call it on a value within the depth).\n */\nexport const normalizeToPhpArrays = (value: unknown, depth = 1): unknown => {\n if (typeof value !== \"object\" || value === null || depth > MAX_JSON_CONTAINER_DEPTH) return value;\n if (Array.isArray(value)) return value.map((element) => normalizeToPhpArrays(element, depth + 1));\n const objectValue = value as Record<string, unknown>;\n if (isSequentialIndexObject(objectValue)) {\n return Object.values(objectValue).map((element) => normalizeToPhpArrays(element, depth + 1));\n }\n const normalized: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(objectValue)) {\n // defineProperty, not assignment: a `__proto__` key stays an own data property instead of replacing the prototype.\n Object.defineProperty(normalized, key, {\n value: normalizeToPhpArrays(nested, depth + 1),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return normalized;\n};\n\nconst structuralSizes = new WeakMap<object, number>();\n\n/**\n * The size of a value as a TREE (every container and scalar counted where it appears) — a shared sub-structure counts\n * once per use, as serialising it would. Memoised per object, so the cost is the number of DISTINCT objects even for a\n * DAG whose tree is exponential; the result saturates at `Number.MAX_SAFE_INTEGER`.\n */\nexport const structuralSizeOf = (value: unknown, depth = 1): number => {\n if (typeof value !== \"object\" || value === null) return 1;\n const memoised = structuralSizes.get(value);\n if (memoised !== undefined) return memoised;\n if (depth > 256) return Number.MAX_SAFE_INTEGER;\n let size = 1;\n for (const nested of Object.values(value)) {\n size = Math.min(Number.MAX_SAFE_INTEGER, size + structuralSizeOf(nested, depth + 1));\n }\n structuralSizes.set(value, size);\n return size;\n};\n\n/** `JSON.stringify(value, null, 2)` — or undefined once the text would pass `maxLength` (checked before it is built). */\nexport const stringifyWithinLimit = (value: unknown, maxLength: number): string | undefined => {\n if (structuralSizeOf(value) > maxLength) return undefined;\n const text = JSON.stringify(value ?? null, null, 2);\n return text.length > maxLength ? undefined : text;\n};\n","import {\n getComposedNodeSchema,\n ComposedNodePropSchema,\n ComposedNodeSchema,\n ComposedNodeSlotSchema,\n ComposedSizeClass,\n resolveComposedSlotForNodeProps,\n sizeClassFitsSlot,\n} from \"./composed-node-schema\";\nimport { resolveCanonicalWidgetName } from \"../widget-name-resolver\";\nimport { exceedsJsonContainerDepth, MAX_JSON_CONTAINER_DEPTH, normalizeToPhpArrays } from \"./bounded-json\";\n\n/**\n * The `ComposedView` tree as typed objects: the frontend twin of the backend reader\n * `ComposedViewTreeReading.php`. The fence plugin hands the widget its `payload` string; this module turns it into\n * {@link ComposedViewTree} — state, datasets, computed expressions, actions and the node tree — and applies THE SAME\n * rules as the backend, read from the generated schema: unknown types, slot mismatches, undeclared props, bad bindings,\n * budgets and three backticks are dropped where they stand and reported as findings; the rest is kept. A `set` on an\n * undeclared name declares it with null; a choice state outside its choices, a set state nothing reads and an `$item`\n * field missing from resolved `$from` rows are kept with a note (`noteFindingCodes` of the schema). The shared\n * fixture `composed-view-parity.json` holds both readers to the same kept tree and the same finding codes.\n *\n * Never throws, never evaluates anything (expressions are compiled by `expression/`).\n */\n\nexport type ComposedViewFindingCode =\n | \"INVALID_NODE\"\n | \"INVALID_PROP\"\n | \"UNKNOWN_BINDING\"\n | \"INVALID_EXPRESSION\"\n | \"INVALID_STATE\"\n | \"INVALID_ACTION\"\n | \"BUDGET_EXCEEDED\"\n | \"INLINE_VALUE_WITHOUT_SOURCE\"\n | \"INVALID_INITIAL_CHOICE\"\n | \"UNREAD_STATE\"\n | \"UNKNOWN_ITEM_KEY\"\n | \"INVALID_SLOT_NODE_COUNT\"\n | \"WIDGET_LIFTED\";\n\nexport interface ComposedViewFinding {\n code: ComposedViewFindingCode;\n path: string;\n message: string;\n}\n\nexport type ComposedViewBindingKind = \"state\" | \"computed\" | \"data\" | \"item\" | \"from\" | \"source\";\n\n/** A bound value (`{\"$state\":\"x\"}` …), see `ComposedViewBinding.php`. */\nexport interface ComposedViewBinding {\n kind: ComposedViewBindingKind | string;\n target: string;\n path: string | null;\n sourceParams: Record<string, unknown>;\n isWellFormed: boolean;\n /** The wire value itself (a `$from` carries its resolution state and snapshot inside, written when the row is stored). */\n wireValue: Record<string, unknown>;\n}\n\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\nexport interface ComposedViewNode {\n type: string;\n id: string | null;\n /** The kept props: literals and bindings as JSON values. */\n props: Record<string, JsonValue>;\n /** The kept nodes per slot name (`children` = the default slot), in wire order. */\n nodesBySlotName: Record<string, ComposedViewNode[]>;\n}\n\nexport interface ComposedViewAction {\n type: string;\n [field: string]: JsonValue;\n}\n\n/**\n * A `Widget` node the reader LIFTED out of the tree (`ComposedViewTreeReading::$liftedWidgetNodesByPath`):\n * its wire path, the widget's canonical name and its fields — shown as its own widget after the view.\n */\nexport interface ComposedViewLiftedWidget {\n path: string;\n widget: string;\n fields: Record<string, JsonValue>;\n}\n\nexport interface ComposedViewTree {\n title: string | null;\n state: Record<string, string | number | boolean | null>;\n data: Record<string, JsonValue>;\n computed: Record<string, string>;\n actions: Record<string, ComposedViewAction>;\n view: ComposedViewNode | null;\n findings: ComposedViewFinding[];\n /** The widgets lifted out of the tree, reading order — never part of `view`. */\n liftedWidgets: ComposedViewLiftedWidget[];\n}\n\nconst RESERVED_WIRE_KEYS = [\"type\", \"id\", \"children\", \"slots\"];\nconst DEFAULT_SLOT_NAME = \"children\";\nconst NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;\n/** Names the pattern admits that would reach an object's prototype — refused for state, data, computed and actions. */\nconst RESERVED_NAMES = [\"__proto__\", \"constructor\", \"prototype\"];\n/** `ComposedViewTreeReading::isAllowedName()`. */\nconst isAllowedName = (name: string): boolean => NAME_PATTERN.test(name) && !RESERVED_NAMES.includes(name);\nconst BINDING_KINDS = [\"state\", \"computed\", \"data\", \"item\", \"from\", \"source\"];\n/** `ComposedViewTreeReading::FIGURE_TEXT_PATTERN` — a text that reads as a figure (\"4,32 %\", \"-3\", \"+2\"). */\nconst FIGURE_TEXT_PATTERN = /^[-+\\u2212]?[0-9]/u;\nconst ACTION_TYPES = [\"copy\", \"resetState\", \"openEntity\", \"openUrl\"];\n/** `ComposedViewTreeReading::readChoiceValues()` — the keys a choice object may be picked by. */\nconst CHOICE_VALUE_KEYS = [\"id\", \"value\", \"key\", \"label\", \"title\", \"name\", \"text\"];\n/** `ComposedViewBindingResolution::STATE_RESOLVED` — a `$from` snapshot that carries its rows. */\nconst RESOLVED_FROM_STATE = \"resolved\";\n/** `ComposedViewBindablePathListing::MAX_LISTED_ROW_KEYS` / `MAX_ROW_LEAF_DEPTH` — the field list of an `$item` finding. */\nconst MAX_LISTED_ROW_KEYS = 12;\nconst MAX_ROW_LEAF_DEPTH = 2;\n\ntype PlainObject = Record<string, unknown>;\n\n/** Own key only — never a prototype key (`toString`, `__proto__`). */\nconst hasOwn = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key);\n\n/** A JSON object (not an array) — PHP's associative array; an EMPTY array counts as both, as `json_decode(…, true)` makes `{}` and `[]` one. */\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst isEmptyContainer = (value: unknown): boolean =>\n (Array.isArray(value) && value.length === 0) || (isPlainObject(value) && Object.keys(value).length === 0);\n/** PHP `is_array`. */\nconst isPhpArray = (value: unknown): value is unknown[] | PlainObject => Array.isArray(value) || isPlainObject(value);\n/** PHP `array_is_list` on a decoded value. */\nconst isPhpList = (value: unknown): boolean => Array.isArray(value) || isEmptyContainer(value);\n/** PHP `mb_strlen` — code points, not UTF-16 units. */\nconst codePointLength = (text: string): number => [...text].length;\nconst entriesOf = (value: unknown[] | PlainObject): Array<[string, unknown]> =>\n Array.isArray(value) ? value.map((entry, index) => [String(index), entry]) : Object.entries(value);\n\n/** The binding a wire value stands for, or null for a literal — `ComposedViewBinding::fromWireValue()`. */\nexport const readComposedViewBinding = (wireValue: unknown): ComposedViewBinding | null => {\n if (!isPlainObject(wireValue)) return null;\n const keys = Object.keys(wireValue);\n if (keys.length !== 1 || !keys[0].startsWith(\"$\")) return null;\n const kind = keys[0].slice(1);\n const bindingValue = wireValue[keys[0]];\n const binding: ComposedViewBinding = {\n kind,\n target: \"\",\n path: null,\n sourceParams: {},\n isWellFormed: true,\n wireValue,\n };\n if (!BINDING_KINDS.includes(kind)) {\n binding.isWellFormed = false;\n return binding;\n }\n if (kind === \"state\" || kind === \"computed\" || kind === \"data\" || kind === \"item\") {\n binding.isWellFormed = typeof bindingValue === \"string\" && bindingValue !== \"\";\n binding.target = typeof bindingValue === \"string\" ? bindingValue : \"\";\n return binding;\n }\n const bindingObject = isPhpArray(bindingValue) ? (bindingValue as PlainObject) : null;\n if (kind === \"from\") {\n binding.target = bindingObject && typeof bindingObject.toolCall === \"string\" ? bindingObject.toolCall : \"\";\n binding.path = bindingObject && typeof bindingObject.path === \"string\" ? bindingObject.path : null;\n binding.isWellFormed = binding.target !== \"\" && binding.path !== null && binding.path !== \"\";\n return binding;\n }\n binding.target = bindingObject && typeof bindingObject.name === \"string\" ? bindingObject.name : \"\";\n const sourceParams = bindingObject ? (bindingObject.params ?? []) : null;\n binding.sourceParams = isPhpArray(sourceParams) ? Object.fromEntries(entriesOf(sourceParams)) : {};\n binding.isWellFormed = binding.target !== \"\" && isPhpArray(sourceParams);\n return binding;\n};\n\n/**\n * The field an `$item` binding names in one row — `ComposedViewBinding::readRowField()`: the key as written, else for a\n * dotted name (`author.name`) the path through the row's nested objects. `found` tells a null field from a missing one.\n */\nexport const readComposedViewRowField = (row: unknown, fieldName: string): { found: boolean; value: unknown } => {\n if (!isPlainObject(row)) return { found: false, value: undefined };\n if (hasOwn(row, fieldName)) return { found: true, value: row[fieldName] };\n if (!fieldName.includes(\".\")) return { found: false, value: undefined };\n let fieldValue: unknown = row;\n for (const fieldNamePart of fieldName.split(\".\")) {\n if (!isPlainObject(fieldValue) || !hasOwn(fieldValue, fieldNamePart)) return { found: false, value: undefined };\n fieldValue = fieldValue[fieldNamePart];\n }\n return { found: true, value: fieldValue };\n};\n\n/** `ComposedViewBindablePathListing::buildListedRowKeys()` — scalar and list keys first, then dotted object leaves. */\nconst collectRowKeys = (row: PlainObject, keyPrefix: string, leafDepth: number): string[] => {\n const ownKeys: string[] = [];\n const leafKeys: string[] = [];\n for (const [rowKey, rowValue] of Object.entries(row)) {\n if (rowKey === \"objectType\") continue;\n const dottedKey = `${keyPrefix}${rowKey}`;\n if (isPlainObject(rowValue) && !isEmptyContainer(rowValue) && leafDepth < MAX_ROW_LEAF_DEPTH) {\n leafKeys.push(...collectRowKeys(rowValue, `${dottedKey}.`, leafDepth + 1));\n continue;\n }\n ownKeys.push(dottedKey);\n }\n return [...ownKeys, ...leafKeys];\n};\n\nconst buildListedRowKeys = (row: PlainObject): string[] => {\n const rowKeys = collectRowKeys(row, \"\", 0);\n const listedRowKeys = rowKeys.slice(0, MAX_LISTED_ROW_KEYS);\n return rowKeys.length > listedRowKeys.length ? [...listedRowKeys, \"…\"] : listedRowKeys;\n};\n\n/** `ComposedViewTreeReading::readChoiceValues()` — the values a choice may be picked by, as text. */\nconst readChoiceValues = (choices: unknown[]): string[] => {\n const choiceValues = new Set<string>();\n for (const choice of choices) {\n const choiceFields = isPhpArray(choice)\n ? CHOICE_VALUE_KEYS.filter((choiceKey) => hasOwn(choice, choiceKey)).map(\n (choiceKey) => (choice as PlainObject)[choiceKey],\n )\n : [choice];\n for (const choiceField of choiceFields) {\n if (typeof choiceField === \"string\" || typeof choiceField === \"number\") choiceValues.add(String(choiceField));\n }\n }\n return [...choiceValues];\n};\n\n/** `ComposedViewTreeReading::findIdentifiersOfExpression()` — identifiers outside string literals, not after a `.`. */\nexport const findComposedViewExpressionIdentifiers = (expressionSource: string): string[] => {\n const sourceWithoutStrings = expressionSource.replace(/'(?:[^'\\\\]|\\\\[^])*'|\"(?:[^\"\\\\]|\\\\[^])*\"/g, \" \");\n const identifierMatches = sourceWithoutStrings.matchAll(/(^|[^A-Za-z0-9_$.])([A-Za-z_][A-Za-z0-9_]*)/g);\n return [...new Set([...identifierMatches].map((identifierMatch) => identifierMatch[2]))];\n};\n\n/** `ComposedViewTreeReading::collectStateBindingTargets()` — every `$state` target inside a value, `$source` params included. */\nconst collectStateBindingTargets = (value: unknown, stateNames: Set<string>): void => {\n if (!isPhpArray(value)) return;\n const binding = readComposedViewBinding(value);\n if (binding !== null) {\n if (binding.kind === \"state\" && binding.isWellFormed) stateNames.add(binding.target);\n if (binding.kind === \"source\") collectStateBindingTargets(binding.sourceParams, stateNames);\n return;\n }\n for (const [, nestedValue] of entriesOf(value)) collectStateBindingTargets(nestedValue, stateNames);\n};\n\n/** `ComposedViewNode::collectBindings()` — the bindings of a node's props by prop path (`data`, `source.url`). */\nconst collectBindingsByPropPath = (\n propPath: string,\n propValue: unknown,\n bindingsByPropPath: Array<[string, ComposedViewBinding]>,\n): void => {\n const binding = readComposedViewBinding(propValue);\n if (binding !== null) {\n bindingsByPropPath.push([propPath, binding]);\n return;\n }\n if (!isPhpArray(propValue)) return;\n for (const [nestedKey, nestedValue] of entriesOf(propValue))\n collectBindingsByPropPath(`${propPath}.${nestedKey}`, nestedValue, bindingsByPropPath);\n};\n\n/**\n * Whether an `openEntity` `ref` names the current row's reference — a well-formed `{\"$item\": \"<key>\"}` binding\n * (`ComposedViewBindingResolution::isRowBoundReference()`): the entity is the row's own, never the action's.\n */\nconst isRowBoundEntityReference = (reference: unknown): boolean => {\n const binding = readComposedViewBinding(reference);\n return binding !== null && binding.kind === \"item\" && binding.isWellFormed;\n};\n\n/** `ComposedViewNodeProp::acceptsLiteral()`. */\nconst propAcceptsLiteral = (prop: ComposedNodePropSchema, value: unknown): boolean => {\n if (prop.allowedValues !== null && !prop.allowedValues.some((allowedValue) => allowedValue === value)) return false;\n return prop.types.some((type) => {\n switch (type) {\n case \"string\":\n return typeof value === \"string\";\n case \"number\":\n return typeof value === \"number\";\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"array\":\n return isPhpArray(value) && isPhpList(value);\n case \"object\":\n return isPhpArray(value) && (isEmptyContainer(value) || !isPhpList(value));\n default:\n return false;\n }\n });\n};\n\nconst containsTripleBackticks = (value: unknown): boolean => {\n if (typeof value === \"string\") return value.includes(\"```\");\n if (!isPhpArray(value)) return false;\n return entriesOf(value).some(([key, nested]) => key.includes(\"```\") || containsTripleBackticks(nested));\n};\n\n/** The reader — one instance per tree, like the PHP `ComposedViewTreeReading`. */\nclass ComposedViewTreeReader {\n readonly tree: ComposedViewTree = {\n title: null,\n state: {},\n data: {},\n computed: {},\n actions: {},\n view: null,\n findings: [],\n liftedWidgets: [],\n };\n protected readNodeCount = 0;\n protected inlineCellCount = 0;\n\n constructor(protected readonly schema: ComposedNodeSchema) {}\n\n get budgets() {\n return this.schema.budgets;\n }\n\n addFinding(code: ComposedViewFindingCode, path: string, message: string) {\n this.tree.findings.push({ code, path, message });\n }\n\n read(widgetFields: PlainObject) {\n this.readTitle(widgetFields.title);\n this.readState(widgetFields.state ?? []);\n this.readData(widgetFields.data ?? []);\n this.readComputed(widgetFields.computed ?? []);\n this.readActions(widgetFields.actions ?? []);\n this.declareStateNamesSetByEvents(widgetFields.view);\n if (widgetFields.view !== undefined && widgetFields.view !== null) {\n this.tree.view = this.readRootNode(widgetFields.view);\n }\n this.flagInlineFiguresWithoutSource();\n this.flagInitialStatesOutsideTheirChoices();\n this.flagStateNamesNothingReads();\n this.flagItemFieldsMissingFromTheirRows();\n this.dedupeFindings();\n }\n\n /**\n * `ComposedViewTreeReading::declareStateNamesSetByEvents()` — every `{\"set\": <name>}` event of a node of a known type\n * declares an undeclared, allowed name that is no dataset or computed value with null (within the state budget).\n */\n declareStateNamesSetByEvents(wireNode: unknown) {\n if (!isPlainObject(wireNode) || typeof wireNode.type !== \"string\" || !hasOwn(this.schema.nodeTypes, wireNode.type))\n return;\n for (const prop of this.schema.nodeTypes[wireNode.type].props) {\n const eventValue = hasOwn(wireNode, prop.name) ? wireNode[prop.name] : undefined;\n if (\n prop.types.includes(\"event\") &&\n isPlainObject(eventValue) &&\n Object.keys(eventValue).length === 1 &&\n typeof eventValue.set === \"string\"\n ) {\n this.declareStateNameSetByEvent(eventValue.set);\n }\n }\n const slotWireNodeLists: unknown[] = [wireNode.children];\n if (isPhpArray(wireNode.slots)) {\n for (const [slotName, slotWireNodes] of entriesOf(wireNode.slots)) {\n if (slotName !== DEFAULT_SLOT_NAME || !hasOwn(wireNode, \"children\")) slotWireNodeLists.push(slotWireNodes);\n }\n }\n for (const slotWireNodes of slotWireNodeLists) {\n if (!isPhpArray(slotWireNodes) || !isPhpList(slotWireNodes)) continue;\n for (const [, slotWireNode] of entriesOf(slotWireNodes)) this.declareStateNamesSetByEvents(slotWireNode);\n }\n }\n\n declareStateNameSetByEvent(stateName: string) {\n if (\n !isAllowedName(stateName) ||\n hasOwn(this.tree.state, stateName) ||\n hasOwn(this.tree.data, stateName) ||\n hasOwn(this.tree.computed, stateName) ||\n Object.keys(this.tree.state).length >= this.budgets.maxStateKeys\n ) {\n return;\n }\n this.tree.state[stateName] = null;\n }\n\n /** `ComposedViewNode::getStateNamesSetByEvents()`. */\n stateNamesSetByEvents(node: ComposedViewNode): string[] {\n const stateNames: string[] = [];\n for (const prop of this.schema.nodeTypes[node.type]?.props ?? []) {\n const eventValue = hasOwn(node.props, prop.name) ? node.props[prop.name] : undefined;\n if (prop.types.includes(\"event\") && isPlainObject(eventValue) && typeof eventValue.set === \"string\")\n stateNames.push(eventValue.set);\n }\n return stateNames;\n }\n\n /** `ComposedViewTreeReading::flagInitialStatesOutsideTheirChoices()`. */\n flagInitialStatesOutsideTheirChoices() {\n if (this.tree.view === null) return;\n for (const [nodePath, node] of getComposedViewSubtreeNodesByPath(this.tree.view, \"view\")) {\n const optionsProp = this.schema.nodeTypes[node.type]?.optionsProp;\n const choices =\n optionsProp !== undefined && hasOwn(node.props, optionsProp) ? node.props[optionsProp] : undefined;\n if (!Array.isArray(choices)) continue;\n const choiceValues = readChoiceValues(choices);\n for (const stateName of new Set(this.stateNamesSetByEvents(node))) {\n const initialValue = hasOwn(this.tree.state, stateName) ? this.tree.state[stateName] : null;\n if (initialValue === null || initialValue === \"\") continue;\n if (\n (typeof initialValue === \"string\" || typeof initialValue === \"number\") &&\n choiceValues.includes(String(initialValue))\n )\n continue;\n this.addFinding(\n \"INVALID_INITIAL_CHOICE\",\n nodePath,\n `the state \"${stateName}\" starts as ${JSON.stringify(initialValue)}, none of the choices (${choiceValues.join(\", \")}) — start it with a choice's id`,\n );\n }\n }\n }\n\n /** `ComposedViewTreeReading::flagStateNamesNothingReads()` — a state a node sets that nothing else reads. */\n flagStateNamesNothingReads() {\n if (Object.keys(this.tree.state).length === 0) return;\n const readStateNames = new Set<string>();\n const setStateNames = new Set<string>();\n for (const expressionSource of Object.values(this.tree.computed)) {\n for (const identifier of findComposedViewExpressionIdentifiers(expressionSource)) readStateNames.add(identifier);\n }\n collectStateBindingTargets(this.tree.data, readStateNames);\n collectStateBindingTargets(this.tree.actions, readStateNames);\n for (const node of this.tree.view === null ? [] : getComposedViewSubtreeNodes(this.tree.view)) {\n const ownSetStateNames = this.stateNamesSetByEvents(node);\n ownSetStateNames.forEach((setStateName) => setStateNames.add(setStateName));\n const nodeReadStateNames = new Set<string>();\n collectStateBindingTargets(node.props, nodeReadStateNames);\n nodeReadStateNames.forEach((readStateName) => {\n if (!ownSetStateNames.includes(readStateName)) readStateNames.add(readStateName);\n });\n if (this.schema.nodeTypes[node.type]?.submitsInputs !== true) continue;\n for (const formSubtreeNode of getComposedViewSubtreeNodes(node)) {\n collectStateBindingTargets(formSubtreeNode.props, readStateNames);\n this.stateNamesSetByEvents(formSubtreeNode).forEach((submittedStateName) =>\n readStateNames.add(submittedStateName),\n );\n }\n }\n for (const stateName of Object.keys(this.tree.state)) {\n if (setStateNames.has(stateName) && !readStateNames.has(stateName)) {\n this.addFinding(\n \"UNREAD_STATE\",\n `state.${stateName}`,\n `nothing reads the state \"${stateName}\" — a Tab or input changes only what reads its state: bind a node to {\"$state\":\"${stateName}\"} or name it in a computed value`,\n );\n }\n }\n }\n\n /** `ComposedViewTreeReading::flagItemFieldsMissingFromTheirRows()`. */\n flagItemFieldsMissingFromTheirRows() {\n if (this.tree.view !== null) this.flagItemFieldsOfSubtree(this.tree.view, \"view\", null);\n }\n\n flagItemFieldsOfSubtree(node: ComposedViewNode, path: string, itemRows: PlainObject[] | null) {\n if (itemRows !== null) {\n const bindingsByPropPath: Array<[string, ComposedViewBinding]> = [];\n for (const [propName, propValue] of Object.entries(node.props))\n collectBindingsByPropPath(propName, propValue, bindingsByPropPath);\n for (const [propPath, binding] of bindingsByPropPath) {\n if (binding.kind !== \"item\" || !binding.isWellFormed) continue;\n if (itemRows.some((row) => readComposedViewRowField(row, binding.target).found)) continue;\n this.addFinding(\n \"UNKNOWN_ITEM_KEY\",\n `${path}.${propPath}`,\n `no row of the bound rows has the field \"${binding.target}\" — it renders empty; the rows have: ${buildListedRowKeys(itemRows[0]).join(\", \")}`,\n );\n }\n }\n const itemsProp = this.schema.nodeTypes[node.type]?.itemsProp;\n const childItemRows = this.schema.nodeTypes[node.type]?.providesItemScope\n ? this.findResolvedRowsOfItems(\n itemsProp !== undefined && hasOwn(node.props, itemsProp) ? node.props[itemsProp] : undefined,\n )\n : itemRows;\n for (const [slotName, slotNodes] of Object.entries(node.nodesBySlotName)) {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n slotNodes.forEach((slotNode, childPosition) =>\n this.flagItemFieldsOfSubtree(slotNode, `${slotPath}[${childPosition}]`, childItemRows),\n );\n }\n }\n\n /** `ComposedViewTreeReading::findResolvedRowsOfItems()` — the object rows of a resolved `$from` list, or null. */\n findResolvedRowsOfItems(itemsValue: unknown): PlainObject[] | null {\n const binding = readComposedViewBinding(itemsValue);\n let fromBinding: unknown = undefined;\n if (binding?.kind === \"from\") fromBinding = binding.wireValue.$from;\n if (binding?.kind === \"data\" && hasOwn(this.tree.data, binding.target)) {\n const dataset = this.tree.data[binding.target];\n fromBinding = isPlainObject(dataset) ? dataset.$from : undefined;\n }\n if (!isPlainObject(fromBinding) || fromBinding.state !== RESOLVED_FROM_STATE || !isPhpList(fromBinding.value))\n return null;\n const objectRows = (fromBinding.value as unknown[]).filter(\n (row): row is PlainObject => isPlainObject(row) && !isEmptyContainer(row),\n );\n return objectRows.length === 0 ? null : objectRows;\n }\n\n /**\n * `ComposedViewTreeReading::flagInlineFiguresWithoutSource()` — each data node of the KEPT view that shows inline\n * figures without its `source`, a source on a data node around it or a source line (`SourceRef`) in the tree gets\n * one `INLINE_VALUE_WITHOUT_SOURCE`; the node stays.\n */\n flagInlineFiguresWithoutSource() {\n const view = this.tree.view;\n if (view === null) return;\n if (getComposedViewSubtreeNodes(view).some((node) => this.sourcingOf(node.type)?.namesSources === true)) return;\n this.flagUnsourcedDataNodesOfSubtree(view, \"view\", false, false);\n }\n\n sourcingOf(nodeType: string) {\n return hasOwn(this.schema.nodeTypes, nodeType) ? this.schema.nodeTypes[nodeType].sourcing : undefined;\n }\n\n flagUnsourcedDataNodesOfSubtree(\n node: ComposedViewNode,\n path: string,\n isSourcedAround: boolean,\n itemsAreInline: boolean,\n ) {\n const needsSource = this.sourcingOf(node.type)?.needsSource === true;\n let isSourced = isSourcedAround || (needsSource && hasOwn(node.props, \"source\"));\n if (needsSource && !isSourced && this.subtreeHoldsInlineFigures(node, itemsAreInline)) {\n this.addFinding(\n \"INLINE_VALUE_WITHOUT_SOURCE\",\n path,\n `a ${node.type} shows figures written inline without \\`source\\` — give it the publisher and page as \\`source\\` {\"name\",\"url\"} (or a SourceRef beside it)`,\n );\n isSourced = true;\n }\n const childItemsAreInline = this.schema.nodeTypes[node.type]?.providesItemScope\n ? this.nodeHoldsInlineRows(node, itemsAreInline)\n : itemsAreInline;\n for (const [slotName, slotNodes] of Object.entries(node.nodesBySlotName)) {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n slotNodes.forEach((slotNode, childPosition) =>\n this.flagUnsourcedDataNodesOfSubtree(slotNode, `${slotPath}[${childPosition}]`, isSourced, childItemsAreInline),\n );\n }\n }\n\n subtreeHoldsInlineFigures(node: ComposedViewNode, itemsAreInline: boolean): boolean {\n if (this.nodeHoldsInlineRows(node, itemsAreInline) || this.nodeHoldsInlineFigure(node, itemsAreInline)) return true;\n const childItemsAreInline = this.schema.nodeTypes[node.type]?.providesItemScope\n ? this.nodeHoldsInlineRows(node, itemsAreInline)\n : itemsAreInline;\n return Object.values(node.nodesBySlotName).some((slotNodes) =>\n slotNodes.some((slotNode) => this.subtreeHoldsInlineFigures(slotNode, childItemsAreInline)),\n );\n }\n\n nodeHoldsInlineRows(node: ComposedViewNode, itemsAreInline: boolean): boolean {\n return (this.sourcingOf(node.type)?.rowsProps ?? []).some((rowsPropName) => {\n if (!hasOwn(node.props, rowsPropName)) return false;\n const rowsValue = node.props[rowsPropName];\n const binding = readComposedViewBinding(rowsValue);\n if (binding === null) return isPhpArray(rowsValue) && !isEmptyContainer(rowsValue);\n if (binding.kind === \"data\") return this.isInlineDataset(binding.target);\n return binding.kind === \"item\" && itemsAreInline;\n });\n }\n\n nodeHoldsInlineFigure(node: ComposedViewNode, itemsAreInline: boolean): boolean {\n return (this.sourcingOf(node.type)?.figureProps ?? []).some((figurePropName) => {\n if (!hasOwn(node.props, figurePropName)) return false;\n const figureValue = node.props[figurePropName];\n const binding = readComposedViewBinding(figureValue);\n if (binding !== null) return binding.kind === \"item\" && itemsAreInline;\n if (typeof figureValue === \"number\") return true;\n return typeof figureValue === \"string\" && FIGURE_TEXT_PATTERN.test(figureValue);\n });\n }\n\n /** Written rows (not a `$from` / `$source` binding) with at least one row. */\n isInlineDataset(dataName: string): boolean {\n if (!hasOwn(this.tree.data, dataName)) return false;\n const dataset = this.tree.data[dataName];\n return isPhpArray(dataset) && !isEmptyContainer(dataset) && readComposedViewBinding(dataset) === null;\n }\n\n readTitle(titleField: unknown) {\n if (typeof titleField !== \"string\") return;\n if (titleField.includes(\"```\")) {\n this.addFinding(\"INVALID_PROP\", \"title\", \"a string with three backticks would end the widget fence\");\n return;\n }\n this.tree.title = titleField;\n }\n\n /**\n * `ComposedViewTreeReading::readRootNode()` — the root held to the root rule; a refused `Widget` root naming a known\n * widget is lifted, a layout root the lift emptied is no view.\n */\n readRootNode(wireRootNode: unknown): ComposedViewNode | null {\n const liftedCountBefore = this.tree.liftedWidgets.length;\n const rootNode = this.readNode(wireRootNode, \"view\", 1, false);\n if (rootNode !== null && this.isPrunedByTheLift(rootNode, liftedCountBefore)) {\n this.pruneNodeEmptiedByTheLift(rootNode, \"view\");\n return null;\n }\n if (rootNode === null || this.isNodeAcceptedAsRoot(rootNode)) return rootNode;\n this.readNodeCount -= countComposedViewNodes(rootNode);\n if (this.isLiftedWhenRefused(rootNode)) {\n this.liftWidgetNode(rootNode, \"view\", null);\n return null;\n }\n this.addFinding(\n \"INVALID_NODE\",\n \"view\",\n rootNode.type === \"Widget\"\n ? this.buildNotEmbeddableMessage(rootNode)\n : `a ${rootNode.type} cannot be the root of the view`,\n );\n return null;\n }\n\n /** `WidgetComposedViewNode::isLiftedWhenRefused()` — a `Widget` node naming a known widget (any registered type). */\n isLiftedWhenRefused(node: ComposedViewNode): boolean {\n return node.type === \"Widget\" && this.findKnownWidgetName(node) !== undefined;\n }\n\n /** The canonical name of the known widget a `Widget` node names (a legacy `…Directive` name resolved), or undefined. */\n findKnownWidgetName(node: ComposedViewNode): string | undefined {\n if (typeof node.props.widget !== \"string\") return undefined;\n return resolveCanonicalWidgetName(node.props.widget, new Set(this.schema.widgetTypes ?? []));\n }\n\n /** `ComposedViewTreeReading::liftWidgetNode()` — out of the tree with its note, shown as its own widget after the view. */\n liftWidgetNode(node: ComposedViewNode, path: string, refusingSlot: ComposedNodeSlotSchema | null) {\n const widget = this.findKnownWidgetName(node) ?? \"\";\n const fields = isPlainObject(node.props.fields) ? (node.props.fields as Record<string, JsonValue>) : {};\n this.tree.liftedWidgets.push({ path, widget, fields });\n const embeddableWidget = this.findEmbeddableWidget(node);\n const reason =\n embeddableWidget !== undefined && refusingSlot !== null\n ? `\"${widget}\" needs a ${embeddableWidget.sizeClass} slot, the slot \"${refusingSlot.name}\" is ${refusingSlot.sizeClass}`\n : `\"${widget}\" does not embed`;\n this.addFinding(\"WIDGET_LIFTED\", path, `${reason} — it is shown as its own widget block after the view`);\n }\n\n /** `ComposedViewTreeReading::isPrunedByTheLift()` — a layout node the lift left with no node. */\n isPrunedByTheLift(node: ComposedViewNode, liftedCountBefore: number): boolean {\n if (this.tree.liftedWidgets.length === liftedCountBefore) return false;\n if (!(this.schema.nodeTypes[node.type]?.categories ?? []).includes(\"layout\")) return false;\n return Object.values(node.nodesBySlotName).every((slotNodes) => slotNodes.length === 0);\n }\n\n /** `ComposedViewTreeReading::pruneNodeEmptiedByTheLift()` — its count back, its slot-minimum notes gone. */\n pruneNodeEmptiedByTheLift(node: ComposedViewNode, path: string) {\n this.readNodeCount -= countComposedViewNodes(node);\n this.tree.findings = this.tree.findings.filter(\n (finding) =>\n finding.code !== \"INVALID_SLOT_NODE_COUNT\" || (finding.path !== path && !finding.path.startsWith(`${path}.`)),\n );\n }\n\n /** `ComposedViewNode::isAcceptedAsRoot()` — every node, but an embedded widget only when it is embeddable. */\n isNodeAcceptedAsRoot(node: ComposedViewNode): boolean {\n return node.type !== \"Widget\" || this.findEmbeddableWidget(node) !== undefined;\n }\n\n /** The embeddable widget a `Widget` node names (a legacy `…Directive` name resolved as everywhere), or undefined. */\n findEmbeddableWidget(node: ComposedViewNode): { sizeClass: ComposedSizeClass } | undefined {\n if (typeof node.props.widget !== \"string\") return undefined;\n const embeddableWidgetName = resolveCanonicalWidgetName(\n node.props.widget,\n new Set(Object.keys(this.schema.embeddableWidgets ?? {})),\n );\n return embeddableWidgetName === undefined ? undefined : this.schema.embeddableWidgets[embeddableWidgetName];\n }\n\n /** The PHP findings are an ObjectSet keyed by code, path and message — a repeat is kept once there, so here too. */\n dedupeFindings() {\n const seenFindingKeys = new Set<string>();\n this.tree.findings = this.tree.findings.filter((finding) => {\n const findingKey = `${finding.code}@${finding.path}@${finding.message}`;\n if (seenFindingKeys.has(findingKey)) return false;\n seenFindingKeys.add(findingKey);\n return true;\n });\n }\n\n readState(stateField: unknown) {\n if (!isPhpArray(stateField) || (!isEmptyContainer(stateField) && isPhpList(stateField))) {\n this.addFinding(\"INVALID_STATE\", \"state\", \"`state` must be an object of name → initial value\");\n return;\n }\n for (const [stateName, initialValue] of entriesOf(stateField)) {\n if (Object.keys(this.tree.state).length >= this.budgets.maxStateKeys) {\n this.addFinding(\"BUDGET_EXCEEDED\", `state.${stateName}`, `more than ${this.budgets.maxStateKeys} state names`);\n break;\n }\n if (!isAllowedName(stateName)) {\n this.addFinding(\n \"INVALID_STATE\",\n `state.${stateName}`,\n \"a state name is an identifier (letters, digits, underscore)\",\n );\n continue;\n }\n const isScalar = [\"string\", \"number\", \"boolean\"].includes(typeof initialValue);\n if (!isScalar && initialValue !== null) {\n this.addFinding(\"INVALID_STATE\", `state.${stateName}`, \"an initial value is a string, number, boolean or null\");\n continue;\n }\n if (typeof initialValue === \"string\" && initialValue.includes(\"```\")) {\n this.addFinding(\n \"INVALID_STATE\",\n `state.${stateName}`,\n \"a string with three backticks would end the widget fence\",\n );\n continue;\n }\n if (typeof initialValue === \"string\" && codePointLength(initialValue) > this.budgets.maxStateStringLength) {\n this.addFinding(\n \"BUDGET_EXCEEDED\",\n `state.${stateName}`,\n `an initial string longer than ${this.budgets.maxStateStringLength} characters`,\n );\n continue;\n }\n this.tree.state[stateName] = initialValue as string | number | boolean | null;\n }\n }\n\n readData(dataField: unknown) {\n if (!isPhpArray(dataField) || (!isEmptyContainer(dataField) && isPhpList(dataField))) {\n this.addFinding(\"INVALID_PROP\", \"data\", \"`data` must be an object of name → rows\");\n return;\n }\n for (const [dataName, dataset] of entriesOf(dataField)) {\n const path = `data.${dataName}`;\n if (!isAllowedName(dataName) || hasOwn(this.tree.state, dataName)) {\n this.addFinding(\"INVALID_PROP\", path, \"a data name is an identifier that is not also a state name\");\n continue;\n }\n const binding = readComposedViewBinding(dataset);\n if (binding !== null) {\n if (binding.kind !== \"from\" && binding.kind !== \"source\") {\n this.addFinding(\"UNKNOWN_BINDING\", path, \"a dataset binds a tool result ($from) or a data source ($source)\");\n continue;\n }\n if (containsTripleBackticks(dataset)) {\n this.addFinding(\"INVALID_PROP\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n if (this.isValidBinding(binding, path, false)) this.tree.data[dataName] = dataset as JsonValue;\n continue;\n }\n if (!isPhpArray(dataset) || !isPhpList(dataset)) {\n this.addFinding(\"INVALID_PROP\", path, \"a dataset is a list of rows, a $from or a $source\");\n continue;\n }\n if (containsTripleBackticks(dataset)) {\n this.addFinding(\"INVALID_PROP\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n // `json_decode(…, true)` makes `{}` and `[]` one empty array — kept as the empty LIST on both sides.\n if (this.isValidInlineData(dataset, path, false))\n this.tree.data[dataName] = (isEmptyContainer(dataset) ? [] : dataset) as JsonValue;\n }\n }\n\n readComputed(computedField: unknown) {\n if (!isPhpArray(computedField) || (!isEmptyContainer(computedField) && isPhpList(computedField))) {\n this.addFinding(\"INVALID_EXPRESSION\", \"computed\", \"`computed` must be an object of name → expression\");\n return;\n }\n for (const [computedName, expressionSource] of entriesOf(computedField)) {\n const path = `computed.${computedName}`;\n if (Object.keys(this.tree.computed).length >= this.budgets.maxComputedExpressions) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `more than ${this.budgets.maxComputedExpressions} computed values`);\n break;\n }\n if (\n !isAllowedName(computedName) ||\n hasOwn(this.tree.state, computedName) ||\n hasOwn(this.tree.data, computedName)\n ) {\n this.addFinding(\n \"INVALID_EXPRESSION\",\n path,\n \"a computed name is an identifier that is not also a state or data name\",\n );\n continue;\n }\n if (typeof expressionSource !== \"string\" || expressionSource.trim() === \"\") {\n this.addFinding(\"INVALID_EXPRESSION\", path, \"an expression is a non-empty string\");\n continue;\n }\n if (codePointLength(expressionSource) > this.budgets.maxExpressionSourceLength) {\n this.addFinding(\n \"BUDGET_EXCEEDED\",\n path,\n `an expression longer than ${this.budgets.maxExpressionSourceLength} characters`,\n );\n continue;\n }\n if (expressionSource.includes(\"```\")) {\n this.addFinding(\"INVALID_EXPRESSION\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n this.tree.computed[computedName] = expressionSource;\n }\n }\n\n readActions(actionsField: unknown) {\n if (!isPhpArray(actionsField) || (!isEmptyContainer(actionsField) && isPhpList(actionsField))) {\n this.addFinding(\"INVALID_ACTION\", \"actions\", \"`actions` must be an object of name → action\");\n return;\n }\n for (const [actionName, action] of entriesOf(actionsField)) {\n const path = `actions.${actionName}`;\n if (Object.keys(this.tree.actions).length >= this.budgets.maxActions) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `more than ${this.budgets.maxActions} actions`);\n break;\n }\n const actionObject = isPhpArray(action) ? (action as PlainObject) : null;\n const actionType = actionObject?.type;\n if (!isAllowedName(actionName) || typeof actionType !== \"string\" || !ACTION_TYPES.includes(actionType)) {\n this.addFinding(\n \"INVALID_ACTION\",\n path,\n `an action has an identifier name and a type of ${ACTION_TYPES.join(\", \")}`,\n );\n continue;\n }\n if (\n actionType === \"openUrl\" &&\n !(typeof actionObject?.url === \"string\" && /^https?:\\/\\//i.test(actionObject.url))\n ) {\n this.addFinding(\"INVALID_ACTION\", path, \"`openUrl` needs an http(s) `url`\");\n continue;\n }\n // `{\"$item\":\"entityRef\"}` — inside a Repeat over a resolved `$from` list, each row opens its own entity\n if (\n actionType === \"openEntity\" &&\n !isRowBoundEntityReference(actionObject?.ref) &&\n !(typeof actionObject?.ref === \"string\" && actionObject.ref !== \"\")\n ) {\n this.addFinding(\n \"INVALID_ACTION\",\n path,\n '`openEntity` needs the platform-minted `ref` of a tool result row, or {\"$item\":\"entityRef\"} inside a Repeat',\n );\n continue;\n }\n if (containsTripleBackticks(action)) {\n this.addFinding(\"INVALID_ACTION\", path, \"a string with three backticks would end the widget fence\");\n continue;\n }\n this.tree.actions[actionName] = action as ComposedViewAction;\n }\n }\n\n readNode(wireNode: unknown, path: string, depth: number, isInItemScope: boolean): ComposedViewNode | null {\n if (!isPlainObject(wireNode) || typeof wireNode.type !== \"string\") {\n this.addFinding(\"INVALID_NODE\", path, \"a node is an object with a string `type`\");\n return null;\n }\n const nodeType = wireNode.type;\n const nodeTypeSchema = Object.prototype.hasOwnProperty.call(this.schema.nodeTypes, nodeType)\n ? this.schema.nodeTypes[nodeType]\n : undefined;\n if (!nodeTypeSchema) {\n this.addFinding(\"INVALID_NODE\", path, `unknown node type \"${nodeType}\"`);\n return null;\n }\n if (depth > this.budgets.maxDepth) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `deeper than ${this.budgets.maxDepth} levels`);\n return null;\n }\n if (this.readNodeCount >= this.budgets.maxNodes) {\n this.addFinding(\"BUDGET_EXCEEDED\", path, `more than ${this.budgets.maxNodes} nodes`);\n return null;\n }\n const ownWireFields = Object.fromEntries(\n Object.entries(wireNode).filter(([key]) => key !== \"children\" && key !== \"slots\"),\n );\n if (containsTripleBackticks(ownWireFields)) {\n this.addFinding(\"INVALID_NODE\", path, \"a string with three backticks would end the widget fence\");\n return null;\n }\n this.readNodeCount++;\n const node: ComposedViewNode = {\n type: nodeType,\n id: typeof wireNode.id === \"string\" ? wireNode.id : null,\n props: {},\n nodesBySlotName: {},\n };\n if (!this.readProps(node, wireNode, path, isInItemScope)) {\n this.readNodeCount--;\n return null;\n }\n const childScope = isInItemScope || nodeTypeSchema.providesItemScope;\n const wireNodesBySlotName: Array<[string, unknown]> = [];\n if (hasOwn(wireNode, \"children\")) wireNodesBySlotName.push([DEFAULT_SLOT_NAME, wireNode.children]);\n if (isPhpArray(wireNode.slots)) {\n for (const [slotName, slotWireNodes] of entriesOf(wireNode.slots)) {\n if (slotName === DEFAULT_SLOT_NAME && hasOwn(wireNode, \"children\")) {\n this.addFinding(\n \"INVALID_NODE\",\n `${path}.slots.${slotName}`,\n \"the default slot is written twice (`children` and `slots.children`) — `slots.children` is dropped\",\n );\n continue;\n }\n wireNodesBySlotName.push([slotName, slotWireNodes]);\n }\n }\n for (const [slotName, slotWireNodes] of wireNodesBySlotName) {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n // the slot of THIS node: a Grid's cells narrow with its `columns` — the props are read above\n const declaredSlot = nodeTypeSchema.slots.find((candidate) => candidate.name === slotName);\n const slot = declaredSlot ? resolveComposedSlotForNodeProps(declaredSlot, node.props) : undefined;\n if (!slot) {\n this.addFinding(\"INVALID_NODE\", slotPath, `${nodeType} has no slot \"${slotName}\" — its nodes are dropped`);\n continue;\n }\n node.nodesBySlotName[slotName] = this.readSlotNodes(slot, slotWireNodes, slotPath, depth, childScope);\n }\n for (const slot of nodeTypeSchema.slots) {\n const slotNodeCount = node.nodesBySlotName[slot.name]?.length ?? 0;\n if (slotNodeCount < slot.minChildren) {\n // the node is kept and renders what it has: a note, never a dropped node\n this.addFinding(\n \"INVALID_SLOT_NODE_COUNT\",\n `${path}.${slot.name}`,\n `${nodeType} needs at least ${slot.minChildren} node(s) in \"${slot.name}\", it has ${slotNodeCount}`,\n );\n }\n }\n return node;\n }\n\n readSlotNodes(\n slot: ComposedNodeSlotSchema,\n slotWireNodes: unknown,\n slotPath: string,\n depth: number,\n isInItemScope: boolean,\n ): ComposedViewNode[] {\n if (!isPhpArray(slotWireNodes) || !isPhpList(slotWireNodes)) {\n this.addFinding(\"INVALID_NODE\", slotPath, \"a slot holds a list of nodes\");\n return [];\n }\n const slotNodes: ComposedViewNode[] = [];\n for (const [childPosition, slotWireNode] of entriesOf(slotWireNodes)) {\n const childPath = `${slotPath}[${childPosition}]`;\n if (slot.maxChildren !== null && slotNodes.length >= slot.maxChildren) {\n this.addFinding(\"INVALID_NODE\", childPath, `the slot \"${slot.name}\" holds at most ${slot.maxChildren} node(s)`);\n break;\n }\n const liftedCountBefore = this.tree.liftedWidgets.length;\n const slotNode = this.readNode(slotWireNode, childPath, depth + 1, isInItemScope);\n if (slotNode === null) continue;\n if (this.isPrunedByTheLift(slotNode, liftedCountBefore)) {\n this.pruneNodeEmptiedByTheLift(slotNode, childPath);\n continue;\n }\n if (!this.isNodeAcceptedBySlot(slotNode, slot)) {\n this.readNodeCount -= countComposedViewNodes(slotNode);\n // a refused widget is lifted, never dropped — inside a repeat it would be lifted once per row\n if (this.isLiftedWhenRefused(slotNode) && !isInItemScope) {\n this.liftWidgetNode(slotNode, childPath, slot);\n continue;\n }\n this.addFinding(\"INVALID_NODE\", childPath, this.buildSlotRefusalMessage(slotNode, slot));\n continue;\n }\n slotNodes.push(slotNode);\n }\n return slotNodes;\n }\n\n /**\n * `ComposedViewNode::buildSlotRefusalMessage()` — with `WidgetComposedViewNode`'s: a widget that does not embed names\n * the way out (its own block next to the ComposedView), an embeddable one too large for the slot names its size class.\n */\n buildSlotRefusalMessage(node: ComposedViewNode, slot: ComposedNodeSlotSchema): string {\n if (node.type === \"Widget\") {\n const embeddedWidget = this.findEmbeddableWidget(node);\n if (embeddedWidget === undefined) return this.buildNotEmbeddableMessage(node);\n if (!sizeClassFitsSlot(embeddedWidget.sizeClass, slot.sizeClass as ComposedSizeClass)) {\n return `the widget \"${String(node.props.widget)}\" needs a ${embeddedWidget.sizeClass} slot — the slot \"${slot.name}\" is ${slot.sizeClass}`;\n }\n }\n return `a ${node.type} does not fit the slot \"${slot.name}\" (${slot.sizeClass}) — it accepts ${[\n ...slot.acceptsCategories,\n ...slot.acceptsNodeTypes,\n ].join(\", \")}`;\n }\n\n /** `WidgetComposedViewNode::buildNotEmbeddableMessage()` — the embeddable widgets in schema order. */\n buildNotEmbeddableMessage(node: ComposedViewNode): string {\n const embeddableWidgetNames = Object.keys(this.schema.embeddableWidgets ?? {});\n const writtenWidgetName = typeof node.props.widget === \"string\" ? node.props.widget : \"\";\n return `\"${writtenWidgetName}\" is no embeddable widget — show it as its own widget block next to the ComposedView, never as a Widget node; ${\n embeddableWidgetNames.length === 0 ? \"no widget embeds\" : `only ${embeddableWidgetNames.join(\", \")} embed`\n }`;\n }\n\n /** `ComposedViewNode::isAcceptedBySlot()` — with the embedded-widget rule of `WidgetComposedViewNode`. */\n isNodeAcceptedBySlot(node: ComposedViewNode, slot: ComposedNodeSlotSchema): boolean {\n const categories = this.schema.nodeTypes[node.type]?.categories ?? [];\n if (node.type === \"Widget\") {\n const embeddedWidget = this.findEmbeddableWidget(node);\n return (\n embeddedWidget !== undefined &&\n sizeClassFitsSlot(embeddedWidget.sizeClass, slot.sizeClass as ComposedSizeClass) &&\n (slot.acceptsNodeTypes.includes(\"Widget\") || slot.acceptsCategories.includes(\"heavy\"))\n );\n }\n if (categories.includes(\"heavy\") && slot.sizeClass === \"compact\" && slot.acceptsHeavyWhenCompact !== true)\n return false;\n return (\n slot.acceptsNodeTypes.includes(node.type) ||\n categories.some((category) => slot.acceptsCategories.includes(category))\n );\n }\n\n readProps(node: ComposedViewNode, wireNode: PlainObject, path: string, isInItemScope: boolean): boolean {\n const nodeTypeSchema = this.schema.nodeTypes[node.type];\n for (const [propName, propValue] of Object.entries(wireNode)) {\n if (RESERVED_WIRE_KEYS.includes(propName)) continue;\n const propPath = `${path}.${propName}`;\n const prop = nodeTypeSchema.props.find((candidate) => candidate.name === propName);\n if (!prop) {\n this.addFinding(\"INVALID_PROP\", propPath, `${node.type} has no prop \"${propName}\" — dropped`);\n continue;\n }\n if (this.isValidPropValue(prop, propValue, propPath, isInItemScope))\n node.props[propName] = propValue as JsonValue;\n }\n for (const prop of nodeTypeSchema.props) {\n if (prop.isRequired && !hasOwn(node.props, prop.name)) {\n this.addFinding(\"INVALID_NODE\", path, `${node.type} needs the prop \"${prop.name}\" — the node is dropped`);\n return false;\n }\n }\n return true;\n }\n\n isValidPropValue(\n prop: ComposedNodePropSchema,\n propValue: unknown,\n propPath: string,\n isInItemScope: boolean,\n ): boolean {\n if (prop.types.includes(\"event\")) return this.isValidEvent(propValue, propPath);\n const binding = readComposedViewBinding(propValue);\n if (binding !== null) {\n if (!prop.isBindable) {\n this.addFinding(\"INVALID_PROP\", propPath, \"this prop takes a literal, not a binding\");\n return false;\n }\n return this.isValidBinding(binding, propPath, isInItemScope);\n }\n if (!propAcceptsLiteral(prop, propValue)) {\n this.addFinding(\n \"INVALID_PROP\",\n propPath,\n `a ${prop.types.join(\" or \")} is expected${prop.allowedValues !== null ? ` (one of ${prop.allowedValues.join(\", \")})` : \"\"}`,\n );\n return false;\n }\n if (typeof propValue === \"string\" && codePointLength(propValue) > this.budgets.maxTextLength) {\n this.addFinding(\"BUDGET_EXCEEDED\", propPath, `a text longer than ${this.budgets.maxTextLength} characters`);\n return false;\n }\n return !isPhpArray(propValue) || this.isValidInlineData(propValue, propPath, isInItemScope);\n }\n\n isValidEvent(propValue: unknown, propPath: string): boolean {\n const eventObject = isPlainObject(propValue) && Object.keys(propValue).length === 1 ? propValue : null;\n if (eventObject && typeof eventObject.set === \"string\" && hasOwn(this.tree.state, eventObject.set)) return true;\n if (eventObject && typeof eventObject.action === \"string\" && hasOwn(this.tree.actions, eventObject.action))\n return true;\n this.addFinding(\n \"UNKNOWN_BINDING\",\n propPath,\n 'an event is {\"set\": <a state name>} or {\"action\": <an action name>} of this tree',\n );\n return false;\n }\n\n isValidBinding(binding: ComposedViewBinding, propPath: string, isInItemScope: boolean): boolean {\n let bindingProblem: string | null = null;\n if (!binding.isWellFormed) {\n bindingProblem =\n \"a malformed binding (one of $state, $computed, $data, $item, $from {toolCall, path}, $source {name, params})\";\n } else if (binding.kind === \"state\" && !hasOwn(this.tree.state, binding.target)) {\n bindingProblem = `no state \"${binding.target}\"`;\n } else if (binding.kind === \"computed\" && !hasOwn(this.tree.computed, binding.target)) {\n bindingProblem = `no computed value \"${binding.target}\"`;\n } else if (binding.kind === \"data\" && !hasOwn(this.tree.data, binding.target)) {\n bindingProblem = `no dataset \"${binding.target}\"`;\n } else if (binding.kind === \"item\" && !isInItemScope) {\n bindingProblem = \"$item outside a node that repeats its children\";\n } else if (binding.kind === \"source\") {\n bindingProblem = this.findSourceBindingProblem(binding);\n }\n if (bindingProblem === null) return true;\n this.addFinding(\"UNKNOWN_BINDING\", propPath, `${bindingProblem} — the prop is dropped`);\n return false;\n }\n\n /** `ComposedViewTreeReading::findSourceBindingProblem()`. */\n findSourceBindingProblem(binding: ComposedViewBinding): string | null {\n const dataSource = hasOwn(this.schema.dataSources ?? {}, binding.target)\n ? this.schema.dataSources[binding.target]\n : undefined;\n if (!dataSource) return `no data source \"${binding.target}\"`;\n const declaredParams = new Map(dataSource.params.map((param) => [param.name, param]));\n for (const [paramName, paramValue] of Object.entries(binding.sourceParams)) {\n if (!declaredParams.has(paramName)) return `the data source \"${binding.target}\" has no param \"${paramName}\"`;\n const paramBinding = readComposedViewBinding(paramValue);\n if (paramBinding !== null && (paramBinding.kind !== \"state\" || !hasOwn(this.tree.state, paramBinding.target))) {\n return `the param \"${paramName}\" binds a declared state name only`;\n }\n }\n for (const [paramName, param] of declaredParams) {\n if (param.isRequired && !hasOwn(binding.sourceParams, paramName)) {\n return `the data source \"${binding.target}\" needs the param \"${paramName}\"`;\n }\n }\n return null;\n }\n\n isValidInlineData(inlineData: unknown[] | PlainObject, propPath: string, isInItemScope: boolean): boolean {\n const isList = isPhpList(inlineData);\n if (isList && entriesOf(inlineData).length > this.budgets.maxInlineArrayItems) {\n this.addFinding(\"BUDGET_EXCEEDED\", propPath, `more than ${this.budgets.maxInlineArrayItems} inline items`);\n return false;\n }\n if (\n isPlainObject(inlineData) &&\n hasOwn(inlineData, \"value\") &&\n !hasOwn(inlineData, \"source\") &&\n !hasOwn(inlineData, \"derivedFrom\")\n ) {\n this.addFinding(\n \"INLINE_VALUE_WITHOUT_SOURCE\",\n propPath,\n \"a value without `source` or `derivedFrom` — rendered without a source line\",\n );\n }\n for (const [inlineKey, inlineValue] of entriesOf(inlineData)) {\n const nestedPath = isList ? `${propPath}[${inlineKey}]` : `${propPath}.${inlineKey}`;\n const binding = readComposedViewBinding(inlineValue);\n if (binding !== null) {\n if (!this.isValidBinding(binding, nestedPath, isInItemScope)) return false;\n continue;\n }\n if (isPhpArray(inlineValue)) {\n if (!this.isValidInlineData(inlineValue, nestedPath, isInItemScope)) return false;\n continue;\n }\n if (++this.inlineCellCount > this.budgets.maxInlineCells) {\n this.addFinding(\n \"BUDGET_EXCEEDED\",\n nestedPath,\n `more than ${this.budgets.maxInlineCells} inline cells in the block`,\n );\n return false;\n }\n }\n return true;\n }\n}\n\n/** Nodes in a subtree, the node included. */\nexport const countComposedViewNodes = (node: ComposedViewNode): number =>\n 1 +\n Object.values(node.nodesBySlotName).reduce(\n (slotNodeCount, slotNodes) =>\n slotNodeCount + slotNodes.reduce((sum, slotNode) => sum + countComposedViewNodes(slotNode), 0),\n 0,\n );\n\n/**\n * The tree of the decoded block fields (without `type`), read and checked against `schema`. Fields nested deeper than\n * the backend decodes give no view; objects keyed `\"0\"`, `\"1\"`, … are lists, as `json_decode` makes them.\n */\nexport const readComposedViewTree = (\n widgetFields: Record<string, unknown>,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): ComposedViewTree => {\n const reader = new ComposedViewTreeReader(schema);\n if (exceedsJsonContainerDepth(widgetFields)) {\n reader.addFinding(\n \"BUDGET_EXCEEDED\",\n \"block\",\n `nested deeper than ${MAX_JSON_CONTAINER_DEPTH} levels — malformed, as the backend decodes it; no view is rendered`,\n );\n return reader.tree;\n }\n reader.read(normalizeToPhpArrays(widgetFields) as PlainObject);\n return reader.tree;\n};\n\nconst utf8ByteLength = (text: string): number => new TextEncoder().encode(text).length;\n\n/**\n * The tree of a widget `payload` (the fence's non-`type` fields as a JSON string). A payload that is not a JSON object\n * gives an empty tree; one over the source budget (counted on the canonical bytes, `measureComposedViewSourceBytes`)\n * gives no view and one `BUDGET_EXCEEDED` finding, as on the backend.\n */\nexport const parseComposedViewTree = (\n payload: string,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): ComposedViewTree => {\n const emptyTree: ComposedViewTree = {\n title: null,\n state: {},\n data: {},\n computed: {},\n actions: {},\n view: null,\n findings: [],\n liftedWidgets: [],\n };\n let widgetFields: unknown;\n try {\n widgetFields = JSON.parse(payload);\n } catch {\n return emptyTree;\n }\n if (!isPlainObject(widgetFields)) return emptyTree;\n // The depth check FIRST: measuring serialises the fields, and a deeper value than the backend decodes would throw.\n if (exceedsJsonContainerDepth(widgetFields)) return readComposedViewTree(widgetFields, schema);\n const sourceBytes = measureComposedViewSourceBytes(widgetFields);\n if (sourceBytes > schema.budgets.maxSourceBytes) {\n emptyTree.findings.push({\n code: \"BUDGET_EXCEEDED\",\n path: \"block\",\n message: `the block has ${sourceBytes} bytes, the budget is ${schema.budgets.maxSourceBytes} — no view is rendered`,\n });\n return emptyTree;\n }\n return readComposedViewTree(widgetFields, schema);\n};\n\n/**\n * The bytes the source budget counts — `ComposedViewTreeReading::measureSourceBytes()`: the fields without `type` as\n * compact JSON, so the written fence's whitespace never decides; the legacy `writtenSyntax` field some stored fences carry\n * (`WidgetBlock::LEGACY_WRITTEN_SYNTAX_FIELD`) does not count.\n */\nexport const measureComposedViewSourceBytes = (widgetFields: Record<string, unknown>): number => {\n const { type: unusedType, writtenSyntax: unusedWrittenSyntax, ...fieldsWithoutType } = widgetFields;\n // Measured as PHP encodes the decoded block: objects keyed \"0\", \"1\", … are lists there (`[…]`, without the keys).\n return utf8ByteLength(JSON.stringify(normalizeToPhpArrays(fieldsWithoutType)));\n};\n\n/** The node in its wire form — `ComposedViewNode::toWireArray()`. */\nexport const composedViewNodeToWire = (node: ComposedViewNode): Record<string, JsonValue> => {\n const wireNode: Record<string, JsonValue> = { type: node.type };\n if (node.id !== null) wireNode.id = node.id;\n Object.assign(wireNode, node.props);\n const namedSlots: Record<string, JsonValue> = {};\n for (const [slotName, slotNodes] of Object.entries(node.nodesBySlotName)) {\n if (slotNodes.length === 0) continue;\n const slotWireNodes = slotNodes.map(composedViewNodeToWire);\n if (slotName === DEFAULT_SLOT_NAME) wireNode.children = slotWireNodes;\n else namedSlots[slotName] = slotWireNodes;\n }\n if (Object.keys(namedSlots).length > 0) wireNode.slots = namedSlots;\n return wireNode;\n};\n\n/** The kept tree in its wire form — `ComposedViewConversationWidget::getWidgetFields()` (empty parts left out). */\nexport const composedViewTreeToWire = (tree: ComposedViewTree): Record<string, JsonValue> => {\n const wireFields: Record<string, JsonValue> = {};\n if (tree.title !== null) wireFields.title = tree.title;\n if (Object.keys(tree.state).length > 0) wireFields.state = tree.state;\n if (Object.keys(tree.data).length > 0) wireFields.data = tree.data;\n if (Object.keys(tree.computed).length > 0) wireFields.computed = tree.computed;\n if (tree.view !== null) wireFields.view = composedViewNodeToWire(tree.view);\n if (Object.keys(tree.actions).length > 0) wireFields.actions = tree.actions as unknown as JsonValue;\n return wireFields;\n};\n\n/** `ComposedViewNode::getNodesOfSubtreeByPath()` — every node of a subtree with its kept-tree path, depth first. */\nexport const getComposedViewSubtreeNodesByPath = (\n node: ComposedViewNode,\n path: string,\n): Array<[string, ComposedViewNode]> => [\n [path, node],\n ...Object.entries(node.nodesBySlotName).flatMap(([slotName, slotNodes]) => {\n const slotPath = slotName === DEFAULT_SLOT_NAME ? `${path}.children` : `${path}.slots.${slotName}`;\n return slotNodes.flatMap((slotNode, childPosition) =>\n getComposedViewSubtreeNodesByPath(slotNode, `${slotPath}[${childPosition}]`),\n );\n }),\n];\n\n/** Every node of a subtree, depth first, the node first. */\nexport const getComposedViewSubtreeNodes = (node: ComposedViewNode): ComposedViewNode[] => [\n node,\n ...Object.values(node.nodesBySlotName).flatMap((slotNodes) => slotNodes.flatMap(getComposedViewSubtreeNodes)),\n];\n\n/** The slot schema of a node type, or undefined. */\nexport const findComposedViewSlotSchema = (\n nodeType: string,\n slotName: string,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): ComposedNodeSlotSchema | undefined => schema.nodeTypes[nodeType]?.slots.find((slot) => slot.name === slotName);\n\n/**\n * Whether a kept view shows nothing: every node of it is a layout node (a Grid, a Stack or a Surface without a node to\n * hold). The renderer shows the explicit fallback line instead — never a title over an empty Grid.\n */\nexport const isComposedViewWithoutContent = (\n view: ComposedViewNode,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): boolean =>\n getComposedViewSubtreeNodes(view).every((node) => {\n const categories = schema.nodeTypes[node.type]?.categories ?? [];\n return categories.length > 0 && categories.every((category) => category === \"layout\");\n });\n","/**\n * The parser of the `ComposedView` expression language — our own tokenizer and recursive-descent\n * parser, never `eval` or `new Function`. The language is closed:\n *\n * literals 12, 3.5, \"text\", 'text', true, false, null, [a, b], {name: expr, \"key\": expr}\n * names a state, dataset or computed name; a lambda parameter\n * member a.b, a[\"b\"], a[0] (own properties of JSON values only — checked when evaluating)\n * operators + - * / % == != < <= > >= && || ! unary - cond ? a : b\n * calls one of the closed functions (`EXPRESSION_FUNCTION_NAMES`), e.g. sum(rows, r => r.visits)\n * lambdas x => expr, (x) => expr, (x, i) => expr — only as an argument of a call\n *\n * There are no statements, assignments, loops or method calls; a call names a function of the closed list, never a\n * value. The AST node count is capped (`maxExpressionAstNodes`); an expression over it does not compile.\n */\n\nexport type ExpressionNode =\n | { kind: \"literal\"; value: string | number | boolean | null }\n | { kind: \"name\"; name: string }\n | { kind: \"array\"; elements: ExpressionNode[] }\n | { kind: \"object\"; entries: Array<{ key: string; value: ExpressionNode }> }\n | { kind: \"member\"; object: ExpressionNode; property: ExpressionNode }\n | { kind: \"unary\"; operator: \"!\" | \"-\"; operand: ExpressionNode }\n | { kind: \"binary\"; operator: string; left: ExpressionNode; right: ExpressionNode }\n | { kind: \"conditional\"; test: ExpressionNode; consequent: ExpressionNode; alternate: ExpressionNode }\n | { kind: \"call\"; functionName: string; args: ExpressionNode[] }\n | { kind: \"lambda\"; params: string[]; body: ExpressionNode };\n\n/** The closed function list (the evaluator implements exactly these). */\nexport const EXPRESSION_FUNCTION_NAMES = [\n \"round\",\n \"floor\",\n \"ceil\",\n \"abs\",\n \"min\",\n \"max\",\n \"sum\",\n \"avg\",\n \"count\",\n \"len\",\n \"filter\",\n \"map\",\n \"sortBy\",\n \"first\",\n \"last\",\n \"concat\",\n \"join\",\n \"string\",\n \"number\",\n \"fixed\",\n \"percent\",\n] as const;\n\nexport type ExpressionFunctionName = (typeof EXPRESSION_FUNCTION_NAMES)[number];\n\nexport type ExpressionCompileResult =\n | { ok: true; ast: ExpressionNode; nodeCount: number }\n | { ok: false; error: string };\n\ntype Token =\n | { type: \"number\"; value: number }\n | { type: \"string\"; value: string }\n | { type: \"name\"; value: string }\n | { type: \"punct\"; value: string }\n | { type: \"end\" };\n\nconst PUNCTUATORS = [\n \"=>\",\n \"==\",\n \"!=\",\n \"<=\",\n \">=\",\n \"&&\",\n \"||\",\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"%\",\n \"<\",\n \">\",\n \"!\",\n \"?\",\n \":\",\n \".\",\n \",\",\n \"(\",\n \")\",\n \"[\",\n \"]\",\n \"{\",\n \"}\",\n];\n\nclass ExpressionSyntaxError extends Error {}\n\nconst tokenize = (source: string): Token[] => {\n const tokens: Token[] = [];\n let position = 0;\n while (position < source.length) {\n const character = source[position];\n if (/\\s/.test(character)) {\n position++;\n continue;\n }\n if (/[0-9]/.test(character) || (character === \".\" && /[0-9]/.test(source[position + 1] ?? \"\"))) {\n const numberMatch = /^(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(source.slice(position));\n if (!numberMatch) throw new ExpressionSyntaxError(`bad number at ${position}`);\n tokens.push({ type: \"number\", value: Number(numberMatch[0]) });\n position += numberMatch[0].length;\n continue;\n }\n if (character === '\"' || character === \"'\") {\n let text = \"\";\n let cursor = position + 1;\n while (cursor < source.length && source[cursor] !== character) {\n if (source[cursor] === \"\\\\\" && cursor + 1 < source.length) {\n const escaped = source[cursor + 1];\n text += escaped === \"n\" ? \"\\n\" : escaped === \"t\" ? \"\\t\" : escaped;\n cursor += 2;\n continue;\n }\n text += source[cursor];\n cursor++;\n }\n if (cursor >= source.length) throw new ExpressionSyntaxError(\"unclosed string\");\n tokens.push({ type: \"string\", value: text });\n position = cursor + 1;\n continue;\n }\n if (/[A-Za-z_$]/.test(character)) {\n const nameMatch = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(source.slice(position));\n tokens.push({ type: \"name\", value: nameMatch![0] });\n position += nameMatch![0].length;\n continue;\n }\n const punctuator = PUNCTUATORS.find((candidate) => source.startsWith(candidate, position));\n if (!punctuator) throw new ExpressionSyntaxError(`unexpected \"${character}\" at ${position}`);\n tokens.push({ type: \"punct\", value: punctuator });\n position += punctuator.length;\n }\n tokens.push({ type: \"end\" });\n return tokens;\n};\n\nconst BINARY_PRECEDENCE: Array<string[]> = [\n [\"||\"],\n [\"&&\"],\n [\"==\", \"!=\"],\n [\"<\", \"<=\", \">\", \">=\"],\n [\"+\", \"-\"],\n [\"*\", \"/\", \"%\"],\n];\n\nclass ExpressionParser {\n protected position = 0;\n nodeCount = 0;\n\n constructor(\n protected readonly tokens: Token[],\n protected readonly maxNodes: number,\n ) {}\n\n protected peek(): Token {\n return this.tokens[this.position];\n }\n\n protected next(): Token {\n return this.tokens[this.position++];\n }\n\n protected isPunct(value: string, offset = 0): boolean {\n const token = this.tokens[this.position + offset];\n return token !== undefined && token.type === \"punct\" && token.value === value;\n }\n\n protected expectPunct(value: string): void {\n if (!this.isPunct(value)) throw new ExpressionSyntaxError(`\"${value}\" expected`);\n this.position++;\n }\n\n protected node<T extends ExpressionNode>(expressionNode: T): T {\n if (++this.nodeCount > this.maxNodes)\n throw new ExpressionSyntaxError(`more than ${this.maxNodes} expression nodes`);\n return expressionNode;\n }\n\n parseExpression(): ExpressionNode {\n const test = this.parseBinary(0);\n if (!this.isPunct(\"?\")) return test;\n this.position++;\n const consequent = this.parseExpression();\n this.expectPunct(\":\");\n const alternate = this.parseExpression();\n return this.node({ kind: \"conditional\", test, consequent, alternate });\n }\n\n protected parseBinary(level: number): ExpressionNode {\n if (level >= BINARY_PRECEDENCE.length) return this.parseUnary();\n let left = this.parseBinary(level + 1);\n for (;;) {\n const token = this.peek();\n if (token.type !== \"punct\" || !BINARY_PRECEDENCE[level].includes(token.value)) return left;\n this.position++;\n const right = this.parseBinary(level + 1);\n left = this.node({ kind: \"binary\", operator: token.value, left, right });\n }\n }\n\n protected parseUnary(): ExpressionNode {\n if (this.isPunct(\"!\") || this.isPunct(\"-\")) {\n const operator = (this.next() as { value: \"!\" | \"-\" }).value;\n return this.node({ kind: \"unary\", operator, operand: this.parseUnary() });\n }\n return this.parsePostfix(this.parsePrimary());\n }\n\n protected parsePostfix(target: ExpressionNode): ExpressionNode {\n let expressionNode = target;\n for (;;) {\n if (this.isPunct(\".\")) {\n this.position++;\n const propertyToken = this.next();\n if (propertyToken.type !== \"name\") throw new ExpressionSyntaxError('a property name expected after \".\"');\n expressionNode = this.node({\n kind: \"member\",\n object: expressionNode,\n property: this.node({ kind: \"literal\", value: propertyToken.value }),\n });\n continue;\n }\n if (this.isPunct(\"[\")) {\n this.position++;\n const property = this.parseExpression();\n this.expectPunct(\"]\");\n expressionNode = this.node({ kind: \"member\", object: expressionNode, property });\n continue;\n }\n if (this.isPunct(\"(\")) throw new ExpressionSyntaxError(\"only the closed functions can be called\");\n return expressionNode;\n }\n }\n\n protected parseArguments(): ExpressionNode[] {\n const args: ExpressionNode[] = [];\n this.expectPunct(\"(\");\n while (!this.isPunct(\")\")) {\n args.push(this.parseLambdaOrExpression());\n if (!this.isPunct(\",\")) break;\n this.position++;\n }\n this.expectPunct(\")\");\n return args;\n }\n\n /** A lambda (`x => …`, `(x, i) => …`) where a call argument may hold one, else an expression. */\n protected parseLambdaOrExpression(): ExpressionNode {\n const token = this.peek();\n if (token.type === \"name\" && this.isPunct(\"=>\", 1)) {\n this.position += 2;\n return this.node({ kind: \"lambda\", params: [token.value], body: this.parseExpression() });\n }\n if (this.isPunct(\"(\")) {\n let cursor = this.position + 1;\n const params: string[] = [];\n while (this.tokens[cursor]?.type === \"name\") {\n params.push((this.tokens[cursor] as { value: string }).value);\n cursor++;\n const separator = this.tokens[cursor];\n if (separator?.type === \"punct\" && separator.value === \",\") {\n cursor++;\n continue;\n }\n break;\n }\n const closing = this.tokens[cursor];\n const arrow = this.tokens[cursor + 1];\n if (closing?.type === \"punct\" && closing.value === \")\" && arrow?.type === \"punct\" && arrow.value === \"=>\") {\n this.position = cursor + 2;\n return this.node({ kind: \"lambda\", params, body: this.parseExpression() });\n }\n }\n return this.parseExpression();\n }\n\n protected parsePrimary(): ExpressionNode {\n const token = this.next();\n if (token.type === \"number\" || token.type === \"string\") return this.node({ kind: \"literal\", value: token.value });\n if (token.type === \"name\") {\n if (token.value === \"true\" || token.value === \"false\")\n return this.node({ kind: \"literal\", value: token.value === \"true\" });\n if (token.value === \"null\") return this.node({ kind: \"literal\", value: null });\n if (this.isPunct(\"(\")) {\n if (!(EXPRESSION_FUNCTION_NAMES as readonly string[]).includes(token.value)) {\n throw new ExpressionSyntaxError(`\"${token.value}\" is not a function of the closed list`);\n }\n return this.node({ kind: \"call\", functionName: token.value, args: this.parseArguments() });\n }\n return this.node({ kind: \"name\", name: token.value });\n }\n if (token.type === \"punct\" && token.value === \"(\") {\n const inner = this.parseExpression();\n this.expectPunct(\")\");\n return inner;\n }\n if (token.type === \"punct\" && token.value === \"[\") {\n const elements: ExpressionNode[] = [];\n while (!this.isPunct(\"]\")) {\n elements.push(this.parseExpression());\n if (!this.isPunct(\",\")) break;\n this.position++;\n }\n this.expectPunct(\"]\");\n return this.node({ kind: \"array\", elements });\n }\n if (token.type === \"punct\" && token.value === \"{\") {\n const entries: Array<{ key: string; value: ExpressionNode }> = [];\n while (!this.isPunct(\"}\")) {\n const keyToken = this.next();\n if (keyToken.type !== \"name\" && keyToken.type !== \"string\")\n throw new ExpressionSyntaxError(\"an object key expected\");\n this.expectPunct(\":\");\n entries.push({ key: String(keyToken.value), value: this.parseExpression() });\n if (!this.isPunct(\",\")) break;\n this.position++;\n }\n this.expectPunct(\"}\");\n return this.node({ kind: \"object\", entries });\n }\n throw new ExpressionSyntaxError(token.type === \"end\" ? \"unexpected end of expression\" : \"unexpected token\");\n }\n\n parseAll(): ExpressionNode {\n const ast = this.parseExpression();\n if (this.peek().type !== \"end\") throw new ExpressionSyntaxError(\"unexpected text after the expression\");\n return ast;\n }\n}\n\nconst compiledExpressions = new Map<string, ExpressionCompileResult>();\n\n/** Compiles an expression once (cached by source and node budget); never throws. */\nexport const compileExpression = (source: string, maxAstNodes: number): ExpressionCompileResult => {\n const cacheKey = `${maxAstNodes}\\u0000${source}`;\n const cached = compiledExpressions.get(cacheKey);\n if (cached) return cached;\n let compileResult: ExpressionCompileResult;\n try {\n const parser = new ExpressionParser(tokenize(source), maxAstNodes);\n const ast = parser.parseAll();\n compileResult = { ok: true, ast, nodeCount: parser.nodeCount };\n } catch (error) {\n compileResult = { ok: false, error: error instanceof Error ? error.message : \"invalid expression\" };\n }\n if (compiledExpressions.size > 2000) compiledExpressions.clear();\n compiledExpressions.set(cacheKey, compileResult);\n return compileResult;\n};\n\n/** The names an expression reads (lambda parameters excluded) — the computed dependency graph. */\nexport const collectExpressionNames = (\n ast: ExpressionNode,\n boundNames: ReadonlySet<string> = new Set(),\n): Set<string> => {\n const names = new Set<string>();\n const visitNode = (expressionNode: ExpressionNode, scope: ReadonlySet<string>): void => {\n switch (expressionNode.kind) {\n case \"name\":\n if (!scope.has(expressionNode.name)) names.add(expressionNode.name);\n return;\n case \"array\":\n expressionNode.elements.forEach((element) => visitNode(element, scope));\n return;\n case \"object\":\n expressionNode.entries.forEach((entry) => visitNode(entry.value, scope));\n return;\n case \"member\":\n visitNode(expressionNode.object, scope);\n visitNode(expressionNode.property, scope);\n return;\n case \"unary\":\n visitNode(expressionNode.operand, scope);\n return;\n case \"binary\":\n visitNode(expressionNode.left, scope);\n visitNode(expressionNode.right, scope);\n return;\n case \"conditional\":\n visitNode(expressionNode.test, scope);\n visitNode(expressionNode.consequent, scope);\n visitNode(expressionNode.alternate, scope);\n return;\n case \"call\":\n expressionNode.args.forEach((arg) => visitNode(arg, scope));\n return;\n case \"lambda\":\n visitNode(expressionNode.body, new Set([...scope, ...expressionNode.params]));\n return;\n default:\n return;\n }\n };\n visitNode(ast, boundNames);\n return names;\n};\n","import type { ComposedViewBudgets } from \"../composed-node-schema\";\nimport { collectExpressionNames, compileExpression, ExpressionNode } from \"./parse-expression\";\n\n/**\n * The evaluator of the `ComposedView` expression language. Values are JSON values; one value\n * means \"empty\": `undefined` — a missing name or member, a division by zero, a non-finite result, an operation on an\n * empty or wrongly typed operand all give it, and it renders as nothing. Member access reads OWN properties of arrays and\n * plain objects only (never `__proto__`, `constructor`, `prototype`, never a method). Every evaluated node and every\n * element a function walks is charged against ONE operation budget per state update (`maxOperationsPerUpdate`), so a\n * nested `map` / `filter` / `sortBy` cannot run away; collections are capped (`maxCollectionItems`), the elements\n * allocated for intermediate collections are charged by their size as a tree (`maxAllocatedItemsPerEvaluation`), and a\n * text result may not pass `maxTextLength`.\n */\n\nexport type ExpressionValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ExpressionValue[]\n | { [key: string]: ExpressionValue };\n\n/** Why an expression gave no value: it did not compile, it ran over a budget, or it read itself (a cycle). */\nexport type ExpressionErrorCode = \"INVALID_EXPRESSION\" | \"BUDGET_EXCEEDED\";\n\nexport class ExpressionBudgetExceededError extends Error {}\n\nconst BLOCKED_MEMBER_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\ninterface LambdaValue {\n readonly isLambda: true;\n readonly params: string[];\n readonly body: ExpressionNode;\n readonly scope: ReadonlyMap<string, ExpressionValue>;\n}\n\ntype RuntimeValue = ExpressionValue | LambdaValue;\n\nconst isLambda = (value: unknown): value is LambdaValue =>\n typeof value === \"object\" && value !== null && (value as { isLambda?: unknown }).isLambda === true;\nconst isPlainObject = (value: unknown): value is Record<string, ExpressionValue> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && !isLambda(value);\nconst isFiniteNumber = (value: unknown): value is number => typeof value === \"number\" && Number.isFinite(value);\nconst toFiniteOrEmpty = (value: number): number | undefined => (Number.isFinite(value) ? value : undefined);\nconst isTruthy = (value: RuntimeValue): boolean => Boolean(value);\n\n/** The budget counters of one state update, shared by every expression it evaluates. */\nexport class ExpressionBudget {\n operationsLeft: number;\n allocatedItemsLeft: number;\n\n constructor(readonly budgets: ComposedViewBudgets) {\n this.operationsLeft = budgets.maxOperationsPerUpdate;\n this.allocatedItemsLeft = budgets.maxAllocatedItemsPerEvaluation;\n }\n\n charge(operations = 1): void {\n this.operationsLeft -= operations;\n if (this.operationsLeft < 0) throw new ExpressionBudgetExceededError(\"operation budget exceeded\");\n }\n\n allocate(items: number): void {\n this.allocatedItemsLeft -= items;\n if (this.allocatedItemsLeft < 0) throw new ExpressionBudgetExceededError(\"allocation budget exceeded\");\n }\n\n checkCollection(items: ExpressionValue[]): void {\n if (items.length > this.budgets.maxCollectionItems) throw new ExpressionBudgetExceededError(\"collection too large\");\n }\n\n /** A text result may not pass `maxTextLength` — checked on the lengths BEFORE the text is built. */\n checkTextLength(textLength: number): void {\n if (textLength > this.budgets.maxTextLength) throw new ExpressionBudgetExceededError(\"text too long\");\n }\n\n /** The containers this update's expressions built, with their size as a tree (a shared one counted per use). */\n protected readonly createdValueSizes = new WeakMap<object, number>();\n\n /**\n * Charges a container an expression just built by its size as a TREE — a value built from earlier results counts\n * them again wherever it repeats them, so `{l: o, r: o}` over `o` doubles and a chain of such values cannot grow\n * past the allocation budget. A value the expression did not build (a dataset) counts 1.\n */\n allocateCreatedValue(createdValue: ExpressionValue[] | Record<string, ExpressionValue>): void {\n let treeSize = 1;\n for (const element of Object.values(createdValue)) {\n treeSize += typeof element === \"object\" && element !== null ? (this.createdValueSizes.get(element) ?? 1) : 1;\n }\n this.allocate(treeSize);\n this.createdValueSizes.set(createdValue, treeSize);\n }\n}\n\n/** Where a name comes from: lambda parameters first, then the tree's names (state, datasets, computed). */\nexport type ExpressionNameResolver = (name: string) => ExpressionValue;\n\nclass ExpressionEvaluator {\n constructor(\n protected readonly budget: ExpressionBudget,\n protected readonly resolveName: ExpressionNameResolver,\n ) {}\n\n evaluate(expressionNode: ExpressionNode, scope: ReadonlyMap<string, ExpressionValue>): RuntimeValue {\n this.budget.charge();\n switch (expressionNode.kind) {\n case \"literal\":\n return expressionNode.value;\n case \"name\":\n return scope.has(expressionNode.name) ? scope.get(expressionNode.name) : this.resolveName(expressionNode.name);\n case \"array\": {\n const arrayValue = expressionNode.elements.map((element) => this.evaluateValue(element, scope));\n this.budget.allocateCreatedValue(arrayValue);\n return arrayValue;\n }\n case \"object\": {\n const objectValue: Record<string, ExpressionValue> = {};\n for (const entry of expressionNode.entries) {\n if (BLOCKED_MEMBER_NAMES.has(entry.key)) continue;\n objectValue[entry.key] = this.evaluateValue(entry.value, scope);\n }\n this.budget.allocateCreatedValue(objectValue);\n return objectValue;\n }\n case \"member\":\n return this.readMember(\n this.evaluateValue(expressionNode.object, scope),\n this.evaluateValue(expressionNode.property, scope),\n );\n case \"unary\": {\n const operand = this.evaluateValue(expressionNode.operand, scope);\n if (expressionNode.operator === \"!\") return !isTruthy(operand);\n return isFiniteNumber(operand) ? -operand : undefined;\n }\n case \"binary\":\n return this.evaluateBinary(expressionNode.operator, expressionNode.left, expressionNode.right, scope);\n case \"conditional\":\n return isTruthy(this.evaluateValue(expressionNode.test, scope))\n ? this.evaluateValue(expressionNode.consequent, scope)\n : this.evaluateValue(expressionNode.alternate, scope);\n case \"lambda\":\n return { isLambda: true, params: expressionNode.params, body: expressionNode.body, scope };\n case \"call\":\n return this.callFunction(\n expressionNode.functionName,\n expressionNode.args.map((arg) => this.evaluate(arg, scope)),\n );\n default:\n return undefined;\n }\n }\n\n /** A value that is never a lambda (a lambda outside a call argument is empty). */\n evaluateValue(expressionNode: ExpressionNode, scope: ReadonlyMap<string, ExpressionValue>): ExpressionValue {\n const value = this.evaluate(expressionNode, scope);\n return isLambda(value) ? undefined : value;\n }\n\n protected readMember(objectValue: ExpressionValue, propertyValue: ExpressionValue): ExpressionValue {\n if (typeof propertyValue !== \"string\" && typeof propertyValue !== \"number\") return undefined;\n const propertyName = String(propertyValue);\n if (BLOCKED_MEMBER_NAMES.has(propertyName)) return undefined;\n if (Array.isArray(objectValue)) {\n if (propertyName === \"length\") return objectValue.length;\n return Object.prototype.hasOwnProperty.call(objectValue, propertyName)\n ? objectValue[Number(propertyName)]\n : undefined;\n }\n if (isPlainObject(objectValue) && Object.prototype.hasOwnProperty.call(objectValue, propertyName)) {\n return objectValue[propertyName];\n }\n return undefined;\n }\n\n protected evaluateBinary(\n operator: string,\n leftNode: ExpressionNode,\n rightNode: ExpressionNode,\n scope: ReadonlyMap<string, ExpressionValue>,\n ): ExpressionValue {\n if (operator === \"&&\" || operator === \"||\") {\n const left = this.evaluateValue(leftNode, scope);\n if (operator === \"&&\") return isTruthy(left) ? this.evaluateValue(rightNode, scope) : left;\n return isTruthy(left) ? left : this.evaluateValue(rightNode, scope);\n }\n const left = this.evaluateValue(leftNode, scope);\n const right = this.evaluateValue(rightNode, scope);\n switch (operator) {\n case \"==\":\n return left === right;\n case \"!=\":\n return left !== right;\n case \"<\":\n case \"<=\":\n case \">\":\n case \">=\": {\n const comparable =\n (isFiniteNumber(left) && isFiniteNumber(right)) || (typeof left === \"string\" && typeof right === \"string\");\n if (!comparable) return undefined;\n if (operator === \"<\") return (left as number) < (right as number);\n if (operator === \"<=\") return (left as number) <= (right as number);\n if (operator === \">\") return (left as number) > (right as number);\n return (left as number) >= (right as number);\n }\n case \"+\":\n if (isFiniteNumber(left) && isFiniteNumber(right)) return toFiniteOrEmpty(left + right);\n if (\n (typeof left === \"string\" || isFiniteNumber(left)) &&\n (typeof right === \"string\" || isFiniteNumber(right))\n ) {\n const leftText = String(left);\n const rightText = String(right);\n this.budget.checkTextLength(leftText.length + rightText.length);\n return leftText + rightText;\n }\n return undefined;\n case \"-\":\n return isFiniteNumber(left) && isFiniteNumber(right) ? toFiniteOrEmpty(left - right) : undefined;\n case \"*\":\n return isFiniteNumber(left) && isFiniteNumber(right) ? toFiniteOrEmpty(left * right) : undefined;\n case \"/\":\n return isFiniteNumber(left) && isFiniteNumber(right) && right !== 0 ? toFiniteOrEmpty(left / right) : undefined;\n case \"%\":\n return isFiniteNumber(left) && isFiniteNumber(right) && right !== 0 ? toFiniteOrEmpty(left % right) : undefined;\n default:\n return undefined;\n }\n }\n\n protected invokeLambda(lambda: RuntimeValue, args: ExpressionValue[]): ExpressionValue {\n if (!isLambda(lambda)) return undefined;\n const lambdaScope = new Map(lambda.scope);\n lambda.params.forEach((param, index) => lambdaScope.set(param, args[index]));\n return this.evaluateValue(lambda.body, lambdaScope);\n }\n\n /** The list argument of a collection function, capped and charged; undefined when it is no list. */\n protected readList(value: RuntimeValue): ExpressionValue[] | undefined {\n if (!Array.isArray(value)) return undefined;\n this.budget.checkCollection(value);\n this.budget.charge(value.length);\n return value;\n }\n\n /** The numbers of a list, through an optional lambda; non-numbers are skipped. */\n protected readNumbers(listValue: RuntimeValue, lambda?: RuntimeValue): number[] | undefined {\n const list = this.readList(listValue);\n if (list === undefined) return undefined;\n const values =\n lambda === undefined ? list : list.map((element, index) => this.invokeLambda(lambda, [element, index]));\n return values.filter(isFiniteNumber);\n }\n\n protected callFunction(functionName: string, args: RuntimeValue[]): ExpressionValue {\n const [first, second, third] = args;\n switch (functionName) {\n case \"round\": {\n if (!isFiniteNumber(first)) return undefined;\n const digits = isFiniteNumber(second) ? Math.max(0, Math.min(10, Math.trunc(second))) : 0;\n const factor = 10 ** digits;\n return toFiniteOrEmpty(Math.round(first * factor) / factor);\n }\n case \"floor\":\n return isFiniteNumber(first) ? Math.floor(first) : undefined;\n case \"ceil\":\n return isFiniteNumber(first) ? Math.ceil(first) : undefined;\n case \"abs\":\n return isFiniteNumber(first) ? Math.abs(first) : undefined;\n case \"min\":\n case \"max\": {\n const numbers = Array.isArray(first) ? this.readNumbers(first, second) : args.filter(isFiniteNumber);\n if (numbers === undefined || numbers.length === 0) return undefined;\n return functionName === \"min\" ? Math.min(...numbers) : Math.max(...numbers);\n }\n case \"sum\": {\n const numbers = this.readNumbers(first, second);\n return numbers === undefined ? undefined : toFiniteOrEmpty(numbers.reduce((total, value) => total + value, 0));\n }\n case \"avg\": {\n const numbers = this.readNumbers(first, second);\n if (numbers === undefined || numbers.length === 0) return undefined;\n return toFiniteOrEmpty(numbers.reduce((total, value) => total + value, 0) / numbers.length);\n }\n case \"count\": {\n const list = this.readList(first);\n if (list === undefined) return undefined;\n if (second === undefined) return list.length;\n return list.filter((element, index) => isTruthy(this.invokeLambda(second, [element, index]))).length;\n }\n case \"len\":\n if (typeof first === \"string\") return [...first].length;\n return Array.isArray(first) ? first.length : undefined;\n case \"filter\": {\n const list = this.readList(first);\n if (list === undefined || !isLambda(second)) return undefined;\n const kept = list.filter((element, index) => isTruthy(this.invokeLambda(second, [element, index])));\n this.budget.allocateCreatedValue(kept);\n return kept;\n }\n case \"map\": {\n const list = this.readList(first);\n if (list === undefined || !isLambda(second)) return undefined;\n const mapped = list.map((element, index) => this.invokeLambda(second, [element, index]));\n this.budget.allocateCreatedValue(mapped);\n return mapped;\n }\n case \"sortBy\": {\n const list = this.readList(first);\n if (list === undefined || !isLambda(second)) return undefined;\n this.budget.charge(Math.ceil(list.length * Math.log2(list.length + 1)));\n const direction = third === \"desc\" ? -1 : 1;\n const keyed = list.map((element, index) => ({\n element,\n key: this.invokeLambda(second, [element, index]),\n index,\n }));\n keyed.sort((a, b) => {\n const comparison =\n isFiniteNumber(a.key) && isFiniteNumber(b.key)\n ? a.key - b.key\n : typeof a.key === \"string\" && typeof b.key === \"string\"\n ? a.key.localeCompare(b.key)\n : a.key === undefined\n ? 1\n : b.key === undefined\n ? -1\n : 0;\n return comparison !== 0 ? comparison * direction : a.index - b.index;\n });\n const sorted = keyed.map((entry) => entry.element);\n this.budget.allocateCreatedValue(sorted);\n return sorted;\n }\n case \"first\": {\n const list = this.readList(first);\n return list === undefined ? undefined : list[0];\n }\n case \"last\": {\n const list = this.readList(first);\n return list === undefined ? undefined : list[list.length - 1];\n }\n case \"concat\": {\n const lists = args.map((arg) => this.readList(arg));\n if (lists.some((list) => list === undefined)) return undefined;\n const joined = (lists as ExpressionValue[][]).flat(1);\n this.budget.checkCollection(joined);\n this.budget.allocateCreatedValue(joined);\n return joined;\n }\n case \"join\": {\n const list = this.readList(first);\n if (list === undefined) return undefined;\n const separator = typeof second === \"string\" ? second : \", \";\n const joinedParts = list\n .filter((element) => typeof element === \"string\" || isFiniteNumber(element))\n .map((element) => String(element));\n this.budget.checkTextLength(\n joinedParts.reduce((textLength, part) => textLength + part.length, 0) +\n separator.length * Math.max(0, joinedParts.length - 1),\n );\n return joinedParts.join(separator);\n }\n case \"string\": {\n if (typeof first !== \"string\" && !isFiniteNumber(first) && typeof first !== \"boolean\") return undefined;\n const text = String(first);\n this.budget.checkTextLength(text.length);\n return text;\n }\n case \"number\": {\n if (isFiniteNumber(first)) return first;\n if (typeof first !== \"string\" || first.trim() === \"\") return undefined;\n return toFiniteOrEmpty(Number(first));\n }\n case \"fixed\": {\n if (!isFiniteNumber(first)) return undefined;\n const digits = isFiniteNumber(second) ? Math.max(0, Math.min(10, Math.trunc(second))) : 0;\n return first.toFixed(digits);\n }\n case \"percent\": {\n if (!isFiniteNumber(first) || !isFiniteNumber(second) || second === 0) return undefined;\n const digits = isFiniteNumber(third) ? Math.max(0, Math.min(10, Math.trunc(third))) : 0;\n const factor = 10 ** digits;\n return toFiniteOrEmpty(Math.round((first / second) * 100 * factor) / factor);\n }\n default:\n return undefined;\n }\n }\n}\n\nexport type ExpressionEvaluationResult =\n | { ok: true; value: ExpressionValue }\n | { ok: false; errorCode: ExpressionErrorCode; message: string };\n\n/** Compiles (cached) and evaluates one expression; never throws. */\nexport const evaluateExpression = (\n source: string,\n resolveName: ExpressionNameResolver,\n budget: ExpressionBudget,\n): ExpressionEvaluationResult => {\n const compiled = compileExpression(source, budget.budgets.maxExpressionAstNodes);\n if (!compiled.ok) return { ok: false, errorCode: \"INVALID_EXPRESSION\", message: compiled.error };\n try {\n return { ok: true, value: new ExpressionEvaluator(budget, resolveName).evaluateValue(compiled.ast, new Map()) };\n } catch (error) {\n if (error instanceof ExpressionBudgetExceededError)\n return { ok: false, errorCode: \"BUDGET_EXCEEDED\", message: error.message };\n return {\n ok: false,\n errorCode: \"INVALID_EXPRESSION\",\n message: error instanceof Error ? error.message : \"evaluation failed\",\n };\n }\n};\n\nexport interface ComputedValuesResult {\n values: Record<string, ExpressionValue>;\n errors: Record<string, { errorCode: ExpressionErrorCode; message: string }>;\n}\n\n/**\n * Every computed value of a tree for one state: each expression evaluated once, in dependency order (a computed value\n * may read state, datasets and other computed values), under ONE budget. A cycle or a dependency chain deeper than\n * `maxComputedDependencyDepth` leaves the values involved empty with `INVALID_EXPRESSION`.\n */\nexport const computeComposedViewValues = (\n computed: Record<string, string>,\n state: Record<string, ExpressionValue>,\n datasets: Record<string, ExpressionValue>,\n budgets: ComposedViewBudgets,\n): ComputedValuesResult => {\n const budget = new ExpressionBudget(budgets);\n const result: ComputedValuesResult = { values: {}, errors: {} };\n const evaluating: string[] = [];\n const done = new Set<string>();\n\n const resolveTreeName = (name: string): ExpressionValue => {\n if (Object.prototype.hasOwnProperty.call(state, name)) return state[name];\n if (Object.prototype.hasOwnProperty.call(datasets, name)) return datasets[name];\n if (Object.prototype.hasOwnProperty.call(computed, name)) return computeOne(name);\n return undefined;\n };\n\n const computeOne = (name: string): ExpressionValue => {\n if (done.has(name)) return result.values[name];\n if (evaluating.includes(name)) {\n for (const cycleName of evaluating.slice(evaluating.indexOf(name))) {\n result.errors[cycleName] = {\n errorCode: \"INVALID_EXPRESSION\",\n message: `a cycle: ${[...evaluating, name].join(\" → \")}`,\n };\n }\n return undefined;\n }\n if (evaluating.length >= budgets.maxComputedDependencyDepth) {\n result.errors[name] = {\n errorCode: \"INVALID_EXPRESSION\",\n message: `deeper than ${budgets.maxComputedDependencyDepth} computed values`,\n };\n return undefined;\n }\n evaluating.push(name);\n const evaluation = evaluateExpression(computed[name], resolveTreeName, budget);\n evaluating.pop();\n done.add(name);\n if (result.errors[name]) {\n result.values[name] = undefined;\n return undefined;\n }\n if (!evaluation.ok) {\n result.errors[name] = { errorCode: evaluation.errorCode, message: evaluation.message };\n result.values[name] = undefined;\n return undefined;\n }\n result.values[name] = evaluation.value;\n return evaluation.value;\n };\n\n for (const name of Object.keys(computed)) computeOne(name);\n return result;\n};\n\n/** The tree names a computed expression reads, for its dependency list (empty when it does not compile). */\nexport const findExpressionDependencies = (source: string, maxAstNodes: number): string[] => {\n const compiled = compileExpression(source, maxAstNodes);\n return compiled.ok ? [...collectExpressionNames(compiled.ast)] : [];\n};\n","import { useCallback, useMemo, useReducer, useRef } from \"react\";\nimport type { ComposedViewBudgets } from \"./composed-node-schema\";\nimport type { ComposedViewTree } from \"./composed-view-tree\";\n\n/**\n * The local state of one `ComposedView` instance: initialised from the tree's `state`, changed only by\n * the tree's own inputs (`onChange: {\"set\": …}`) and the `resetState` action — never written anywhere, so a replayed\n * message's inputs stay usable. Budgets: a string longer than `maxStateStringLength` is cut, a name the tree did\n * not declare is ignored, and at most `maxInputUpdatesPerSecond` updates per second are applied (a dragged slider\n * cannot flood the evaluator). A new tree (the payload changed under the same instance) starts from its own state.\n */\n\nexport type ComposedViewStateValue = string | number | boolean | null;\n\ntype StateValues = Record<string, ComposedViewStateValue>;\n\n/** The values with the tree state they started from — a NEW tree (another payload) starts again from its own state. */\ninterface StateBox {\n initialState: StateValues;\n values: StateValues;\n}\n\ntype StateAction =\n | { kind: \"set\"; name: string; value: ComposedViewStateValue; initialState: StateValues }\n | { kind: \"reset\"; initialState: StateValues };\n\n/** The values for `initialState`: the box's while it still belongs to that tree, else the tree's own initial state. */\nconst valuesOfTree = (stateBox: StateBox, initialState: StateValues): StateValues =>\n stateBox.initialState === initialState ? stateBox.values : initialState;\n\nconst stateReducer = (stateBox: StateBox, action: StateAction): StateBox => {\n const { initialState } = action;\n if (action.kind === \"reset\") return { initialState, values: initialState };\n const currentValues = valuesOfTree(stateBox, initialState);\n if (!Object.prototype.hasOwnProperty.call(initialState, action.name)) return { initialState, values: currentValues };\n if (currentValues[action.name] === action.value) return { initialState, values: currentValues };\n return { initialState, values: { ...currentValues, [action.name]: action.value } };\n};\n\nexport interface ComposedViewStateStore {\n state: Record<string, ComposedViewStateValue>;\n setStateValue: (name: string, value: unknown) => void;\n resetState: () => void;\n}\n\nconst toStateValue = (value: unknown, budgets: ComposedViewBudgets): ComposedViewStateValue | undefined => {\n if (typeof value === \"string\") return [...value].slice(0, budgets.maxStateStringLength).join(\"\");\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value === \"boolean\" || value === null) return value;\n return undefined;\n};\n\nexport const useComposedViewState = (tree: ComposedViewTree, budgets: ComposedViewBudgets): ComposedViewStateStore => {\n const initialState = tree.state;\n const [stateBox, dispatch] = useReducer(stateReducer, { initialState, values: initialState });\n const state = valuesOfTree(stateBox, initialState);\n const updateTimestamps = useRef<number[]>([]);\n\n const setStateValue = useCallback(\n (name: string, value: unknown) => {\n const stateValue = toStateValue(value, budgets);\n if (stateValue === undefined) return;\n const now = Date.now();\n updateTimestamps.current = updateTimestamps.current.filter((timestamp) => now - timestamp < 1000);\n if (updateTimestamps.current.length >= budgets.maxInputUpdatesPerSecond) return;\n updateTimestamps.current.push(now);\n dispatch({ kind: \"set\", name, value: stateValue, initialState });\n },\n [budgets, initialState],\n );\n const resetState = useCallback(() => dispatch({ kind: \"reset\", initialState }), [initialState]);\n\n return useMemo(() => ({ state, setStateValue, resetState }), [state, setStateValue, resetState]);\n};\n","import type { ExpressionValue } from \"./expression/evaluate-expression\";\nimport { JsonValue, readComposedViewBinding, readComposedViewRowField } from \"./composed-view-tree\";\n\n/**\n * Turns bound props and datasets of a `ComposedView` tree into values. A binding is resolved in the\n * browser from what the tree already holds: `$state` (the instance state), `$computed` (the evaluated expressions),\n * `$data` (a dataset), `$item` (a field of the current row of an item scope — a dotted `author.name` reads a nested\n * object, `readComposedViewRowField`), `$from` (the snapshot the backend writes INTO the\n * binding when the row is stored — `{\"$from\": {\"toolCall\", \"path\", \"state\": \"resolved\", \"value\": …}}`;\n * before that the binding is `pending`) and `$source` (a registered data source the frontend hydrates through the\n * widget-hydration mechanism, `composed-view-data-sources.ts`; looked up by its binding key, `pending` until the rows\n * arrive). A value that does not resolve is `undefined` and the prop renders empty.\n */\n\nexport type ResolvedBindingStatus = \"resolved\" | \"pending\" | \"failed\";\n\nexport interface ComposedViewValueScope {\n state: Record<string, ExpressionValue>;\n computed: Record<string, ExpressionValue>;\n datasets: Record<string, ExpressionValue>;\n /**\n * Each dataset's binding status (`resolveComposedViewDatasets().statusByDatasetName`): a prop bound with `$data` to a\n * dataset whose `$from` / `$source` is still pending is pending itself, exactly like a direct `$from` binding.\n */\n datasetStatuses?: Record<string, ResolvedBindingStatus>;\n /** The current row of the innermost item scope (`Repeat`), when inside one. */\n item?: ExpressionValue;\n /** The hydrated `$source` values, by binding key (`composedViewSourceBindingKey`). */\n sources?: Record<string, ComposedViewSourceValue>;\n}\n\nexport interface ComposedViewSourceValue {\n status: ResolvedBindingStatus;\n value: ExpressionValue;\n}\n\n/** The identity of a `$source` wire value — its name and parameters as written; null for another value. */\nexport const composedViewSourceBindingKey = (wireValue: unknown): string | null => {\n const binding = readComposedViewBinding(wireValue);\n if (binding === null || binding.kind !== \"source\" || !binding.isWellFormed) return null;\n return `${binding.target}|${JSON.stringify(binding.sourceParams)}`;\n};\n\nconst readSourceValue = (\n wireValue: unknown,\n sourceValuesByBindingKey: Record<string, ComposedViewSourceValue> | undefined,\n): ComposedViewSourceValue => {\n const bindingKey = composedViewSourceBindingKey(wireValue);\n if (bindingKey === null) return { status: \"failed\", value: undefined };\n return sourceValuesByBindingKey?.[bindingKey] ?? { status: \"pending\", value: undefined };\n};\n\nexport interface ResolvedComposedViewDatasets {\n datasets: Record<string, ExpressionValue>;\n statusByDatasetName: Record<string, ResolvedBindingStatus>;\n}\n\nconst hasOwn = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key);\n\n/** The value and status a `$from` binding's stored snapshot carries. */\nexport const readFromBindingSnapshot = (\n fromBindingObject: Record<string, unknown>,\n): { status: ResolvedBindingStatus; value: ExpressionValue } => {\n const snapshotState = fromBindingObject.state;\n if (snapshotState === \"resolved\") return { status: \"resolved\", value: fromBindingObject.value as ExpressionValue };\n if (snapshotState === \"failed\") return { status: \"failed\", value: undefined };\n return { status: \"pending\", value: undefined };\n};\n\n/**\n * The tree's datasets as values: inline rows as written, `$from` from its snapshot, `$source` from\n * `sourceValuesByBindingKey` (filled by the data-source hydration; pending without).\n */\nexport const resolveComposedViewDatasets = (\n data: Record<string, JsonValue>,\n sourceValuesByBindingKey: Record<string, ComposedViewSourceValue> = {},\n): ResolvedComposedViewDatasets => {\n const resolved: ResolvedComposedViewDatasets = { datasets: {}, statusByDatasetName: {} };\n for (const [datasetName, dataset] of Object.entries(data)) {\n const binding = readComposedViewBinding(dataset);\n if (binding === null) {\n resolved.datasets[datasetName] = dataset as ExpressionValue;\n resolved.statusByDatasetName[datasetName] = \"resolved\";\n continue;\n }\n const snapshot =\n binding.kind === \"from\"\n ? readFromBindingSnapshot((binding.wireValue.$from ?? {}) as Record<string, unknown>)\n : readSourceValue(dataset, sourceValuesByBindingKey);\n resolved.datasets[datasetName] = snapshot.value;\n resolved.statusByDatasetName[datasetName] = snapshot.status;\n }\n return resolved;\n};\n\n/** One prop value with its bindings resolved (nested bindings in inline data included). */\nexport const resolveComposedViewValue = (\n wireValue: JsonValue | undefined,\n scope: ComposedViewValueScope,\n onBindingStatus?: (status: ResolvedBindingStatus) => void,\n): ExpressionValue => {\n const binding = readComposedViewBinding(wireValue);\n if (binding !== null) {\n switch (binding.kind) {\n case \"state\":\n return hasOwn(scope.state, binding.target) ? scope.state[binding.target] : undefined;\n case \"computed\":\n return hasOwn(scope.computed, binding.target) ? scope.computed[binding.target] : undefined;\n case \"data\": {\n const datasetStatus = scope.datasetStatuses?.[binding.target];\n if (datasetStatus !== undefined) onBindingStatus?.(datasetStatus);\n return hasOwn(scope.datasets, binding.target) ? scope.datasets[binding.target] : undefined;\n }\n case \"item\": {\n const rowField = readComposedViewRowField(scope.item, binding.target);\n return rowField.found ? (rowField.value as ExpressionValue) : undefined;\n }\n case \"from\": {\n const snapshot = readFromBindingSnapshot((binding.wireValue.$from ?? {}) as Record<string, unknown>);\n onBindingStatus?.(snapshot.status);\n return snapshot.value;\n }\n case \"source\": {\n const sourceValue = readSourceValue(wireValue, scope.sources);\n onBindingStatus?.(sourceValue.status);\n return sourceValue.value;\n }\n default:\n onBindingStatus?.(\"pending\");\n return undefined;\n }\n }\n if (Array.isArray(wireValue))\n return wireValue.map((element) => resolveComposedViewValue(element, scope, onBindingStatus));\n if (typeof wireValue === \"object\" && wireValue !== null) {\n return Object.fromEntries(\n Object.entries(wireValue).map(([key, nested]) => [key, resolveComposedViewValue(nested, scope, onBindingStatus)]),\n );\n }\n return wireValue;\n};\n","import { registerWidgetHydrator } from \"../widget-hydration\";\nimport { getComposedNodeSchema, ComposedNodeSchema } from \"./composed-node-schema\";\nimport {\n ComposedViewNode,\n ComposedViewTree,\n getComposedViewSubtreeNodes,\n JsonValue,\n readComposedViewBinding,\n} from \"./composed-view-tree\";\nimport type { ExpressionValue } from \"./expression/evaluate-expression\";\nimport { composedViewSourceBindingKey } from \"./resolve-composed-view-values\";\n\n/**\n * The frontend side of the `$source` data path: a registered source is read through the existing\n * widget-hydration mechanism (`widget-hydration/`), so the e-mail capture waits for it like for any self-hydrating\n * widget. A source is added with TWO files: the backend `<Name>ComposedViewDataSource` (endpoint, params,\n * columns — exported into the schema) and the frontend fetcher `<name>.composed-data-source.ts` anywhere below\n * `widgets/` exporting `composedViewDataSourceFetcher` (it reads the endpoint through the generated SDK store and returns\n * the response; the rows are taken at the schema's `rowsPath`). The read rights are the endpoint's own entity rights,\n * server-side — the fetcher passes the agent space key and the parameters, nothing else.\n */\n\nexport interface ComposedViewDataSourceFetcher {\n /** The source name (the backend `NAME`). */\n name: string;\n /** Reads the source for an agent space and the resolved parameters; resolves with the endpoint's response. */\n fetchResponse: (\n params: Record<string, ExpressionValue>,\n agentSpaceKey: number | undefined,\n signal: AbortSignal,\n ) => Promise<unknown>;\n}\n\nexport interface ComposedViewDataSourcePayload {\n params: Record<string, ExpressionValue>;\n agentSpaceKey: number | undefined;\n}\n\n/** The hydration type a source registers under. */\nexport const composedViewDataSourceHydrationType = (dataSourceName: string): string =>\n `ComposedViewDataSource:${dataSourceName}`;\n\n/** The rows at a schema `rowsPath` (`$`, `$.field`, `$.a.b`) of a response; undefined when the path does not hold a list. */\nexport const readRowsAtPath = (response: unknown, rowsPath: string): ExpressionValue[] | undefined => {\n let current: unknown = response;\n for (const segment of rowsPath\n .replace(/^\\$\\.?/, \"\")\n .split(\".\")\n .filter(Boolean)) {\n if (typeof current !== \"object\" || current === null || !Object.prototype.hasOwnProperty.call(current, segment)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return Array.isArray(current) ? (current as ExpressionValue[]) : undefined;\n};\n\nconst registeredFetcherNames = new Set<string>();\n\n/** Registers a fetcher as a widget hydrator; the rows land in the hydration memory like any widget's data. */\nexport const registerComposedViewDataSourceFetcher = (\n fetcher: ComposedViewDataSourceFetcher,\n schema: ComposedNodeSchema = getComposedNodeSchema(),\n): void => {\n const dataSourceSchema = schema.dataSources?.[fetcher.name];\n registeredFetcherNames.add(fetcher.name);\n registerWidgetHydrator<ComposedViewDataSourcePayload, ExpressionValue[]>(\n composedViewDataSourceHydrationType(fetcher.name),\n {\n hydrator: async (payload, context) => {\n const response = await fetcher.fetchResponse(payload.params, payload.agentSpaceKey, context.signal);\n const rows = readRowsAtPath(response, dataSourceSchema?.rowsPath ?? \"$\");\n if (rows === undefined)\n throw new Error(`the data source \"${fetcher.name}\" returned no rows at ${dataSourceSchema?.rowsPath ?? \"$\"}`);\n return rows.slice(0, schema.budgets.maxCollectionItems);\n },\n deriveKey: (type, payload) => `${type}:${payload.agentSpaceKey ?? \"active\"}:${JSON.stringify(payload.params)}`,\n staleMs: (dataSourceSchema?.freshnessSeconds ?? 300) * 1000,\n },\n );\n};\n\n/** Whether a fetcher is registered for a source name. */\nexport const hasComposedViewDataSourceFetcher = (dataSourceName: string): boolean =>\n registeredFetcherNames.has(dataSourceName);\n\nconst fetcherModules = import.meta.glob<{ composedViewDataSourceFetcher?: ComposedViewDataSourceFetcher }>(\n [\"../../widgets/**/*.composed-data-source.ts\", \"../../kit/**/*.composed-data-source.ts\"],\n { eager: true },\n);\nfor (const fetcherModule of Object.values(fetcherModules)) {\n if (fetcherModule.composedViewDataSourceFetcher)\n registerComposedViewDataSourceFetcher(fetcherModule.composedViewDataSourceFetcher);\n}\n\n/** One `$source` binding of a tree, with its parameters as written (`$state` bindings inside). */\nexport interface ComposedViewSourceBinding {\n /** The binding's identity in the tree: name + parameters as written. */\n bindingKey: string;\n dataSourceName: string;\n writtenParams: Record<string, JsonValue>;\n}\n\nconst collectFromValue = (value: unknown, sourceBindings: Map<string, ComposedViewSourceBinding>): void => {\n const binding = readComposedViewBinding(value);\n if (binding !== null) {\n const bindingKey = composedViewSourceBindingKey(value);\n if (bindingKey !== null && !sourceBindings.has(bindingKey)) {\n sourceBindings.set(bindingKey, {\n bindingKey,\n dataSourceName: binding.target,\n writtenParams: binding.sourceParams as Record<string, JsonValue>,\n });\n }\n return;\n }\n if (Array.isArray(value)) value.forEach((element) => collectFromValue(element, sourceBindings));\n else if (typeof value === \"object\" && value !== null)\n Object.values(value).forEach((nested) => collectFromValue(nested, sourceBindings));\n};\n\n/** Every distinct `$source` binding of a tree — its datasets and every node's props — in tree order. */\nexport const collectComposedViewSourceBindings = (tree: ComposedViewTree): ComposedViewSourceBinding[] => {\n const sourceBindings = new Map<string, ComposedViewSourceBinding>();\n collectFromValue(tree.data, sourceBindings);\n const nodes: ComposedViewNode[] = tree.view ? getComposedViewSubtreeNodes(tree.view) : [];\n for (const node of nodes) collectFromValue(node.props, sourceBindings);\n return [...sourceBindings.values()];\n};\n\n/** The parameters with their `$state` bindings resolved against the instance state. */\nexport const resolveComposedViewSourceParams = (\n writtenParams: Record<string, JsonValue>,\n state: Record<string, ExpressionValue>,\n): Record<string, ExpressionValue> =>\n Object.fromEntries(\n Object.entries(writtenParams).map(([paramName, paramValue]) => {\n const paramBinding = readComposedViewBinding(paramValue);\n if (paramBinding?.kind === \"state\") {\n return [\n paramName,\n Object.prototype.hasOwnProperty.call(state, paramBinding.target) ? state[paramBinding.target] : undefined,\n ];\n }\n return [paramName, paramValue as ExpressionValue];\n }),\n );\n","import type { ComponentType } from \"react\";\nimport ReactApexChartImport from \"react-apexcharts\";\nimport type { Props as ReactApexChartProps } from \"react-apexcharts\";\n\n/**\n * The `react-apexcharts` component, whatever the bundler made of its CommonJS export: the app build hands the\n * component itself, the Storybook / preview Vite dev server the module object with the component on `default`\n * (rendering that object throws \"Element type is invalid … got: object\").\n */\nconst moduleWithDefault = ReactApexChartImport as unknown as { default?: ComponentType<ReactApexChartProps> };\n\nexport const ApexChart: ComponentType<ReactApexChartProps> =\n moduleWithDefault.default ?? (ReactApexChartImport as unknown as ComponentType<ReactApexChartProps>);\n","/**\n * The ONE tone list of the composable kit (the backend twin is `ComposedViewTone.php`):\n * the judgement or role a text, a badge, a value, an icon or a map status line takes. Every node with a `tone` prop\n * reads it through {@link readComposedViewTone}, so a model that learned one word uses it everywhere. The words some\n * nodes accepted before the list existed stay accepted on the wire (both tree readers list them as allowed values) and\n * read as their tone here: `default` (Text) is `neutral`, `positive` / `negative` (Map status lines) are `success` /\n * `danger`.\n */\nexport const COMPOSED_VIEW_TONES = [\"neutral\", \"muted\", \"success\", \"warning\", \"danger\", \"info\"] as const;\n\nexport type ComposedViewTone = (typeof COMPOSED_VIEW_TONES)[number];\n\n/** The older words, accepted on the wire and read as their tone. */\nexport const COMPOSED_VIEW_TONE_ALIASES: Readonly<Record<string, ComposedViewTone>> = {\n default: \"neutral\",\n positive: \"success\",\n negative: \"danger\",\n};\n\nconst isComposedViewTone = (value: string): value is ComposedViewTone =>\n (COMPOSED_VIEW_TONES as readonly string[]).includes(value);\n\n/** The tone a prop names — one of the list or an alias — else `fallback` (a bound value may hold anything). */\nexport const readComposedViewTone = (value: unknown, fallback: ComposedViewTone = \"neutral\"): ComposedViewTone => {\n if (typeof value !== \"string\") return fallback;\n if (isComposedViewTone(value)) return value;\n return Object.prototype.hasOwnProperty.call(COMPOSED_VIEW_TONE_ALIASES, value)\n ? COMPOSED_VIEW_TONE_ALIASES[value]\n : fallback;\n};\n\n/** The tone a prop names, or `undefined` when it names none (a status line without a tone stays plain). */\nexport const readOptionalComposedViewTone = (value: unknown): ComposedViewTone | undefined =>\n typeof value === \"string\" && (isComposedViewTone(value) || value in COMPOSED_VIEW_TONE_ALIASES)\n ? readComposedViewTone(value)\n : undefined;\n\n/** The text colour of a tone, for the component library's `Text`'s `color` prop — judgement text in the 900 step (500 on dark). */\nexport const COMPOSED_VIEW_TONE_TEXT_COLOR: Readonly<Record<ComposedViewTone, string>> = {\n neutral: \"var(--agents-fg)\",\n muted: \"var(--agents-fg-light)\",\n success: \"light-dark(var(--agents-success-900), var(--agents-success-500))\",\n warning: \"light-dark(var(--agents-warning-900), var(--agents-warning-500))\",\n danger: \"light-dark(var(--agents-danger-900), var(--agents-danger-500))\",\n info: \"light-dark(var(--agents-info-900), var(--agents-info-500))\",\n};\n\n/** The graphic colour of a tone — an icon fill in the 500 step. */\nexport const COMPOSED_VIEW_TONE_GRAPHIC_COLOR: Readonly<Record<ComposedViewTone, string>> = {\n neutral: \"var(--agents-fg)\",\n muted: \"var(--agents-fg-light)\",\n success: \"var(--agents-success-500)\",\n warning: \"var(--agents-warning-500)\",\n danger: \"var(--agents-danger-500)\",\n info: \"var(--agents-info-500)\",\n};\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n ComposedViewTone,\n readComposedViewTone,\n} from \"../../composed-view-tones\";\n\n/**\n * How the data nodes show a value — the frontend twin of `ComposedViewDataValueFormat.php`: the\n * closed `format`, `tone` and `align` words every data node accepts, and the one formatter they all use, so a number\n * reads the same in a KPI tile, a table cell and a chart axis. Pure functions, no React.\n */\n\nexport type DataValueFormat = \"number\" | \"percent\" | \"currency\" | \"compact\" | \"date\" | \"text\";\n/** The kit's one tone list (`composed-view-tones.ts`). */\nexport type DataValueTone = ComposedViewTone;\nexport type DataValueAlign = \"start\" | \"center\" | \"end\";\n\nconst DATA_VALUE_FORMATS: readonly DataValueFormat[] = [\"number\", \"percent\", \"currency\", \"compact\", \"date\", \"text\"];\nconst DATA_VALUE_ALIGNS: readonly DataValueAlign[] = [\"start\", \"center\", \"end\"];\n\n/** The value as one of `allowed`, or `fallback` (a resolved binding may carry anything). */\nconst readOneOf = <T extends string>(value: unknown, allowed: readonly T[], fallback: T): T =>\n typeof value === \"string\" && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;\n\nexport const readDataValueFormat = (value: unknown, fallback: DataValueFormat = \"number\"): DataValueFormat =>\n readOneOf(value, DATA_VALUE_FORMATS, fallback);\nexport const readDataValueTone = (value: unknown, fallback: DataValueTone = \"neutral\"): DataValueTone =>\n readComposedViewTone(value, fallback);\nexport const readDataValueAlign = (value: unknown, fallback: DataValueAlign = \"start\"): DataValueAlign =>\n readOneOf(value, DATA_VALUE_ALIGNS, fallback);\n\n/** A finite number from a number or a numeric string (\"1207\", \"36.5\"); undefined otherwise. */\nexport const readFiniteNumber = (value: unknown): number | undefined => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value === \"string\" && value.trim() !== \"\" && /^[-+]?\\d*\\.?\\d+(e[-+]?\\d+)?$/i.test(value.trim())) {\n const parsed = Number(value.trim());\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n};\n\n/** A string prop, or undefined (a binding resolved to a non-string, an absent prop). */\nexport const readText = (value: unknown): string | undefined =>\n typeof value === \"string\" && value !== \"\" ? value : typeof value === \"number\" ? String(value) : undefined;\n\n/** The plain object a resolved prop holds, or undefined. */\nexport const readObject = (value: unknown): Record<string, ExpressionValue> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, ExpressionValue>)\n : undefined;\n\n/** The rows (plain objects) a resolved `data` / `rows` / `items` prop holds; non-object entries are skipped. */\nexport const readRows = (value: unknown): Record<string, ExpressionValue>[] | undefined =>\n Array.isArray(value)\n ? value.filter(\n (row): row is Record<string, ExpressionValue> => typeof row === \"object\" && row !== null && !Array.isArray(row),\n )\n : undefined;\n\n/** The locale the numbers are written in: the app's UI language, `en` when it is unset or invalid. */\nexport const toNumberLocale = (languageCode: string | undefined): string => {\n if (!languageCode) return \"en\";\n try {\n return Intl.NumberFormat.supportedLocalesOf([languageCode.replace(\"_\", \"-\")])[0] ?? \"en\";\n } catch {\n return \"en\";\n }\n};\n\nexport interface DataValueFormatOptions {\n format?: DataValueFormat;\n currency?: string;\n decimals?: number;\n /** A unit written after the value (\"km\", \"visits\"). */\n unit?: string;\n /** A positive number gets a plus sign. */\n signed?: boolean;\n locale: string;\n}\n\nconst readCurrencyCode = (currency: string | undefined): string =>\n typeof currency === \"string\" && /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : \"EUR\";\n\nconst readFractionDigits = (decimals: number | undefined): number | undefined =>\n typeof decimals === \"number\" && Number.isInteger(decimals) && decimals >= 0 && decimals <= 6 ? decimals : undefined;\n\nconst formatNumberWithOptions = (value: number, options: DataValueFormatOptions): string => {\n const { format = \"number\", currency, decimals, signed = false, locale } = options;\n const fractionDigits = readFractionDigits(decimals);\n const signDisplay: Intl.NumberFormatOptions[\"signDisplay\"] = signed ? \"exceptZero\" : \"auto\";\n const digitOptions: Intl.NumberFormatOptions =\n fractionDigits === undefined\n ? { maximumFractionDigits: 2 }\n : { minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits };\n switch (format) {\n case \"currency\":\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: readCurrencyCode(currency),\n signDisplay,\n ...(fractionDigits === undefined\n ? {\n minimumFractionDigits: 0,\n maximumFractionDigits: Number.isInteger(value) || Math.abs(value) >= 1000 ? 0 : 2,\n }\n : digitOptions),\n }).format(value);\n case \"percent\":\n // The value IS the percentage (36 → 36 %); Intl's percent style would multiply by 100.\n return `${new Intl.NumberFormat(locale, { signDisplay, ...digitOptions }).format(value)} %`;\n case \"compact\":\n return new Intl.NumberFormat(locale, {\n notation: \"compact\",\n signDisplay,\n maximumFractionDigits: fractionDigits ?? 1,\n }).format(value);\n default:\n return new Intl.NumberFormat(locale, { signDisplay, ...digitOptions }).format(value);\n }\n};\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(T[\\d:.]+(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\nconst formatDate = (value: string, locale: string): string | undefined => {\n if (!ISO_DATE.test(value)) return undefined;\n const date = new Date(value.length === 10 ? `${value}T00:00:00` : value);\n if (Number.isNaN(date.getTime())) return undefined;\n return new Intl.DateTimeFormat(locale, { day: \"numeric\", month: \"short\", year: \"numeric\" }).format(date);\n};\n\n/**\n * One value as the owner reads it: a number in the locale and `format`, a date in the locale's short form, text as\n * written; the `unit` after it. `undefined` / `null` give the empty string (the caller decides what an empty cell\n * shows); a boolean gives an empty string too — a table shows a boolean as an `Icon`, never as \"true\".\n */\nexport const formatDataValue = (value: unknown, options: DataValueFormatOptions): string => {\n const { format = \"number\", unit, locale } = options;\n let formatted: string;\n const numericValue = format === \"text\" ? undefined : readFiniteNumber(value);\n if (numericValue !== undefined && format !== \"date\") {\n formatted = formatNumberWithOptions(numericValue, options);\n } else if (typeof value === \"string\") {\n formatted = format === \"date\" ? (formatDate(value, locale) ?? value) : value;\n } else if (typeof value === \"number\") {\n formatted = String(value);\n } else {\n return \"\";\n }\n return unit ? `${formatted} ${unit}` : formatted;\n};\n\n/** Whether `value` reads as a number — numeric columns and cells align at the end. */\nexport const isNumericValue = (value: unknown): boolean => readFiniteNumber(value) !== undefined;\n\n/** A value clamped to 0..1, or undefined (the `bar` and `heat` props). */\nexport const readFraction = (value: unknown): number | undefined => {\n const numericValue = readFiniteNumber(value);\n if (numericValue === undefined) return undefined;\n return Math.min(1, Math.max(0, numericValue));\n};\n","import { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ApexOptions } from \"apexcharts\";\nimport type { ComposedSizeClass } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n DataValueFormat,\n DataValueTone,\n formatDataValue,\n readDataValueFormat,\n readFiniteNumber,\n readObject,\n readRows,\n readText,\n} from \"./data-value-format\";\n\n/**\n * The `Chart` node's props turned into ApexCharts input — pure, so the spec checks what reaches the\n * chart library without drawing it. Every value goes through `formatDataValue`, so the axis, the tooltip and a KPI\n * tile write the same number the same way.\n */\n\nexport type ChartKind = \"line\" | \"area\" | \"bar\" | \"pie\" | \"donut\" | \"scatter\" | \"heatmap\" | \"funnel\" | \"radar\";\n\nconst CHART_KINDS: readonly ChartKind[] = [\n \"line\",\n \"area\",\n \"bar\",\n \"pie\",\n \"donut\",\n \"scatter\",\n \"heatmap\",\n \"funnel\",\n \"radar\",\n];\n\nexport interface ChartSeriesDeclaration {\n field: string;\n label: string;\n /** The model wrote the label — a single named series gets its legend entry (ChatGPT's \"MRR\"). */\n hasExplicitLabel: boolean;\n}\n\n/** The theme colours the chart draws with, resolved from the `--agents-*` tokens at render time. */\nexport interface ChartPalette {\n seriesColors: string[];\n axisTextColor: string;\n /** The main text colour, for the total in a donut's middle. */\n textColor: string;\n gridColor: string;\n surfaceColor: string;\n}\n\nexport interface ChartModel {\n kind: ChartKind;\n apexType: \"line\" | \"area\" | \"bar\" | \"pie\" | \"donut\" | \"scatter\" | \"heatmap\" | \"radar\";\n series: ApexAxisChartSeries | ApexNonAxisChartSeries;\n options: ApexOptions;\n height: number;\n /** The plotted series names, for the accessible label. */\n seriesLabels: string[];\n}\n\nexport type ChartModelResult =\n | { status: \"ok\"; model: ChartModel }\n | { status: \"empty\"; detail: string }\n | { status: \"invalid\"; detail: string };\n\nexport interface ChartModelInput {\n props: Record<string, ExpressionValue>;\n sizeClass: ComposedSizeClass;\n locale: string;\n palette: ChartPalette;\n isEmailRender: boolean;\n /** The measured width of the plot in px (0 before the first measurement): a narrow plot gets fewer numeric ticks. */\n plotWidth?: number;\n}\n\nconst APEX_HTML_ENTITIES: Record<string, string> = { \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&#39;\" };\n\n/**\n * A plain text as ApexCharts' legend and tooltip take it: they write their texts as HTML, so the characters that open\n * markup or an attribute are escaped here, whatever the host does to the texts of its own components.\n */\nconst escapeApexHtml = (text: string): string =>\n text.replace(/[&<>\"']/g, (character) => APEX_HTML_ENTITIES[character]);\n\n/** Below this plot width a numeric category axis (a scatter's) gets about three ticks instead of five. */\nconst NARROW_PLOT_WIDTH = 320;\n\nconst HEIGHT_BY_SIZE_CLASS: Record<ComposedSizeClass, number> = { compact: 40, regular: 280, full: 320 };\n\n/** What a per-bar change counts (`ChartComposedViewNode::DELTA_UNITS`): percentage points or percent. */\nexport type ChartDeltaUnit = \"pp\" | \"%\";\n\nconst CHART_DELTA_UNITS: readonly ChartDeltaUnit[] = [\"pp\", \"%\"];\n\n/** The theme's series colour tokens, one per bar of a single-series bar chart (the distributed colours). */\nexport const CHART_SERIES_COLOR_TOKENS = [\n \"--agents-chart-01\",\n \"--agents-chart-02\",\n \"--agents-chart-03\",\n \"--agents-chart-04\",\n \"--agents-chart-05\",\n \"--agents-chart-06\",\n \"--agents-chart-07\",\n \"--agents-chart-08\",\n] as const;\n\n/** One bar of a bar chart with a change per bar. */\nexport interface ChartBarRow {\n label: string;\n valueText: string;\n /** The filled part of the track, 0 to 1. */\n fraction: number;\n /** The colour token of the bar (`--agents-chart-0N`). */\n colorToken: string;\n /** The signed change (\"+2\", \"-3\", \"0\"); undefined when the row has no number in the delta field. */\n deltaText?: string;\n /** Plus green, minus red, zero (and no change) muted. */\n deltaTone: DataValueTone;\n}\n\nexport interface ChartBarRowsModel {\n rows: ChartBarRow[];\n /** The plotted series' label, for the accessible label. */\n seriesLabel: string;\n deltaUnit?: ChartDeltaUnit;\n}\n\nexport type ChartBarRowsModelResult =\n | { status: \"ok\"; model: ChartBarRowsModel }\n | { status: \"empty\"; detail: string }\n | { status: \"invalid\"; detail: string };\n\n/** The row field of the change per bar — set on a bar chart only (another kind ignores it). */\nexport const readChartDeltaField = (props: Record<string, ExpressionValue>): string | undefined =>\n readChartKind(props.kind) === \"bar\" ? readText(props.deltaField) : undefined;\n\nexport const readChartDeltaUnit = (value: unknown): ChartDeltaUnit | undefined =>\n CHART_DELTA_UNITS.find((deltaUnit) => deltaUnit === value);\n\n/** The tone of a change by its sign: a rise green, a fall red, no change muted. */\nexport const readChartDeltaTone = (delta: number | undefined): DataValueTone =>\n delta === undefined || delta === 0 ? \"muted\" : delta > 0 ? \"success\" : \"danger\";\n\n/**\n * A bar chart with a change per bar (`deltaField`): one horizontal bar per row of the first plotted\n * series on a track, its value at the right, the signed change after it. The track's end is `max`, else the largest\n * value with a tenth of room (the longest bar never fills the track, as in the reference). A change counted in\n * percent (`deltaUnit` `%`) carries its unit; percentage points and a plain change show the figure alone — the line\n * under the bars (`deltaLabel`) says what it counts.\n */\nexport const buildChartBarRowsModel = (input: {\n props: Record<string, ExpressionValue>;\n locale: string;\n}): ChartBarRowsModelResult => {\n const { props, locale } = input;\n const rows = readRows(props.data) ?? [];\n const xField = readText(props.x) ?? \"\";\n const deltaField = readChartDeltaField(props) ?? \"\";\n const seriesDeclaration = readChartSeries(props.series).find((candidate) =>\n rows.some((row) => readFiniteNumber(row[candidate.field]) !== undefined),\n );\n if (rows.length === 0) return { status: \"empty\", detail: \"the Chart has no rows\" };\n if (!seriesDeclaration) {\n return { status: \"invalid\", detail: \"no row has a number in the Chart's series\" };\n }\n const valueFormat = readDataValueFormat(props.valueFormat);\n const currency = readText(props.currency);\n const deltaUnit = readChartDeltaUnit(props.deltaUnit);\n const plottedRows = rows\n .map((row) => ({ row, value: readFiniteNumber(row[seriesDeclaration.field]) }))\n .filter(\n (plottedRow): plottedRow is { row: (typeof rows)[number]; value: number } => plottedRow.value !== undefined,\n );\n const largestValue = Math.max(0, ...plottedRows.map((plottedRow) => plottedRow.value));\n const axisMax = readFiniteNumber(props.max) ?? largestValue * 1.1;\n return {\n status: \"ok\",\n model: {\n seriesLabel: seriesDeclaration.label,\n deltaUnit,\n rows: plottedRows.map((plottedRow, rowIndex) => {\n const delta = readFiniteNumber(plottedRow.row[deltaField]);\n return {\n label: readText(plottedRow.row[xField]) ?? \"\",\n valueText: formatDataValue(plottedRow.value, { format: valueFormat, currency, locale }),\n fraction: axisMax > 0 ? Math.min(1, Math.max(0, plottedRow.value / axisMax)) : 0,\n colorToken: CHART_SERIES_COLOR_TOKENS[rowIndex % CHART_SERIES_COLOR_TOKENS.length],\n deltaText:\n delta === undefined\n ? undefined\n : formatDataValue(delta, { format: deltaUnit === \"%\" ? \"percent\" : \"number\", signed: true, locale }),\n deltaTone: readChartDeltaTone(delta),\n };\n }),\n },\n };\n};\n\n/** One stage of a funnel chart: its bar (centered, as wide as its share of the largest stage) and its figures. */\nexport interface ChartFunnelStage {\n label: string;\n valueText: string;\n /** The bar's width, 0 to 1 of the largest stage. */\n fraction: number;\n /** The stage's value as a percentage of the stage before it (\"62 %\"); undefined for the first stage. */\n conversionText?: string;\n}\n\nexport interface ChartFunnelModel {\n stages: ChartFunnelStage[];\n /** The plotted series' label, for the accessible label. */\n seriesLabel: string;\n}\n\nexport type ChartFunnelModelResult =\n | { status: \"ok\"; model: ChartFunnelModel }\n | { status: \"empty\"; detail: string }\n | { status: \"invalid\"; detail: string };\n\n/** The narrowest bar a stage with a positive value gets, so a small last stage stays visible. */\nconst MIN_FUNNEL_BAR_FRACTION = 0.04;\n\n/**\n * A funnel chart (`kind` `funnel`): the rows are the stages of a process in their written order, the first plotted\n * series their values; each stage is a centered bar as wide as its share of the largest stage, with its value and its\n * conversion from the stage before it in percent (one decimal at most). A stage without a number is left out.\n */\n/**\n * The radius of a radar polygon that leaves room for its axis names (ApexCharts sizes the polygon by the plot alone and\n * clips a long name at the side): half the plot width minus the longest side-axis name, at most what the height\n * leaves under the names and the legend. Undefined before the plot is measured (ApexCharts' own size).\n */\nexport const readRadarRadius = (input: {\n axisNames: string[];\n plotWidth: number;\n height: number;\n fontSizePx: number;\n hasLegend: boolean;\n}): number | undefined => {\n const { axisNames, plotWidth, height, fontSizePx, hasLegend } = input;\n if (plotWidth <= 0 || axisNames.length === 0) return undefined;\n // a side axis points left or right (the top and bottom names only need a line of height)\n const sideAxisNameLengths = axisNames\n .filter((_axisName, axisIndex) => Math.abs(Math.sin((2 * Math.PI * axisIndex) / axisNames.length)) > 0.3)\n .map((axisName) => axisName.length);\n const nameRoom = Math.max(0, ...sideAxisNameLengths) * fontSizePx * 0.5 + 8;\n const heightRoom = (height - (hasLegend ? 48 : 0)) / 2 - fontSizePx * 2;\n return Math.max(40, Math.round(Math.min(plotWidth / 2 - nameRoom, heightRoom)));\n};\n\nexport const buildChartFunnelModel = (input: {\n props: Record<string, ExpressionValue>;\n locale: string;\n}): ChartFunnelModelResult => {\n const { props, locale } = input;\n const rows = readRows(props.data) ?? [];\n const xField = readText(props.x) ?? \"\";\n const seriesDeclaration = readChartSeries(props.series).find((candidate) =>\n rows.some((row) => readFiniteNumber(row[candidate.field]) !== undefined),\n );\n if (rows.length === 0) return { status: \"empty\", detail: \"the Chart has no rows\" };\n if (!seriesDeclaration) return { status: \"invalid\", detail: \"no row has a number in the Chart's series\" };\n const valueFormat = readDataValueFormat(props.valueFormat);\n const currency = readText(props.currency);\n const stageValues = rows\n .map((row) => ({ label: readText(row[xField]) ?? \"\", value: readFiniteNumber(row[seriesDeclaration.field]) }))\n .filter((stageValue): stageValue is { label: string; value: number } => stageValue.value !== undefined);\n const largestValue = Math.max(0, ...stageValues.map((stageValue) => stageValue.value));\n return {\n status: \"ok\",\n model: {\n seriesLabel: seriesDeclaration.label,\n stages: stageValues.map((stageValue, stageIndex) => {\n const previousValue = stageIndex > 0 ? stageValues[stageIndex - 1].value : undefined;\n const fraction = largestValue > 0 ? Math.min(1, Math.max(0, stageValue.value / largestValue)) : 0;\n return {\n label: stageValue.label,\n valueText: formatDataValue(stageValue.value, { format: valueFormat, currency, locale }),\n fraction: stageValue.value > 0 ? Math.max(MIN_FUNNEL_BAR_FRACTION, fraction) : 0,\n conversionText:\n previousValue !== undefined && previousValue > 0\n ? formatDataValue(Math.round((stageValue.value / previousValue) * 1000) / 10, {\n format: \"percent\",\n locale,\n })\n : undefined,\n };\n }),\n },\n };\n};\n\nexport const readChartKind = (value: unknown): ChartKind | undefined =>\n CHART_KINDS.find((chartKind) => chartKind === value);\n\n/** The visible series: entries with a string `field`; `visible: false` (often a bound state) hides one. */\nexport const readChartSeries = (seriesValue: ExpressionValue): ChartSeriesDeclaration[] => {\n if (!Array.isArray(seriesValue)) return [];\n const seriesDeclarations: ChartSeriesDeclaration[] = [];\n for (const seriesEntry of seriesValue) {\n const seriesObject = readObject(seriesEntry);\n const field = readText(seriesObject?.field) ?? readText(seriesObject?.key);\n if (!seriesObject || !field || seriesObject.visible === false) continue;\n const explicitLabel = readText(seriesObject.label);\n seriesDeclarations.push({ field, label: explicitLabel ?? field, hasExplicitLabel: explicitLabel !== undefined });\n }\n return seriesDeclarations;\n};\n\n/**\n * With both bounds written, the tick count that gives whole steps (0–45 → 3 ticks of 15); 4 otherwise.\n * Without both bounds ApexCharts picks a nice scale itself (undefined).\n */\nconst readTickAmountForBounds = (axisMin: number | undefined, axisMax: number | undefined): number | undefined => {\n if (axisMin === undefined || axisMax === undefined || axisMax <= axisMin) return undefined;\n return [3, 4, 5].find((tickAmount) => Number.isInteger((axisMax - axisMin) / tickAmount)) ?? 4;\n};\n\n/** The largest plotted number of axis series (0 when none). */\nconst readLargestValue = (series: ApexAxisChartSeries): number =>\n Math.max(\n 0,\n ...series.flatMap((seriesEntry) =>\n (seriesEntry.data as unknown[]).filter((value): value is number => typeof value === \"number\"),\n ),\n );\n\n/** A step of 1, 2, 2.5 or 5 times a power of ten that is at least `roughStep` — the steps an axis reads naturally. */\nconst readNiceStep = (roughStep: number): number => {\n const magnitude = 10 ** Math.floor(Math.log10(roughStep));\n return ([1, 2, 2.5, 5, 10].find((factor) => factor * magnitude >= roughStep) ?? 10) * magnitude;\n};\n\n/**\n * Round bounds and the tick count for a numeric axis over `values` (ChatGPT's scatter: 900 … 1500 in steps of\n * 150, never 980, 1076, 1172): the bounds snap outward to whole steps of about `targetTickAmount` ticks.\n */\nexport const readNiceAxisBounds = (\n values: number[],\n targetTickAmount: number,\n): { min: number; max: number; tickAmount: number } | undefined => {\n if (values.length === 0) return undefined;\n const smallestValue = Math.min(...values);\n const largestValue = Math.max(...values);\n if (smallestValue === largestValue) return undefined;\n const step = readNiceStep((largestValue - smallestValue) / targetTickAmount);\n const min = Math.floor(smallestValue / step) * step;\n const max = Math.ceil(largestValue / step) * step;\n return { min, max, tickAmount: Math.round((max - min) / step) };\n};\n\nconst buildValueFormatter =\n (format: DataValueFormat, currency: string | undefined, locale: string) =>\n (value: number | null | undefined): string =>\n value === null || value === undefined ? \"\" : formatDataValue(value, { format, currency, locale });\n\n/**\n * The ApexCharts series and options for the props, or why there is nothing to draw: no rows / no plottable value\n * (`empty`), or no series field present in the rows (`invalid`).\n */\nexport const buildChartModel = (input: ChartModelInput): ChartModelResult => {\n const { props, sizeClass, locale, palette, isEmailRender, plotWidth = 0 } = input;\n const writtenKind = readChartKind(props.kind);\n // A funnel draws its own rows (`buildChartFunnelModel`); in a compact slot it is a bar sparkline.\n const kind = writtenKind === \"funnel\" ? \"bar\" : writtenKind;\n if (!kind) return { status: \"invalid\", detail: `the Chart kind \"${String(props.kind)}\" is not a chart kind` };\n const rows = readRows(props.data) ?? [];\n const xField = readText(props.x) ?? \"\";\n const seriesDeclarations = readChartSeries(props.series);\n if (rows.length === 0) return { status: \"empty\", detail: \"the Chart has no rows\" };\n if (seriesDeclarations.length === 0) return { status: \"empty\", detail: \"the Chart shows no series\" };\n const presentSeries = seriesDeclarations.filter((seriesDeclaration) =>\n rows.some((row) => readFiniteNumber(row[seriesDeclaration.field]) !== undefined),\n );\n if (presentSeries.length === 0) {\n return {\n status: \"invalid\",\n detail: `no row has a number in ${seriesDeclarations.map((seriesDeclaration) => `\"${seriesDeclaration.field}\"`).join(\", \")}`,\n };\n }\n const isSparkline = sizeClass === \"compact\";\n const valueFormat = readDataValueFormat(props.valueFormat);\n const formatValue = buildValueFormatter(valueFormat, readText(props.currency), locale);\n const categories = rows.map((row) => readText(row[xField]) ?? \"\");\n const height = HEIGHT_BY_SIZE_CLASS[sizeClass];\n const isHorizontalBar = kind === \"bar\" && props.horizontal === true;\n const isDistributedBar = kind === \"bar\" && presentSeries.length === 1;\n const textStyle = { colors: palette.axisTextColor, fontSize: \"12px\", fontFamily: \"inherit\" };\n const baseOptions: ApexOptions = {\n chart: {\n type: kind,\n toolbar: { show: false },\n zoom: { enabled: false },\n animations: { enabled: !isEmailRender, speed: 250 },\n sparkline: { enabled: isSparkline },\n background: \"transparent\",\n fontFamily: \"inherit\",\n foreColor: palette.axisTextColor,\n stacked: (kind === \"bar\" || kind === \"area\") && props.stacked === true,\n },\n colors: palette.seriesColors,\n dataLabels: { enabled: false },\n legend: {\n show:\n !isSparkline &&\n (presentSeries.length > 1 ||\n kind === \"pie\" ||\n kind === \"donut\" ||\n presentSeries.some((seriesDeclaration) => seriesDeclaration.hasExplicitLabel)),\n showForSingleSeries: true,\n // ApexCharts writes legend and tooltip texts as HTML: the model's names are escaped there (axis labels are SVG text).\n formatter: (seriesName: string) => escapeApexHtml(String(seriesName)),\n position: \"bottom\",\n horizontalAlign: \"center\",\n fontSize: \"13px\",\n labels: { colors: palette.axisTextColor },\n // ApexCharts before 3.45 rounds legend markers with `radius`, later versions with `shape`; the peer range spans both\n markers: { radius: 12, shape: \"circle\" } as ApexLegend[\"markers\"],\n itemMargin: { horizontal: 8, vertical: 4 },\n },\n grid: {\n borderColor: palette.gridColor,\n strokeDashArray: 4,\n xaxis: { lines: { show: isHorizontalBar } },\n yaxis: { lines: { show: !isHorizontalBar } },\n padding: { left: 8, right: 24 },\n },\n tooltip: {\n enabled: !isEmailRender,\n theme: \"light\",\n x: { formatter: (value: number | string) => escapeApexHtml(String(value)) },\n y: {\n formatter: (value: number) => formatValue(value),\n title: {\n formatter: (seriesName: string) => (seriesName ? `${escapeApexHtml(String(seriesName))}: ` : \"\"),\n },\n },\n },\n stroke: {\n width: kind === \"line\" || kind === \"area\" ? 2 : kind === \"pie\" || kind === \"donut\" ? 2 : 0,\n curve: \"straight\",\n colors: kind === \"pie\" || kind === \"donut\" ? [palette.surfaceColor] : undefined,\n },\n markers: {\n size: kind === \"scatter\" ? 6 : kind === \"line\" && !isSparkline && rows.length <= 24 ? 4 : 0,\n strokeWidth: 0,\n },\n states: { active: { filter: { type: \"none\" } } },\n };\n const axisMin = readFiniteNumber(props.min);\n const axisMax = readFiniteNumber(props.max);\n const valueAxis = {\n min: axisMin,\n max: axisMax,\n tickAmount: readTickAmountForBounds(axisMin, axisMax),\n forceNiceScale: axisMax === undefined,\n title: { text: readText(props.yLabel), style: { color: palette.axisTextColor, fontWeight: 400 } },\n labels: { formatter: (value: number) => formatValue(value), style: textStyle },\n };\n const seriesLabels = presentSeries.map((seriesDeclaration) => seriesDeclaration.label);\n // The tooltip header names the category of the hovered point (`Jan. 2026`), never ApexCharts' 1-based index.\n const categoryTooltip = {\n ...baseOptions.tooltip,\n x: {\n formatter: (value: number | string, tooltipContext?: { dataPointIndex?: number }) =>\n escapeApexHtml(\n String(\n tooltipContext?.dataPointIndex !== undefined ? (categories[tooltipContext.dataPointIndex] ?? value) : value,\n ),\n ),\n },\n };\n\n if (kind === \"pie\" || kind === \"donut\") {\n const valueField = presentSeries[0].field;\n const slices = rows\n .map((row, rowIndex) => ({ label: categories[rowIndex], value: readFiniteNumber(row[valueField]) }))\n .filter((slice): slice is { label: string; value: number } => slice.value !== undefined && slice.value > 0);\n if (slices.length === 0) return { status: \"empty\", detail: \"the Chart has no positive slice\" };\n return {\n status: \"ok\",\n model: {\n kind,\n apexType: kind,\n series: slices.map((slice) => slice.value),\n height,\n seriesLabels: slices.map((slice) => slice.label),\n options: {\n ...baseOptions,\n labels: slices.map((slice) => slice.label),\n dataLabels: {\n enabled: !isSparkline,\n formatter: (percent: number) => `${Math.round(percent)} %`,\n dropShadow: { enabled: false },\n },\n plotOptions: {\n pie: {\n expandOnClick: false,\n donut: {\n size: \"62%\",\n // A donut names the whole in its middle: the total under the series' label (\"130 · Bewertungen\"), a\n // hovered slice's name and value instead. A pie has no middle.\n labels: {\n show: kind === \"donut\" && !isSparkline,\n name: { show: true, fontSize: \"13px\", color: palette.axisTextColor, offsetY: 20 },\n value: {\n show: true,\n fontSize: \"24px\",\n fontWeight: 700,\n color: palette.textColor,\n offsetY: -12,\n formatter: (value: string) => formatValue(Number(value)),\n },\n total: {\n show: true,\n showAlways: false,\n label: presentSeries[0].hasExplicitLabel ? escapePlainTextForText(presentSeries[0].label) : \"\",\n fontSize: \"13px\",\n color: palette.axisTextColor,\n formatter: () => formatValue(slices.reduce((total, slice) => total + slice.value, 0)),\n },\n },\n },\n },\n },\n },\n },\n };\n }\n\n if (kind === \"radar\") {\n // One axis per data row (named by x), one polygon per series: a profile across its dimensions.\n if (rows.length < 3) return { status: \"invalid\", detail: \"a radar Chart needs at least 3 rows (one per axis)\" };\n const valueValues = presentSeries.flatMap((seriesDeclaration) =>\n rows\n .map((row) => readFiniteNumber(row[seriesDeclaration.field]))\n .filter((value): value is number => value !== undefined),\n );\n const radarMax = axisMax ?? readNiceAxisBounds([0, ...valueValues], 4)?.max;\n const radarFontSizePx = plotWidth > 0 && plotWidth < NARROW_PLOT_WIDTH ? 11 : 12;\n const hasRadarLegend = baseOptions.legend?.show === true;\n const radarRadius = isSparkline\n ? undefined\n : readRadarRadius({\n axisNames: categories,\n plotWidth,\n height: Math.max(height, 320),\n fontSizePx: radarFontSizePx,\n hasLegend: hasRadarLegend,\n });\n // A radar the width holds smaller than the height allows (a phone) gets only the height it fills.\n const radarHeight = isSparkline\n ? height\n : Math.min(\n Math.max(height, 320),\n radarRadius === undefined\n ? Number.POSITIVE_INFINITY\n : radarRadius * 2 + radarFontSizePx * 4 + (hasRadarLegend ? 48 : 0) + 16,\n );\n return {\n status: \"ok\",\n model: {\n kind,\n apexType: \"radar\",\n series: presentSeries.map((seriesDeclaration) => ({\n name: seriesDeclaration.label,\n data: rows.map((row) => readFiniteNumber(row[seriesDeclaration.field]) ?? 0),\n })),\n height: radarHeight,\n seriesLabels,\n options: {\n ...baseOptions,\n chart: { ...baseOptions.chart, type: \"radar\" },\n stroke: { width: 2 },\n fill: { opacity: 0.18 },\n markers: { size: isSparkline ? 0 : 3, strokeWidth: 0 },\n plotOptions: {\n radar: {\n size: radarRadius,\n polygons: {\n strokeColors: palette.gridColor,\n connectorColors: palette.gridColor,\n fill: { colors: [\"transparent\"] },\n },\n },\n },\n tooltip: categoryTooltip,\n xaxis: {\n categories,\n labels: {\n show: !isSparkline,\n style: {\n ...textStyle,\n fontSize: `${radarFontSizePx}px`,\n colors: categories.map(() => palette.axisTextColor),\n },\n },\n },\n yaxis: {\n show: false,\n min: axisMin ?? 0,\n max: radarMax,\n tickAmount: 4,\n labels: { formatter: (value: number) => formatValue(value) },\n },\n },\n },\n };\n }\n\n if (kind === \"heatmap\") {\n // One heat row per data row (top to bottom as written), one column per series: a cohort table.\n const heatRows = rows\n .map((row, rowIndex) => ({\n name: categories[rowIndex],\n data: presentSeries.map((seriesDeclaration) => ({\n x: seriesDeclaration.label,\n y: readFiniteNumber(row[seriesDeclaration.field]) ?? null,\n })),\n }))\n .reverse();\n const heatValues = heatRows.flatMap((heatRow) =>\n heatRow.data.map((heatCell) => heatCell.y).filter((value): value is number => value !== null),\n );\n const smallestHeat = Math.min(...heatValues);\n const heatRange = Math.max(...heatValues) - smallestHeat;\n // A count on a dark cell is written in the surface colour, on a pale cell in the text colour (ApexCharts shades a\n // cell by its place between the smallest and the largest value).\n const readHeatLabelColor = (labelContext: { seriesIndex: number; dataPointIndex: number }): string => {\n const heatValue = heatRows[labelContext.seriesIndex]?.data[labelContext.dataPointIndex]?.y;\n return typeof heatValue === \"number\" && heatRange > 0 && (heatValue - smallestHeat) / heatRange > 0.55\n ? palette.surfaceColor\n : palette.textColor;\n };\n return {\n status: \"ok\",\n model: {\n kind,\n apexType: \"heatmap\",\n series: heatRows as ApexAxisChartSeries,\n height: Math.max(height, rows.length * 44 + 16),\n seriesLabels,\n options: {\n ...baseOptions,\n colors: [palette.seriesColors[0]],\n legend: { show: false },\n dataLabels: {\n enabled: !isSparkline,\n formatter: (value: number) => formatValue(value),\n style: { colors: [readHeatLabelColor] as unknown as string[], fontWeight: 500 },\n },\n stroke: { width: 4, colors: [palette.surfaceColor] },\n plotOptions: { heatmap: { radius: 8, shadeIntensity: 0.6, enableShades: true } },\n xaxis: {\n position: \"top\",\n labels: { style: textStyle },\n axisBorder: { show: false },\n axisTicks: { show: false },\n },\n yaxis: { labels: { style: textStyle } },\n },\n },\n };\n }\n\n const series: ApexAxisChartSeries =\n kind === \"scatter\"\n ? presentSeries.map((seriesDeclaration) => ({\n name: seriesDeclaration.label,\n data: rows\n .map((row) => [readFiniteNumber(row[xField]), readFiniteNumber(row[seriesDeclaration.field])])\n .filter((point): point is [number, number] => point[0] !== undefined && point[1] !== undefined),\n }))\n : presentSeries.map((seriesDeclaration) => ({\n name: seriesDeclaration.label,\n data: rows.map((row) => readFiniteNumber(row[seriesDeclaration.field]) ?? null),\n }));\n const scatterAxisBounds =\n kind === \"scatter\"\n ? readNiceAxisBounds(\n rows.map((row) => readFiniteNumber(row[xField])).filter((value): value is number => value !== undefined),\n plotWidth > 0 && plotWidth < NARROW_PLOT_WIDTH ? 3 : 5,\n )\n : undefined;\n const formatAxisNumber = buildValueFormatter(\"number\", undefined, locale);\n const categoryAxisTitle = { text: readText(props.xLabel), style: { color: palette.axisTextColor, fontWeight: 400 } };\n return {\n status: \"ok\",\n model: {\n kind: writtenKind ?? kind,\n apexType: kind,\n series,\n height: isHorizontalBar ? Math.max(height, rows.length * 36 + 40) : height,\n seriesLabels,\n options: {\n ...baseOptions,\n tooltip: kind === \"scatter\" ? baseOptions.tooltip : categoryTooltip,\n fill: kind === \"area\" ? { type: \"gradient\", gradient: { opacityFrom: 0.35, opacityTo: 0.02 } } : { opacity: 1 },\n plotOptions: {\n bar: {\n horizontal: isHorizontalBar,\n distributed: isDistributedBar,\n borderRadius: 4,\n columnWidth: \"60%\",\n barHeight: \"60%\",\n dataLabels: { position: isHorizontalBar ? \"top\" : \"center\" },\n },\n },\n dataLabels: isHorizontalBar\n ? {\n enabled: true,\n formatter: (value: number) => formatValue(value),\n offsetX: 28,\n style: { colors: [palette.axisTextColor], fontWeight: 500 },\n }\n : { enabled: false },\n legend: { ...baseOptions.legend, show: baseOptions.legend?.show === true && !isDistributedBar },\n xaxis:\n kind === \"scatter\"\n ? {\n type: \"numeric\",\n min: scatterAxisBounds?.min,\n max: scatterAxisBounds?.max,\n tickAmount: scatterAxisBounds?.tickAmount ?? 5,\n title: categoryAxisTitle,\n labels: {\n style: textStyle,\n rotate: 0,\n hideOverlappingLabels: true,\n formatter: (value: string) => formatAxisNumber(Number(value)),\n },\n }\n : isHorizontalBar\n ? {\n categories,\n title: categoryAxisTitle,\n labels: { show: false, formatter: (value: string) => formatValue(Number(value)) },\n axisBorder: { show: false },\n axisTicks: { show: false },\n }\n : {\n categories,\n title: categoryAxisTitle,\n labels: { style: textStyle, hideOverlappingLabels: true, rotate: 0, trim: false },\n axisBorder: { show: false },\n axisTicks: { show: false },\n tickAmount: categories.length > 12 ? 6 : undefined,\n tooltip: { enabled: false },\n },\n // Horizontal bars: the value labels sit right of the bar end — the axis leaves room for the longest one.\n yaxis: isHorizontalBar\n ? {\n max: axisMax ?? readLargestValue(series) * 1.15,\n min: axisMin ?? 0,\n labels: { style: { ...textStyle, fontSize: \"14px\" }, maxWidth: 160 },\n }\n : valueAxis,\n },\n },\n };\n};\n","import {\n COMPOSED_VIEW_TONE_GRAPHIC_COLOR,\n COMPOSED_VIEW_TONE_TEXT_COLOR,\n} from \"../../composed-view-tones\";\nimport type { DataValueTone } from \"./data-value-format\";\nimport styles from \"./data-tones.module.scss\";\n\n/** The text class of a tone (judgement text in the 900 tone, through light-dark()). */\nexport const TONE_TEXT_CLASS: Record<DataValueTone, string> = {\n neutral: styles.textNeutral,\n muted: styles.textMuted,\n success: styles.textSuccess,\n warning: styles.textWarning,\n danger: styles.textDanger,\n info: styles.textInfo,\n};\n\n/** The graphic colour of a tone — the kit's (`composed-view-tones.ts`). */\nexport const TONE_GRAPHIC_COLOR: Readonly<Record<DataValueTone, string>> = COMPOSED_VIEW_TONE_GRAPHIC_COLOR;\n\n/** The same judgement text colours as values for the component library's `Text`'s `color` prop — the kit's. */\nexport const TONE_TEXT_COLOR: Readonly<Record<DataValueTone, string>> = COMPOSED_VIEW_TONE_TEXT_COLOR;\n","import { Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { CSSProperties } from \"react\";\nimport type { ChartBarRowsModel } from \"../chart-model\";\nimport { TONE_TEXT_COLOR } from \"../data-tones\";\nimport styles from \"./ChartBarRows.module.scss\";\n\nexport interface ChartBarRowsProps {\n model: ChartBarRowsModel;\n /** The chart's accessible name (title and series). */\n accessibleLabel?: string;\n testId?: string;\n}\n\n/**\n * The bars of a bar chart with a change per bar: per row the category, the bar on\n * its track in the row's chart colour, the value, and the signed change coloured by its sign. A table, because it is\n * one: each row reads \"CSU · 36 % · -3\" to a screen reader. The bar's length and colour travel as CSS custom\n * properties — the one dynamic value, no inline style rule.\n */\nexport const ChartBarRows = (props: ChartBarRowsProps) => {\n const { model, accessibleLabel, testId } = props;\n const hasDeltas = model.rows.some((row) => row.deltaText !== undefined);\n return (\n <table className={styles.rows} aria-label={accessibleLabel} data-testid={testId}>\n <tbody>\n {model.rows.map((row, rowIndex) => (\n <tr\n key={`${row.label}-${rowIndex}`}\n className={styles.row}\n data-testid={testId ? `${testId}-row-${rowIndex}` : undefined}\n >\n <th scope=\"row\" className={styles.label}>\n <Text role=\"help\" className={styles.labelText} translate={false}>\n {escapePlainTextForText(row.label)}\n </Text>\n </th>\n <td className={styles.track} aria-hidden=\"true\">\n <span\n className={styles.bar}\n style={\n {\n \"--agents-chart-bar-fraction\": `${Math.round(row.fraction * 1000) / 10}%`,\n \"--agents-chart-bar-color\": `var(${row.colorToken})`,\n } as CSSProperties\n }\n />\n </td>\n <td className={styles.value}>\n <Text\n role=\"help\"\n weight=\"medium\"\n className={styles.figure}\n translate={false}\n >\n {escapePlainTextForText(row.valueText)}\n </Text>\n </td>\n {hasDeltas ? (\n <td className={styles.delta}>\n {row.deltaText !== undefined ? (\n <Text\n role=\"help\"\n color={TONE_TEXT_COLOR[row.deltaTone]}\n className={styles.figure}\n translate={false}\n >\n {escapePlainTextForText(row.deltaText)}\n </Text>\n ) : null}\n </td>\n ) : null}\n </tr>\n ))}\n </tbody>\n </table>\n );\n};\n","import { Icon, Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { CSSProperties } from \"react\";\nimport type { ChartFunnelModel } from \"../chart-model\";\nimport styles from \"./ChartFunnelRows.module.scss\";\n\nexport interface ChartFunnelRowsProps {\n model: ChartFunnelModel;\n /** The chart's accessible name (title and series). */\n accessibleLabel?: string;\n testId?: string;\n}\n\n/**\n * The stages of a funnel chart (ChatGPT composes its funnel from SVG): per\n * stage its name and value on one line, under it a centered bar as wide as the stage's share of the largest one, and\n * between two stages the conversion from the stage before. An ordered list, because the stages are a sequence: each\n * item reads \"Link opened · 41 · 64 % of the previous stage\" to a screen reader. The bar's width travels as a CSS\n * custom property — the one dynamic value, no inline style rule.\n */\nexport const ChartFunnelRows = (props: ChartFunnelRowsProps) => {\n const { model, accessibleLabel, testId } = props;\n return (\n <ol className={styles.stages} aria-label={accessibleLabel} data-testid={testId}>\n {model.stages.map((stage, stageIndex) => (\n <li\n key={`${stage.label}-${stageIndex}`}\n className={styles.stage}\n data-testid={testId ? `${testId}-stage-${stageIndex}` : undefined}\n >\n {stage.conversionText !== undefined ? (\n <div className={styles.conversion}>\n <Icon className={styles.conversionIcon} name=\"arrowDown\" />\n <Text\n role=\"caption\"\n color=\"var(--agents-fg-light)\"\n className={styles.figure}\n replacements={{ conversion: stage.conversionText }}\n >\n {\"%conversion% of the previous stage\"}\n </Text>\n </div>\n ) : null}\n <div className={styles.stageHead}>\n <Text role=\"help\" className={styles.label} translate={false}>\n {escapePlainTextForText(stage.label)}\n </Text>\n <Text role=\"help\" weight=\"bold\" className={styles.figure} translate={false}>\n {escapePlainTextForText(stage.valueText)}\n </Text>\n </div>\n <span\n className={styles.bar}\n aria-hidden=\"true\"\n style={{ \"--agents-chart-funnel-fraction\": `${Math.round(stage.fraction * 1000) / 10}%` } as CSSProperties}\n />\n </li>\n ))}\n </ol>\n );\n};\n","import { useMemo } from \"react\";\nimport { CHART_SERIES_COLOR_TOKENS, type ChartPalette } from \"./chart-model\";\n\n/** Fallbacks for a host without the theme stylesheet (a spec): the direct-channel values are irrelevant there. */\nconst FALLBACK_SERIES_COLOR = \"#4f7fe8\";\nconst FALLBACK_TEXT_COLOR = \"#6b7280\";\nconst FALLBACK_STRONG_TEXT_COLOR = \"#111827\";\nconst FALLBACK_GRID_COLOR = \"#e5e7eb\";\nconst FALLBACK_SURFACE_COLOR = \"#ffffff\";\n\nconst readToken = (computedStyle: CSSStyleDeclaration | undefined, token: string, fallback: string): string =>\n computedStyle?.getPropertyValue(token).trim() || fallback;\n\n/**\n * The chart's colours, read from the theme tokens (`--agents-chart-01` … `--agents-chart-08` for the series,\n * `--agents-fg-light` for the axis text, `--agents-fg` for a donut's total,\n * `--agents-divider-gl` for the grid, `--agents-bg-surface` for the slice gaps). ApexCharts writes colours into SVG attributes\n * and computes shades from them, where a `var()` does not resolve — so the values are read once per scheme from the\n * element's computed style, never written as hex in the component.\n */\nexport const useChartPalette = (element: HTMLElement | null, colorScheme: string | null): ChartPalette =>\n useMemo(() => {\n const computedStyle = element && typeof window !== \"undefined\" ? window.getComputedStyle(element) : undefined;\n return {\n seriesColors: CHART_SERIES_COLOR_TOKENS.map((token) => readToken(computedStyle, token, FALLBACK_SERIES_COLOR)),\n axisTextColor: readToken(computedStyle, \"--agents-fg-light\", FALLBACK_TEXT_COLOR),\n textColor: readToken(computedStyle, \"--agents-fg\", FALLBACK_STRONG_TEXT_COLOR),\n gridColor: readToken(computedStyle, \"--agents-divider-gl\", FALLBACK_GRID_COLOR),\n surfaceColor: readToken(computedStyle, \"--agents-bg-surface\", FALLBACK_SURFACE_COLOR),\n };\n // The scheme is read so a light/dark switch re-reads the tokens.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [element, colorScheme]);\n","import { useAgentsOwnerSettings } from \"../../../provider/AgentsProvider\";\nimport { toNumberLocale } from \"./data-value-format\";\n\n/**\n * The locale the data nodes write numbers in — the owner's UI language from the app (`useOwnerSettings`), read\n * defensively: a tree renders in hosts without it too (the e-mail capture, a spec, the preview), and then numbers are `en`.\n */\nexport const useNumberLocale = (): string => {\n const { languageCode } = useAgentsOwnerSettings();\n return toNumberLocale(languageCode ?? undefined);\n};\n","import { Button, Icon, Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport styles from \"./DataFootnote.module.scss\";\nimport type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { readObject, readText } from \"../data-value-format\";\n\nexport interface DataFootnoteProps {\n /** The model's muted line under the data (what the figures are, the period). */\n caption?: ExpressionValue;\n /** `{\"name\",\"url\"}` — where the figures come from; a list of them (a Table whose values come from several pages). */\n source?: ExpressionValue;\n /** The e-mail capture: chip sources are plain text; KPI sources are omitted. */\n isEmailRender: boolean;\n appearance?: \"chip\" | \"quiet\";\n testId?: string;\n}\n\n/** An http(s) link target; the quiet KPI appearance additionally requires a parseable host. */\nconst readHttpUrl = (value: unknown): string | undefined =>\n typeof value === \"string\" && /^https?:\\/\\//i.test(value) ? value : undefined;\n\n/** The host name of a URL for a source without a name, or undefined for a URL that does not parse. */\nconst readHostName = (url: string | undefined): string | undefined => {\n if (!url) return undefined;\n try {\n return new URL(url).hostname;\n } catch {\n return undefined;\n }\n};\n\n/** One source chip: the name (or the page's host name) and the http(s) page, when it has one. */\ninterface FootnoteSource {\n name: string;\n url: string | undefined;\n}\n\n/** The sources a `source` prop holds — one object or a list of them; entries without a name or a page are left out. */\nconst readFootnoteSources = (source: ExpressionValue | undefined): FootnoteSource[] => {\n const sourceValues: unknown[] = Array.isArray(source) ? source : [source];\n const footnoteSources: FootnoteSource[] = [];\n for (const sourceValue of sourceValues) {\n const sourceObject = readObject(sourceValue);\n const url = readHttpUrl(sourceObject?.url);\n const name = readText(sourceObject?.name) ?? readHostName(url);\n if (name) footnoteSources.push({ name, url });\n }\n return footnoteSources;\n};\n\ninterface SourceChipProps {\n footnoteSource: FootnoteSource;\n isEmailRender: boolean;\n appearance: \"chip\" | \"quiet\";\n testId?: string;\n}\n\n/** A small flat chip: a link opening in a new tab, plain text in the e-mail capture or without a page. */\nconst SourceChip = (props: SourceChipProps) => {\n const { footnoteSource, isEmailRender, appearance, testId } = props;\n const openSource = () => {\n if (footnoteSource.url) window.open(footnoteSource.url, \"_blank\", \"noopener,noreferrer\");\n };\n if (appearance === \"quiet\") {\n return (\n <Button\n variant=\"default\"\n size=\"small\"\n icon=\"link\"\n iconPosition=\"left\"\n htmlType=\"button\"\n translate={false}\n className={styles.sourceButton}\n testId={testId}\n onClick={openSource}\n >\n {escapePlainTextForText(footnoteSource.name)}\n </Button>\n );\n }\n const className = styles.sourceChip;\n const sourceChipContent = (\n <>\n <Icon pixelSize={12} color=\"var(--agents-fg-light)\" name=\"link\" />\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(footnoteSource.name)}\n </Text>\n </>\n );\n if (footnoteSource.url && !isEmailRender) {\n return (\n <a className={className} data-testid={testId} href={footnoteSource.url} target=\"_blank\" rel=\"noopener noreferrer\">\n {sourceChipContent}\n </a>\n );\n }\n return (\n <span className={className} data-testid={testId}>\n {sourceChipContent}\n </span>\n );\n};\n\n// Charts/tables keep chips (plain text in email). KPI footers show only valid page links and omit sources in email.\nexport const DataFootnote = (props: DataFootnoteProps) => {\n const { caption, source, isEmailRender, appearance = \"chip\", testId } = props;\n const captionText = readText(caption);\n const footnoteSources = readFootnoteSources(source)\n .map((footnoteSource, sourceIndex) => ({ footnoteSource, sourceIndex }))\n .filter(({ footnoteSource }) => appearance === \"chip\" || (!isEmailRender && readHostName(footnoteSource.url)));\n if (!captionText && footnoteSources.length === 0) return null;\n return (\n <div className={classNames(styles.footnote, appearance === \"quiet\" && styles.quiet)} data-testid={testId}>\n {captionText ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(captionText)}\n </Text>\n ) : null}\n {footnoteSources.map(({ footnoteSource, sourceIndex }) => (\n <SourceChip\n key={`${sourceIndex}-${footnoteSource.name}`}\n footnoteSource={footnoteSource}\n isEmailRender={isEmailRender}\n appearance={appearance}\n testId={testId && `${testId}-source-${sourceIndex}`}\n />\n ))}\n </div>\n );\n};\n","import { Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport { readText } from \"../data-value-format\";\n\nexport interface DataEmptyLineProps {\n /** The model's own empty line (`emptyText`); the kit's chrome sentence otherwise. */\n emptyText?: unknown;\n testId?: string;\n}\n\n/** The one muted line a data node shows when it has nothing to show (empty data). */\nexport const DataEmptyLine = (props: DataEmptyLineProps) => {\n const { emptyText, testId } = props;\n const modelText = readText(emptyText);\n return modelText ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false} testId={testId}>\n {escapePlainTextForText(modelText)}\n </Text>\n ) : (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={testId}>\n {\"No data to show.\"}\n </Text>\n );\n};\n","import { useEffect } from \"react\";\nimport type {\n WidgetRenderReportCode,\n WidgetRenderStatus,\n} from \"../../../renderer/render-report/widget-render-report\";\nimport type { ComposedViewRuntime } from \"../../composed-view-component-types\";\n\n/**\n * Reports a data node's status into the block's render report on every change — `mounted` included, so\n * a node that was `empty` or `pending` and then got its rows clears its earlier report instead of leaving it standing.\n */\nexport const useReportDataNodeStatus = (\n runtime: ComposedViewRuntime,\n status: WidgetRenderStatus,\n code?: WidgetRenderReportCode,\n detail?: string,\n): void => {\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n reportNodeStatus(status, code, detail);\n }, [reportNodeStatus, status, code, detail]);\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useCallback, useEffect, useState } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ApexChart } from \"./apex-chart-component\";\nimport {\n buildChartBarRowsModel,\n buildChartFunnelModel,\n buildChartModel,\n readChartDeltaField,\n readChartKind,\n} from \"./chart-model\";\nimport { ChartBarRows } from \"./ChartBarRows/ChartBarRows\";\nimport { ChartFunnelRows } from \"./ChartFunnelRows/ChartFunnelRows\";\nimport { readText } from \"./data-value-format\";\nimport { useChartPalette } from \"./use-chart-palette\";\nimport { useNumberLocale } from \"./use-number-locale\";\nimport { DataFootnote } from \"./DataFootnote/DataFootnote\";\nimport { DataEmptyLine } from \"./DataEmptyLine/DataEmptyLine\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./Chart.module.scss\";\n\n/** The light/dark scheme the page is in (`data-color-scheme` on `<html>`), so the palette is re-read on a switch. */\nconst useColorScheme = (): string | null => {\n const [colorScheme, setColorScheme] = useState<string | null>(() =>\n typeof document === \"undefined\" ? null : document.documentElement.getAttribute(\"data-color-scheme\"),\n );\n useEffect(() => {\n if (typeof MutationObserver === \"undefined\") return undefined;\n const observer = new MutationObserver(() =>\n setColorScheme(document.documentElement.getAttribute(\"data-color-scheme\")),\n );\n observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"data-color-scheme\"] });\n return () => observer.disconnect();\n }, []);\n return colorScheme;\n};\n\n/**\n * A remount key that changes when the chart's container width changes. ApexCharts measures its parent once and misses\n * the chat column narrowing when a canvas opens (an app widget that draws an ApexCharts chart keys it the same way).\n */\nconst useContainerWidthKey = () => {\n const [element, setElement] = useState<HTMLDivElement | null>(null);\n const [widthKey, setWidthKey] = useState(0);\n useEffect(() => {\n if (!element || typeof ResizeObserver === \"undefined\") return undefined;\n const observer = new ResizeObserver((entries) => {\n const measuredWidth = Math.round(entries[0]?.contentRect.width ?? 0);\n setWidthKey((previousWidth) => (previousWidth === measuredWidth ? previousWidth : measuredWidth));\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, [element]);\n const containerRef = useCallback((container: HTMLDivElement | null) => setElement(container), []);\n return { element, containerRef, widthKey };\n};\n\n/**\n * The `Chart` node: line, area, bar (horizontal for a ranking\n * or poll), pie, donut, scatter and heatmap through ApexCharts, in the theme's chart colours, with the legend under\n * the plot (a click on an entry hides its series), tooltips on hover and the values formatted like every data node. In a\n * compact slot (a table cell) it is a sparkline without axes, legend and title. A chart still waiting for its bound\n * rows shows a plot-shaped skeleton; no rows show one muted line and report `empty`; rows without any number in the\n * named series report `failed` (`INVALID_PROP`). The e-mail capture draws it without animation and tooltips.\n *\n * A bar chart with a `deltaField` (a measurement against an earlier one) draws its bars itself\n * ({@link ChartBarRows}): one horizontal bar per category with its value and the signed change at the right, coloured\n * by sign, and the `deltaLabel` line under the bars (\"Right: change in percentage points since January 2026\"; without\n * one, a `pp` change names its unit in the kit's own line). In a compact slot it stays a sparkline.\n *\n * A funnel (no ApexCharts funnel in the installed 3.35) draws its stages itself ({@link ChartFunnelRows}): centered\n * bars in the written order with each stage's value and its conversion from the stage before. A radar is ApexCharts'\n * radar: one axis per row, one polygon per series, the value axis hidden (the tooltip names the values).\n */\nconst ChartNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime, isPending, sizeClass, testId } = props;\n const locale = useNumberLocale();\n const colorScheme = useColorScheme();\n const { element, containerRef, widthKey } = useContainerWidthKey();\n const palette = useChartPalette(element, colorScheme);\n const isSparkline = sizeClass === \"compact\";\n const hasChangePerBar = readChartDeltaField(nodeProps) !== undefined && !isSparkline;\n const isFunnel = readChartKind(nodeProps.kind) === \"funnel\" && !isSparkline;\n const barRowsModelResult = hasChangePerBar ? buildChartBarRowsModel({ props: nodeProps, locale }) : undefined;\n const funnelModelResult = isFunnel ? buildChartFunnelModel({ props: nodeProps, locale }) : undefined;\n const chartModelResult =\n barRowsModelResult ??\n funnelModelResult ??\n buildChartModel({\n props: nodeProps,\n sizeClass,\n locale,\n palette,\n isEmailRender: runtime.isEmailRender,\n plotWidth: widthKey,\n });\n const drawsItsOwnRows = hasChangePerBar || isFunnel;\n const isWaiting = isPending && chartModelResult.status !== \"ok\";\n useReportDataNodeStatus(\n runtime,\n isWaiting\n ? \"pending\"\n : chartModelResult.status === \"ok\"\n ? \"mounted\"\n : chartModelResult.status === \"empty\"\n ? \"empty\"\n : \"failed\",\n isWaiting || chartModelResult.status === \"ok\"\n ? undefined\n : chartModelResult.status === \"empty\"\n ? \"NO_DATA\"\n : \"INVALID_PROP\",\n isWaiting || chartModelResult.status === \"ok\" ? undefined : chartModelResult.detail,\n );\n const title = readText(nodeProps.title);\n const kind = readChartKind(nodeProps.kind) ?? \"line\";\n const plottedSeriesLabels =\n barRowsModelResult?.status === \"ok\"\n ? [barRowsModelResult.model.seriesLabel]\n : funnelModelResult?.status === \"ok\"\n ? [funnelModelResult.model.seriesLabel]\n : chartModelResult.status === \"ok\" && \"seriesLabels\" in chartModelResult.model\n ? chartModelResult.model.seriesLabels\n : [];\n const accessibleLabel =\n chartModelResult.status === \"ok\" ? [title, plottedSeriesLabels.join(\", \")].filter(Boolean).join(\": \") : title;\n const deltaLabel = readText(nodeProps.deltaLabel);\n const deltaUnitLine =\n barRowsModelResult?.status === \"ok\" && barRowsModelResult.model.deltaUnit === \"pp\"\n ? \"Right: change in percentage points\"\n : barRowsModelResult?.status === \"ok\" && barRowsModelResult.model.deltaUnit === \"%\"\n ? \"Right: change in percent\"\n : undefined;\n return (\n <figure className={classNames(styles.chart, isSparkline && styles.sparkline)} data-testid={testId}>\n {title && !isSparkline ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n <div\n ref={containerRef}\n className={styles.plot}\n role={chartModelResult.status === \"ok\" && !drawsItsOwnRows ? \"img\" : undefined}\n aria-label={drawsItsOwnRows ? undefined : accessibleLabel}\n data-chart-kind={kind}\n >\n {isWaiting ? (\n <div className={styles.skeleton} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <SkeletonLine width=\"100%\" height={isSparkline ? 32 : 240} radius={12} />\n </div>\n ) : barRowsModelResult?.status === \"ok\" ? (\n <ChartBarRows model={barRowsModelResult.model} accessibleLabel={accessibleLabel} testId={`${testId}-rows`} />\n ) : funnelModelResult?.status === \"ok\" ? (\n <ChartFunnelRows\n model={funnelModelResult.model}\n accessibleLabel={accessibleLabel}\n testId={`${testId}-stages`}\n />\n ) : chartModelResult.status === \"ok\" && \"options\" in chartModelResult.model ? (\n <ApexChart\n key={`${widthKey}-${chartModelResult.model.apexType}`}\n type={chartModelResult.model.apexType}\n series={chartModelResult.model.series}\n options={chartModelResult.model.options}\n height={chartModelResult.model.height}\n width=\"100%\"\n />\n ) : isSparkline ? null : (\n <DataEmptyLine testId={`${testId}-empty`} />\n )}\n </div>\n {hasChangePerBar && chartModelResult.status === \"ok\" && deltaLabel ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(deltaLabel)}\n </Text>\n ) : hasChangePerBar && chartModelResult.status === \"ok\" && deltaUnitLine ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\">\n {deltaUnitLine}\n </Text>\n ) : null}\n {isSparkline ? null : (\n <DataFootnote caption={nodeProps.caption} source={nodeProps.source} isEmailRender={runtime.isEmailRender} />\n )}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Chart\", component: ChartNode };\n","import { Icon, isAgentsIconName, type AgentsIconName } from \"../../../provider/components\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readDataValueTone, readText } from \"./data-value-format\";\nimport { TONE_GRAPHIC_COLOR } from \"./data-tones\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./Icon.module.scss\";\n\nconst ICON_SIZE_PX: Record<string, number> = { small: 16, medium: 20, large: 24 };\n\n/** The icon a wire name stands for — the node's names are package icon names (`IconComposedViewNode::ICON_NAMES`). */\nconst readIconName = (value: unknown): AgentsIconName | undefined => (isAgentsIconName(value) ? value : undefined);\n\n/**\n * The `Icon` node (the check and cross of a majority column): one component-library icon in\n * its tone's graphic colour. A `label` makes it an image with a name for screen readers and a tooltip; without one it\n * is decoration. A bound name that is not an icon renders nothing and reports `failed`.\n */\nconst IconNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime, isPending } = props;\n const iconName = readIconName(nodeProps.name);\n const label = readText(nodeProps.label);\n const tone = readDataValueTone(nodeProps.tone);\n const sizePx = ICON_SIZE_PX[typeof nodeProps.size === \"string\" ? nodeProps.size : \"small\"] ?? ICON_SIZE_PX.small;\n const hasUnknownName = !isPending && iconName === undefined;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : hasUnknownName ? \"failed\" : \"mounted\",\n hasUnknownName ? \"INVALID_PROP\" : undefined,\n hasUnknownName ? `the Icon name \"${String(nodeProps.name)}\" is not an icon` : undefined,\n );\n if (iconName === undefined) return null;\n return (\n <span\n className={styles.icon}\n role={label ? \"img\" : undefined}\n aria-label={label}\n aria-hidden={label ? undefined : true}\n title={label}\n >\n <Icon pixelSize={sizePx} color={TONE_GRAPHIC_COLOR[tone]} name={iconName} />\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Icon\", component: IconNode };\n","import { createContext, useContext } from \"react\";\n\n/**\n * What a layout node needs to know about the layout nodes around it:\n *\n * - inside a `Surface` → a nested surface is a FLAT tile, never a second raised surface (two background levels, never\n * three);\n * - inside a `Pressable` → the content is already one button, so a nested `Pressable` or `Popover` renders without a\n * control of its own (no button inside a button).\n */\nexport interface LayoutNesting {\n isInsideSurface: boolean;\n isInsidePressable: boolean;\n}\n\nexport const LayoutNestingContext = createContext<LayoutNesting>({ isInsideSurface: false, isInsidePressable: false });\n\nexport const useLayoutNesting = () => useContext(LayoutNestingContext);\n","import styles from \"./KpiMeter.module.scss\";\nimport { SegmentBar } from \"../../../../provider/components\";\n\nexport interface KpiMeterProps {\n value: number;\n max: number;\n /** The fill colour (a tone's graphic colour). */\n color: string;\n testId?: string;\n}\n\n/**\n * The thin meter under a written score (\"61,4/100\", \"5/5\"): the `SegmentBar` component, filled part and track. It\n * repeats the figure the hero already states, so assistive technology skips it.\n */\nexport const KpiMeter = (props: KpiMeterProps) => {\n const { value, max, color, testId } = props;\n const segments = [\n { value, color },\n { value: max - value, color: \"var(--agents-kpi-meter-track)\" },\n ].filter((segment) => segment.value > 0);\n return (\n <div className={styles.meter} aria-hidden=\"true\" data-testid={testId}>\n <SegmentBar segments={segments} height={6} />\n </div>\n );\n};\n","import { Icon, type AgentsIconName } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport styles from \"./KpiToneAccent.module.scss\";\nimport { TONE_GRAPHIC_COLOR } from \"../data-tones\";\nimport type { DataValueTone } from \"../data-value-format\";\n\nconst TONE_ICON: Partial<Record<DataValueTone, AgentsIconName>> = {\n success: \"check\",\n warning: \"warning\",\n danger: \"exclamation\",\n info: \"info\",\n};\n\nconst TONE_CLASS: Partial<Record<DataValueTone, string>> = {\n success: styles.success,\n warning: styles.warning,\n danger: styles.danger,\n info: styles.info,\n};\n\nexport interface KpiToneAccentProps {\n tone: DataValueTone;\n testId?: string;\n}\n\n/**\n * The status accent of a judged KPI: a small tinted badge with the tone's glyph beside the label. The value carries the\n * same tone in its colour, so the badge is decoration. Neutral and muted values show none.\n */\nexport const KpiToneAccent = (props: KpiToneAccentProps) => {\n const { tone, testId } = props;\n const icon = TONE_ICON[tone];\n if (!icon) return null;\n return (\n <span className={classNames(styles.accent, TONE_CLASS[tone])} aria-hidden=\"true\" data-testid={testId}>\n <Icon pixelSize={14} color={TONE_GRAPHIC_COLOR[tone]} name={icon} />\n </span>\n );\n};\n","import type { DataValueFormat } from \"./data-value-format\";\nimport { readFiniteNumber } from \"./data-value-format\";\n\n// Only whole numeric values and scores use the hero; numerals in prose remain readable text.\nconst NUMBER_PATTERN = String.raw`[-+]?(?:\\d+(?:[   ]\\d{3})*(?:[.,]\\d+)?|[.,]\\d+)`;\nconst NUMERIC_SCORE = new RegExp(String.raw`^${NUMBER_PATTERN}(?:\\s*\\/\\s*${NUMBER_PATTERN}|\\s*%)?$`);\nconst RATIO = new RegExp(String.raw`^(${NUMBER_PATTERN})(\\s*\\/\\s*(${NUMBER_PATTERN}))$`);\n// A written value may join its headline figure and a remark with a middle dot (\"5/5 · 22 recenzii\").\nconst SEGMENT_SEPARATOR = /\\s+[·•]\\s+/;\n\nexport interface KpiValueParts {\n presentation: \"hero\" | \"text\";\n /** The headline: the whole value, or the numerator of a ratio. */\n lead: string;\n /** The denominator of a ratio exactly as written (\"/100\", \" / 5\"). */\n denominator?: string;\n /** The remark after a numeric headline, shown on the unit line. */\n secondary?: string;\n /** A ratio the meter can draw: 0 ≤ value ≤ max, max > 0. */\n ratio?: { value: number; max: number };\n}\n\n/** A written number as a JS number: grouping spaces dropped, a lone comma read as the decimal mark. */\nconst readWrittenNumber = (written: string): number => {\n const compact = written.replace(/[   ]/g, \"\");\n return Number(compact.includes(\".\") ? compact.replace(/,/g, \"\") : compact.replace(\",\", \".\"));\n};\n\nconst readHeroParts = (lead: string, secondary: string | undefined): KpiValueParts => {\n const ratioMatch = RATIO.exec(lead);\n if (!ratioMatch) return { presentation: \"hero\", lead, secondary };\n const value = readWrittenNumber(ratioMatch[1]);\n const max = readWrittenNumber(ratioMatch[3]);\n const ratio = max > 0 && value >= 0 && value <= max ? { value, max } : undefined;\n return { presentation: \"hero\", lead: ratioMatch[1], denominator: ratioMatch[2], secondary, ratio };\n};\n\n/**\n * How a KPI value is laid out, never what it says: a number or a written score takes the hero, a leading score with a\n * remark splits at its middle dot, any other text stays one headline. Every character of the value is kept.\n */\nexport const readKpiValueParts = (\n rawValue: unknown,\n formattedValue: string,\n format: DataValueFormat = \"number\",\n): KpiValueParts => {\n if (format === \"date\") return { presentation: \"text\", lead: formattedValue };\n if (typeof rawValue === \"number\") {\n return { presentation: Number.isFinite(rawValue) ? \"hero\" : \"text\", lead: formattedValue };\n }\n if (typeof rawValue !== \"string\" || rawValue === \"\" || readFiniteNumber(rawValue) !== undefined) {\n return { presentation: \"hero\", lead: formattedValue };\n }\n const written = formattedValue.trim();\n if (NUMERIC_SCORE.test(written)) return readHeroParts(written, undefined);\n const separator = SEGMENT_SEPARATOR.exec(written);\n if (separator && NUMERIC_SCORE.test(written.slice(0, separator.index))) {\n return readHeroParts(written.slice(0, separator.index), written.slice(separator.index + separator[0].length));\n }\n return { presentation: \"text\", lead: formattedValue };\n};\n\n/** The presentation alone of a raw value in its format. */\nexport const readKpiValuePresentation = (value: unknown, format: DataValueFormat = \"number\"): \"hero\" | \"text\" =>\n readKpiValueParts(value, typeof value === \"string\" ? value : String(value ?? \"\"), format).presentation;\n","import { TrendDelta } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport styles from \"./KpiTile.module.scss\";\nimport { WidgetKpiValue, WidgetSurface, WidgetText } from \"../../../widgets/_shared/modern\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport { useLayoutNesting } from \"../layout/layout-nesting-context\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataFootnote } from \"./DataFootnote/DataFootnote\";\nimport { TONE_GRAPHIC_COLOR, TONE_TEXT_CLASS } from \"./data-tones\";\nimport {\n formatDataValue,\n readDataValueFormat,\n readDataValueTone,\n readFiniteNumber,\n readText,\n} from \"./data-value-format\";\nimport { KpiMeter } from \"./KpiMeter/KpiMeter\";\nimport { KpiToneAccent } from \"./KpiToneAccent/KpiToneAccent\";\nimport { readKpiValueParts } from \"./kpi-value-parts\";\nimport { useNumberLocale } from \"./use-number-locale\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\n\n// A neutral score fills in the call-to-action colour; a judged one in its tone's graphic colour.\nconst readMeterColor = (tone: keyof typeof TONE_GRAPHIC_COLOR): string =>\n tone === \"neutral\" ? \"var(--agents-fg-cta)\" : TONE_GRAPHIC_COLOR[tone];\n\n/**\n * The `KpiTile` node: label → hero value → unit and change → detail → source,\n * the design's anatomy of a number tile, built on `WidgetKpiValue` (the ONE hero scale).\n * The change is the component library's `TrendDelta`: its arrow colour says whether the change is good (`higherIsBetter`), not its\n * direction; the number carries its sign (\"+12.4 %\"). On the chat (no `Surface` around it, the nesting context of the layout nodes) the tile is an elevated surface; inside a\n * `Surface` it is a flat tile on the nested background, so a grid of tiles in a card has two background levels, never\n * three. Outside the root slot it takes the compact padding. A value that is still\n * loading is the hero's skeleton; a value that resolved to nothing shows a dash and reports `empty`.\n */\nconst KpiTileNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime, isPending, sizeClass, testId } = props;\n const locale = useNumberLocale();\n const { isInsideSurface } = useLayoutNesting();\n const label = readText(nodeProps.label) ?? \"\";\n const format = readDataValueFormat(nodeProps.format);\n const currency = readText(nodeProps.currency);\n const decimals = readFiniteNumber(nodeProps.decimals);\n const formattedValue = formatDataValue(nodeProps.value, {\n format,\n currency,\n decimals,\n signed: nodeProps.signed === true,\n locale,\n });\n const hasValue = formattedValue !== \"\";\n const delta = readFiniteNumber(nodeProps.delta);\n const deltaFormat = readDataValueFormat(nodeProps.deltaFormat);\n const deltaLabel = readText(nodeProps.deltaLabel);\n const higherIsBetter = nodeProps.higherIsBetter !== false;\n const tone = readDataValueTone(nodeProps.tone);\n const unit = readText(nodeProps.unit);\n const detail = readText(nodeProps.detail);\n const valueParts = readKpiValueParts(nodeProps.value, formattedValue, format);\n const { ratio, secondary } = valueParts;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : hasValue ? \"mounted\" : \"empty\",\n !isPending && !hasValue ? \"NO_DATA\" : undefined,\n !isPending && !hasValue ? `the KpiTile \"${label}\" has no value` : undefined,\n );\n const deltaElement =\n delta === undefined ? undefined : (\n <span className={styles.delta} data-testid={`${testId}-delta`}>\n <TrendDelta\n current={delta}\n previous={0}\n higherIsBetter={higherIsBetter}\n // TrendDelta hands over the magnitude only; the change keeps its sign (\"+6\", \"+5 %\", \"-0.49\").\n format={(magnitude) =>\n formatDataValue(delta < 0 ? -magnitude : magnitude, { format: deltaFormat, currency, locale, signed: true })\n }\n />\n {deltaLabel ? (\n <WidgetText variant=\"caption\" tone=\"light\" translate={false} testId={`${testId}-delta-label`}>\n {escapePlainTextForText(deltaLabel)}\n </WidgetText>\n ) : null}\n </span>\n );\n return (\n <WidgetSurface\n level={isInsideSurface ? \"flat\" : \"elevated\"}\n compact={sizeClass !== \"full\"}\n className={styles.tile}\n testId={testId}\n >\n {isPending ? (\n // The primitive's own loading skeleton animates its style every frame — a capture never settles on it.\n <div className={styles.loading} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <WidgetText variant=\"caption\" tone=\"light\" translate={false} testId={`${testId}-label`}>\n {escapePlainTextForText(label)}\n </WidgetText>\n <SkeletonLine width=\"60%\" height={40} radius={8} />\n </div>\n ) : (\n <WidgetKpiValue\n testId={testId}\n valuePresentation={valueParts.presentation}\n label={escapePlainTextForText(label)}\n accent={\n tone === \"neutral\" || tone === \"muted\" ? undefined : (\n <KpiToneAccent tone={tone} testId={`${testId}-accent`} />\n )\n }\n value={\n <span className={TONE_TEXT_CLASS[tone]} data-testid={`${testId}-value`}>\n <WidgetText translate={false}>{hasValue ? escapePlainTextForText(valueParts.lead) : \"—\"}</WidgetText>\n {valueParts.denominator ? (\n <span className={styles.denominator}>\n <WidgetText translate={false}>{escapePlainTextForText(valueParts.denominator)}</WidgetText>\n </span>\n ) : null}\n </span>\n }\n meter={\n ratio ? (\n <KpiMeter value={ratio.value} max={ratio.max} color={readMeterColor(tone)} testId={`${testId}-meter`} />\n ) : undefined\n }\n unit={\n secondary ? (\n <span className={styles.unitParts}>\n <WidgetText variant=\"value\" translate={false} inline testId={`${testId}-value-secondary`}>\n {escapePlainTextForText(secondary)}\n </WidgetText>\n {unit ? <WidgetText translate={false}>{escapePlainTextForText(unit)}</WidgetText> : null}\n </span>\n ) : unit ? (\n escapePlainTextForText(unit)\n ) : undefined\n }\n delta={deltaElement}\n />\n )}\n {detail ? (\n <WidgetText variant=\"caption\" tone=\"light\" translate={false} testId={`${testId}-detail`}>\n {escapePlainTextForText(detail)}\n </WidgetText>\n ) : null}\n <DataFootnote\n source={nodeProps.source}\n isEmailRender={runtime.isEmailRender}\n appearance=\"quiet\"\n testId={`${testId}-footnote`}\n />\n </WidgetSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"KpiTile\", component: KpiTileNode };\n","import { createContext, useContext } from \"react\";\n/**\n * Where a data node sits: a `TableRow` must know it is inside a `Table` to render a `<tr>`,\n * a `TableCell` inside a header row to render a `<th>`, a `Repeat` inside a `Table` or `List` to repeat only the row\n * nodes those containers take. Outside its container each node renders a standalone fallback instead of invalid\n * markup — a model may put a `TableRow` at the root, the reader does not forbid it.\n */\n\nexport type DataContainerKind = \"table\" | \"list\" | null;\n\nexport const DataContainerContext = createContext<DataContainerKind>(null);\nexport const useDataContainer = () => useContext(DataContainerContext);\n\nexport interface TableRowContextValue {\n isHeader: boolean;\n isEmphasis: boolean;\n}\n\nexport const TableRowContext = createContext<TableRowContextValue | null>(null);\nexport const useTableRow = () => useContext(TableRowContext);\n\nexport interface ListContextValue {\n marker: \"none\" | \"bullet\" | \"number\" | \"check\";\n}\n\nexport const ListContext = createContext<ListContextValue>({ marker: \"none\" });\nexport const useListMarker = () => useContext(ListContext).marker;\n\n/** The node types a container takes from a `Repeat` inside it. */\nexport const REPEATABLE_NODE_TYPES_BY_CONTAINER: Record<Exclude<DataContainerKind, null>, string> = {\n table: \"TableRow\",\n list: \"ListItem\",\n};\n","import { Icon, Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport type { ListContextValue } from \"../data-containers\";\nimport styles from \"./ListEntry.module.scss\";\n\nexport interface ListEntryProps {\n marker: ListContextValue[\"marker\"];\n title?: string;\n description?: string;\n meta?: string;\n value?: string;\n /** Nodes under the title (a ListItem's slot). */\n children?: ReactNode;\n /** Nodes at the end of the entry (a ListItem's `trailing` slot). */\n trailing?: ReactNode;\n /** Render a `<div>` instead of an `<li>` — an entry outside a list. */\n isStandalone?: boolean;\n testId?: string;\n}\n\n/**\n * One list entry: marker | title over description\n * and muted meta, then the nodes under them | value and trailing nodes. All text is the model's (no translation).\n */\nexport const ListEntry = (props: ListEntryProps) => {\n const { marker, title, description, meta, value, children, trailing, isStandalone = false, testId } = props;\n const EntryElement = isStandalone ? \"div\" : \"li\";\n return (\n <EntryElement className={classNames(styles.entry, marker !== \"none\" && styles.withMarker)} data-testid={testId}>\n {marker === \"bullet\" ? <span className={styles.bullet} aria-hidden=\"true\" /> : null}\n {marker === \"number\" ? <span className={styles.number} aria-hidden=\"true\" /> : null}\n {marker === \"check\" ? (\n <span className={styles.check} aria-hidden=\"true\">\n <Icon pixelSize={16} color=\"var(--agents-success-500)\" name=\"check\" />\n </span>\n ) : null}\n <span className={styles.text}>\n {title ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n {description ? (\n <Text role=\"help\" translate={false}>\n {escapePlainTextForText(description)}\n </Text>\n ) : null}\n {meta ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(meta)}\n </Text>\n ) : null}\n {children}\n </span>\n {value || trailing ? (\n <span className={styles.trailing}>\n {value ? (\n <Text role=\"body\" weight=\"medium\" className={styles.value} translate={false}>\n {escapePlainTextForText(value)}\n </Text>\n ) : null}\n {trailing}\n </span>\n ) : null}\n </EntryElement>\n );\n};\n","import { classNames } from \"../../../provider/class-names\";\nimport { useMemo } from \"react\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, ListContext, ListContextValue } from \"./data-containers\";\nimport { readObject, readText } from \"./data-value-format\";\nimport { ListEntry } from \"./ListEntry/ListEntry\";\nimport { DataEmptyLine } from \"./DataEmptyLine/DataEmptyLine\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./List.module.scss\";\n\nconst MARKERS: ReadonlyArray<ListContextValue[\"marker\"]> = [\"none\", \"bullet\", \"number\", \"check\"];\n\ninterface ShortFormListEntry {\n title?: string;\n description?: string;\n meta?: string;\n value?: string;\n}\n\n/** One entry of the short form: a string is the title; an object gives title / description / meta / value. */\nconst readShortFormEntry = (itemValue: ExpressionValue): ShortFormListEntry | undefined => {\n const itemText = readText(itemValue);\n if (itemText !== undefined) return { title: itemText };\n const itemObject = readObject(itemValue);\n if (!itemObject) return undefined;\n const entry: ShortFormListEntry = {\n title: readText(itemObject.title) ?? readText(itemObject.label) ?? readText(itemObject.name),\n description: readText(itemObject.description) ?? readText(itemObject.text),\n meta: readText(itemObject.meta),\n value: readText(itemObject.value),\n };\n return entry.title || entry.description ? entry : undefined;\n};\n\n/**\n * The `List` node: entries divided by hairlines, an `<ol>` when\n * the marker is `number`, a `<ul>` otherwise. The short form `items` renders before the node form's `ListItem` /\n * `Repeat` children. The short form is capped at `maxRepeatRows` (reported); no entry at all shows one muted line and\n * reports `empty`.\n */\nconst ListNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, isPending, testId } = props;\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n const marker = MARKERS.find((knownMarker) => knownMarker === nodeProps.marker) ?? \"none\";\n const listContextValue = useMemo<ListContextValue>(() => ({ marker }), [marker]);\n const shortFormEntries = (Array.isArray(nodeProps.items) ? nodeProps.items : [])\n .map(readShortFormEntry)\n .filter((entry): entry is ShortFormListEntry => entry !== undefined);\n const shownEntries = shortFormEntries.slice(0, maxRepeatRows);\n const childEntries = slots.children ?? [];\n const isEmpty = !isPending && shortFormEntries.length === 0 && childEntries.length === 0;\n const isOverEntryBudget = shortFormEntries.length > maxRepeatRows;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : isOverEntryBudget ? \"failed\" : isEmpty ? \"empty\" : \"mounted\",\n isOverEntryBudget ? \"BUDGET_EXCEEDED\" : isEmpty ? \"NO_DATA\" : undefined,\n isOverEntryBudget\n ? `the List shows the first ${maxRepeatRows} of ${shortFormEntries.length} entries only`\n : isEmpty\n ? \"the List has no entries\"\n : undefined,\n );\n if (isEmpty) return <DataEmptyLine emptyText={nodeProps.emptyText} testId={`${testId}-empty`} />;\n const ListElement = marker === \"number\" ? \"ol\" : \"ul\";\n return (\n <ListElement className={classNames(styles.list, marker === \"number\" && styles.numbered)} data-testid={testId}>\n <ListContext.Provider value={listContextValue}>\n {shownEntries.map((entry, entryIndex) => (\n <ListEntry\n key={entryIndex}\n testId={`${testId}-entry-${entryIndex}`}\n marker={marker}\n title={entry.title}\n description={entry.description}\n meta={entry.meta}\n value={entry.value}\n />\n ))}\n <DataContainerContext.Provider value=\"list\">{childEntries}</DataContainerContext.Provider>\n </ListContext.Provider>\n </ListElement>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"List\", component: ListNode };\n","import type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, useDataContainer, useListMarker } from \"./data-containers\";\nimport { readText } from \"./data-value-format\";\nimport { ListEntry } from \"./ListEntry/ListEntry\";\n\n/**\n * The `ListItem` node: one `List` entry — title, description, meta, value — with the nodes of its\n * slot under the title and those of `trailing` at its end. The nodes inside are no longer \"in the list\", so a\n * `Repeat` in an entry repeats freely. Outside a `List` it renders the same entry as a standalone row.\n */\nconst ListItemNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, testId } = props;\n const container = useDataContainer();\n const marker = useListMarker();\n const isInList = container === \"list\";\n return (\n <ListEntry\n testId={testId}\n marker={isInList ? marker : \"none\"}\n title={readText(nodeProps.title)}\n description={readText(nodeProps.description)}\n meta={readText(nodeProps.meta)}\n value={readText(nodeProps.value)}\n trailing={\n slots.trailing && slots.trailing.length > 0 ? (\n <DataContainerContext.Provider value={null}>{slots.trailing}</DataContainerContext.Provider>\n ) : undefined\n }\n isStandalone={!isInList}\n >\n {slots.children && slots.children.length > 0 ? (\n <DataContainerContext.Provider value={null}>{slots.children}</DataContainerContext.Provider>\n ) : null}\n </ListEntry>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"ListItem\", component: ListItemNode };\n","import type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { REPEATABLE_NODE_TYPES_BY_CONTAINER, useDataContainer } from \"./data-containers\";\nimport { readFiniteNumber } from \"./data-value-format\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\n\n/**\n * The `Repeat` node: its children once per item, with `{\"$item\":…}` bound to the item. It\n * renders no element of its own, so the repeated nodes sit where it sits — table rows in a `Table`, entries in a\n * `List`, tiles in a `Grid`. Inside a `Table` it repeats only its `TableRow`s, inside a `List` only its `ListItem`s\n * (anything else would be invalid markup there) and reports the rest. The renderer caps the items at `maxRepeatRows`\n * (`renderSlotForItem`) and reports the overflow; `limit` cuts earlier. An empty list reports `empty`.\n */\nconst RepeatNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, runtime, isPending, renderSlotForItem } = props;\n const container = useDataContainer();\n const items = Array.isArray(nodeProps.items) ? nodeProps.items : undefined;\n const limit = readFiniteNumber(nodeProps.limit);\n const shownItems = items && limit !== undefined && limit >= 0 ? items.slice(0, Math.floor(limit)) : (items ?? []);\n const childNodeTypes = (node.nodesBySlotName.children ?? []).map((childNode) => childNode.type);\n const acceptedNodeType = container ? REPEATABLE_NODE_TYPES_BY_CONTAINER[container] : undefined;\n const droppedNodeTypes = acceptedNodeType\n ? childNodeTypes.filter((childNodeType) => childNodeType !== acceptedNodeType)\n : [];\n const hasNoList = !isPending && items === undefined;\n useReportDataNodeStatus(\n runtime,\n isPending\n ? \"pending\"\n : hasNoList || droppedNodeTypes.length > 0\n ? \"failed\"\n : shownItems.length === 0\n ? \"empty\"\n : \"mounted\",\n hasNoList\n ? \"UNRESOLVED_BINDING\"\n : droppedNodeTypes.length > 0\n ? \"INVALID_NODE\"\n : shownItems.length === 0 && !isPending\n ? \"NO_DATA\"\n : undefined,\n hasNoList\n ? \"the Repeat items are not a list\"\n : droppedNodeTypes.length > 0\n ? `a Repeat in a ${container} repeats ${acceptedNodeType} nodes only — ${droppedNodeTypes.join(\", \")} not shown`\n : shownItems.length === 0 && !isPending\n ? \"the Repeat has no items\"\n : undefined,\n );\n const repeatedNodes = shownItems.flatMap((item, itemIndex) =>\n renderSlotForItem(\"children\", item, itemIndex).filter(\n (renderedNode, childPosition) =>\n acceptedNodeType === undefined || childNodeTypes[childPosition] === acceptedNodeType,\n ),\n );\n return <>{repeatedNodes}</>;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Repeat\", component: RepeatNode };\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n DataValueAlign,\n DataValueFormat,\n isNumericValue,\n readDataValueAlign,\n readDataValueFormat,\n readFiniteNumber,\n readObject,\n readText,\n} from \"./data-value-format\";\n\n/** One column of a `Table`'s short form (`columns`): the row field, its header and how its cells are shown. */\nexport interface TableColumn {\n key: string;\n label: string;\n align: DataValueAlign;\n format: DataValueFormat;\n currency?: string;\n decimals?: number;\n unit?: string;\n}\n\n/**\n * The short form's columns from the resolved `columns` prop: every entry with a string `key` (alias `field`, which a\n * model writes because `Chart` series use it); the header falls back to the key; a column without an `align` aligns\n * at the end when every value in it is a number.\n */\nexport const readTableColumns = (\n columnsValue: ExpressionValue,\n rows: Record<string, ExpressionValue>[],\n): TableColumn[] => {\n if (!Array.isArray(columnsValue)) return [];\n const columns: TableColumn[] = [];\n for (const columnValue of columnsValue) {\n const column = readObject(columnValue);\n const key = readText(column?.key) ?? readText(column?.field);\n if (!column || !key) continue;\n const values = rows.map((row) => row[key]).filter((value) => value !== undefined && value !== null && value !== \"\");\n const isNumericColumn = values.length > 0 && values.every((value) => isNumericValue(value));\n columns.push({\n key,\n label: readText(column.label) ?? key,\n align: readDataValueAlign(column.align, isNumericColumn ? \"end\" : \"start\"),\n format: readDataValueFormat(column.format),\n currency: readText(column.currency),\n decimals: readFiniteNumber(column.decimals),\n unit: readText(column.unit),\n });\n }\n return columns;\n};\n","import { Icon, Text } from \"../../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { DataValueFormat, DataValueTone, formatDataValue } from \"../data-value-format\";\nimport { TONE_GRAPHIC_COLOR, TONE_TEXT_COLOR } from \"../data-tones\";\nimport { useNumberLocale } from \"../use-number-locale\";\nimport { translateText } from \"../../../../provider/environment\";\nimport styles from \"./TableValue.module.scss\";\n\nexport interface TableValueProps {\n value: ExpressionValue;\n format: DataValueFormat;\n currency?: string;\n decimals?: number;\n unit?: string;\n signed?: boolean;\n tone?: DataValueTone;\n isBold?: boolean;\n}\n\n/**\n * One table value: a formatted number or text in the cell's tone, tabular figures; a boolean as a check (yes, green)\n * or a cross (no, red) with its meaning for screen readers — ChatGPT's majority column. Empty renders nothing.\n */\nexport const TableValue = (props: TableValueProps) => {\n const { value, format, currency, decimals, unit, signed = false, tone = \"neutral\", isBold = false } = props;\n const locale = useNumberLocale();\n if (typeof value === \"boolean\") {\n return (\n <span className={styles.booleanValue} role=\"img\" aria-label={translateText(value ? \"Yes\" : \"No\")}>\n <Icon pixelSize={16} color={TONE_GRAPHIC_COLOR[value ? \"success\" : \"danger\"]} name={value ? \"check\" : \"close\"} />\n </span>\n );\n }\n const formattedValue = formatDataValue(value, { format, currency, decimals, unit, signed, locale });\n if (formattedValue === \"\") return null;\n return (\n <Text\n role=\"help\"\n weight={isBold ? \"bold\" : \"regular\"}\n color={TONE_TEXT_COLOR[tone]}\n className={styles.value}\n translate={false}\n >\n {escapePlainTextForText(formattedValue)}\n </Text>\n );\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext } from \"./data-containers\";\nimport { readRows } from \"./data-value-format\";\nimport { readTableColumns } from \"./table-columns\";\nimport { TableValue } from \"./TableValue/TableValue\";\nimport { DataFootnote } from \"./DataFootnote/DataFootnote\";\nimport { DataEmptyLine } from \"./DataEmptyLine/DataEmptyLine\";\nimport { useReportDataNodeStatus } from \"./use-report-data-node-status\";\nimport styles from \"./Table.module.scss\";\n\nconst SKELETON_ROW_COUNT = 3;\n\n/**\n * The `Table` node. The short form — `columns` + `rows` — writes the\n * header row and one row per data row, each cell formatted by its column (a boolean as a check or a cross). The node\n * form — `TableRow` / `Repeat` children — follows it in the same body, so a total row can close the data rows. Rows\n * are hairline-divided, never boxed; a table wider than the chat pane scrolls inside itself. A\n * table still waiting for bound rows shows row-shaped skeletons; one with nothing to show one muted line and reports\n * `empty`. The short form renders at most `maxRepeatRows` rows and reports the rest.\n */\nconst TableNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, isPending, testId } = props;\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n const rows = readRows(nodeProps.rows) ?? [];\n const columns = readTableColumns(nodeProps.columns, rows);\n const shownRows = rows.slice(0, maxRepeatRows);\n const childRows = slots.children ?? [];\n const isWaitingForRows = isPending && rows.length === 0;\n const isEmpty = !isPending && (columns.length === 0 || rows.length === 0) && childRows.length === 0;\n const isOverRowBudget = rows.length > maxRepeatRows;\n useReportDataNodeStatus(\n runtime,\n isPending ? \"pending\" : isOverRowBudget ? \"failed\" : isEmpty ? \"empty\" : \"mounted\",\n isOverRowBudget ? \"BUDGET_EXCEEDED\" : isEmpty && !isPending ? \"NO_DATA\" : undefined,\n isOverRowBudget\n ? `the Table shows the first ${maxRepeatRows} of ${rows.length} rows only`\n : isEmpty && !isPending\n ? \"the Table has no rows\"\n : undefined,\n );\n return (\n <div className={styles.table} data-testid={testId}>\n <div className={styles.scroller}>\n <table className={styles.grid}>\n {columns.length > 0 ? (\n <thead>\n <tr>\n {columns.map((column) => (\n <th key={column.key} scope=\"col\" className={classNames(styles.cell, styles[column.align])}>\n <Text role=\"help\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(column.label)}\n </Text>\n </th>\n ))}\n </tr>\n </thead>\n ) : null}\n <tbody>\n {shownRows.map((row, rowIndex) => (\n <tr key={rowIndex} className={styles.row} data-testid={`${testId}-row-${rowIndex}`}>\n {columns.map((column) => (\n <td key={column.key} className={classNames(styles.cell, styles[column.align])}>\n <TableValue\n value={row[column.key]}\n format={column.format}\n currency={column.currency}\n decimals={column.decimals}\n unit={column.unit}\n />\n </td>\n ))}\n </tr>\n ))}\n {isWaitingForRows && columns.length > 0\n ? Array.from({ length: SKELETON_ROW_COUNT }, (unused, skeletonIndex) => (\n <tr\n key={`skeleton-${skeletonIndex}`}\n className={styles.row}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton-${skeletonIndex}`}\n >\n {columns.map((column) => (\n <td key={column.key} className={classNames(styles.cell, styles[column.align])}>\n <SkeletonLine width=\"70%\" height={12} />\n </td>\n ))}\n </tr>\n ))\n : null}\n <DataContainerContext.Provider value=\"table\">{childRows}</DataContainerContext.Provider>\n </tbody>\n </table>\n </div>\n {isEmpty ? <DataEmptyLine emptyText={nodeProps.emptyText} testId={`${testId}-empty`} /> : null}\n <DataFootnote caption={nodeProps.caption} source={nodeProps.source} isEmailRender={runtime.isEmailRender} />\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Table\", component: TableNode };\n","import { classNames } from \"../../../provider/class-names\";\nimport { CSSProperties } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, useTableRow } from \"./data-containers\";\nimport {\n formatDataValue,\n isNumericValue,\n readDataValueAlign,\n readDataValueFormat,\n readDataValueTone,\n readFiniteNumber,\n readFraction,\n readText,\n} from \"./data-value-format\";\nimport { TableValue } from \"./TableValue/TableValue\";\nimport { useNumberLocale } from \"./use-number-locale\";\nimport tableStyles from \"./Table.module.scss\";\nimport styles from \"./TableCell.module.scss\";\n\n/**\n * The `TableCell` node (`Cell.content`): a formatted `value`, then the nodes of its compact slot\n * (an `Icon`, a `Badge`, a sparkline `Chart`) — the cell is the place where a table holds other nodes. `bar` draws a\n * share bar before the value, `heat` tints the whole cell by intensity with the value on top (no value = a muted dash on the untinted tile). In a header row the cell is a `<th>`; outside a row it is a plain\n * inline block. The bar and heat widths travel as CSS custom properties — the one dynamic value, no inline style.\n */\nconst TableCellNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots } = props;\n const tableRow = useTableRow();\n const locale = useNumberLocale();\n const isHeader = tableRow?.isHeader ?? false;\n const isBold = isHeader || (tableRow?.isEmphasis ?? false);\n const align = readDataValueAlign(nodeProps.align, isNumericValue(nodeProps.value) ? \"end\" : \"start\");\n const format = readDataValueFormat(nodeProps.format);\n const bar = readFraction(nodeProps.bar);\n const heat = readFraction(nodeProps.heat);\n // A heat cell is one whose node declares `heat`, even when its binding resolved to nothing (a missing cohort month).\n const isHeatCell = Object.prototype.hasOwnProperty.call(node.props, \"heat\");\n const hasValue = formatDataValue(nodeProps.value, { format, locale }) !== \"\" || typeof nodeProps.value === \"boolean\";\n const cellStyle = {\n ...(bar !== undefined ? { \"--agents-table-cell-bar\": `${Math.round(bar * 1000) / 10}%` } : {}),\n ...(heat !== undefined ? { \"--agents-table-cell-heat\": `${Math.round(10 + heat * 70)}%` } : {}),\n } as CSSProperties;\n const content = (\n <span\n className={classNames(\n styles.content,\n styles[align],\n bar !== undefined && styles.withBar,\n isHeatCell && styles.heat,\n isHeatCell && heat === undefined && styles.heatEmpty,\n )}\n >\n {bar !== undefined ? <span className={styles.bar} aria-hidden=\"true\" /> : null}\n {hasValue ? (\n <TableValue\n value={nodeProps.value}\n format={format}\n currency={readText(nodeProps.currency)}\n decimals={readFiniteNumber(nodeProps.decimals)}\n unit={readText(nodeProps.unit)}\n signed={nodeProps.signed === true}\n tone={readDataValueTone(nodeProps.tone)}\n isBold={isBold}\n />\n ) : isHeatCell ? (\n <span className={styles.dash}>{\"—\"}</span>\n ) : null}\n {slots.children && slots.children.length > 0 ? (\n <DataContainerContext.Provider value={null}>{slots.children}</DataContainerContext.Provider>\n ) : null}\n </span>\n );\n if (!tableRow) return <span style={cellStyle}>{content}</span>;\n const cellClassName = classNames(tableStyles.cell, tableStyles[align], isHeatCell && styles.heatCell);\n return isHeader ? (\n <th scope=\"col\" className={cellClassName} style={cellStyle}>\n {content}\n </th>\n ) : (\n <td className={cellClassName} style={cellStyle}>\n {content}\n </td>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"TableCell\",\n component: TableCellNode,\n};\n","import { classNames } from \"../../../provider/class-names\";\nimport { useMemo } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { DataContainerContext, TableRowContext, TableRowContextValue, useDataContainer } from \"./data-containers\";\nimport styles from \"./Table.module.scss\";\n\n/**\n * The `TableRow` node (`Row.cells`): a `<tr>` of its `TableCell`s; `header` makes the cells\n * column headers, `emphasis` a bold total row. Outside a `Table` (a row at the root, a `Repeat` of rows without a\n * table) it wraps itself in a one-row table, so the markup stays valid.\n */\nconst TableRowNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, testId } = props;\n const container = useDataContainer();\n const isHeader = nodeProps.header === true;\n const isEmphasis = nodeProps.emphasis === true;\n const tableRowContextValue = useMemo<TableRowContextValue>(() => ({ isHeader, isEmphasis }), [isHeader, isEmphasis]);\n const row = (\n <tr className={classNames(styles.row, isHeader && styles.headerRow)} data-testid={testId}>\n <TableRowContext.Provider value={tableRowContextValue}>{slots.children}</TableRowContext.Provider>\n </tr>\n );\n if (container === \"table\") return row;\n return (\n <div className={styles.scroller}>\n <table className={styles.grid}>\n <tbody>\n <DataContainerContext.Provider value=\"table\">{row}</DataContainerContext.Provider>\n </tbody>\n </table>\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"TableRow\", component: TableRowNode };\n","import React from \"react\";\nimport { reportWidgetCrash } from \"../provider/environment\";\n\ninterface Props {\n /** Canonical widget name, for the error log. */\n widgetName: string;\n /** Called once when the widget threw — the render report marks the block `failed`. */\n onCrash?: () => void;\n children: React.ReactNode;\n}\n\ninterface State {\n hasError: boolean;\n}\n\n/**\n * Per-widget error boundary. Widget props originate from LLM output, so a\n * malformed payload can throw anywhere in a widget's render/effects — without a\n * boundary one bad widget unmounts the entire chat message. On error the\n * widget renders nothing (the surrounding prose stays intact) and the failure\n * is logged with the widget name.\n */\nexport class ConversationWidgetErrorBoundary extends React.Component<Props, State> {\n state: State = { hasError: false };\n\n static getDerivedStateFromError(): State {\n return { hasError: true };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {\n console.error(`[ConversationMarkdown] widget \"${this.props.widgetName}\" crashed`, error, errorInfo);\n reportWidgetCrash(this.props.widgetName, error, errorInfo);\n this.props.onCrash?.();\n }\n\n render(): React.ReactNode {\n if (this.state.hasError) {\n return null;\n }\n\n return this.props.children;\n }\n}\n","import React from \"react\";\nimport { WidgetFeatureGate } from \"../../provider/components\";\n\n/** Shared prop contract for any widget upgrade offer (a widget's own `upsellTrigger`); the flag is the app's object. */\nexport interface ConversationWidgetUpsellProps {\n flag: unknown;\n}\n\ninterface ConversationWidgetFeatureGateProps {\n /** The requirement the widget declares in the registry (an app feature flag, opaque to the package). */\n featureFlag: string;\n /** Optional per-widget upgrade offer; falls back to the app gate's own. */\n UpsellTrigger?: React.ComponentType<ConversationWidgetUpsellProps>;\n /** The widget's raw agent space key attribute (renders for another agent space). */\n agentSpaceKeyAttribute?: string | number;\n children: React.ReactNode;\n}\n\n/**\n * Gates a widget on the requirement its registry entry declares, through the app's `WidgetFeatureGate` component (the\n * environment's): the widget, a placeholder while the requirements load, or an upgrade offer. Without an app gate\n * every widget renders.\n */\nexport const ConversationWidgetFeatureGate = (props: ConversationWidgetFeatureGateProps) => {\n const { featureFlag, UpsellTrigger, agentSpaceKeyAttribute, children } = props;\n return (\n <WidgetFeatureGate featureFlag={featureFlag} UpsellTrigger={UpsellTrigger} agentSpaceKeyAttribute={agentSpaceKeyAttribute}>\n {children}\n </WidgetFeatureGate>\n );\n};\n","import { useEffect, useMemo } from \"react\";\nimport { conversationWidgetRegistry } from \"../../../renderer/conversationWidgetRegistry\";\nimport { resolveWidgetName } from \"../../../renderer/widget-name-resolver\";\nimport { ConversationWidgetErrorBoundary } from \"../../../renderer/ConversationWidgetErrorBoundary\";\nimport {\n buildWidgetAgentSpaceKeyProps,\n readWidgetAgentSpaceKeyAttribute,\n} from \"../../../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport { ConversationWidgetFeatureGate } from \"../../../renderer/_access/ConversationWidgetFeatureGate\";\nimport {\n WidgetRenderReportCode,\n WidgetRenderReportContext,\n WidgetRenderReporter,\n WidgetRenderStatus,\n} from \"../../../renderer/render-report/widget-render-report\";\n\nexport interface EmbeddedConversationWidgetProps {\n /** The wire name as written (a legacy `…Directive` name resolves as everywhere). */\n widgetName: string;\n /** The widget's own fields — its `payload`, exactly as its own fence would carry them next to `type`. */\n fields: Record<string, unknown>;\n /** The key of the tree's agent space; the key in the fields wins. */\n agentSpaceKey?: string | number;\n interactive: boolean;\n messageId?: string | number;\n /**\n * Where the widget's own render report goes — the tree's report at the node's path, never the host block's reporter\n * (an embedded widget and the tree would otherwise overwrite each other's report).\n */\n reportStatus: (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) => void;\n}\n\n/**\n * A domain widget rendered inside a `ComposedView` — as a `Widget` node in the tree, or as a widget the readers LIFTED\n * out of it and show after the view. It renders the registered component with the tree's\n * context: `interactive` and `messageId` of the host message, the agent space, and `justDelivered = false`, so it never\n * auto-opens a canvas (the owner opens it by clicking). It gets its OWN render-report context, which forwards its\n * statuses into the tree's report, names the widget in the detail, and turns a crash (`RENDER_FAILED`) or an unknown\n * name (`INVALID_NODE`) into a report instead of a silent nothing. The registry's feature gate applies as it does to\n * the widget's own fence. The registry is read at render time, never at module load (the registry imports this kit).\n */\nexport const EmbeddedConversationWidget = (props: EmbeddedConversationWidgetProps) => {\n const { widgetName, fields, agentSpaceKey, interactive, messageId, reportStatus } = props;\n const resolvedWidgetName = resolveWidgetName(widgetName);\n const entry = resolvedWidgetName\n ? conversationWidgetRegistry.widgets.find((widget) => widget.name === resolvedWidgetName)\n : undefined;\n const reporter = useMemo<WidgetRenderReporter>(\n () => ({\n report: (reportEntry) =>\n reportStatus(\n reportEntry.status,\n reportEntry.code,\n reportEntry.detail ? `${resolvedWidgetName ?? widgetName}: ${reportEntry.detail}` : undefined,\n ),\n }),\n [reportStatus, resolvedWidgetName, widgetName],\n );\n const payload = useMemo(() => JSON.stringify(fields), [fields]);\n\n useEffect(() => {\n if (!entry) reportStatus(\"failed\", \"INVALID_NODE\", `no registered widget \"${widgetName}\"`);\n }, [entry, reportStatus, widgetName]);\n\n if (!entry) return null;\n const EmbeddedComponent = entry.component;\n const fieldAgentSpaceKey = readWidgetAgentSpaceKeyAttribute(fields) ?? agentSpaceKey;\n const embeddedAgentSpaceKey =\n typeof fieldAgentSpaceKey === \"string\" || typeof fieldAgentSpaceKey === \"number\"\n ? String(fieldAgentSpaceKey)\n : undefined;\n const embeddedWidget = (\n <WidgetRenderReportContext.Provider value={reporter}>\n <ConversationWidgetErrorBoundary\n widgetName={entry.name}\n onCrash={() => reportStatus(\"failed\", \"RENDER_FAILED\", `the embedded ${entry.name} threw`)}\n >\n <EmbeddedComponent\n payload={payload}\n {...buildWidgetAgentSpaceKeyProps(embeddedAgentSpaceKey)}\n interactive={interactive}\n fresh={interactive}\n justDelivered={false}\n messageId={messageId}\n />\n </ConversationWidgetErrorBoundary>\n </WidgetRenderReportContext.Provider>\n );\n // The registry's feature gate holds inside a tree exactly as for the widget's own fence.\n if (!entry.featureFlag) return embeddedWidget;\n return (\n <ConversationWidgetFeatureGate\n featureFlag={entry.featureFlag}\n UpsellTrigger={entry.upsellTrigger}\n agentSpaceKeyAttribute={embeddedAgentSpaceKey}\n >\n {embeddedWidget}\n </ConversationWidgetFeatureGate>\n );\n};\n","import { useMemo } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { EmbeddedConversationWidget } from \"./EmbeddedConversationWidget\";\n\n/**\n * The core `Widget` node (`WidgetComposedViewNode.php`): an existing domain widget inside the tree,\n * rendered through {@link EmbeddedConversationWidget} with the tree's per-slot context. The node's `fields` become the\n * widget's `payload`, exactly as its own fence would carry them next to `type`. The widget reports into the tree at this\n * node's path (`runtime.reportNodeStatus`), never into the host block's reporter.\n */\nconst WidgetNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, runtime } = props;\n const fields = useMemo(\n () =>\n typeof nodeProps.fields === \"object\" && nodeProps.fields !== null && !Array.isArray(nodeProps.fields)\n ? (nodeProps.fields as Record<string, unknown>)\n : {},\n [nodeProps.fields],\n );\n return (\n <EmbeddedConversationWidget\n widgetName={typeof nodeProps.widget === \"string\" ? nodeProps.widget : \"\"}\n fields={fields}\n agentSpaceKey={runtime.agentSpaceKey}\n interactive={runtime.interactive}\n messageId={runtime.messageId}\n reportStatus={runtime.reportNodeStatus}\n />\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Widget\", component: WidgetNode };\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { readOpenEntityActionTarget } from \"../../../renderer/canvas/entity-detail-instance\";\nimport type { ComposedViewRuntime } from \"../../composed-view-component-types\";\n\n/**\n * Whether an `EntityLink`'s click opens a detail panel. Pure; never throws.\n *\n * - `missing` — no action name (`action` absent, empty or not text);\n * - `unresolved` — the tree's action of that name is gone (the persist pass dropped it), is not `openEntity`, or\n * carries no resolved `entity` — the reference did not resolve, a click would open nothing;\n * - `resolved` — an `openEntity` action with its resolved entity — for a row-bound action (`ref: {\"$item\":\"entityRef\"}`)\n * the `entity` of the row the link renders in (`runtime.currentRow`);\n * - `unchecked` — the runtime cannot look actions up (it has no `findAction`), so the name is trusted and the click\n * runs the action; the widget opens nothing for an unresolved one.\n */\nexport type EntityLinkTargetState = \"missing\" | \"unresolved\" | \"resolved\" | \"unchecked\";\n\nexport interface EntityLinkTarget {\n state: EntityLinkTargetState;\n actionName: string;\n}\n\n/**\n * The runtime's optional action lookup: the tree action by name, or undefined. Not on `ComposedViewRuntime` yet — the\n * renderer adds it; until then every link is `unchecked`.\n */\ntype RuntimeWithActionLookup = ComposedViewRuntime & {\n findAction?: (actionName: string) => Record<string, unknown> | undefined;\n};\n\nexport const readEntityLinkTarget = (actionProp: ExpressionValue, runtime: ComposedViewRuntime): EntityLinkTarget => {\n const actionName = typeof actionProp === \"string\" ? actionProp.trim() : \"\";\n if (actionName === \"\") return { state: \"missing\", actionName: \"\" };\n const { findAction } = runtime as RuntimeWithActionLookup;\n if (typeof findAction !== \"function\") return { state: \"unchecked\", actionName };\n const action = findAction(actionName);\n if (\n action === undefined ||\n action.type !== \"openEntity\" ||\n readOpenEntityActionTarget(action, runtime.currentRow) === undefined\n ) {\n return { state: \"unresolved\", actionName };\n }\n return { state: \"resolved\", actionName };\n};\n","import { Icon, InteractiveSurface, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type {\n ComposedViewComponentDefinition,\n ComposedViewComponentProps,\n} from \"../../composed-view-component-types\";\nimport {\n readAllowedValue,\n readTextNodeContent,\n} from \"../text/shared/text-node-values\";\nimport { readEntityLinkTarget, type EntityLinkTargetState } from \"./entity-link-target\";\nimport styles from \"./EntityLink.module.scss\";\n\nconst VARIANTS = [\"link\", \"title\", \"chip\"] as const;\n\n/**\n * The `EntityLink` node (`EntityLinkComposedViewNode.php`; ChatGPT's `Entity` — the dotted-underlined\n * business name that opens a detail panel): the name of an entity a tool returned. A\n * click runs the tree's `openEntity` action named by `action`; the widget opens the `entityDetail` canvas for the\n * entity the backend resolved the platform-minted reference to. `link` (default) sits in a sentence or a table cell,\n * `title` is the bold headline of a Surface (a business name), `chip` a small pill with the detail\n * glyph.\n *\n * Without a usable action — no `action`, an action that is not `openEntity`, a reference the backend did not resolve —\n * the name shows as plain text and the node reports `failed UNRESOLVED_REF`, so the model learns the panel does not\n * open. In the e-mail capture the name shows without a control. A link never sends a chat message.\n */\nconst EntityLinkNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const content = readTextNodeContent(nodeProps.text);\n const variant = readAllowedValue(nodeProps.variant, VARIANTS, \"link\");\n const target = readEntityLinkTarget(nodeProps.action, runtime);\n const targetState: EntityLinkTargetState = target.state;\n const contentKind = content.kind;\n\n useEffect(() => {\n if (isPending) reportNodeStatus(\"pending\");\n else if (contentKind === \"missing\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the EntityLink has no name to show\");\n else if (contentKind === \"invalid\")\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the EntityLink got a name that is not text\");\n else if (targetState === \"missing\") {\n reportNodeStatus(\n \"failed\",\n \"UNRESOLVED_REF\",\n \"the EntityLink names no openEntity action — its name shows without a link\",\n );\n } else if (targetState === \"unresolved\") {\n reportNodeStatus(\n \"failed\",\n \"UNRESOLVED_REF\",\n \"the EntityLink's openEntity action has no resolved entity reference — its name shows without a link\",\n );\n } else reportNodeStatus(\"mounted\");\n }, [isPending, contentKind, targetState, reportNodeStatus]);\n\n if (isPending) return <SkeletonLine width=\"7em\" height={12} radius={4} />;\n if (content.kind !== \"text\") return null;\n const name = escapePlainTextForText(content.text);\n const isClickable = target.state !== \"missing\" && target.state !== \"unresolved\" && !runtime.isEmailRender;\n\n const isTitle = variant === \"title\";\n const textType = isTitle ? \"intro\" : \"body\";\n const fontWeight = isTitle ? \"bold\" : undefined;\n if (!isClickable) {\n return (\n <Text\n role={textType}\n weight={fontWeight}\n translate={false}\n display=\"inline\"\n className={classNames(styles.plainName, variant === \"chip\" && styles.plainChip)}\n testId={`${testId}-name`}\n >\n {name}\n </Text>\n );\n }\n const openDetail = () => runtime.runEvent({ action: target.actionName });\n if (variant === \"chip\") {\n return (\n <InteractiveSurface hoverable className={styles.chip}>\n <button type=\"button\" className={styles.chipButton} onClick={openDetail} data-testid=\"composed-entity-link\">\n <Text\n role=\"help\"\n translate={false}\n display=\"inline\"\n className={styles.chipName}\n testId={`${testId}-name`}\n >\n {name}\n </Text>\n <Icon color=\"var(--agents-fg-light)\" className={styles.chipIcon} pixelSize={14} name=\"details\" />\n </button>\n </InteractiveSurface>\n );\n }\n return (\n <button type=\"button\" className={styles.link} onClick={openDetail} data-testid=\"composed-entity-link\">\n <Text\n role={textType}\n weight={fontWeight}\n translate={false}\n display=\"inline\"\n className={styles.linkName}\n testId={`${testId}-name`}\n >\n {name}\n </Text>\n </button>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"EntityLink\",\n component: EntityLinkNode,\n};\n","import type {\n ComposedViewNode,\n JsonValue,\n} from \"../../../renderer/widget-tree/composed-view-tree\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\n\n/**\n * The reaction sentences of a `ComposedView` `Form` node — the frontend half of\n * `composed-view-widget-contract.json`; the backend reader is `ComposedViewConversationWidget::readAnswer()`:\n *\n * ComposedView form \"<name>\" submitted:\n * - <field>: <value>\n *\n * or `ComposedView form \"<name>\" declined.` Posted as a FRONTEND_WIDGET_CLICK signal. A stored contract: never reword it.\n */\n\n/** `FormComposedViewNode::FORM_NAME_PATTERN` — a name the quoted span of the signal can carry. */\nexport const FORM_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** `AIConversationMessage::MAX_SIGNAL_TEXT_CHARS` — the backend cuts a longer signal, so the composer stays below it. */\nexport const MAX_FORM_SIGNAL_CHARS = 2000;\n\nconst ELLIPSIS = \"…\";\n\nexport const isFormNameAllowed = (formName: unknown): formName is string =>\n typeof formName === \"string\" && FORM_NAME_PATTERN.test(formName);\n\n/**\n * One value on its signal line: a boolean as `true` / `false`, an empty value as nothing; inside a text a backslash is\n * written `\\\\`, a line break `\\n`, any other control character becomes a space — so a value never leaves its line.\n */\nexport const formatFormFieldValue = (value: ExpressionValue | undefined): string => {\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return Number.isFinite(value) ? String(value) : \"\";\n if (typeof value !== \"string\") return \"\";\n return value\n .trim()\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\\r\\n|\\r|\\n/g, \"\\\\n\")\n .replace(/\\p{Cc}/gu, \" \");\n};\n\n/** Cuts an escaped value to `maxLength` characters without splitting an escape (`\\\\`, `\\n`) in two. */\nconst cutEscapedValue = (escapedValue: string, maxLength: number): string => {\n if (escapedValue.length <= maxLength) return escapedValue;\n let cutValue = escapedValue.slice(0, Math.max(0, maxLength - ELLIPSIS.length));\n const trailingBackslashCount = /\\\\+$/.exec(cutValue)?.[0].length ?? 0;\n if (trailingBackslashCount % 2 === 1) cutValue = cutValue.slice(0, -1);\n return cutValue + ELLIPSIS;\n};\n\nconst buildFieldLine = (fieldName: string, formattedValue: string) =>\n formattedValue === \"\" ? `- ${fieldName}:` : `- ${fieldName}: ${formattedValue}`;\n\nconst joinSignalLines = (headLine: string, formattedFieldValues: ReadonlyArray<readonly [string, string]>) =>\n [\n headLine,\n ...formattedFieldValues.map(([fieldName, formattedValue]) => buildFieldLine(fieldName, formattedValue)),\n ].join(\"\\n\");\n\n/**\n * The submit sentence: the head line, then one line per field in the given order. Over {@link MAX_FORM_SIGNAL_CHARS}\n * the values share what the head and the field names leave, each cut to its share with an ellipsis.\n */\nexport const composeFormSubmitSignal = (\n formName: string,\n fieldValues: ReadonlyArray<readonly [string, ExpressionValue | undefined]>,\n): string => {\n const headLine = `ComposedView form \"${formName}\" submitted:`;\n const formattedFieldValues = fieldValues.map(\n ([fieldName, value]) => [fieldName, formatFormFieldValue(value)] as const,\n );\n const fullSignal = joinSignalLines(headLine, formattedFieldValues);\n if (fullSignal.length <= MAX_FORM_SIGNAL_CHARS || formattedFieldValues.length === 0) return fullSignal;\n const lengthWithoutValues = joinSignalLines(\n headLine,\n formattedFieldValues.map(([fieldName]) => [fieldName, \"\"] as const),\n ).length;\n // A filled field line is one space plus its value longer than the empty one.\n const valueShare = Math.max(\n ELLIPSIS.length + 1,\n Math.floor((MAX_FORM_SIGNAL_CHARS - lengthWithoutValues) / formattedFieldValues.length) - 1,\n );\n return joinSignalLines(\n headLine,\n formattedFieldValues.map(\n ([fieldName, formattedValue]) => [fieldName, cutEscapedValue(formattedValue, valueShare)] as const,\n ),\n );\n};\n\nexport const composeFormDeclineSignal = (formName: string) => `ComposedView form \"${formName}\" declined.`;\n\n/** The state name a prop value reads or writes: a `{\"$state\": …}` binding or a `{\"set\": …}` event. */\nconst readBoundStateName = (propValue: JsonValue): string | undefined => {\n if (typeof propValue !== \"object\" || propValue === null || Array.isArray(propValue)) return undefined;\n if (typeof propValue.$state === \"string\") return propValue.$state;\n if (typeof propValue.set === \"string\") return propValue.set;\n return undefined;\n};\n\nconst collectBoundStateNamesOfNode = (node: ComposedViewNode, stateNames: string[]): void => {\n for (const propValue of Object.values(node.props)) {\n const stateName = readBoundStateName(propValue);\n if (stateName !== undefined && !stateNames.includes(stateName)) stateNames.push(stateName);\n }\n for (const slotNodes of Object.values(node.nodesBySlotName)) {\n for (const slotNode of slotNodes) collectBoundStateNamesOfNode(slotNode, stateNames);\n }\n};\n\n/**\n * The fields a form sends when its `fields` prop names none: every state name its body binds (`{\"$state\": …}` values,\n * `{\"set\": …}` events), tree order, each once.\n */\nexport const collectBoundStateNames = (formNode: ComposedViewNode): string[] => {\n const stateNames: string[] = [];\n for (const slotNodes of Object.values(formNode.nodesBySlotName)) {\n for (const slotNode of slotNodes) collectBoundStateNamesOfNode(slotNode, stateNames);\n }\n return stateNames;\n};\n\n/** The state names a list prop (`fields`, `requiredFields`) names, each once, kept only when the tree declares that state. */\nexport const readStateNameList = (propValue: JsonValue | undefined, state: Record<string, unknown>): string[] => {\n if (!Array.isArray(propValue)) return [];\n const stateNames: string[] = [];\n for (const stateName of propValue) {\n if (\n typeof stateName === \"string\" &&\n Object.prototype.hasOwnProperty.call(state, stateName) &&\n !stateNames.includes(stateName)\n ) {\n stateNames.push(stateName);\n }\n }\n return stateNames;\n};\n\n/** A required field is filled: not empty, not only spaces, and a checkbox ticked. */\nexport const isFormFieldFilled = (value: ExpressionValue | undefined): boolean => {\n if (value === undefined || value === null || value === false) return false;\n if (typeof value === \"string\") return value.trim() !== \"\";\n return true;\n};\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { createContext, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useConversationWidgetContext } from \"../../../renderer/ConversationWidgetCallbacksContext\";\nimport { ConversationWidgetButton } from \"../../../widgets/_shared/ConversationWidgetButton\";\nimport { DonePill } from \"../../../widgets/_shared/DonePill\";\nimport { WidgetSurface } from \"../../../widgets/_shared/modern\";\nimport { ModelText } from \"../../ModelText/ModelText\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n collectBoundStateNames,\n composeFormDeclineSignal,\n composeFormSubmitSignal,\n isFormFieldFilled,\n isFormNameAllowed,\n readStateNameList,\n} from \"./compose-form-signal\";\nimport styles from \"./Form.module.scss\";\n\n/** True inside a Form's body: a nested Form gives its body to the outer form instead of submitting on its own. */\nconst ComposedViewFormContext = createContext(false);\n\n/** Judgement text in the 900 tone, flipped for the dark scheme (no functional error token). */\nconst ERROR_TEXT_COLOR = \"light-dark(var(--agents-danger-900), var(--agents-danger-500))\";\n\ntype FormSubmissionStatus = \"idle\" | \"sending\" | \"sent\" | \"declined\" | \"failed\";\n\n/**\n * The `Form` node (`FormComposedViewNode.php`): the kit's inputs inside one surface with a submit\n * and an optional decline. The inputs write the tree's local state as everywhere; only the submit reaches the agent — as\n * ONE FRONTEND_WIDGET_CLICK signal through `injectSignal` (`ComposedView form \"<name>\" submitted:` + one `- <field>:\n * <value>` line per field, `compose-form-signal.ts`; the stored contract is `composed-view-widget-contract.json`). The\n * fields are the state names of `fields`, else every state name the body binds; `requiredFields` must be filled first.\n *\n * Answered only once the host accepted the signal: then a done pill replaces the buttons and the body is disabled;\n * an undelivered signal keeps the form and offers the retry. A replayed reply shows the body without buttons (its answer\n * belongs to its own turn), the e-mail capture shows the body frozen without any action row. A name the signal cannot\n * carry and a Form inside a Form render their body and report `failed`, so the model learns the form cannot submit.\n */\nconst FormNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots, sizeClass, runtime, testId } = props;\n const { state, interactive, isEmailRender, reportNodeStatus } = runtime;\n const isInsideForm = useContext(ComposedViewFormContext);\n const { injectSignal } = useConversationWidgetContext();\n const [submissionStatus, setSubmissionStatus] = useState<FormSubmissionStatus>(\"idle\");\n const [hasTriedWithMissingFields, setHasTriedWithMissingFields] = useState(false);\n const isSignalInFlightRef = useRef(false);\n\n const formName = isFormNameAllowed(nodeProps.name) ? nodeProps.name : undefined;\n const fieldNames = useMemo(\n () =>\n Array.isArray(node.props.fields)\n ? readStateNameList(node.props.fields, state)\n : collectBoundStateNames(node).filter((stateName) => Object.prototype.hasOwnProperty.call(state, stateName)),\n [node, state],\n );\n const requiredFieldNames = useMemo(() => readStateNameList(node.props.requiredFields, state), [node, state]);\n const hasMissingRequiredField = requiredFieldNames.some((stateName) => !isFormFieldFilled(state[stateName]));\n\n useEffect(() => {\n if (isInsideForm) {\n reportNodeStatus(\n \"failed\",\n \"INVALID_NODE\",\n \"a Form inside a Form has no submit of its own — its inputs belong to the outer form\",\n );\n } else if (formName === undefined) {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n 'a Form name is letters, digits, \"_\" or \"-\", at most 64 — this form renders but cannot submit',\n );\n }\n }, [isInsideForm, formName, reportNodeStatus]);\n\n if (isInsideForm)\n return (\n <div className={styles.nestedBody} data-testid={testId}>\n {slots.children}\n </div>\n );\n\n const canSend = formName !== undefined && interactive && !isEmailRender;\n const isAnswered = submissionStatus === \"sent\" || submissionStatus === \"declined\";\n\n /** One signal at a time; the form counts as answered only once the host accepted it. */\n const sendSignal = async (signalText: string, answeredStatus: \"sent\" | \"declined\") => {\n if (isSignalInFlightRef.current) return;\n isSignalInFlightRef.current = true;\n setSubmissionStatus(\"sending\");\n try {\n const accepted = await injectSignal(signalText);\n setSubmissionStatus(accepted === true ? answeredStatus : \"failed\");\n } catch {\n setSubmissionStatus(\"failed\");\n } finally {\n isSignalInFlightRef.current = false;\n }\n };\n\n const submit = () => {\n if (!canSend || formName === undefined || isAnswered) return;\n if (hasMissingRequiredField) {\n setHasTriedWithMissingFields(true);\n return;\n }\n void sendSignal(\n composeFormSubmitSignal(\n formName,\n fieldNames.map((fieldName) => [fieldName, state[fieldName]] as const),\n ),\n \"sent\",\n );\n };\n\n const decline = () => {\n if (!canSend || formName === undefined || isAnswered) return;\n void sendSignal(composeFormDeclineSignal(formName), \"declined\");\n };\n\n const title = typeof nodeProps.title === \"string\" && nodeProps.title.trim() !== \"\" ? nodeProps.title : undefined;\n const description =\n typeof nodeProps.description === \"string\" && nodeProps.description.trim() !== \"\"\n ? nodeProps.description\n : undefined;\n const submitLabel =\n typeof nodeProps.submitLabel === \"string\" && nodeProps.submitLabel.trim() !== \"\"\n ? nodeProps.submitLabel\n : undefined;\n const declineLabel =\n typeof nodeProps.declineLabel === \"string\" && nodeProps.declineLabel.trim() !== \"\"\n ? nodeProps.declineLabel\n : undefined;\n const isSending = submissionStatus === \"sending\";\n const headerItems = slots.header ?? [];\n const showsMissingFields = hasTriedWithMissingFields && hasMissingRequiredField;\n\n const renderActionRow = () => {\n if (isEmailRender || formName === undefined) return null;\n if (submissionStatus === \"sent\") return <DonePill testId={`${testId}-done`}>{\"Sent\"}</DonePill>;\n if (submissionStatus === \"declined\")\n return (\n <DonePill status=\"neutral\" testId={`${testId}-done`}>\n {\"Declined\"}\n </DonePill>\n );\n if (!interactive) {\n return (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" testId={`${testId}-replay-note`}>\n {\"This form can only be sent from the newest reply.\"}\n </Text>\n );\n }\n return (\n <div className={styles.actions}>\n <ConversationWidgetButton\n variant=\"primary\"\n size=\"medium\"\n isLoading={isSending}\n disabled={isSending}\n translate={submitLabel === undefined}\n onClick={submit}\n testId={`${testId}-submit`}\n >\n {submitLabel === undefined ? \"Send\" : escapePlainTextForText(submitLabel)}\n </ConversationWidgetButton>\n {declineLabel !== undefined ? (\n <ConversationWidgetButton\n variant=\"muted\"\n // Every type shares the muted size set, so submit and decline are both medium.\n size=\"medium\"\n disabled={isSending}\n translate={false}\n onClick={decline}\n testId={`${testId}-decline`}\n >\n {escapePlainTextForText(declineLabel)}\n </ConversationWidgetButton>\n ) : null}\n </div>\n );\n };\n\n return (\n <WidgetSurface level={sizeClass === \"full\" ? \"elevated\" : \"flat\"} testId={testId}>\n {/* The browser never submits: the component library buttons are submit buttons, the body's own buttons included — only the\n action row's onClick sends. */}\n <form className={styles.form} noValidate onSubmit={(submitEvent) => submitEvent.preventDefault()}>\n {title !== undefined || description !== undefined || headerItems.length > 0 ? (\n <div className={styles.headerRow}>\n <div className={styles.header}>\n {title !== undefined ? (\n <ModelText role=\"body\" weight=\"bold\">\n {title}\n </ModelText>\n ) : null}\n {description !== undefined ? (\n <ModelText role=\"help\" color=\"var(--agents-fg-light)\">\n {description}\n </ModelText>\n ) : null}\n </div>\n {headerItems.length > 0 ? <div className={styles.headerItems}>{headerItems}</div> : null}\n </div>\n ) : null}\n {/* Disabled while the answer is on its way and after it was given; the e-mail capture keeps the normal look\n (its page is inert and the renderer freezes the state). */}\n <ComposedViewFormContext.Provider value={true}>\n <fieldset className={styles.fields} disabled={isAnswered || isSending}>\n {slots.children}\n </fieldset>\n </ComposedViewFormContext.Provider>\n <div className={styles.footer} aria-live=\"polite\">\n {showsMissingFields ? (\n <Text role=\"caption\" color={ERROR_TEXT_COLOR} testId={`${testId}-error-required`}>\n {\"Please fill in the required fields.\"}\n </Text>\n ) : null}\n {submissionStatus === \"failed\" ? (\n <Text role=\"caption\" color={ERROR_TEXT_COLOR} testId={`${testId}-error`}>\n {\"Something went wrong. Please try again.\"}\n </Text>\n ) : null}\n {renderActionRow()}\n </div>\n </form>\n </WidgetSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Form\", component: FormNode };\n","/** The date pattern per locale — the same table the app's date picker reads (`DD.MM.YYYY` for `de_DE`). */\nconst DATE_PATTERNS_BY_LOCALE: Record<string, string> = {\n en_US: \"MM/DD/YYYY\",\n en_GB: \"DD/MM/YYYY\",\n de_DE: \"DD.MM.YYYY\",\n de_AT: \"DD.MM.YYYY\",\n fr_FR: \"DD/MM/YYYY\",\n nl_NL: \"DD-MM-YYYY\",\n es_ES: \"DD/MM/YYYY\",\n it_IT: \"DD/MM/YYYY\",\n pl_PL: \"YYYY-MM-DD\",\n pt_PT: \"DD/MM/YYYY\",\n ja_JP: \"YYYY/MM/DD\",\n id_ID: \"DD/MM/YYYY\",\n fi_FI: \"DD.MM.YYYY\",\n sk_SK: \"DD.MM.YYYY\",\n sv_SE: \"YYYY-MM-DD\",\n cs_CZ: \"DD.MM.YYYY\",\n el_GR: \"DD/MM/YYYY\",\n};\n\n/** The date pattern of a locale written with an underscore (`de_DE`); an unknown locale reads `DD.MM.YYYY`. */\nexport const getDatePatternFromLocale = (locale: string): string => {\n const datePattern = DATE_PATTERNS_BY_LOCALE[locale];\n if (!datePattern) {\n console.error(\"ERROR | getDatePatternFromLocale | Details: locale not found \", locale);\n return \"DD.MM.YYYY\";\n }\n return datePattern;\n};\n","import type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { getDatePatternFromLocale } from \"./date-pattern-of-locale\";\nimport type { ComposedViewRuntime } from \"../../../composed-view-component-types\";\n\n/**\n * The value readers the kit's input components share. Every reader is total: a value the model wrote\n * in another shape gives the documented default, never an exception — the readers on both sides already dropped what\n * the schema refuses, these readers only narrow what is left.\n */\n\n/** One choice of a `Tabs`, `Select` or `RadioGroup`: the id written to the state and the label the owner reads. */\nexport interface ComposedInputOption {\n id: string | number;\n label: string;\n description?: string;\n disabled: boolean;\n}\n\n/** Choices beyond this count are not shown (a drop-down with more is a list, not an input). */\nexport const MAX_INPUT_OPTIONS = 100;\n\nconst readOptionId = (optionObject: Record<string, unknown>): string | number | undefined => {\n // `id` is the documented key; `value` / `key` are what a model transcribing ChatGPT's `<Option value=…>` writes.\n for (const idKey of [\"id\", \"value\", \"key\"]) {\n const candidate = optionObject[idKey];\n if (typeof candidate === \"string\" && candidate !== \"\") return candidate;\n if (typeof candidate === \"number\" && Number.isFinite(candidate)) return candidate;\n }\n return undefined;\n};\n\nconst readOptionLabel = (optionObject: Record<string, unknown>): string | undefined => {\n for (const labelKey of [\"label\", \"title\", \"name\", \"text\"]) {\n const candidate = optionObject[labelKey];\n if (typeof candidate === \"string\" && candidate.trim() !== \"\") return candidate;\n if (typeof candidate === \"number\" && Number.isFinite(candidate)) return String(candidate);\n }\n return undefined;\n};\n\nconst readOption = (optionValue: unknown): ComposedInputOption | undefined => {\n if (typeof optionValue === \"string\") {\n return optionValue.trim() === \"\" ? undefined : { id: optionValue, label: optionValue, disabled: false };\n }\n if (typeof optionValue === \"number\") {\n return Number.isFinite(optionValue) ? { id: optionValue, label: String(optionValue), disabled: false } : undefined;\n }\n if (typeof optionValue !== \"object\" || optionValue === null || Array.isArray(optionValue)) return undefined;\n const optionObject = optionValue as Record<string, unknown>;\n const label = readOptionLabel(optionObject);\n const id = readOptionId(optionObject) ?? label;\n if (id === undefined || label === undefined) return undefined;\n const description = optionObject.description;\n return {\n id,\n label,\n description: typeof description === \"string\" && description.trim() !== \"\" ? description : undefined,\n disabled: optionObject.disabled === true,\n };\n};\n\n/**\n * The choices of an `options` prop: a label list (`[\"Bear\", \"Base\"]`, the label is the id) or objects with an `id` (or\n * `value` / `key`) and a `label`. An entry without a usable id and label is skipped, a repeated id keeps its first entry.\n */\nexport const readComposedInputOptions = (optionsValue: ExpressionValue | undefined): ComposedInputOption[] => {\n if (!Array.isArray(optionsValue)) return [];\n const options: ComposedInputOption[] = [];\n const seenIds = new Set<string>();\n for (const optionValue of optionsValue) {\n if (options.length >= MAX_INPUT_OPTIONS) break;\n const option = readOption(optionValue);\n if (!option || seenIds.has(String(option.id))) continue;\n seenIds.add(String(option.id));\n options.push(option);\n }\n return options;\n};\n\n/** The option whose id equals `value` (a number state matches a numeric-string id and the reverse). */\nexport const findComposedInputOption = (\n options: ComposedInputOption[],\n value: ExpressionValue | undefined,\n): ComposedInputOption | undefined =>\n value === undefined || value === null ? undefined : options.find((option) => String(option.id) === String(value));\n\n/** A text prop, or `undefined` when it is not a non-empty string (a number is shown as written). */\nexport const readComposedText = (value: ExpressionValue | undefined): string | undefined => {\n if (typeof value === \"string\") return value.trim() === \"\" ? undefined : value;\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return undefined;\n};\n\n/** A finite number prop, or `fallback`. */\nexport const readComposedNumber = (value: ExpressionValue | undefined, fallback: number): number =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n\n/** Whether the owner may use the control: a live (interactive) message, never a replay or the e-mail capture. */\nexport const isComposedInputUsable = (runtime: ComposedViewRuntime): boolean =>\n runtime.interactive && !runtime.isEmailRender;\n\n/** The decimals a number is written with (`0.1` → 1, `5` → 0, `0.25` → 2), capped at 6. */\nexport const countDecimals = (value: number): number => {\n if (!Number.isFinite(value)) return 0;\n const [, fraction = \"\"] = String(value).split(\".\");\n return Math.min(fraction.length, 6);\n};\n\n/** A number with `decimals` places in the owner's language, `unit` after it: `3` + \"%\" + 1 → \"3.0 %\". */\nexport const formatComposedNumber = (\n value: number,\n decimals: number,\n unit: string | undefined,\n languageCode: string,\n): string => {\n const fractionDigits = Math.max(0, Math.min(6, Math.round(decimals)));\n const formatOptions: Intl.NumberFormatOptions = {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n };\n let formattedNumber: string;\n try {\n formattedNumber = new Intl.NumberFormat(languageCode || \"en\", formatOptions).format(value);\n } catch {\n formattedNumber = new Intl.NumberFormat(\"en\", formatOptions).format(value);\n }\n if (!unit) return formattedNumber;\n // A scale written as \"/100\" joins the number (\"51/100\"); any other unit follows a no-break space, so \"3.0 %\" never\n // wraps between the number and its unit.\n return unit.startsWith(\"/\") ? `${formattedNumber}${unit}` : `${formattedNumber}\\u00a0${unit}`;\n};\n\n/** A value clamped into `[min, max]` and snapped onto the step grid that starts at `min`. */\nexport const snapToSliderStep = (value: number, min: number, max: number, step: number): number => {\n const clampedValue = Math.min(Math.max(value, min), max);\n if (!(step > 0)) return clampedValue;\n const snappedValue = min + Math.round((clampedValue - min) / step) * step;\n const decimals = Math.max(countDecimals(step), countDecimals(min));\n return Math.min(Number(snappedValue.toFixed(decimals)), max);\n};\n\nconst ISO_DAY_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** A `YYYY-MM-DD` day as its local midnight in milliseconds, or `undefined` for anything else (`2026-02-30` too). */\nexport const parseIsoDay = (value: ExpressionValue | undefined): number | undefined => {\n if (typeof value !== \"string\") return undefined;\n const dayMatch = ISO_DAY_PATTERN.exec(value.trim());\n if (!dayMatch) return undefined;\n const year = Number(dayMatch[1]);\n const monthIndex = Number(dayMatch[2]) - 1;\n const dayOfMonth = Number(dayMatch[3]);\n const localDate = new Date(year, monthIndex, dayOfMonth);\n if (localDate.getMonth() !== monthIndex || localDate.getDate() !== dayOfMonth) return undefined;\n return localDate.getTime();\n};\n\n/**\n * The locale as the date pattern table of the component library's `DatePicker` keys it (`de-DE` → `de_DE`): the owner settings\n * write a BCP 47 tag, the picker looks the pattern up by the underscore form and falls back to `DD.MM.YYYY`.\n */\nexport const toDatePatternLocale = (locale: string): string => locale.replace(\"-\", \"_\");\n\n/**\n * A `YYYY-MM-DD` day as the owner reads it in `locale` (\"25/10/2026\" for `en-GB`, \"25.10.2026\" for `de-DE`) — in the\n * same pattern the editable `DatePicker` shows (`getDatePatternFromLocale`, the table the component library's picker reads), so the\n * frozen value on a replay and in the e-mail matches the field the owner edited; `undefined` for no valid day.\n */\nexport const formatIsoDayForReading = (isoDay: string | undefined, locale: string): string | undefined => {\n const timestamp = parseIsoDay(isoDay);\n if (timestamp === undefined) return undefined;\n const localDate = new Date(timestamp);\n const twoDigits = (datePart: number) => String(datePart).padStart(2, \"0\");\n return getDatePatternFromLocale(toDatePatternLocale(locale))\n .replace(\"YYYY\", String(localDate.getFullYear()))\n .replace(\"MM\", twoDigits(localDate.getMonth() + 1))\n .replace(\"DD\", twoDigits(localDate.getDate()));\n};\n\n/** A timestamp in milliseconds as its local `YYYY-MM-DD` day. */\nexport const formatIsoDay = (timestamp: number): string => {\n const localDate = new Date(timestamp);\n const twoDigits = (datePart: number) => String(datePart).padStart(2, \"0\");\n return `${localDate.getFullYear()}-${twoDigits(localDate.getMonth() + 1)}-${twoDigits(localDate.getDate())}`;\n};\n","import { type AgentsIconName } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { ConversationWidgetButton } from \"../../../widgets/_shared/ConversationWidgetButton\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { isComposedInputUsable, readComposedText } from \"./shared/composed-input-values\";\nimport styles from \"./ComposedInputs.module.scss\";\n\n/** The closed glyph list of the node's `icon` prop → the component-library icon. */\nconst BUTTON_ICON_NAMES: Record<string, AgentsIconName> = {\n copy: \"duplicate\",\n reset: \"refresh\",\n link: \"link\",\n add: \"add\",\n check: \"check\",\n next: \"arrowRight\",\n calendar: \"calendar\",\n info: \"info\",\n};\n\n/** How long a copy button says \"Copied\" after the click (the confirmation ChatGPT's \"Copy result\" gives). */\nexport const COPIED_CONFIRMATION_MS = 2000;\n\n/** The name of the tree action a click runs (`onClick: {\"action\": \"<name>\"}`), or undefined for a `set` click. */\nconst readClickActionName = (onClick: unknown): string | undefined => {\n if (typeof onClick !== \"object\" || onClick === null || Array.isArray(onClick)) return undefined;\n const actionName = (onClick as Record<string, unknown>).action;\n return typeof actionName === \"string\" ? actionName : undefined;\n};\n\n/**\n * `Button` — runs one of the tree's own actions or writes a value to its state (`ButtonComposedViewNode.php`; ChatGPT's \"Copy result\" / \"Reset\" of the simulators): `onClick: {\"action\": \"<name>\"}`\n * runs `copy`, `resetState`, `openUrl` or `openEntity`; `onClick: {\"set\": \"<name>\"}` writes `value`. It never sends a\n * chat message. `primary` is the one main action (a square button, for real-effect\n * actions), `secondary` sits beside it. It is an affordance only, so a replayed message and the e-mail capture show no\n * button at all. The component library renders a `<button>` without a type — a submit button inside a `Form` would become the Enter\n * target and submit the form; this one is set to `type=\"button\"`. A button that runs a `copy` action confirms the copy\n * for {@link COPIED_CONFIRMATION_MS}: its label turns into \"Copied\" with a check glyph. A label longer than the chat column\n * wraps onto a second line (copy wraps, never cut) instead of pushing the button out of the widget.\n */\nconst ComposedButton = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, runtime, testId } = props;\n const wrapperRef = useRef<HTMLDivElement>(null);\n const label = readComposedText(nodeProps.label);\n const isUsable = isComposedInputUsable(runtime);\n const [isCopyConfirmed, setIsCopyConfirmed] = useState(false);\n const clickActionName = readClickActionName(node.props.onClick);\n const isCopyButton = clickActionName !== undefined && runtime.findAction?.(clickActionName)?.type === \"copy\";\n useEffect(() => {\n if (!isCopyConfirmed) return;\n const confirmationTimer = setTimeout(() => setIsCopyConfirmed(false), COPIED_CONFIRMATION_MS);\n return () => clearTimeout(confirmationTimer);\n }, [isCopyConfirmed]);\n useLayoutEffect(() => {\n wrapperRef.current?.querySelectorAll(\"button\").forEach((buttonElement) => {\n buttonElement.type = \"button\";\n });\n });\n if (!label || !isUsable) return null;\n const nodeIcon = typeof nodeProps.icon === \"string\" ? BUTTON_ICON_NAMES[nodeProps.icon] : undefined;\n const icon = isCopyConfirmed ? \"check\" : nodeIcon;\n const isFullWidth = nodeProps.fullWidth === true;\n const buttonType = nodeProps.variant === \"secondary\" ? \"muted\" : \"primary\";\n const click = () => {\n runtime.runEvent(node.props.onClick, nodeProps.value);\n if (isCopyButton) setIsCopyConfirmed(true);\n };\n return (\n <div ref={wrapperRef} className={isFullWidth ? styles.buttonFullWidth : styles.button}>\n <ConversationWidgetButton\n variant={buttonType}\n size=\"medium\"\n icon={icon}\n iconPosition=\"left\"\n wrapsLabel\n translate={isCopyConfirmed}\n fullWidth={isFullWidth}\n onClick={click}\n testId={testId}\n >\n {isCopyConfirmed ? \"Copied\" : escapePlainTextForText(label)}\n </ConversationWidgetButton>\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Button\", component: ComposedButton };\n","import { Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport { SkeletonLine } from \"../../../../widgets/_shared/skeleton-primitives\";\nimport styles from \"./ComposedInputField.module.scss\";\n\nexport interface ComposedInputFieldProps {\n /** The model's label above the control (business content, never translated). */\n label?: string;\n /** The id of the control the label names — a native `<label for>`; omit when the control labels itself. */\n controlId?: string;\n /** Shown at the end of the label row — the slider's formatted value. */\n labelRowValue?: string;\n /** One muted line under the control. */\n description?: string;\n /** False on a replay and in the e-mail capture: the control stays visible, but takes no pointer, key or focus. */\n isUsable: boolean;\n /** A bound value is still loading: the control's place is a skeleton of the same height. */\n isPending?: boolean;\n /** The height of that skeleton in px (the control's own height). */\n pendingHeight?: number;\n className?: string;\n testId?: string;\n children: ReactNode;\n}\n\n/**\n * The frame every kit input sits in: the label row (label left, a value right), the control, an\n * optional muted line. A control the owner may not use (a replayed message, the e-mail capture) keeps its look and its\n * current value but is `inert` — no click, no key, no focus — so a frozen tree never pretends to answer. Every model\n * string goes through `escapePlainTextForText`: the app's `Text` may parse a string child as markup.\n */\nexport const ComposedInputField = (props: ComposedInputFieldProps) => {\n const {\n label,\n controlId,\n labelRowValue,\n description,\n isUsable,\n isPending = false,\n pendingHeight = 40,\n className,\n testId,\n children,\n } = props;\n const labelText = label ? (\n <Text role=\"body\" weight=\"medium\" translate={false}>\n {escapePlainTextForText(label)}\n </Text>\n ) : null;\n return (\n <div\n className={classNames(styles.field, !isUsable && styles.frozen, className)}\n inert={!isUsable || undefined}\n data-usable={isUsable ? \"true\" : \"false\"}\n data-testid={testId ? `${testId}-field` : undefined}\n >\n {labelText || labelRowValue ? (\n <div className={styles.labelRow}>\n {labelText && controlId ? (\n <label htmlFor={controlId} className={styles.label}>\n {labelText}\n </label>\n ) : (\n <span className={styles.label}>{labelText}</span>\n )}\n {labelRowValue ? (\n <Text role=\"body\" weight=\"bold\" translate={false} className={styles.labelValue}>\n {escapePlainTextForText(labelRowValue)}\n </Text>\n ) : null}\n </div>\n ) : null}\n {isPending ? (\n <span aria-busy=\"true\" className={styles.pending} data-testid={testId ? `${testId}-skeleton` : undefined}>\n <SkeletonLine height={pendingHeight} radius={12} />\n </span>\n ) : (\n children\n )}\n {description ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false} className={styles.description}>\n {escapePlainTextForText(description)}\n </Text>\n ) : null}\n </div>\n );\n};\n","import { useState } from \"react\";\nimport type { ComposedViewNode } from \"../../../../renderer/widget-tree/composed-view-tree\";\nimport type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewRuntime } from \"../../../composed-view-component-types\";\nimport { isComposedInputUsable } from \"./composed-input-values\";\n\nexport interface ComposedInputValueOptions<ValueType> {\n node: ComposedViewNode;\n runtime: ComposedViewRuntime;\n /** The prop that carries the value (`value`, `checked`), resolved. */\n resolvedValue: ExpressionValue | undefined;\n /** Narrows the resolved value to the control's type; `undefined` for a value of another shape. */\n readValue: (resolvedValue: ExpressionValue | undefined) => ValueType | undefined;\n /** What the control shows when nothing is set. */\n fallbackValue: ValueType;\n valuePropName?: string;\n eventPropName?: string;\n /** What the event writes for a shown value (a number field shows text but writes a number); the value itself by default. */\n toEventValue?: (nextValue: ValueType) => unknown;\n}\n\nexport interface ComposedInputValue<ValueType> {\n /** The value the control shows. */\n value: ValueType;\n /** The owner changed the control: keep it and run the node's event (`{\"set\": …}` writes the tree state). */\n changeValue: (nextValue: ValueType) => void;\n}\n\n/**\n * The value of one kit input. A tree normally BINDS the control to its state (`value: {\"$state\":\n * \"period\"}` + `onChange: {\"set\": \"period\"}`): the state is the truth and every node bound to it follows. A control\n * written with no value but a `{\"set\": <name>}` event shows its own set target (the lenient state\n * rule — the readers declare an undeclared target with null). A control with a literal value, or with neither, still\n * works on its own — it keeps the owner's last choice, so a click never looks dead. The event is the node's RAW wire\n * value (`node.props[eventPropName]`), as the runtime expects it.\n */\nexport const useComposedInputValue = <ValueType>(\n options: ComposedInputValueOptions<ValueType>,\n): ComposedInputValue<ValueType> => {\n const {\n node,\n runtime,\n resolvedValue,\n readValue,\n fallbackValue,\n valuePropName = \"value\",\n eventPropName = \"onChange\",\n toEventValue,\n } = options;\n const [ownValue, setOwnValue] = useState<ValueType | undefined>(undefined);\n const wireValue = node.props[valuePropName];\n const eventWireValue = node.props[eventPropName];\n const ownSetTarget =\n wireValue === undefined &&\n typeof eventWireValue === \"object\" &&\n eventWireValue !== null &&\n !Array.isArray(eventWireValue) &&\n typeof eventWireValue.set === \"string\" &&\n Object.prototype.hasOwnProperty.call(runtime.state, eventWireValue.set)\n ? eventWireValue.set\n : undefined;\n const isBoundToTheTree =\n ownSetTarget !== undefined || (typeof wireValue === \"object\" && wireValue !== null && !Array.isArray(wireValue));\n const treeValue = readValue(ownSetTarget !== undefined ? runtime.state[ownSetTarget] : resolvedValue);\n const value = (isBoundToTheTree ? (treeValue ?? ownValue) : (ownValue ?? treeValue)) ?? fallbackValue;\n // A frozen control (a replay, the e-mail capture) is `inert` in the browser; this guard holds where inert does not.\n const changeValue = (nextValue: ValueType) => {\n if (!isComposedInputUsable(runtime)) return;\n setOwnValue(nextValue);\n runtime.runEvent(node.props[eventPropName], toEventValue ? toEventValue(nextValue) : nextValue);\n };\n return { value, changeValue };\n};\n","import { escapePlainTextForText } from \"../../../provider/environment\";\nimport { Checkbox } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { isComposedInputUsable, readComposedText } from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\n\nconst readChecked = (resolvedValue: ExpressionValue | undefined): boolean | undefined =>\n typeof resolvedValue === \"boolean\" ? resolvedValue : undefined;\n\n/**\n * `Checkbox` — one option on or off (`CheckboxComposedViewNode.php`; ChatGPT's \"show the comparison\n * values\" of the analytics studio): writes `true` / `false` to the tree state through `onChange`. The label is the\n * model's text, an optional muted line explains it. Frozen on a replay and in the e-mail capture.\n */\nconst ComposedCheckbox = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const label = readComposedText(nodeProps.label) ?? \"\";\n const description = readComposedText(nodeProps.description);\n const isUsable = isComposedInputUsable(runtime);\n const { value: isChecked, changeValue } = useComposedInputValue<boolean>({\n node,\n runtime,\n resolvedValue: nodeProps.checked,\n readValue: readChecked,\n fallbackValue: false,\n valuePropName: \"checked\",\n });\n return (\n <ComposedInputField\n description={description}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={24}\n testId={testId}\n >\n <Checkbox\n testId={testId}\n label={escapePlainTextForText(label)}\n translate={false}\n checked={isChecked}\n breaksLongWords\n onChange={() => changeValue(!isChecked)}\n />\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"Checkbox\",\n component: ComposedCheckbox,\n};\n","import { Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../../provider/environment\";\nimport styles from \"./ComposedInputFrozenValue.module.scss\";\n\nexport interface ComposedInputFrozenValueProps {\n /** The control's current value as the owner reads it; empty shows a muted dash. */\n shownValue: string | undefined;\n /** Keep the line breaks of a multi-line text. */\n isMultiline?: boolean;\n testId?: string;\n}\n\n/**\n * A text-like control (a select, a field, a date) on a replayed message or in the e-mail capture:\n * its value as plain readable text in the field's shape — normal text colour, no disabled grey, no caret, no chevron.\n * Only the affordance goes; what the owner had chosen stays legible.\n */\nexport const ComposedInputFrozenValue = (props: ComposedInputFrozenValueProps) => {\n const { shownValue, isMultiline = false, testId } = props;\n const hasValue = shownValue !== undefined && shownValue.trim() !== \"\";\n return (\n <div\n className={classNames(styles.frozenValue, isMultiline && styles.multiline)}\n data-frozen-value=\"true\"\n data-testid={testId}\n >\n {hasValue ? (\n <Text role=\"body\" translate={false} allowNewLines={isMultiline}>\n {escapePlainTextForText(shownValue)}\n </Text>\n ) : (\n <Text role=\"body\" translate={false} color=\"var(--agents-fg-lightest)\">\n {\"—\"}\n </Text>\n )}\n </div>\n );\n};\n","import { useAgentsOwnerSettings } from \"../../../../provider/AgentsProvider\";\n\n/** The date format when no owner date locale is loaded (a preview, a story, a spec): day/month/year. */\nconst FALLBACK_DATE_LOCALE = \"en-GB\";\n\nconst readBrowserLanguage = (): string => (typeof navigator === \"undefined\" ? \"en\" : navigator.language || \"en\");\n\n/**\n * The owner's language for number formatting, from the app (`useOwnerSettings`). Read defensively: the kit renders in\n * hosts that know no language (the widget preview, a spec, the e-mail capture) — there the browser's language formats\n * the numbers.\n */\nexport const useComposedInputLanguage = (): string => useAgentsOwnerSettings().languageCode || readBrowserLanguage();\n\n/** The owner's date locale, read as defensively as the language. */\nexport const useComposedInputDateLocale = (): string => useAgentsOwnerSettings().dateLocale || FALLBACK_DATE_LOCALE;\n","import { DateInput, Icon } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport {\n formatIsoDay,\n formatIsoDayForReading,\n isComposedInputUsable,\n parseIsoDay,\n readComposedText,\n toDatePatternLocale,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputDateLocale } from \"./shared/use-composed-input-language\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport styles from \"./ComposedInputs.module.scss\";\n\nconst readIsoDay = (resolvedValue: ExpressionValue | undefined): string | undefined =>\n parseIsoDay(resolvedValue) === undefined ? undefined : String(resolvedValue).trim();\n\n/**\n * `DatePicker` — one day from a calendar (`DatePickerComposedViewNode.php`; the reference date of\n * ChatGPT's analytics studio): shown in the owner's date format (the field and the frozen value in one pattern), written to the tree state as `YYYY-MM-DD` through\n * `onChange`; `min` / `max` (also `YYYY-MM-DD`) bound the calendar. A value that is no valid day shows an empty field.\n * On a replay and in the e-mail capture it shows its current day as plain text.\n */\nconst ComposedDatePicker = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const dateLocale = useComposedInputDateLocale();\n const label = readComposedText(nodeProps.label);\n const minDay = parseIsoDay(nodeProps.min);\n const maxDay = parseIsoDay(nodeProps.max);\n const isUsable = isComposedInputUsable(runtime);\n const { value, changeValue } = useComposedInputValue<string | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readIsoDay,\n fallbackValue: undefined,\n });\n const pickDay = (pickedTimestamp: number | null | undefined) => {\n if (typeof pickedTimestamp !== \"number\" || !Number.isFinite(pickedTimestamp)) return;\n changeValue(formatIsoDay(pickedTimestamp));\n };\n return (\n <ComposedInputField label={label} isUsable={isUsable} isPending={isPending} pendingHeight={48} testId={testId}>\n {isUsable ? (\n <div className={styles.datePicker} data-testid={testId}>\n <DateInput\n // A new day from the tree (a reset) remounts the picker: it keeps its own copy of the value otherwise.\n key={value ?? \"none\"}\n value={parseIsoDay(value)}\n minDate={minDay}\n maxDate={maxDay}\n locale={toDatePatternLocale(dateLocale)}\n onChange={pickDay}\n />\n {/* The field says what it opens (ChatGPT's date field carries the calendar glyph); the click stays the field's. */}\n <Icon className={styles.datePickerIcon} color=\"var(--agents-fg-light)\" pixelSize={18} name=\"calendar\" />\n </div>\n ) : (\n <ComposedInputFrozenValue shownValue={formatIsoDayForReading(value, dateLocale)} testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"DatePicker\",\n component: ComposedDatePicker,\n};\n","import { useId, useState } from \"react\";\nimport { TextInput } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport { isComposedInputUsable, readComposedNumber, readComposedText } from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\n\nconst readFieldText = (resolvedValue: ExpressionValue | undefined): string | undefined => {\n if (typeof resolvedValue === \"string\") return resolvedValue;\n if (typeof resolvedValue === \"number\" && Number.isFinite(resolvedValue)) return String(resolvedValue);\n if (resolvedValue === null) return \"\";\n return undefined;\n};\n\n/** The typed text as the state value: a number field writes a finite number, or null while it is empty or unparsable. */\nconst toStateValue = (typedText: string, isNumberField: boolean): string | number | null => {\n if (!isNumberField) return typedText;\n const trimmedText = typedText.trim().replace(\",\", \".\");\n if (trimmedText === \"\") return null;\n const typedNumber = Number(trimmedText);\n return Number.isFinite(typedNumber) ? typedNumber : null;\n};\n\n/**\n * `Input` — a one-line text or number field (`InputComposedViewNode.php`; ChatGPT's `Input`): what\n * the owner types is written to the tree state through `onChange` on every keystroke, so a computed result follows. A\n * `number` field writes a number (null while empty). The browser checks nothing beyond the type; the tree computes with\n * what it gets. On a replay and in the e-mail capture it shows its current text as plain text.\n */\nconst ComposedInput = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const controlId = useId();\n const inputType = nodeProps.inputType === \"number\" || nodeProps.inputType === \"email\" ? nodeProps.inputType : \"text\";\n const isNumberField = inputType === \"number\";\n const label = readComposedText(nodeProps.label);\n const placeholder = readComposedText(nodeProps.placeholder);\n const maxLength = readComposedNumber(nodeProps.maxLength, 0);\n const isUsable = isComposedInputUsable(runtime);\n const { value, changeValue } = useComposedInputValue<string>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readFieldText,\n fallbackValue: \"\",\n toEventValue: (typedText) => toStateValue(typedText, isNumberField),\n });\n // The text as typed survives a state that holds the same number (\"3.\" and \"3,0\" stay on screen while the state is 3).\n const [typedText, setTypedText] = useState<string | undefined>(undefined);\n const shownText =\n typedText !== undefined && toStateValue(typedText, isNumberField) === toStateValue(value, isNumberField)\n ? typedText\n : value;\n const typeText = (nextText: string) => {\n const limitedText = maxLength > 0 ? nextText.slice(0, maxLength) : nextText;\n setTypedText(limitedText);\n changeValue(limitedText);\n };\n return (\n <ComposedInputField\n label={label}\n controlId={controlId}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={48}\n testId={testId}\n >\n {isUsable ? (\n <TextInput\n id={controlId}\n testId={testId}\n type={inputType}\n value={shownText}\n placeholder={placeholder}\n maxLength={maxLength > 0 ? maxLength : undefined}\n onChange={typeText}\n />\n ) : (\n <ComposedInputFrozenValue shownValue={shownText} testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Input\", component: ComposedInput };\n","import { useEffect } from \"react\";\nimport type { ComposedViewRuntime } from \"../../../composed-view-component-types\";\n\n/**\n * A choice input with no usable option renders nothing — and says so in the block's render report, so\n * the model learns the control did not show and answers in prose instead of \"pick one above\".\n */\nexport const useReportMissingOptions = (\n optionCount: number,\n nodeType: string,\n isPending: boolean,\n runtime: ComposedViewRuntime,\n): void => {\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n if (isPending || optionCount > 0) return;\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `${nodeType} has no usable option — it is not shown`);\n }, [optionCount, nodeType, isPending, reportNodeStatus]);\n};\n","import { RadioGroup, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useId } from \"react\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport {\n findComposedInputOption,\n isComposedInputUsable,\n readComposedInputOptions,\n readComposedText,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport { useReportMissingOptions } from \"./shared/use-report-missing-options\";\nimport styles from \"./ComposedInputs.module.scss\";\n\nconst readChoiceId = (resolvedValue: ExpressionValue | undefined): string | undefined =>\n typeof resolvedValue === \"string\" || typeof resolvedValue === \"number\" ? String(resolvedValue) : undefined;\n\n/**\n * `RadioGroup` — radio buttons (`RadioGroupComposedViewNode.php`; ChatGPT's `RadioGroup`): one of a\n * few choices that each carry a visible explanation (`description` under the label), the picked one written to the\n * tree state through `onChange`. Under each other by default, side by side with `direction: \"row\"`. Frozen on a replay\n * and in the e-mail capture.\n */\nconst ComposedRadioGroup = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const groupName = useId();\n const options = readComposedInputOptions(nodeProps.options);\n const label = readComposedText(nodeProps.label);\n const direction = nodeProps.direction === \"row\" ? \"row\" : \"column\";\n const { value, changeValue } = useComposedInputValue<string | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readChoiceId,\n fallbackValue: undefined,\n });\n useReportMissingOptions(options.length, \"RadioGroup\", isPending, runtime);\n if (!isPending && options.length === 0) return null;\n const selectedOption = findComposedInputOption(options, value);\n const radioOptions = options.map((option) => ({\n // The label and its explanation as one node.\n label: (\n <span className={styles.radioOptionText} data-testid={`${testId}-option-${option.id}`}>\n <Text role=\"body\" translate={false}>\n {escapePlainTextForText(option.label)}\n </Text>\n {option.description ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(option.description)}\n </Text>\n ) : null}\n </span>\n ),\n value: String(option.id),\n disabled: option.disabled,\n }));\n const selectOption = (selectedRadioValue: unknown) => {\n const pickedOption = options.find((option) => String(option.id) === String(selectedRadioValue));\n if (pickedOption) changeValue(String(pickedOption.id));\n };\n return (\n <ComposedInputField\n label={label}\n isUsable={isComposedInputUsable(runtime)}\n isPending={isPending}\n pendingHeight={72}\n testId={testId}\n >\n <div role=\"radiogroup\" aria-label={label} data-testid={testId}>\n <RadioGroup\n name={groupName}\n value={selectedOption ? String(selectedOption.id) : \"\"}\n options={radioOptions}\n direction={direction}\n onChange={selectOption}\n />\n </div>\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"RadioGroup\",\n component: ComposedRadioGroup,\n};\n","import { useId } from \"react\";\nimport { Select } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport {\n findComposedInputOption,\n isComposedInputUsable,\n readComposedInputOptions,\n readComposedText,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport { useReportMissingOptions } from \"./shared/use-report-missing-options\";\n\nconst readChoiceId = (resolvedValue: ExpressionValue | undefined): string | number | undefined =>\n typeof resolvedValue === \"string\" || typeof resolvedValue === \"number\" ? resolvedValue : undefined;\n\n/**\n * `Select` — a drop-down (`SelectComposedViewNode.php`; ChatGPT's channel select of the analytics\n * studio): one of a longer list of choices, the picked one written to the tree state through `onChange`. The option\n * texts are the model's (not translated). On a replay and in the e-mail capture it shows its current choice as plain\n * text.\n */\nconst ComposedSelect = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const controlId = useId();\n const options = readComposedInputOptions(nodeProps.options);\n const label = readComposedText(nodeProps.label);\n const placeholder = readComposedText(nodeProps.placeholder);\n const { value, changeValue } = useComposedInputValue<string | number | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readChoiceId,\n fallbackValue: undefined,\n });\n useReportMissingOptions(options.length, \"Select\", isPending, runtime);\n if (!isPending && options.length === 0) return null;\n const selectedOption = findComposedInputOption(options, value);\n const isUsable = isComposedInputUsable(runtime);\n // The option texts are the model's, shown as written.\n const selectOptions = options.map((option) => ({\n value: String(option.id),\n label: option.label,\n description: option.description,\n disabled: option.disabled,\n }));\n const selectOption = (selectedKey: string) => {\n const pickedOption = options.find((option) => String(option.id) === selectedKey);\n if (pickedOption) changeValue(pickedOption.id);\n };\n return (\n <ComposedInputField\n label={label}\n controlId={controlId}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={48}\n testId={testId}\n >\n {isUsable ? (\n <Select\n id={controlId}\n testId={testId}\n options={selectOptions}\n value={selectedOption ? String(selectedOption.id) : \"\"}\n placeholder={placeholder}\n onChange={selectOption}\n />\n ) : (\n <ComposedInputFrozenValue shownValue={selectedOption?.label} testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Select\", component: ComposedSelect };\n","import { useEffect, useRef, useState } from \"react\";\nimport { RangeSlider } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport {\n countDecimals,\n formatComposedNumber,\n isComposedInputUsable,\n readComposedNumber,\n readComposedText,\n snapToSliderStep,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputLanguage } from \"./shared/use-composed-input-language\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport styles from \"./ComposedInputs.module.scss\";\n\n/** While dragging, the tree state is written at most this often (the state store caps inputs at 30 updates a second). */\nconst DRAG_STATE_WRITE_INTERVAL_MS = 60;\n\nconst readFiniteNumber = (resolvedValue: ExpressionValue | undefined): number | undefined =>\n typeof resolvedValue === \"number\" && Number.isFinite(resolvedValue) ? resolvedValue : undefined;\n\n/**\n * `Slider` — a number between `min` and `max` (`SliderComposedViewNode.php`; the sliders of ChatGPT's\n * revenue and MRR simulators): the label left, the formatted value right (\"35,000\", \"3.0 %\", \"70 €\" — `unit` and\n * `decimals`, in the owner's language), the track below. Dragging writes the tree state about 16 times a second so\n * computed KPIs follow the thumb; letting go always writes the final value. An invalid range (`max` not above `min`)\n * renders nothing and is reported. Frozen on a replay and in the e-mail capture.\n */\nconst ComposedSlider = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const languageCode = useComposedInputLanguage();\n const [dragValue, setDragValue] = useState<number | undefined>(undefined);\n const lastDragWriteAtRef = useRef(0);\n const min = readComposedNumber(nodeProps.min, 0);\n const max = readComposedNumber(nodeProps.max, 100);\n const rawStep = readComposedNumber(nodeProps.step, 1);\n const step = rawStep > 0 ? rawStep : 1;\n const unit = readComposedText(nodeProps.unit);\n const decimals = readComposedNumber(nodeProps.decimals, countDecimals(step));\n const label = readComposedText(nodeProps.label);\n const showsValue = nodeProps.showValue !== false;\n const isRangeValid = max > min;\n const { value, changeValue } = useComposedInputValue<number>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readFiniteNumber,\n fallbackValue: min,\n });\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n if (isRangeValid) return;\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `Slider max (${max}) must be above min (${min}) — it is not shown`);\n }, [isRangeValid, min, max, reportNodeStatus]);\n if (!isRangeValid) return null;\n const shownValue = snapToSliderStep(dragValue ?? value, min, max, step);\n const moveThumb = (movedValue: number) => {\n if (!isComposedInputUsable(runtime)) return;\n const snappedValue = snapToSliderStep(movedValue, min, max, step);\n setDragValue(snappedValue);\n const now = Date.now();\n if (now - lastDragWriteAtRef.current < DRAG_STATE_WRITE_INTERVAL_MS) return;\n lastDragWriteAtRef.current = now;\n runtime.runEvent(node.props.onChange, snappedValue);\n };\n const releaseThumb = (releasedValue: number) => {\n setDragValue(undefined);\n changeValue(snapToSliderStep(releasedValue, min, max, step));\n };\n const isUsable = isComposedInputUsable(runtime);\n return (\n <ComposedInputField\n label={label}\n labelRowValue={\n showsValue && !isPending ? formatComposedNumber(shownValue, decimals, unit, languageCode) : undefined\n }\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={28}\n testId={testId}\n >\n <div className={styles.sliderTrack} aria-label={label} data-testid={testId}>\n <RangeSlider\n value={shownValue}\n min={min}\n max={max}\n step={step}\n onMove={moveThumb}\n onRelease={releaseThumb}\n />\n </div>\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Slider\", component: ComposedSlider };\n","import { Tabs, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport {\n findComposedInputOption,\n isComposedInputUsable,\n readComposedInputOptions,\n readComposedText,\n} from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\nimport { useReportMissingOptions } from \"./shared/use-report-missing-options\";\nimport styles from \"./ComposedInputs.module.scss\";\n\nconst readChoiceId = (resolvedValue: ExpressionValue | undefined): string | number | undefined =>\n typeof resolvedValue === \"string\" || typeof resolvedValue === \"number\" ? resolvedValue : undefined;\n\n/**\n * `Tabs` — the segmented control (`TabsComposedViewNode.php`; ChatGPT's 7/30-day toggle of the\n * analytics dashboard, the Bear/Base/Bull scenarios of the MRR simulator): a few short choices side by side, the picked\n * one written to the tree state through `onChange`. Labels are the model's text. A disabled choice is not shown. Frozen on a replay and in the e-mail capture.\n */\nconst ComposedTabs = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const options = readComposedInputOptions(nodeProps.options);\n const label = readComposedText(nodeProps.label);\n const { value, changeValue } = useComposedInputValue<string | number | undefined>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readChoiceId,\n fallbackValue: options[0]?.id,\n });\n useReportMissingOptions(options.length, \"Tabs\", isPending, runtime);\n if (!isPending && options.length === 0) return null;\n const selectedOption = findComposedInputOption(options, value) ?? options[0];\n const tabs = options.map((option) => ({\n value: String(option.id),\n disabled: option.disabled,\n testId: `${testId}-option-${option.id}`,\n label: <Text translate={false}>{escapePlainTextForText(option.label)}</Text>,\n }));\n const selectOption = (selectedTabValue: unknown) => {\n const pickedOption = options.find((option) => String(option.id) === String(selectedTabValue));\n if (pickedOption && String(pickedOption.id) !== String(selectedOption?.id)) changeValue(pickedOption.id);\n };\n return (\n <ComposedInputField\n label={label}\n isUsable={isComposedInputUsable(runtime)}\n isPending={isPending}\n pendingHeight={36}\n testId={testId}\n >\n <div className={styles.tabsBar} data-testid={testId}>\n <Tabs\n options={tabs}\n value={selectedOption ? String(selectedOption.id) : undefined}\n onChange={selectOption}\n ariaLabel={label}\n />\n </div>\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Tabs\", component: ComposedTabs };\n","import { useId } from \"react\";\nimport { TextArea } from \"../../../provider/components\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { ComposedInputField } from \"./shared/ComposedInputField\";\nimport { ComposedInputFrozenValue } from \"./shared/ComposedInputFrozenValue\";\nimport { isComposedInputUsable, readComposedNumber, readComposedText } from \"./shared/composed-input-values\";\nimport { useComposedInputValue } from \"./shared/use-composed-input-value\";\n\n/** The visible lines a textarea may ask for — beyond that it is a document, not a field. */\nconst MAX_TEXTAREA_ROWS = 12;\n\nconst readFieldText = (resolvedValue: ExpressionValue | undefined): string | undefined =>\n typeof resolvedValue === \"string\" ? resolvedValue : resolvedValue === null ? \"\" : undefined;\n\n/**\n * `Textarea` — a multi-line text field (`TextareaComposedViewNode.php`; ChatGPT's `Textarea`): what\n * the owner types is written to the tree state through `onChange`; with `maxLength` the field shows a counter and takes\n * no more. It starts at `rows` lines and grows with its text up to {@link MAX_TEXTAREA_ROWS}. The tree state caps a string at its own length budget, so a longer text is cut there. On a replay and in\n * the e-mail capture it shows its current text as plain text, line breaks kept.\n */\nconst ComposedTextarea = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime, testId } = props;\n const controlId = useId();\n const label = readComposedText(nodeProps.label);\n const placeholder = readComposedText(nodeProps.placeholder);\n const maxLength = readComposedNumber(nodeProps.maxLength, 0);\n const rows = Math.min(Math.max(Math.round(readComposedNumber(nodeProps.rows, 3)), 1), MAX_TEXTAREA_ROWS);\n const isUsable = isComposedInputUsable(runtime);\n const { value, changeValue } = useComposedInputValue<string>({\n node,\n runtime,\n resolvedValue: nodeProps.value,\n readValue: readFieldText,\n fallbackValue: \"\",\n });\n const typeText = (nextText: string) => changeValue(maxLength > 0 ? nextText.slice(0, maxLength) : nextText);\n return (\n <ComposedInputField\n label={label}\n controlId={controlId}\n isUsable={isUsable}\n isPending={isPending}\n pendingHeight={24 * rows + 24}\n testId={testId}\n >\n {isUsable ? (\n <TextArea\n id={controlId}\n testId={testId}\n value={value}\n placeholder={placeholder}\n // No fixed `rows`: the field starts at `rows` lines and grows with the text up to the cap, so a drafted\n // e-mail shows whole (ChatGPT's writing block) instead of scrolling inside a short box.\n minRows={rows}\n maxRows={Math.max(rows, MAX_TEXTAREA_ROWS)}\n maxLength={maxLength > 0 ? maxLength : undefined}\n showsCounter={maxLength > 0}\n onChange={typeText}\n />\n ) : (\n <ComposedInputFrozenValue shownValue={value} isMultiline testId={`${testId}-frozen`} />\n )}\n </ComposedInputField>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"Textarea\",\n component: ComposedTextarea,\n};\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\n\n/**\n * Reads the resolved props of the layout nodes. A prop arrives as a JSON value after its binding was\n * resolved — or `undefined` when it was dropped or is still pending — so every reader falls back to the node's\n * default instead of trusting the type. The closed vocabularies mirror `ComposedViewLayoutSpacing.php`.\n */\n\nexport type LayoutGap = \"none\" | \"xsmall\" | \"small\" | \"medium\" | \"large\";\n\nconst LAYOUT_GAPS: readonly LayoutGap[] = [\"none\", \"xsmall\", \"small\", \"medium\", \"large\"];\n\n/** The value when it is one of `allowedValues`, else `fallback`. */\nexport const readEnumProp = <AllowedValue extends string | number>(\n value: ExpressionValue | undefined,\n allowedValues: readonly AllowedValue[],\n fallback: AllowedValue,\n): AllowedValue => (allowedValues.includes(value as AllowedValue) ? (value as AllowedValue) : fallback);\n\nexport const readGapProp = (value: ExpressionValue | undefined, fallback: LayoutGap = \"medium\"): LayoutGap =>\n readEnumProp(value, LAYOUT_GAPS, fallback);\n\n/** A non-empty text (a number is shown as written), else `undefined`. */\nexport const readTextProp = (value: ExpressionValue | undefined): string | undefined => {\n if (typeof value === \"string\") return value.trim() === \"\" ? undefined : value;\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return undefined;\n};\n\nexport const readBooleanProp = (value: ExpressionValue | undefined, fallback: boolean): boolean =>\n typeof value === \"boolean\" ? value : fallback;\n\nexport interface LayoutSourceLink {\n name?: string;\n url?: string;\n}\n\n/** A `{\"name\",\"url\"}` source; the url only when it is http(s). */\nexport const readSourceLinkProp = (value: ExpressionValue | undefined): LayoutSourceLink | undefined => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n const sourceObject = value as Record<string, ExpressionValue>;\n const name = readTextProp(sourceObject.name);\n const rawUrl = readTextProp(sourceObject.url);\n const url = rawUrl !== undefined && /^https?:\\/\\//i.test(rawUrl) ? rawUrl : undefined;\n if (name === undefined && url === undefined) return undefined;\n return { name, url };\n};\n","import { Icon, InteractiveSurface } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readBooleanProp, readEnumProp, readTextProp } from \"./layout-props\";\nimport styles from \"./Carousel.module.scss\";\n\nconst VISIBLE_ITEM_COUNTS = [1, 2, 3, 4] as const;\n\nconst VISIBLE_CLASS_NAMES: Record<(typeof VISIBLE_ITEM_COUNTS)[number], string> = {\n 1: styles.visible1,\n 2: styles.visible2,\n 3: styles.visible3,\n 4: styles.visible4,\n};\n\nconst SKELETON_SLIDE_COUNT = 3;\n\n/** Whether the track can scroll further back / forward (a pixel of rounding counts as the end). */\nconst readScrollEdges = (track: HTMLDivElement) => ({\n canScrollBack: track.scrollLeft > 1,\n canScrollForward: track.scrollLeft + track.clientWidth < track.scrollWidth - 1,\n});\n\n/**\n * `Carousel` (`CarouselComposedViewNode.php`): slides in one horizontal row the owner pages through —\n * by swipe, by the keyboard on the focused track, or by the previous / next buttons, which show only while there is\n * something to scroll to. Each child node is a slide; with `items` the children are one slide's template rendered per\n * item (`$item` bound; the renderer caps it at `maxRepeatRows`). The e-mail capture shows the first slides without\n * controls. No slides → `empty`; `items` still waiting for its data → skeleton slides.\n */\nconst Carousel = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, renderSlotForItem, runtime, isPending, testId } = props;\n const trackRef = useRef<HTMLDivElement>(null);\n const [scrollEdges, setScrollEdges] = useState({ canScrollBack: false, canScrollForward: false });\n const visibleItemCount = readEnumProp(nodeProps.visibleItems, VISIBLE_ITEM_COUNTS, 2);\n const isShowingArrows = readBooleanProp(nodeProps.showArrows, true) && !runtime.isEmailRender;\n const carouselLabel = readTextProp(nodeProps.label);\n // With `items` written, the slides come from the list only — a list that did not resolve shows no slides.\n const isRepeatingItems = node.props.items !== undefined;\n const items = Array.isArray(nodeProps.items) ? nodeProps.items : [];\n const isWaitingForItems = isRepeatingItems && isPending && !Array.isArray(nodeProps.items);\n\n // One slide per item (the template's nodes together), or one slide per child node when there are no items.\n const slides: ReactNode[][] = isWaitingForItems\n ? []\n : isRepeatingItems\n ? items\n .map((item, itemIndex) => renderSlotForItem(\"children\", item, itemIndex))\n .filter((slide) => slide.length > 0)\n : renderSlotForItem(\"children\", null, 0).map((slideNode) => [slideNode]);\n const slideCount = slides.length;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (isWaitingForItems) reportNodeStatus(\"pending\");\n else if (slideCount > 0) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Carousel has no slides to show\");\n }, [isWaitingForItems, slideCount, reportNodeStatus]);\n\n const updateScrollEdges = useCallback(() => {\n if (trackRef.current) setScrollEdges(readScrollEdges(trackRef.current));\n }, []);\n\n useEffect(() => {\n const track = trackRef.current;\n if (!track) return undefined;\n updateScrollEdges();\n track.addEventListener(\"scroll\", updateScrollEdges, { passive: true });\n const resizeObserver = typeof ResizeObserver === \"undefined\" ? undefined : new ResizeObserver(updateScrollEdges);\n resizeObserver?.observe(track);\n return () => {\n track.removeEventListener(\"scroll\", updateScrollEdges);\n resizeObserver?.disconnect();\n };\n }, [updateScrollEdges, slideCount]);\n\n const scrollBySlide = (direction: 1 | -1) => {\n const track = trackRef.current;\n if (!track) return;\n const firstSlide = track.firstElementChild as HTMLElement | null;\n const slideStep = firstSlide ? firstSlide.getBoundingClientRect().width : track.clientWidth;\n const prefersReducedMotion = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false;\n track.scrollBy?.({ left: direction * slideStep, behavior: prefersReducedMotion ? \"auto\" : \"smooth\" });\n };\n\n if (isWaitingForItems) {\n return (\n <div\n className={classNames(styles.carousel, VISIBLE_CLASS_NAMES[visibleItemCount])}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n <div className={classNames(styles.track, styles.frozenTrack)}>\n {Array.from({ length: SKELETON_SLIDE_COUNT }, (unused, skeletonIndex) => (\n <div key={skeletonIndex} className={styles.slide}>\n <div className={styles.skeletonSlide}>\n <SkeletonLine width=\"50%\" height={12} />\n <SkeletonLine width=\"70%\" height={24} />\n <SkeletonLine width=\"40%\" height={10} />\n </div>\n </div>\n ))}\n </div>\n </div>\n );\n }\n if (slideCount === 0) return null;\n\n return (\n <div className={classNames(styles.carousel, VISIBLE_CLASS_NAMES[visibleItemCount])} data-testid={testId}>\n <div className={styles.viewport}>\n <div\n ref={trackRef}\n data-testid={`${testId}-track`}\n className={classNames(styles.track, runtime.isEmailRender && styles.frozenTrack)}\n role=\"group\"\n aria-roledescription={translateText(\"carousel\")}\n aria-label={carouselLabel}\n tabIndex={runtime.isEmailRender ? undefined : 0}\n >\n {slides.map((slideNodes, slideIndex) => (\n <div\n key={slideIndex}\n className={styles.slide}\n data-testid={`${testId}-slide-${slideIndex}`}\n role=\"group\"\n aria-roledescription={translateText(\"slide\")}\n aria-label={\n translateText(\"%position% of %count%\", { position: slideIndex + 1, count: slideCount })\n }\n >\n {slideNodes}\n </div>\n ))}\n </div>\n {isShowingArrows && scrollEdges.canScrollBack ? (\n <InteractiveSurface hoverable className={classNames(styles.arrow, styles.arrowPrevious)}>\n <button\n type=\"button\"\n className={styles.arrowButton}\n data-testid={`${testId}-previous`}\n aria-label={translateText(\"Show the previous slides\")}\n onClick={() => scrollBySlide(-1)}\n >\n <Icon name=\"arrowLeft\" />\n </button>\n </InteractiveSurface>\n ) : null}\n {isShowingArrows && scrollEdges.canScrollForward ? (\n <InteractiveSurface hoverable className={classNames(styles.arrow, styles.arrowNext)}>\n <button\n type=\"button\"\n className={styles.arrowButton}\n data-testid={`${testId}-next`}\n aria-label={translateText(\"Show the next slides\")}\n onClick={() => scrollBySlide(1)}\n >\n <Icon name=\"arrowRight\" />\n </button>\n </InteractiveSurface>\n ) : null}\n </div>\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Carousel\", component: Carousel };\n","import type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp } from \"./layout-props\";\nimport styles from \"./Divider.module.scss\";\n\nconst ORIENTATIONS = [\"horizontal\", \"vertical\"] as const;\n\n/** `Divider` (`DividerComposedViewNode.php`): a hairline, horizontal in a column, vertical in a row. */\nconst Divider = (props: ComposedViewComponentProps) => {\n const { props: nodeProps } = props;\n const orientation = readEnumProp(nodeProps.orientation, ORIENTATIONS, \"horizontal\");\n return <div role=\"separator\" aria-orientation={orientation} className={styles[orientation]} />;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Divider\", component: Divider };\n","import type { LayoutGap } from \"./layout-props\";\n\n/** The CSS-module class of a gap step (`_layout-gaps.scss`): `medium` → `gapMedium`. */\nexport const layoutGapClassName = (styles: Record<string, string>, gap: LayoutGap): string | undefined =>\n styles[`gap${gap.charAt(0).toUpperCase()}${gap.slice(1)}`];\n","import { classNames } from \"../../../provider/class-names\";\nimport { useEffect } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readGapProp } from \"./layout-props\";\nimport { layoutGapClassName } from \"./layout-gap-class\";\nimport styles from \"./Flow.module.scss\";\n\nconst ALIGNMENTS = [\"start\", \"center\", \"end\"] as const;\n\nconst ALIGNMENT_CLASS_NAMES: Record<(typeof ALIGNMENTS)[number], string> = {\n start: styles.alignStart,\n center: styles.alignCenter,\n end: styles.alignEnd,\n};\n\n/**\n * `Flow` (`FlowComposedViewNode.php`): badges, labels, chips and small controls side by side,\n * wrapping onto as many lines as they need. Without items it shows nothing and reports `empty`.\n */\nconst Flow = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime } = props;\n const items = slots.children ?? [];\n const alignment = readEnumProp(nodeProps.align, ALIGNMENTS, \"center\");\n const hasItems = items.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasItems) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Flow has no items to show\");\n }, [hasItems, reportNodeStatus]);\n\n if (!hasItems) return null;\n return (\n <div\n className={classNames(\n styles.flow,\n ALIGNMENT_CLASS_NAMES[alignment],\n layoutGapClassName(styles, readGapProp(nodeProps.gap, \"small\")),\n )}\n >\n {items}\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Flow\", component: Flow };\n","import { classNames } from \"../../../provider/class-names\";\nimport { useEffect } from \"react\";\nimport { getComposedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readGapProp } from \"./layout-props\";\nimport { layoutGapClassName } from \"./layout-gap-class\";\nimport styles from \"./Grid.module.scss\";\n\nconst COLUMN_COUNTS = [1, 2, 3, 4] as const;\nconst MIN_COLUMN_WIDTHS = [\"compact\", \"regular\"] as const;\n\n/**\n * The cells a compact column fits: a number tile, a pressable tile, a status, a button. Any other cell — a surface with\n * a title and a description, a text, a chart — needs the regular minimum, or a phone shows two columns of four-word lines.\n */\nconst COMPACT_CELL_NODE_TYPES: ReadonlySet<string> = new Set([\n \"KpiTile\",\n \"Pressable\",\n \"Badge\",\n \"Icon\",\n \"Favicon\",\n \"Button\",\n]);\n\n/** A cell that fits a compact column: a compact node type, or an embedded widget whose size class is compact (a snapshot tile). */\nconst isCompactCell = (cellNode: ComposedViewComponentProps[\"node\"]): boolean => {\n if (COMPACT_CELL_NODE_TYPES.has(cellNode.type)) return true;\n const embeddedWidgetName = cellNode.type === \"Widget\" ? cellNode.props.widget : undefined;\n const embeddableWidgets = getComposedNodeSchema().embeddableWidgets;\n return (\n typeof embeddedWidgetName === \"string\" &&\n Object.prototype.hasOwnProperty.call(embeddableWidgets, embeddedWidgetName) &&\n embeddableWidgets[embeddedWidgetName].sizeClass === \"compact\"\n );\n};\n\n/** The written minimum wins; KPI-only grids use regular width, otherwise the existing compact-cell rules apply. */\nexport const readMinColumnWidth = (node: ComposedViewComponentProps[\"node\"], writtenMinColumnWidth: unknown) => {\n if (MIN_COLUMN_WIDTHS.includes(writtenMinColumnWidth as (typeof MIN_COLUMN_WIDTHS)[number])) {\n return writtenMinColumnWidth as (typeof MIN_COLUMN_WIDTHS)[number];\n }\n const cellNodes = node.nodesBySlotName.children ?? [];\n if (cellNodes.length > 0 && cellNodes.every((cell) => cell.type === \"KpiTile\")) return \"regular\";\n return cellNodes.every(isCompactCell) ? \"compact\" : \"regular\";\n};\n\nconst COLUMN_CLASS_NAMES: Record<(typeof COLUMN_COUNTS)[number], string> = {\n 1: styles.columns1,\n 2: styles.columns2,\n 3: styles.columns3,\n 4: styles.columns4,\n};\n\n/**\n * `Grid` (`GridComposedViewNode.php`): one cell per child, at most `columns` side by side, every\n * cell in a row as tall as the tallest. On a narrow pane it shows fewer columns (the cell keeps its minimum width). The\n * minimum is the written `minColumnWidth`; without one KPI-only grids take the regular minimum so textual KPI values\n * stay readable. Other grids keep their compact-cell default.\n * A grid without children shows nothing and reports `empty`.\n */\nconst Grid = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots, runtime, testId } = props;\n const cells = slots.children ?? [];\n const columnCount = readEnumProp(nodeProps.columns, COLUMN_COUNTS, 2);\n const minColumnWidth = readMinColumnWidth(node, nodeProps.minColumnWidth);\n const hasCells = cells.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasCells) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Grid has no cells to show\");\n }, [hasCells, reportNodeStatus]);\n\n if (!hasCells) return null;\n return (\n <div\n data-testid={testId}\n className={classNames(\n styles.grid,\n COLUMN_CLASS_NAMES[columnCount],\n minColumnWidth === \"regular\" ? styles.minColumnRegular : styles.minColumnCompact,\n layoutGapClassName(styles, readGapProp(nodeProps.gap)),\n )}\n >\n {cells}\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Grid\", component: Grid };\n","import { Icon, InteractiveSurface, Text, type AgentsIconName } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readTextProp } from \"./layout-props\";\nimport { useLayoutNesting } from \"./layout-nesting-context\";\nimport styles from \"./Popover.module.scss\";\n\nconst ICONS = [\"info\", \"help\", \"none\"] as const;\nconst PLACEMENTS = [\"start\", \"end\"] as const;\n\nconst ICON_NAMES: Record<Exclude<(typeof ICONS)[number], \"none\">, AgentsIconName> = {\n info: \"info\",\n help: \"help\",\n};\n\n/**\n * `Popover` (`PopoverComposedViewNode.php`; ChatGPT's \"ⓘ Methodik\"): a small text button that opens a\n * floating explanation — `text`, or the nodes of `content`. A click opens it, a second click, Escape or a click\n * elsewhere closes it; the button carries `aria-expanded` and names the panel. The component library's `Popover` is a hover tooltip,\n * which a phone cannot open, so the kit uses a disclosure button instead. Inside a `Pressable` (already one button) and\n * in the e-mail capture it shows its label only. A popover with nothing to explain → `empty`.\n */\nconst Popover = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, testId } = props;\n const { isInsidePressable } = useLayoutNesting();\n const [isOpen, setIsOpen] = useState(false);\n const popoverRef = useRef<HTMLSpanElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const panelId = useId();\n const label = readTextProp(nodeProps.label);\n const text = readTextProp(nodeProps.text);\n const contentNodes = slots.content ?? [];\n const icon = readEnumProp(nodeProps.icon, ICONS, \"info\");\n const placement = readEnumProp(nodeProps.placement, PLACEMENTS, \"end\");\n const hasExplanation = text !== undefined || contentNodes.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (label !== undefined && hasExplanation) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Popover has no label or nothing to explain\");\n }, [label, hasExplanation, reportNodeStatus]);\n\n // While open: a press outside the popover or Escape closes it (Escape returns the focus to the button).\n useEffect(() => {\n if (!isOpen) return undefined;\n const closeOnOutsidePress = (pointerEvent: PointerEvent) => {\n if (popoverRef.current && !popoverRef.current.contains(pointerEvent.target as Node)) setIsOpen(false);\n };\n const closeOnEscape = (keyboardEvent: KeyboardEvent) => {\n if (keyboardEvent.key !== \"Escape\") return;\n setIsOpen(false);\n triggerRef.current?.focus();\n };\n document.addEventListener(\"pointerdown\", closeOnOutsidePress);\n document.addEventListener(\"keydown\", closeOnEscape);\n return () => {\n document.removeEventListener(\"pointerdown\", closeOnOutsidePress);\n document.removeEventListener(\"keydown\", closeOnEscape);\n };\n }, [isOpen]);\n\n if (label === undefined || !hasExplanation) return null;\n const labelContent = (\n <>\n {icon !== \"none\" ? <Icon className={styles.icon} name={ICON_NAMES[icon]} /> : null}\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(label)}\n </Text>\n </>\n );\n if (isInsidePressable || runtime.isEmailRender)\n return (\n <span className={styles.staticLabel} data-testid={testId}>\n {labelContent}\n </span>\n );\n\n return (\n <span ref={popoverRef} className={styles.popover}>\n <InteractiveSurface hoverable className={styles.triggerWrapper}>\n <button\n ref={triggerRef}\n type=\"button\"\n className={styles.trigger}\n data-testid={testId}\n aria-expanded={isOpen}\n aria-controls={isOpen ? panelId : undefined}\n onClick={() => setIsOpen((wasOpen) => !wasOpen)}\n >\n {labelContent}\n </button>\n </InteractiveSurface>\n {isOpen ? (\n <span\n id={panelId}\n role=\"note\"\n data-testid={`${testId}-panel`}\n className={classNames(styles.panel, placement === \"start\" ? styles.placementStart : styles.placementEnd)}\n >\n {text !== undefined ? (\n <Text role=\"help\" translate={false}>\n {escapePlainTextForText(text)}\n </Text>\n ) : null}\n {contentNodes}\n </span>\n ) : null}\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Popover\", component: Popover };\n","import { InteractiveSurface } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useMemo } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readTextProp } from \"./layout-props\";\nimport { LayoutNestingContext, useLayoutNesting } from \"./layout-nesting-context\";\nimport styles from \"./Pressable.module.scss\";\n\n/**\n * `Pressable` (`PressableComposedViewNode.php`): its content as one clickable area. A click runs the\n * node's `onClick` — `{\"set\": <state>}` writes `value`, `{\"action\": <name>}` runs the tree's action — through the\n * renderer, so a frozen tree (the e-mail) writes nothing. `isSelected` draws the one selection ring of the design\n * (inset ring + 8 % tint) and sets `aria-pressed`. In the e-mail capture, and inside another pressable, the content\n * shows without a control. Nothing inside → `empty`.\n */\nconst Pressable = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, slots, runtime, testId } = props;\n const nesting = useLayoutNesting();\n const contentNodes = slots.children ?? [];\n const isSelected = typeof nodeProps.isSelected === \"boolean\" ? nodeProps.isSelected : undefined;\n const accessibleLabel = readTextProp(nodeProps.label);\n const hasContent = contentNodes.length > 0;\n const { reportNodeStatus } = runtime;\n const innerNesting = useMemo(() => ({ ...nesting, isInsidePressable: true }), [nesting]);\n\n useEffect(() => {\n if (hasContent) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Pressable has no content to click\");\n }, [hasContent, reportNodeStatus]);\n\n if (!hasContent) return null;\n if (runtime.isEmailRender || nesting.isInsidePressable) {\n return (\n <div className={classNames(styles.pressable, styles.content, isSelected && styles.selected)} data-testid={testId}>\n {contentNodes}\n </div>\n );\n }\n return (\n <InteractiveSurface hoverable className={classNames(styles.pressable, isSelected && styles.selected)}>\n <button\n type=\"button\"\n className={styles.button}\n data-testid={testId}\n aria-pressed={isSelected}\n aria-label={accessibleLabel}\n onClick={() => runtime.runEvent(node.props.onClick, nodeProps.value)}\n >\n <LayoutNestingContext.Provider value={innerNesting}>{contentNodes}</LayoutNestingContext.Provider>\n </button>\n </InteractiveSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Pressable\", component: Pressable };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readSourceLinkProp, readTextProp } from \"./layout-props\";\nimport styles from \"./Quote.module.scss\";\n\n/**\n * `Quote` (`QuoteComposedViewNode.php`): the quoted words (`text`, or the text nodes in the\n * children), then one caption line — who said it and where it was published, joined by a middle dot; the source opens\n * in a new tab. All of it is the model's business content (never translated). Nothing to quote → `empty`.\n */\nconst Quote = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, testId } = props;\n const text = readTextProp(nodeProps.text);\n const attribution = readTextProp(nodeProps.attribution);\n const source = readSourceLinkProp(nodeProps.source);\n const contentNodes = slots.children ?? [];\n const hasQuotedContent = text !== undefined || contentNodes.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasQuotedContent) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Quote has no quoted text\");\n }, [hasQuotedContent, reportNodeStatus]);\n\n if (!hasQuotedContent) return null;\n const sourceLabel = source?.name ?? source?.url;\n const canOpenSource = source?.url !== undefined && !runtime.isEmailRender;\n return (\n <figure className={styles.quote} data-testid={testId}>\n <blockquote className={styles.quotedContent} cite={source?.url}>\n {text !== undefined ? (\n <Text role=\"body\" translate={false}>\n {escapePlainTextForText(text)}\n </Text>\n ) : null}\n {contentNodes}\n </blockquote>\n {attribution !== undefined || sourceLabel !== undefined ? (\n <figcaption className={styles.caption}>\n {attribution !== undefined ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(attribution)}\n </Text>\n ) : null}\n {attribution !== undefined && sourceLabel !== undefined ? (\n <Text role=\"caption\" color=\"var(--agents-fg-lightest)\" translate={false} ariaHidden>\n {\"·\"}\n </Text>\n ) : null}\n {sourceLabel !== undefined && canOpenSource ? (\n <a\n className={styles.sourceLink}\n href={source?.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n data-testid={`${testId}-source`}\n >\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(sourceLabel)}\n </Text>\n </a>\n ) : null}\n {sourceLabel !== undefined && !canOpenSource ? (\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(sourceLabel)}\n </Text>\n ) : null}\n </figcaption>\n ) : null}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Quote\", component: Quote };\n","import { classNames } from \"../../../provider/class-names\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readBooleanProp, readEnumProp } from \"./layout-props\";\nimport styles from \"./Spacer.module.scss\";\n\nconst SIZES = [\"small\", \"medium\", \"large\"] as const;\n\n/** `Spacer` (`SpacerComposedViewNode.php`): a fixed step of room, or all the free room (`grow`). */\nconst Spacer = (props: ComposedViewComponentProps) => {\n const { props: nodeProps } = props;\n const size = readEnumProp(nodeProps.size, SIZES, \"medium\");\n const isGrowing = readBooleanProp(nodeProps.grow, false);\n return <div aria-hidden=\"true\" className={classNames(styles.spacer, styles[size], isGrowing && styles.grow)} />;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Spacer\", component: Spacer };\n","import { classNames } from \"../../../provider/class-names\";\nimport { useEffect } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readBooleanProp, readEnumProp, readGapProp } from \"./layout-props\";\nimport { layoutGapClassName } from \"./layout-gap-class\";\nimport styles from \"./Stack.module.scss\";\n\nconst DIRECTIONS = [\"row\", \"column\"] as const;\nconst ALIGNMENTS = [\"start\", \"center\", \"end\", \"stretch\", \"baseline\"] as const;\nconst JUSTIFICATIONS = [\"start\", \"center\", \"end\", \"between\"] as const;\n\nconst ALIGNMENT_CLASS_NAMES: Record<(typeof ALIGNMENTS)[number], string> = {\n start: styles.alignStart,\n center: styles.alignCenter,\n end: styles.alignEnd,\n stretch: styles.alignStretch,\n baseline: styles.alignBaseline,\n};\n\nconst JUSTIFICATION_CLASS_NAMES: Record<(typeof JUSTIFICATIONS)[number], string> = {\n start: styles.justifyStart,\n center: styles.justifyCenter,\n end: styles.justifyEnd,\n between: styles.justifyBetween,\n};\n\n/**\n * `Stack` (`StackComposedViewNode.php`): the children in a row or a column with one gap step between\n * them. A row centres its items and wraps by default, so a title with a control at its end (`justify: \"between\"`)\n * stays readable on a phone. A stack without children shows nothing and reports `empty`.\n */\nconst Stack = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime } = props;\n const children = slots.children ?? [];\n const direction = readEnumProp(nodeProps.direction, DIRECTIONS, \"column\");\n const alignment = readEnumProp(nodeProps.align, ALIGNMENTS, direction === \"row\" ? \"center\" : \"stretch\");\n const justification = readEnumProp(nodeProps.justify, JUSTIFICATIONS, \"start\");\n const isWrapping = direction === \"row\" && readBooleanProp(nodeProps.wrap, true);\n const hasChildren = children.length > 0;\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n if (hasChildren) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Stack has no children to show\");\n }, [hasChildren, reportNodeStatus]);\n\n if (!hasChildren) return null;\n return (\n <div\n className={classNames(\n styles.stack,\n styles[direction],\n isWrapping && styles.wrap,\n ALIGNMENT_CLASS_NAMES[alignment],\n JUSTIFICATION_CLASS_NAMES[justification],\n layoutGapClassName(styles, readGapProp(nodeProps.gap)),\n )}\n >\n {children}\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Stack\", component: Stack };\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useMemo } from \"react\";\nimport { WidgetSurface } from \"../../../widgets/_shared/modern\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readEnumProp, readTextProp } from \"./layout-props\";\nimport { LayoutNestingContext, useLayoutNesting } from \"./layout-nesting-context\";\nimport styles from \"./Surface.module.scss\";\n\nconst DENSITIES = [\"regular\", \"compact\"] as const;\n\n/**\n * `Surface` (`SurfaceComposedViewNode.php`; ChatGPT's `Card` — named Surface, the project's noun is\n * never \"card\"): a titled group of nodes. The outermost surface is raised on the chat (`WidgetSurface` elevated); a\n * surface inside another one is a flat tile, so a composition never stacks three background levels. The title is the\n * widget title (`textIntro` bold) on the outer surface and a tile title (`text` bold) inside; the subtitle is one muted\n * line. Slots: `media` flush at the top, `header` at the end of the title row, the body, `footer` at the foot. A\n * surface with nothing to show reports `empty`.\n */\nconst Surface = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, slots, runtime, testId } = props;\n const nesting = useLayoutNesting();\n const title = readTextProp(nodeProps.title);\n const subtitle = readTextProp(nodeProps.subtitle);\n const isCompact = readEnumProp(nodeProps.density, DENSITIES, \"regular\") === \"compact\";\n const mediaNodes = slots.media ?? [];\n const headerNodes = slots.header ?? [];\n const bodyNodes = slots.children ?? [];\n const footerNodes = slots.footer ?? [];\n const hasContent =\n title !== undefined ||\n subtitle !== undefined ||\n mediaNodes.length + headerNodes.length + bodyNodes.length + footerNodes.length > 0;\n const { reportNodeStatus } = runtime;\n const innerNesting = useMemo(() => ({ ...nesting, isInsideSurface: true }), [nesting]);\n\n useEffect(() => {\n if (hasContent) reportNodeStatus(\"mounted\");\n else reportNodeStatus(\"empty\", undefined, \"the Surface has no title and no content\");\n }, [hasContent, reportNodeStatus]);\n\n if (!hasContent) return null;\n const isOutermost = !nesting.isInsideSurface;\n const hasHeader = title !== undefined || subtitle !== undefined || headerNodes.length > 0;\n return (\n <WidgetSurface\n level={isOutermost ? \"elevated\" : \"flat\"}\n compact={isCompact}\n testId={testId}\n className={classNames(styles.surface, isCompact && styles.compact)}\n >\n <LayoutNestingContext.Provider value={innerNesting}>\n {mediaNodes.length > 0 ? (\n <div className={classNames(styles.media, isCompact && styles.compactMedia)}>{mediaNodes}</div>\n ) : null}\n {hasHeader ? (\n <div className={styles.header}>\n {title !== undefined || subtitle !== undefined ? (\n <div className={styles.titles}>\n {title !== undefined ? (\n <Text\n role={isOutermost ? \"intro\" : \"body\"}\n weight=\"bold\"\n translate={false}\n >\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n {subtitle !== undefined ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(subtitle)}\n </Text>\n ) : null}\n </div>\n ) : null}\n {headerNodes.length > 0 ? <div className={styles.headerEnd}>{headerNodes}</div> : null}\n </div>\n ) : null}\n {bodyNodes.length > 0 ? <div className={styles.body}>{bodyNodes}</div> : null}\n {footerNodes.length > 0 ? <div className={styles.footer}>{footerNodes}</div> : null}\n </LayoutNestingContext.Provider>\n </WidgetSurface>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Surface\", component: Surface };\n","import type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport {\n type ComposedViewTone,\n readOptionalComposedViewTone,\n} from \"../../composed-view-tones\";\n\n/**\n * The `Map` node's props, read into one typed map view (`MapComposedViewNode.php`). The props arrive\n * with every binding resolved; the reader checked their JSON types, not the shape of a point, so this reading is\n * alias-tolerant (a model that writes `name` / `latitude` / `lon` still gets its point), caps the points at the\n * repeat budget and never throws: a point without valid coordinates is dropped and counted, so the component can\n * report it. Pure — no React, no Google SDK.\n */\n\nexport interface MapPoint {\n /** Stable within one map: the point's position in the written list. */\n key: string;\n label: string;\n lat: number;\n lng: number;\n /** 0–5, one decimal. */\n rating?: number;\n /** The category line (\"Café\", \"Restaurant\"). */\n subtitle?: string;\n /** A status line (\"Closed\", \"Open until 18:00\"). */\n detail?: string;\n /**\n * How the status line reads, a tone of the kit's list (`composed-view-tones.ts`): `success` (open), `danger`\n * (closed), `warning` (closes soon) — the older `positive` / `negative` read as `success` / `danger`; none = plain text.\n */\n detailTone?: MapPointDetailTone;\n /** An http(s) or data: image URL. */\n image?: string;\n /** The name of a tree action the point runs on click (an `openEntity` action opens the entity's detail panel). */\n actionName?: string;\n /**\n * The point as the props hand it — a row of a resolved `$from` list carries its own `entityRef` + `entity`. The click\n * runs the action in this row, so a row-bound `openEntity` action (`ref: {\"$item\":\"entityRef\"}`) opens its entity.\n */\n row: Record<string, unknown>;\n}\n\nexport type MapPointDetailTone = ComposedViewTone;\n\nexport interface MapLatLng {\n lat: number;\n lng: number;\n}\n\nexport interface MapView {\n title?: string;\n points: MapPoint[];\n showRoute: boolean;\n /** The route line: `routePath` when given, else the points in their order (only when `showRoute`). */\n routeLine: MapLatLng[];\n routeLabel?: string;\n showCarousel: boolean;\n heightPx: number;\n /** Points dropped for missing or invalid coordinates. */\n droppedPointCount: number;\n /** Points past the repeat budget, not shown. */\n cappedPointCount: number;\n}\n\nexport const MAP_DEFAULT_HEIGHT_PX = 330;\nexport const MAP_MIN_HEIGHT_PX = 240;\nexport const MAP_MAX_HEIGHT_PX = 560;\n\nconst LABEL_KEYS = [\"label\", \"name\", \"title\"];\nconst LAT_KEYS = [\"lat\", \"latitude\"];\nconst LNG_KEYS = [\"lng\", \"lon\", \"long\", \"longitude\"];\nconst SUBTITLE_KEYS = [\"subtitle\", \"category\", \"type\"];\nconst DETAIL_KEYS = [\"detail\", \"status\", \"caption\"];\nconst IMAGE_KEYS = [\"image\", \"imageUrl\", \"photo\", \"thumbnail\"];\nconst ACTION_KEYS = [\"action\", \"onClick\", \"onSelect\"];\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readFirst = (record: Record<string, unknown>, keys: string[]): unknown => {\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined && record[key] !== null) {\n return record[key];\n }\n }\n return undefined;\n};\n\nconst readText = (record: Record<string, unknown>, keys: string[]): string | undefined => {\n const value = readFirst(record, keys);\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed === \"\" ? undefined : trimmed;\n};\n\nconst readNumber = (value: unknown): number | undefined => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value.trim().replace(\",\", \".\"));\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n};\n\n/** A coordinate pair inside the valid range, or undefined. Also takes `{position: {lat, lng}}` / `{location: …}`. */\nexport const readLatLng = (record: Record<string, unknown>): MapLatLng | undefined => {\n const nested = readFirst(record, [\"position\", \"location\", \"coordinates\"]);\n const source = isPlainObject(nested) ? nested : record;\n const lat = readNumber(readFirst(source, LAT_KEYS));\n const lng = readNumber(readFirst(source, LNG_KEYS));\n if (lat === undefined || lng === undefined) return undefined;\n if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return undefined;\n return { lat, lng };\n};\n\n/** Only http(s) and inline `data:image/` URLs reach an `<img src>`. */\nconst readImageUrl = (record: Record<string, unknown>): string | undefined => {\n const value = readText(record, IMAGE_KEYS);\n if (!value) return undefined;\n return /^https?:\\/\\//i.test(value) || /^data:image\\//i.test(value) ? value : undefined;\n};\n\n/** The action name: a plain string, or the event form `{\"action\": \"<name>\"}`. */\nconst readActionName = (record: Record<string, unknown>): string | undefined => {\n const value = readFirst(record, ACTION_KEYS);\n if (typeof value === \"string\" && value.trim() !== \"\") return value.trim();\n if (isPlainObject(value) && typeof value.action === \"string\" && value.action.trim() !== \"\")\n return value.action.trim();\n return undefined;\n};\n\nconst readDetailTone = (record: Record<string, unknown>): MapPointDetailTone | undefined => {\n return readOptionalComposedViewTone(readText(record, [\"detailTone\", \"statusTone\", \"tone\"]));\n};\n\nconst readRating = (record: Record<string, unknown>): number | undefined => {\n const rating = readNumber(readFirst(record, [\"rating\", \"stars\", \"score\"]));\n if (rating === undefined || rating < 0 || rating > 5) return undefined;\n return Math.round(rating * 10) / 10;\n};\n\n/**\n * One point. `fallbackActionName` is the Map's `pointAction`: the action a point without its own `action` runs — over\n * points bound to a resolved `$from` list a row-bound `openEntity` action opens each row's `entity`, since such a row carries no `action` key.\n */\nconst readPoint = (pointValue: unknown, pointIndex: number, fallbackActionName?: string): MapPoint | undefined => {\n if (!isPlainObject(pointValue)) return undefined;\n const position = readLatLng(pointValue);\n if (!position) return undefined;\n return {\n key: `point-${pointIndex}`,\n label: readText(pointValue, LABEL_KEYS) ?? \"\",\n lat: position.lat,\n lng: position.lng,\n rating: readRating(pointValue),\n subtitle: readText(pointValue, SUBTITLE_KEYS),\n detail: readText(pointValue, DETAIL_KEYS),\n detailTone: readDetailTone(pointValue),\n image: readImageUrl(pointValue),\n actionName: readActionName(pointValue) ?? fallbackActionName,\n row: pointValue,\n };\n};\n\nconst readHeight = (value: ExpressionValue | undefined): number => {\n const height = readNumber(value);\n if (height === undefined) return MAP_DEFAULT_HEIGHT_PX;\n return Math.min(MAP_MAX_HEIGHT_PX, Math.max(MAP_MIN_HEIGHT_PX, Math.round(height)));\n};\n\nconst readRoutePath = (value: ExpressionValue | undefined, maxVertices: number): MapLatLng[] => {\n if (!Array.isArray(value)) return [];\n const routePath: MapLatLng[] = [];\n for (const pathValue of value.slice(0, maxVertices)) {\n const position = isPlainObject(pathValue) ? readLatLng(pathValue) : undefined;\n if (position) routePath.push(position);\n }\n return routePath;\n};\n\nconst readTrimmedString = (value: ExpressionValue | undefined): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\n/**\n * The map view of a `Map` node's resolved props. `maxPoints` is the schema's `maxRepeatRows`; `maxRouteVertices` the\n * collection cap (a real road path from a tool is long).\n */\nexport const readMapView = (\n props: Record<string, ExpressionValue>,\n maxPoints: number,\n maxRouteVertices: number,\n): MapView => {\n const pointValues = Array.isArray(props.points) ? props.points : [];\n const cappedPointCount = Math.max(0, pointValues.length - maxPoints);\n const points: MapPoint[] = [];\n let droppedPointCount = 0;\n const pointActionName = readTrimmedString(props.pointAction);\n pointValues.slice(0, maxPoints).forEach((pointValue, pointIndex) => {\n const point = readPoint(pointValue, pointIndex, pointActionName);\n if (point) points.push(point);\n else droppedPointCount += 1;\n });\n const showRoute = props.route === true;\n const routePath = readRoutePath(props.routePath, maxRouteVertices);\n let routeLine: MapLatLng[] = [];\n if (showRoute) {\n routeLine = routePath.length >= 2 ? routePath : points.map((point) => ({ lat: point.lat, lng: point.lng }));\n }\n return {\n title: readTrimmedString(props.title),\n points,\n showRoute,\n routeLine,\n routeLabel: showRoute ? readTrimmedString(props.routeLabel) : undefined,\n showCarousel: props.carousel !== \"hidden\" && points.length > 0,\n heightPx: readHeight(props.minHeight),\n droppedPointCount,\n cappedPointCount,\n };\n};\n\n/** The rating as the owner's locale writes it (one decimal: \"4,7\" in German, \"4.7\" in English). */\nexport const formatMapRating = (rating: number, languageCode?: string): string => {\n try {\n return new Intl.NumberFormat(languageCode || undefined, {\n minimumFractionDigits: 1,\n maximumFractionDigits: 1,\n }).format(rating);\n } catch {\n return rating.toFixed(1);\n }\n};\n","import { createContext, useContext } from \"react\";\n\n/**\n * Where a `Map` node renders: `inline` in the chat (the map card with its carousel and the expand\n * control), or `fullScreen` in the `mapFullScreen` canvas (the map filling the pane beside the list of points). The\n * canvas body renders the same node through the same renderer and provides `fullScreen`; nothing else changes.\n */\nexport type MapPresentation = \"inline\" | \"fullScreen\";\n\nexport const MapPresentationContext = createContext<MapPresentation>(\"inline\");\n\nexport const useMapPresentation = () => useContext(MapPresentationContext);\n","import { exceedsJsonContainerDepth } from \"./widget-tree/bounded-json\";\n\n/**\n * The JSON of a widget block as every frontend reader decodes it — the twin of the backend's\n * `WidgetBlocks::buildWidgetJsonWithoutSurplusClosers()`: a block whose JSON does not decode is read\n * once more without the surplus closing brackets a model wrote at its end (one `}` too many after a correct tree), up to\n * {@link MAX_SURPLUS_CLOSERS} trailing `}` / `]` dropped one by one. The parity fixture `composed-view-parity.json`\n * (`surplusCloserCases`) holds both readers equal.\n */\n\n/** The most trailing `}` / `]` a block read drops to decode a block (the backend's `WidgetBlocks::MAX_SURPLUS_CLOSERS`). */\nexport const MAX_SURPLUS_CLOSERS = 3;\n\n/** The decoded value of `jsonText` when it is a JSON object no deeper than the backend decodes; undefined otherwise. */\nconst decodeJsonObject = (jsonText: string): Record<string, unknown> | undefined => {\n let decoded: unknown;\n try {\n decoded = JSON.parse(jsonText);\n } catch {\n return undefined;\n }\n if (typeof decoded !== \"object\" || decoded === null || Array.isArray(decoded) || exceedsJsonContainerDepth(decoded)) {\n return undefined;\n }\n return decoded as Record<string, unknown>;\n};\n\n/**\n * The block JSON without its surplus trailing closers, or null when it decodes as written or when no shortened text\n * decodes to a JSON object — exactly the backend's answer.\n */\nexport const readWidgetJsonWithoutSurplusClosers = (widgetJson: string): string | null => {\n if (decodeJsonObject(widgetJson) !== undefined) return null;\n let candidateJson = widgetJson.trimEnd();\n for (let droppedCloserCount = 0; droppedCloserCount < MAX_SURPLUS_CLOSERS; droppedCloserCount++) {\n const lastCharacter = candidateJson.slice(-1);\n if (lastCharacter !== \"}\" && lastCharacter !== \"]\") return null;\n candidateJson = candidateJson.slice(0, -1).trimEnd();\n if (decodeJsonObject(candidateJson) !== undefined) return candidateJson;\n }\n return null;\n};\n\n/** The block's JSON object — as written, or without its surplus trailing closers; undefined for a malformed block. */\nexport const parseWidgetJsonObject = (widgetJson: string): Record<string, unknown> | undefined =>\n decodeJsonObject(widgetJson) ?? decodeJsonObject(readWidgetJsonWithoutSurplusClosers(widgetJson) ?? \"\");\n","import { visit } from \"unist-util-visit\";\nimport { BARE_WIDGET_PARAGRAPH, WIDGET_FENCE_LANG } from \"./widget-fence-syntax\";\nimport { resolveWidgetName } from \"./widget-name-resolver\";\nimport { parseWidgetJsonObject } from \"./widget-fence-json\";\nimport { buildWidgetAgentSpaceKeyProps, readWidgetAgentSpaceKeyAttribute } from \"./_agent-space/widget-agent-space-key-attribute\";\n\n/**\n * Render a widget the agent emitted in either form:\n *\n * 1. a ```widget fenced code block (the base-prompt convention):\n * ```widget\n * { \"type\": \"<WidgetName>\", ...fields }\n * ```\n * 2. a bare `widget { \"type\": \"<WidgetName>\", ...fields }` line (no fence) — the same intent when the model\n * drops the backticks, which happens in practice. Markdown parses this as a plain `paragraph`, so it never\n * reached the fence path and leaked as raw JSON to the customer (the block shown verbatim).\n *\n * Both are rewritten into the SAME `leafDirective` node that `::WidgetName{payload='…'}` produces, so the existing\n * pipeline (conversationWidgetAstPlugin → ConversationWidgetHost → feature-gate → hydration) renders it unchanged —\n * the non-`type` fields become the node's `payload` (a JSON string), exactly what the widgets parse.\n *\n * MUST run BEFORE conversationWidgetAstPlugin. The `type` is resolved through the ONE legacy rule\n * (`resolveWidgetName`): the canonical `ExampleWidget` matches exactly, the legacy `ExampleWidgetDirective` resolves\n * onto it. A block whose JSON decodes only without surplus trailing `}` / `]` renders like the backend reads it\n * (`widget-fence-json.ts`). A malformed JSON block or an unknown widget name is dropped (renders nothing) — the kill switch; never leak\n * raw JSON or a `:name` fallback to the user.\n */\nexport default function remarkWidgetFencePlugin() {\n // `resolveWidgetName` (widget-name-resolver) is the ONE source of truth for \"is this a real widget\", shared with\n // the unrendered-widget detector so a dropped block here and a reported block there always agree.\n return (tree: any) => {\n // In-place replacement only (no splice) so the visitor's indices stay valid: rewrite the node into a\n // `leafDirective`, or drop it to an empty text node (malformed JSON / unknown widget → render nothing).\n const rewrite = (parent: any, index: number, widgetJson: string) => {\n const drop = () => {\n parent.children[index] = { type: \"text\", value: \"\" };\n };\n\n // A JSON object as written or without the model's surplus trailing `}` / `]` (the backend reads it the same way);\n // deeper than the backend decodes (`json_decode(…, 32)`), not an object, or malformed → dropped.\n const parsed = parseWidgetJsonObject(widgetJson);\n if (parsed === undefined) {\n drop();\n return;\n }\n\n const { type, ...fields } = parsed as Record<string, unknown>;\n const widgetName = typeof type === \"string\" ? resolveWidgetName(type) : undefined;\n if (!widgetName) {\n drop(); // unknown / unsupported widget → render nothing\n return;\n }\n\n const agentSpaceKeyAttribute = readWidgetAgentSpaceKeyAttribute(fields);\n parent.children[index] = {\n // `\"leafDirective\"` is remark-directive's node type — its contract, not our vocabulary.\n type: \"leafDirective\",\n name: widgetName,\n // The fence's place in the message travels on: it is the block's identity in the render report (two blocks\n // of one type in one message are told apart by it) — without it every block sat at offset 0.\n ...(parent.children[index]?.position ? { position: parent.children[index].position } : {}),\n attributes: {\n payload: JSON.stringify(fields),\n // The agent space key is the one fence field the FRAMEWORK consumes rather than the widget: the block field\n // the app declares (`AgentsEnvironment.widgetSelfHydrationKeyFieldName`) is documented on every widget and\n // resolved centrally by `useResolvedConversationWidgetAgentSpaceKey`. Without lifting it here it stayed\n // buried in the payload string and never arrived as a prop, so a fence targeting another agent space\n // silently rendered the ACTIVE agent space's data — every widget except the ones that happened to parse\n // it back out themselves. Carried as a string under the declared field name, matching what the\n // `::Name{<field>=123}` attribute form delivers; the resolver normalizes both. It stays in the payload too,\n // so widgets that parse it keep working.\n ...buildWidgetAgentSpaceKeyProps(agentSpaceKeyAttribute === undefined ? undefined : String(agentSpaceKeyAttribute)),\n },\n children: [],\n data: {},\n };\n };\n\n // Concatenate a node's text (paragraph children are text nodes; the bare JSON carries no markdown syntax).\n const textOf = (node: any): string =>\n typeof node.value === \"string\"\n ? node.value\n : Array.isArray(node.children)\n ? node.children.map(textOf).join(\"\")\n : \"\";\n\n visit(tree, (node: any, index, parent) => {\n if (!parent || index === null || index === undefined) {\n return;\n }\n if (node.type === \"code\") {\n if (node.lang !== WIDGET_FENCE_LANG) {\n return;\n }\n rewrite(parent, index, node.value);\n return;\n }\n if (node.type === \"paragraph\") {\n const match = BARE_WIDGET_PARAGRAPH.exec(textOf(node));\n if (match) {\n rewrite(parent, index, match[1]);\n }\n }\n });\n };\n}\n","import { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport remarkDirective from \"remark-directive\";\nimport { visit } from \"unist-util-visit\";\nimport remarkWidgetFencePlugin from \"../remarkWidgetFencePlugin\";\nimport { resolveWidgetName } from \"../widget-name-resolver\";\nimport { readWidgetAgentSpaceKeyAttribute } from \"../_agent-space/widget-agent-space-key-attribute\";\nimport { shortStringHash } from \"./canvas-state\";\nimport { getComposedViewSubtreeNodes, parseComposedViewTree } from \"../widget-tree/composed-view-tree\";\n\n/** The wire name of the composable widget kit — its tree may embed domain widgets as `Widget` nodes. */\nconst COMPOSED_VIEW_WIDGET_NAME = \"ComposedView\";\n\n/** One widget the anchor message carries — what a canvas body parses its own payload from. */\nexport interface WidgetFenceInMessage {\n /** The CANONICAL wire name (a stored legacy `<Name>Directive` resolves onto it). */\n readonly name: string;\n /** The fence's non-`type` fields as the JSON string every widget parser takes (`payload`). */\n readonly payload: string;\n /** The agent space key the framework lifts out of the fence (the block field the app declares), when present. */\n readonly agentSpaceKey?: string;\n /** `shortStringHash(payload)` — what `canvasInstanceIdForMessagePayload` puts into the instance id. */\n readonly payloadHash: string;\n /** Every string attribute of the node (`target`, `mode`, … — widgets that do not use `payload`). */\n readonly attributes: Readonly<Record<string, string>>;\n}\n\n/**\n * Every widget in a message's markdown, in document order, through the SAME pipeline the message renders with\n * (`remarkDirective` for the stored `::Name{payload='…'}` form, `remarkWidgetFencePlugin` for the ```widget fence and\n * the bare `widget { … }` line) — so a canvas body re-reads exactly the payload its inline widget rendered from, in\n * both the canonical and the legacy wire form. Malformed or unknown widgets are dropped, as when rendering.\n *\n * A `ComposedView` block is followed by the domain widgets its tree embeds (`Widget` nodes), each as if\n * its own fence stood there — `payload` = the node's `fields` — so a canvas opened from a widget in a slot finds its\n * payload like any other canvas body, and the reload restore finds the widget that opens the canvas.\n *\n * Shell-side only (the pipeline imports the widget registry through the name resolver): imported by canvas bodies,\n * never by the slice or the canvas model modules.\n */\nexport const findWidgetFencesInMarkdown = (markdown: string): WidgetFenceInMessage[] => {\n if (!markdown) return [];\n const processor = unified().use(remarkParse).use(remarkDirective).use(remarkWidgetFencePlugin);\n const tree = processor.runSync(processor.parse(markdown));\n const fences: WidgetFenceInMessage[] = [];\n visit(tree, \"leafDirective\", (node: any) => {\n const name = typeof node.name === \"string\" ? resolveWidgetName(node.name) : undefined;\n if (!name) return;\n const attributes = (node.attributes ?? {}) as Record<string, unknown>;\n const payload = typeof attributes.payload === \"string\" ? attributes.payload : \"{}\";\n const stringAttributes = Object.fromEntries(\n Object.entries(attributes).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"),\n );\n const agentSpaceKey = readWidgetAgentSpaceKeyAttribute(attributes);\n fences.push({\n name,\n payload,\n ...(typeof agentSpaceKey === \"string\" ? { agentSpaceKey } : {}),\n payloadHash: shortStringHash(payload),\n attributes: stringAttributes,\n });\n if (name === COMPOSED_VIEW_WIDGET_NAME) fences.push(...findWidgetsEmbeddedInComposedView(payload));\n });\n return fences;\n};\n\n/**\n * The domain widgets a `ComposedView` payload embeds (its KEPT `Widget` nodes — only embeddable ones survive the\n * reader), in tree order, as fences. Total: a payload the reader cannot take gives none, it never throws (the canvas\n * restore and the anchor lookups call this outside any error boundary).\n */\nconst findWidgetsEmbeddedInComposedView = (composedViewPayload: string): WidgetFenceInMessage[] => {\n try {\n return readWidgetsEmbeddedInComposedView(composedViewPayload);\n } catch {\n return [];\n }\n};\n\nconst readWidgetsEmbeddedInComposedView = (composedViewPayload: string): WidgetFenceInMessage[] => {\n const tree = parseComposedViewTree(composedViewPayload);\n if (tree.view === null) return [];\n const embeddedFences: WidgetFenceInMessage[] = [];\n for (const node of getComposedViewSubtreeNodes(tree.view)) {\n if (node.type !== \"Widget\" || typeof node.props.widget !== \"string\") continue;\n const name = resolveWidgetName(node.props.widget);\n if (!name) continue;\n const fields = typeof node.props.fields === \"object\" && node.props.fields !== null ? node.props.fields : {};\n const payload = JSON.stringify(fields);\n const agentSpaceKey = readWidgetAgentSpaceKeyAttribute(fields);\n embeddedFences.push({\n name,\n payload,\n ...(agentSpaceKey !== undefined ? { agentSpaceKey: String(agentSpaceKey) } : {}),\n payloadHash: shortStringHash(payload),\n attributes: { payload },\n });\n }\n return embeddedFences;\n};\n\n/**\n * The fence a canvas is anchored on: the widget of `name` whose payload hash the canvas instance id carries\n * (`canvasInstanceIdForMessagePayload`). Two identical widgets in one message share one canvas by design.\n */\nexport const findWidgetFenceByPayloadHash = (\n markdown: string,\n name: string,\n payloadHash: string,\n): WidgetFenceInMessage | undefined =>\n findWidgetFencesInMarkdown(markdown).find((fence) => fence.name === name && fence.payloadHash === payloadHash);\n","import { shortStringHash } from \"../../../renderer/canvas/canvas-state\";\nimport { findWidgetFencesInMarkdown } from \"../../../renderer/canvas/find-widget-fences-in-markdown\";\nimport {\n getComposedViewSubtreeNodes,\n parseComposedViewTree,\n type ComposedViewNode,\n type ComposedViewTree,\n} from \"../../../renderer/widget-tree/composed-view-tree\";\n\n/**\n * Which `Map` node a `mapFullScreen` canvas shows. A canvas is a pointer to its anchor message, so the\n * instance id carries only the message and a short hash of the node — its id and its\n * wire props — and the body finds the node again in the message's `ComposedView` fences. Two identical maps in one\n * message are one canvas; a map whose message no longer carries it opens nothing.\n *\n * Format `mapFullScreen:message:<messageId>:map-<hash>` — the `map-` part keeps it apart from the payload-hash form\n * (`payloadHashOfInstanceId`), which the shared canvas helpers would otherwise read as a fence hash.\n */\n\nexport const MAP_NODE_TYPE = \"Map\";\nconst COMPOSED_VIEW_WIDGET_NAME = \"ComposedView\";\nconst MAP_FULL_SCREEN_INSTANCE_ID = /^mapFullScreen:message:(\\d+):map-([0-9a-z]+)$/;\n\n/** The short hash of a map node: its id and its props as written (bindings unresolved), so it is stable across renders. */\nexport const buildMapNodeKey = (mapNode: ComposedViewNode): string =>\n shortStringHash(JSON.stringify({ id: mapNode.id, props: mapNode.props }));\n\nexport const canvasInstanceIdForMapFullScreen = (messageId: number, mapNode: ComposedViewNode): string =>\n `mapFullScreen:message:${messageId}:map-${buildMapNodeKey(mapNode)}`;\n\n/** The map node key a `mapFullScreen` instance id carries, or undefined for another shape. */\nexport const readMapNodeKeyOfInstanceId = (instanceId: string): string | undefined =>\n MAP_FULL_SCREEN_INSTANCE_ID.exec(instanceId)?.[2];\n\nexport interface MapNodeInComposedView {\n /** The whole tree the map sits in — its state, data, computed values and actions resolve the map's bindings. */\n tree: ComposedViewTree;\n mapNode: ComposedViewNode;\n}\n\n/**\n * The `Map` node with this key among the `ComposedView` fences of a message, with its tree. Total: an unparsable\n * message or a missing map gives undefined, never a throw (a canvas body runs outside the message's error boundary).\n */\nexport const findMapNodeInMarkdown = (markdown: string, mapNodeKey: string): MapNodeInComposedView | undefined => {\n try {\n for (const fence of findWidgetFencesInMarkdown(markdown)) {\n if (fence.name !== COMPOSED_VIEW_WIDGET_NAME) continue;\n const tree = parseComposedViewTree(fence.payload);\n if (tree.view === null) continue;\n const mapNode = getComposedViewSubtreeNodes(tree.view).find(\n (node) => node.type === MAP_NODE_TYPE && buildMapNodeKey(node) === mapNodeKey,\n );\n if (mapNode) return { tree, mapNode };\n }\n } catch {\n return undefined;\n }\n return undefined;\n};\n","import { Button, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { formatMapRating, type MapPoint } from \"./map-points\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapPointMarkerProps {\n point: MapPoint;\n /** 1-based, shown instead of the rating when the map draws a route (the stops in their order). */\n routeStopNumber?: number;\n isSelected: boolean;\n languageCode?: string;\n /** Undefined → a static pin (the e-mail capture): no button, nothing to focus. */\n onClick?: () => void;\n}\n\n/**\n * One point on the map: a small dark pill — the rating with a star, the stop number on a route, or a\n * plain dot — over the point's label with a halo so it reads on any map tile. The pill is a component-library muted `onDark`\n * Button; only the pill takes clicks, never the label.\n */\nexport const MapPointMarker = (props: MapPointMarkerProps) => {\n const { point, routeStopNumber, isSelected, languageCode, onClick } = props;\n const hasRating = point.rating !== undefined && routeStopNumber === undefined;\n let pillText = \"•\";\n if (routeStopNumber !== undefined) pillText = String(routeStopNumber);\n else if (point.rating !== undefined) pillText = formatMapRating(point.rating, languageCode);\n\n return (\n <div\n className={classNames(styles.marker, isSelected && styles.markerSelected)}\n data-testid=\"map-point-marker\"\n data-point-key={point.key}\n >\n <span\n // The component library's Button takes no aria-label: the point's name goes onto its native button.\n ref={(node) => {\n if (point.label) node?.querySelector(\"button\")?.setAttribute(\"aria-label\", point.label);\n }}\n className={classNames(styles.markerPill, onClick && styles.markerPillInteractive)}\n inert={!onClick}\n aria-hidden={onClick ? undefined : \"true\"}\n >\n <Button\n variant=\"muted\"\n size=\"small\"\n rounded\n onDark\n pressed={onClick ? isSelected : undefined}\n icon={hasRating ? \"starActive\" : undefined}\n translate={false}\n onClick={onClick}\n testId={`map-point-marker-pill-${point.key}`}\n >\n {pillText}\n </Button>\n </span>\n {point.label ? (\n <span className={styles.markerLabel}>\n <Text role=\"caption\" weight=\"medium\" display=\"inline\" translate={false}>\n {escapePlainTextForText(point.label)}\n </Text>\n </span>\n ) : null}\n </div>\n );\n};\n","import { useCallback, useContext, useEffect, useState } from \"react\";\nimport { Map as AgentsMap, MapMarker } from \"../../../provider/components\";\nimport { WidgetImageReadinessContext } from \"../../../image-render/WidgetImageRenderContext\";\nimport type { MapPoint, MapView } from \"./map-points\";\nimport { MapPointMarker } from \"./MapPointMarker\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapGoogleMapProps {\n mapView: MapView;\n selectedPointKey?: string;\n languageCode?: string;\n /** The Google SDK is loaded (`useGoogleMapApiLoader`, the one loader of the app). */\n isJsApiLoaded: boolean;\n isEmailRender: boolean;\n /** Undefined → markers are static (the e-mail capture, a replay without interaction). */\n onPointClick?: (point: MapPoint) => void;\n /** Extra bottom room kept free of points when fitting — the carousel lies over the map's bottom edge. */\n bottomOverlayPx: number;\n className?: string;\n}\n\nconst FIT_PADDING_PX = 48;\nconst SINGLE_POINT_ZOOM = 15;\nconst ROUTE_STROKE_WEIGHT = 4;\nconst ROUTE_STROKE_OPACITY = 0.85;\n/** Used only when the theme token cannot be read (a host without the theme stylesheet). */\nconst ROUTE_STROKE_FALLBACK = \"#1f2329\";\n\n/** The route line's colour: the theme's foreground token, read once at draw time (the SDK takes a colour, not a var). */\nconst readRouteStrokeColor = (mapDiv: HTMLElement | null): string => {\n if (!mapDiv) return ROUTE_STROKE_FALLBACK;\n const tokenValue = getComputedStyle(mapDiv).getPropertyValue(\"--agents-fg\").trim();\n return tokenValue || ROUTE_STROKE_FALLBACK;\n};\n\n/**\n * The Google map of a `Map` node: the environment's map (the app supplies the key and the map id), one marker per point, the route polyline when the node asks\n * for one, the view fitted to every point and the route, and a pan to the selected point. In the e-mail capture the\n * map has no controls and no gestures, and it reports `MAP_SDK_LOAD_FAILED` to the capture readiness on a load error.\n */\nexport const MapGoogleMap = (props: MapGoogleMapProps) => {\n const {\n mapView,\n selectedPointKey,\n languageCode,\n isJsApiLoaded,\n isEmailRender,\n onPointClick,\n bottomOverlayPx,\n className,\n } = props;\n const readiness = useContext(WidgetImageReadinessContext);\n const [map, setMap] = useState<google.maps.Map>();\n const [hasTilesLoaded, setHasTilesLoaded] = useState(false);\n const handleOnLoad = useCallback((loadedMap: google.maps.Map) => setMap(loadedMap), []);\n // The first frame's centre only — a centre prop that changed on every render would undo every pan and fit.\n const [initialCenter] = useState(() =>\n mapView.points[0] ? { lat: mapView.points[0].lat, lng: mapView.points[0].lng } : undefined,\n );\n\n // The view: every point and the whole route; one point alone gets a street-level zoom instead of a fit.\n const fitKey = JSON.stringify([mapView.points.map((point) => [point.lat, point.lng]), mapView.routeLine.length]);\n useEffect(() => {\n if (!map || typeof google === \"undefined\") return;\n const positions = [...mapView.points, ...mapView.routeLine];\n if (positions.length === 0) return;\n if (positions.length === 1) {\n map.setCenter({ lat: positions[0].lat, lng: positions[0].lng });\n map.setZoom(SINGLE_POINT_ZOOM);\n return;\n }\n const bounds = new google.maps.LatLngBounds();\n positions.forEach((position) => bounds.extend({ lat: position.lat, lng: position.lng }));\n map.fitBounds(bounds, {\n top: FIT_PADDING_PX,\n right: FIT_PADDING_PX,\n bottom: FIT_PADDING_PX + bottomOverlayPx,\n left: FIT_PADDING_PX,\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map, fitKey, bottomOverlayPx]);\n\n // The route line through the stops (or the tool's path), removed with the map or a new route.\n useEffect(() => {\n if (!map || typeof google === \"undefined\" || mapView.routeLine.length < 2) return;\n const routePolyline = new google.maps.Polyline({\n path: mapView.routeLine,\n map,\n strokeColor: readRouteStrokeColor(map.getDiv()),\n strokeWeight: ROUTE_STROKE_WEIGHT,\n strokeOpacity: ROUTE_STROKE_OPACITY,\n clickable: false,\n });\n return () => routePolyline.setMap(null);\n }, [map, mapView.routeLine]);\n\n // A click on a card or a marker brings its point into view.\n useEffect(() => {\n const selectedPoint = mapView.points.find((point) => point.key === selectedPointKey);\n if (map && selectedPoint) map.panTo({ lat: selectedPoint.lat, lng: selectedPoint.lng });\n }, [map, selectedPointKey, mapView.points]);\n\n // The e-mail capture waits for the tiles; a map that cannot render fails the capture instead of a blank image.\n useEffect(() => {\n if (!map || !isEmailRender) return;\n const tilesListener = map.addListener(\"tilesloaded\", () => setHasTilesLoaded(true));\n return () => tilesListener.remove();\n }, [map, isEmailRender]);\n useEffect(() => {\n if (isEmailRender && isJsApiLoaded && mapView.points.length === 0) readiness?.fail(\"MAP_COORDINATES_MISSING\");\n }, [isEmailRender, isJsApiLoaded, mapView.points.length, readiness]);\n\n const staticOptions: google.maps.MapOptions = isEmailRender\n ? {\n disableDefaultUI: true,\n zoomControl: false,\n fullscreenControl: false,\n mapTypeControl: false,\n keyboardShortcuts: false,\n gestureHandling: \"none\",\n clickableIcons: false,\n }\n : { fullscreenControl: false, clickableIcons: false };\n\n return (\n <div className={className} aria-busy={isEmailRender ? !hasTilesLoaded : undefined}>\n <AgentsMap\n testId=\"ComposedViewMap-GoogleMaps\"\n isLoaded={isJsApiLoaded}\n languageCode={languageCode}\n onLoad={handleOnLoad}\n zoom={12}\n center={initialCenter}\n className={styles.mapContainer}\n options={{\n ...staticOptions,\n streetViewControl: false,\n mapTypeControlOptions: { mapTypeIds: [] },\n }}\n >\n {mapView.points.map((point, pointIndex) => (\n <MapMarker\n key={point.key}\n id={`composed-map-${point.key}`}\n isLoaded={isJsApiLoaded}\n position={{ lat: point.lat, lng: point.lng }}\n zIndex={point.key === selectedPointKey ? 20 : 10}\n title={point.label || undefined}\n >\n <MapPointMarker\n point={point}\n routeStopNumber={mapView.showRoute ? pointIndex + 1 : undefined}\n isSelected={point.key === selectedPointKey}\n languageCode={languageCode}\n onClick={onPointClick ? () => onPointClick(point) : undefined}\n />\n </MapMarker>\n ))}\n </AgentsMap>\n </div>\n );\n};\n","import { Icon, InteractiveSurface, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useState } from \"react\";\nimport { COMPOSED_VIEW_TONE_TEXT_COLOR } from \"../../composed-view-tones\";\nimport { formatMapRating, type MapPoint } from \"./map-points\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapPointCardProps {\n point: MapPoint;\n /** `carousel`: a card along the map's bottom edge (inline); `row`: a row of the full-screen list. */\n variant: \"carousel\" | \"row\";\n isSelected: boolean;\n languageCode?: string;\n /** 1-based stop number on a route. */\n routeStopNumber?: number;\n /** Undefined → a static card (the e-mail capture). */\n onClick?: () => void;\n}\n\n/**\n * One point as a card: the thumbnail, the label, the rating with its category, and the\n * status line. Clickable through the GlobalStateComponent hover layer around a native button; selected = the inner CTA\n * ring. A point without an image shows the pin glyph on a flat tile, never an empty box.\n */\nexport const MapPointCard = (props: MapPointCardProps) => {\n const { point, variant, isSelected, languageCode, routeStopNumber, onClick } = props;\n const [isImageBroken, setIsImageBroken] = useState(false);\n const showImage = point.image !== undefined && !isImageBroken;\n\n const ratingLine = [\n point.rating !== undefined ? formatMapRating(point.rating, languageCode) : undefined,\n point.subtitle,\n ].filter((part): part is string => part !== undefined);\n\n const content = (\n <>\n <span className={styles.cardThumbnail} aria-hidden=\"true\">\n {showImage ? (\n <img src={point.image} alt=\"\" loading=\"lazy\" onError={() => setIsImageBroken(true)} />\n ) : routeStopNumber !== undefined ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {String(routeStopNumber)}\n </Text>\n ) : (\n <Icon className={styles.cardThumbnailIcon} name=\"pinFilled\" />\n )}\n </span>\n <span className={styles.cardText}>\n {point.label ? (\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(point.label)}\n </Text>\n ) : null}\n {ratingLine.length > 0 ? (\n <span className={styles.cardMeta}>\n {point.rating !== undefined ? (\n <Icon className={styles.cardStar} size=\"small\" name=\"starActive\" />\n ) : null}\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(ratingLine.join(\" · \"))}\n </Text>\n </span>\n ) : null}\n {point.detail ? (\n <Text\n role=\"caption\"\n weight={point.detailTone ? \"medium\" : undefined}\n color={point.detailTone ? COMPOSED_VIEW_TONE_TEXT_COLOR[point.detailTone] : \"var(--agents-fg-light)\"}\n translate={false}\n >\n {escapePlainTextForText(point.detail)}\n </Text>\n ) : null}\n </span>\n </>\n );\n\n const cardClassName = classNames(\n styles.card,\n variant === \"carousel\" ? styles.cardCarousel : styles.cardRow,\n isSelected && styles.cardSelected,\n );\n if (!onClick) {\n return (\n <div className={cardClassName} data-point-key={point.key}>\n <span className={styles.cardInner}>{content}</span>\n </div>\n );\n }\n return (\n <InteractiveSurface hoverable className={cardClassName}>\n <button\n type=\"button\"\n className={classNames(styles.cardInner, styles.cardButton)}\n onClick={onClick}\n aria-pressed={isSelected}\n data-point-key={point.key}\n data-testid=\"map-point-card\"\n >\n {content}\n </button>\n </InteractiveSurface>\n );\n};\n","import { Icon, InteractiveSurface } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport type { MapPoint } from \"./map-points\";\nimport { MapPointCard } from \"./MapPointCard\";\nimport styles from \"./Map.module.scss\";\n\nexport interface MapPointCarouselProps {\n points: MapPoint[];\n selectedPointKey?: string;\n languageCode?: string;\n /** Whether the points are the stops of a route — the cards then show their stop number. */\n isRoute: boolean;\n /** Undefined → static cards and no paging buttons (the e-mail capture). */\n onPointSelect?: (point: MapPoint) => void;\n}\n\n/** Whether the track can scroll further back / forward (a pixel of rounding counts as the end). */\nconst readScrollEdges = (track: HTMLDivElement) => ({\n canScrollBack: track.scrollLeft > 1,\n canScrollForward: track.scrollLeft + track.clientWidth < track.scrollWidth - 1,\n});\n\nconst prefersReducedMotion = (): boolean =>\n typeof window !== \"undefined\" && (window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false);\n\n/**\n * The point cards along the map's bottom edge: one horizontal, snapping row the owner pages through\n * by swipe, trackpad or the previous / next buttons, which show only while there is a card to scroll to — without\n * them a mouse could not reach the cards past the second one (the row hides its scrollbar so the map stays clean). A\n * selected point (a marker click) scrolls its card into view.\n */\nexport const MapPointCarousel = (props: MapPointCarouselProps) => {\n const { points, selectedPointKey, languageCode, isRoute, onPointSelect } = props;\n const trackRef = useRef<HTMLDivElement>(null);\n const [scrollEdges, setScrollEdges] = useState({ canScrollBack: false, canScrollForward: false });\n const isPageable = onPointSelect !== undefined;\n\n const updateScrollEdges = useCallback(() => {\n if (trackRef.current) setScrollEdges(readScrollEdges(trackRef.current));\n }, []);\n\n useEffect(() => {\n const track = trackRef.current;\n if (!track) return undefined;\n updateScrollEdges();\n track.addEventListener(\"scroll\", updateScrollEdges, { passive: true });\n const resizeObserver = typeof ResizeObserver === \"undefined\" ? undefined : new ResizeObserver(updateScrollEdges);\n resizeObserver?.observe(track);\n return () => {\n track.removeEventListener(\"scroll\", updateScrollEdges);\n resizeObserver?.disconnect();\n };\n }, [updateScrollEdges, points.length]);\n\n // A marker click selects a point whose card may sit outside the row's visible part: bring it in.\n useEffect(() => {\n const track = trackRef.current;\n if (!track || selectedPointKey === undefined) return;\n const selectedCard = Array.from(track.querySelectorAll<HTMLElement>(\"[data-point-key]\")).find(\n (cardElement) => cardElement.dataset.pointKey === selectedPointKey,\n );\n if (!selectedCard) return;\n const trackBox = track.getBoundingClientRect();\n const cardBox = selectedCard.getBoundingClientRect();\n if (cardBox.left >= trackBox.left && cardBox.right <= trackBox.right) return;\n track.scrollBy?.({\n left: cardBox.left < trackBox.left ? cardBox.left - trackBox.left : cardBox.right - trackBox.right,\n behavior: prefersReducedMotion() ? \"auto\" : \"smooth\",\n });\n }, [selectedPointKey]);\n\n const scrollByCard = (direction: 1 | -1) => {\n const track = trackRef.current;\n if (!track) return;\n const firstCard = track.firstElementChild as HTMLElement | null;\n const cardStep = firstCard ? firstCard.getBoundingClientRect().width : track.clientWidth;\n track.scrollBy?.({ left: direction * cardStep, behavior: prefersReducedMotion() ? \"auto\" : \"smooth\" });\n };\n\n return (\n <div className={styles.carouselViewport}>\n <div ref={trackRef} className={styles.carousel} role=\"list\" data-testid=\"map-carousel\">\n {points.map((point, pointIndex) => (\n <div\n role=\"listitem\"\n key={point.key}\n className={styles.carouselItem}\n data-testid={`map-carousel-item-${point.key}`}\n >\n <MapPointCard\n point={point}\n variant=\"carousel\"\n isSelected={point.key === selectedPointKey}\n languageCode={languageCode}\n routeStopNumber={isRoute ? pointIndex + 1 : undefined}\n onClick={onPointSelect ? () => onPointSelect(point) : undefined}\n />\n </div>\n ))}\n </div>\n {isPageable && scrollEdges.canScrollBack ? (\n <InteractiveSurface hoverable className={classNames(styles.carouselArrow, styles.carouselArrowPrevious)}>\n <button\n type=\"button\"\n className={styles.carouselArrowButton}\n aria-label={translateText(\"Show the previous slides\")}\n onClick={() => scrollByCard(-1)}\n data-testid=\"map-carousel-previous\"\n >\n <Icon name=\"arrowLeft\" />\n </button>\n </InteractiveSurface>\n ) : null}\n {isPageable && scrollEdges.canScrollForward ? (\n <InteractiveSurface hoverable className={classNames(styles.carouselArrow, styles.carouselArrowNext)}>\n <button\n type=\"button\"\n className={styles.carouselArrowButton}\n aria-label={translateText(\"Show the next slides\")}\n onClick={() => scrollByCard(1)}\n data-testid=\"map-carousel-next\"\n >\n <Icon name=\"arrowRight\" />\n </button>\n </InteractiveSurface>\n ) : null}\n </div>\n );\n};\n","import { Icon, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { translateText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { MapPoint, MapView } from \"./map-points\";\nimport type { MapPresentation } from \"./map-presentation-context\";\nimport { MapGoogleMap } from \"./MapGoogleMap\";\nimport { MapPointCard } from \"./MapPointCard\";\nimport { MapPointCarousel } from \"./MapPointCarousel\";\nimport styles from \"./Map.module.scss\";\n\nexport interface ComposedMapViewProps {\n mapView: MapView;\n presentation: MapPresentation;\n /** A bound `points` prop still waits for its data. */\n isPending: boolean;\n /** The Google SDK state from the app's one loader (`useGoogleMapApiLoader`). */\n isJsApiLoaded: boolean;\n hasLoadError: boolean;\n isEmailRender: boolean;\n languageCode?: string;\n selectedPointKey?: string;\n /** Undefined → points are static (the e-mail capture). */\n onPointSelect?: (point: MapPoint) => void;\n /** Undefined → no expand control (the e-mail capture, a reply still streaming, the full-screen canvas itself). */\n onExpand?: () => void;\n /** The `mapFullScreen` canvas shows this map now: the control closes it again. */\n isShownFullScreen?: boolean;\n}\n\n/** The bottom band the inline carousel covers, kept free of points when the map fits its view. */\nconst CAROUSEL_OVERLAY_PX = 112;\n\n/**\n * The look of a `Map` node. Inline: the map in a rounded frame, the\n * route line's label top left, the expand control top right, the point cards along the bottom edge. Full screen (the\n * `mapFullScreen` canvas): the map filling the pane beside the list of every point. Loading is a frame-shaped\n * skeleton; no points renders nothing; a map that cannot load keeps its cards with one muted line in the frame —\n * the component reports each.\n */\nexport const ComposedMapView = (props: ComposedMapViewProps) => {\n const {\n mapView,\n presentation,\n isPending,\n isJsApiLoaded,\n hasLoadError,\n isEmailRender,\n languageCode,\n selectedPointKey,\n onPointSelect,\n onExpand,\n isShownFullScreen = false,\n } = props;\n const isFullScreen = presentation === \"fullScreen\";\n const frameStyle = isFullScreen ? undefined : { height: mapView.heightPx };\n\n if (isPending) {\n return (\n <div className={styles.frame} style={frameStyle} aria-busy=\"true\" data-testid=\"map-skeleton\">\n <SkeletonLine width=\"100%\" height={mapView.heightPx} radius={0} />\n </div>\n );\n }\n // No points: nothing on screen (the prose answer stands); the node reports `empty` so the model knows.\n if (mapView.points.length === 0) return null;\n\n // Without the map the cards are the only place the points show, so they stay even when the node hid them.\n const showCarousel = mapView.showCarousel || hasLoadError;\n const routeStopNumberOf = (pointIndex: number) => (mapView.showRoute ? pointIndex + 1 : undefined);\n // A map that cannot load keeps its points: the frame shows one muted line where the map would be, the cards and the\n // full-screen list stay.\n const googleMap = hasLoadError ? (\n <div className={styles.mapUnavailable} data-testid=\"map-unavailable\">\n <Text role=\"help\" color=\"var(--agents-fg-light)\">\n {\"The map could not be loaded.\"}\n </Text>\n </div>\n ) : isJsApiLoaded ? (\n <MapGoogleMap\n className={styles.mapLayer}\n mapView={mapView}\n selectedPointKey={selectedPointKey}\n languageCode={languageCode}\n isJsApiLoaded={isJsApiLoaded}\n isEmailRender={isEmailRender}\n onPointClick={onPointSelect}\n bottomOverlayPx={!isFullScreen && showCarousel ? CAROUSEL_OVERLAY_PX : 0}\n />\n ) : (\n <div className={styles.mapLayer} aria-busy=\"true\">\n <SkeletonLine width=\"100%\" height={mapView.heightPx} radius={0} />\n </div>\n );\n const routeChip = mapView.routeLabel ? (\n <div className={styles.routeChip} data-testid=\"map-route-label\">\n <Icon className={styles.routeChipIcon} size=\"small\" name=\"clock\" />\n <Text role=\"caption\" weight=\"medium\" translate={false}>\n {escapePlainTextForText(mapView.routeLabel)}\n </Text>\n </div>\n ) : null;\n\n if (isFullScreen) {\n return (\n <div className={styles.fullScreen} data-testid=\"map-full-screen\">\n <div className={styles.fullScreenMap}>\n {googleMap}\n {routeChip}\n </div>\n <aside className={styles.fullScreenList}>\n <div className={styles.fullScreenHeader}>\n {mapView.title ? (\n <Text role=\"intro\" weight=\"bold\" translate={false}>\n {escapePlainTextForText(mapView.title)}\n </Text>\n ) : null}\n <Text\n role=\"caption\"\n color=\"var(--agents-fg-light)\"\n replacements={{ count: mapView.points.length }}\n context={mapView.points.length === 1 ? \"one\" : \"other\"}\n >\n {\"%count% place\"}\n </Text>\n </div>\n <div className={styles.fullScreenRows} role=\"list\" data-testid=\"map-full-screen-list\">\n {mapView.points.map((point, pointIndex) => (\n <div role=\"listitem\" key={point.key} data-testid={`map-full-screen-row-${point.key}`}>\n <MapPointCard\n point={point}\n variant=\"row\"\n isSelected={point.key === selectedPointKey}\n languageCode={languageCode}\n routeStopNumber={routeStopNumberOf(pointIndex)}\n onClick={onPointSelect ? () => onPointSelect(point) : undefined}\n />\n </div>\n ))}\n </div>\n </aside>\n </div>\n );\n }\n\n return (\n <div className={styles.frame} style={frameStyle} data-testid=\"map-inline\">\n {googleMap}\n {routeChip}\n {onExpand ? (\n <button\n type=\"button\"\n className={styles.expandButton}\n onClick={onExpand}\n aria-pressed={isShownFullScreen}\n aria-label={\n translateText(isShownFullScreen ? \"Close the full-screen map\" : \"Open the map in full screen\")\n }\n data-testid=\"map-expand\"\n >\n <Icon name={isShownFullScreen ? \"minimize\" : \"maximize\"} />\n </button>\n ) : null}\n {showCarousel ? (\n <MapPointCarousel\n points={mapView.points}\n selectedPointKey={selectedPointKey}\n languageCode={languageCode}\n isRoute={mapView.showRoute}\n onPointSelect={onPointSelect}\n />\n ) : null}\n </div>\n );\n};\n","import { useSyncExternalStore } from \"react\";\n\n/**\n * Whether Google refused the Maps key for this page. The SDK reports a refused key — a referrer the\n * key does not allow, a disabled API — only through the global `window.gm_authFailure` callback; the script itself\n * loads fine, so `useGoogleMapApiLoader` sees no error. After a refusal every new map fails inside the SDK, so the\n * `Map` node stops creating Google maps, shows its points without the map and reports `failed`.\n *\n * One page-wide flag: the handler is installed once and keeps any handler that was there before.\n */\n\ndeclare global {\n interface Window {\n gm_authFailure?: () => void;\n }\n}\n\nlet hasGoogleMapsAuthFailed = false;\nconst authFailureListeners = new Set<() => void>();\nlet isHandlerInstalled = false;\n\nconst markGoogleMapsAuthFailed = () => {\n hasGoogleMapsAuthFailed = true;\n authFailureListeners.forEach((listener) => listener());\n};\n\nconst installAuthFailureHandler = () => {\n if (isHandlerInstalled || typeof window === \"undefined\") return;\n isHandlerInstalled = true;\n const previousHandler = window.gm_authFailure;\n window.gm_authFailure = () => {\n markGoogleMapsAuthFailed();\n previousHandler?.();\n };\n};\n\nconst subscribeToAuthFailure = (listener: () => void) => {\n installAuthFailureHandler();\n authFailureListeners.add(listener);\n return () => {\n authFailureListeners.delete(listener);\n };\n};\n\nconst readAuthFailure = () => hasGoogleMapsAuthFailed;\nconst readAuthFailureOnServer = () => false;\n\nexport const useGoogleMapsAuthFailure = (): boolean =>\n useSyncExternalStore(subscribeToAuthFailure, readAuthFailure, readAuthFailureOnServer);\n\n/** For specs: the flag back to its initial state. */\nexport const resetGoogleMapsAuthFailureForTests = () => {\n hasGoogleMapsAuthFailed = false;\n};\n\n/** For specs and stories: what the SDK's callback does. */\nexport const simulateGoogleMapsAuthFailure = () => markGoogleMapsAuthFailed();\n","import { useEffect, useMemo, useState } from \"react\";\nimport { useAgentsMapsLoader } from \"../../../provider/AgentsProvider\";\nimport { useConversationWidgetContext } from \"../../../renderer/ConversationWidgetCallbacksContext\";\nimport { messageAnchor } from \"../../../renderer/canvas/canvas-state\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { WidgetRenderReportEntry } from \"../../../renderer/render-report/widget-render-report\";\nimport type { ExpressionValue } from \"../../../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readMapView, type MapPoint, type MapView } from \"./map-points\";\nimport { useMapPresentation } from \"./map-presentation-context\";\nimport { canvasInstanceIdForMapFullScreen, MAP_NODE_TYPE } from \"./map-full-screen-instance\";\nimport { ComposedMapView } from \"./ComposedMapView\";\nimport { useGoogleMapsAuthFailure } from \"./use-google-maps-auth-failure\";\n\ninterface MapLoadState {\n isPending: boolean;\n isJsApiLoaded: boolean;\n hasLoadError: boolean;\n /** Google refused the key (`gm_authFailure`): the script loaded, the map cannot render. */\n hasAuthFailed: boolean;\n}\n\n/** What the block reports for this map: never a silent nothing. */\nexport const buildMapRenderReport = (mapView: MapView, loadState: MapLoadState): WidgetRenderReportEntry => {\n if (loadState.isPending) return { status: \"pending\" };\n if (loadState.hasLoadError || loadState.hasAuthFailed) {\n const reason = loadState.hasAuthFailed ? \"Google refused the Maps key\" : \"the Google Maps script did not load\";\n return { status: \"failed\", code: \"RENDER_FAILED\", detail: `${reason} — the points show without the map` };\n }\n if (mapView.points.length === 0 && mapView.droppedPointCount > 0) {\n return {\n status: \"failed\",\n code: \"INVALID_PROP\",\n detail: `none of the ${mapView.droppedPointCount} Map points has valid \"lat\"/\"lng\" coordinates — no map shown`,\n };\n }\n if (mapView.points.length === 0) {\n return { status: \"empty\", code: \"NO_DATA\", detail: \"the Map has no points — no map shown\" };\n }\n if (!loadState.isJsApiLoaded) return { status: \"pending\" };\n if (mapView.droppedPointCount > 0) {\n return {\n status: \"failed\",\n code: \"INVALID_PROP\",\n detail: `${mapView.droppedPointCount} Map point(s) without valid \"lat\"/\"lng\" coordinates are not on the map`,\n };\n }\n if (mapView.cappedPointCount > 0) {\n return {\n status: \"failed\",\n code: \"BUDGET_EXCEEDED\",\n detail: `the Map shows the first ${mapView.points.length} points only`,\n };\n }\n return { status: \"mounted\" };\n};\n\n/**\n * The `Map` node (`MapComposedViewNode.php`): labelled points with rating badges, the view fitted to\n * them, a card carousel, an optional route line, and an expand control that opens the `mapFullScreen` canvas (anchored\n * on the host message; the body finds this node again by its key). A marker or card click selects the point and runs\n * the point's `action` — an `openEntity` action opens the entity's detail panel. The Google SDK comes from the app's one\n * loader (`AgentsEnvironment.useMapsLoader`), the key and map id from the app, as every map widget of the chat.\n */\nconst MapNode = (props: ComposedViewComponentProps) => {\n const { node, props: nodeProps, isPending, runtime } = props;\n const presentation = useMapPresentation();\n const { openCanvas, closeCanvas, canvas } = useConversationWidgetContext();\n const { isLoaded, loadError, languageCode } = useAgentsMapsLoader();\n const hasAuthFailed = useGoogleMapsAuthFailure();\n const hasLoadError = loadError !== undefined || hasAuthFailed;\n const [selectedPointKey, setSelectedPointKey] = useState<string>();\n const { maxRepeatRows, maxCollectionItems } = composedNodeSchema.budgets;\n\n // The resolved props are a new object on every render; the view is rebuilt only when their content changes.\n const nodePropsKey = JSON.stringify(nodeProps);\n const mapView = useMemo(\n () => readMapView(nodeProps, maxRepeatRows, maxCollectionItems),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [nodePropsKey, maxRepeatRows, maxCollectionItems],\n );\n\n const report = buildMapRenderReport(mapView, {\n isPending,\n isJsApiLoaded: isLoaded,\n hasLoadError: loadError !== undefined,\n hasAuthFailed,\n });\n const { reportNodeStatus } = runtime;\n useEffect(() => {\n reportNodeStatus(report.status, report.code, report.detail);\n }, [reportNodeStatus, report.status, report.code, report.detail]);\n\n const selectPoint = (point: MapPoint) => {\n setSelectedPointKey(point.key);\n if (point.actionName) runtime.runEvent({ action: point.actionName }, undefined, point.row as ExpressionValue);\n };\n\n const numericMessageId = runtime.messageId === undefined ? Number.NaN : Number(runtime.messageId);\n const canExpand = presentation === \"inline\" && !runtime.isEmailRender && Number.isFinite(numericMessageId);\n const fullScreenInstanceId = canExpand ? canvasInstanceIdForMapFullScreen(numericMessageId, node) : undefined;\n const isShownFullScreen =\n fullScreenInstanceId !== undefined &&\n canvas?.canvasId === \"mapFullScreen\" &&\n canvas.instanceId === fullScreenInstanceId;\n // The control toggles: it opens this map full screen, and closes the canvas again while it shows this map.\n const toggleFullScreen = () => {\n if (fullScreenInstanceId === undefined) return;\n if (isShownFullScreen) {\n closeCanvas(true);\n return;\n }\n openCanvas({\n canvasId: \"mapFullScreen\",\n instanceId: fullScreenInstanceId,\n anchor: messageAnchor(numericMessageId),\n origin: \"cardClick\",\n justDelivered: false,\n });\n };\n\n return (\n <ComposedMapView\n mapView={mapView}\n presentation={presentation}\n isPending={isPending}\n isJsApiLoaded={isLoaded}\n hasLoadError={hasLoadError}\n isEmailRender={runtime.isEmailRender}\n languageCode={languageCode}\n selectedPointKey={selectedPointKey}\n onPointSelect={runtime.isEmailRender ? undefined : selectPoint}\n onExpand={canExpand ? toggleFullScreen : undefined}\n isShownFullScreen={isShownFullScreen}\n />\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: MAP_NODE_TYPE, component: MapNode };\n","import { ModelText } from \"../../ModelText/ModelText\";\nimport styles from \"./MediaCaption.module.scss\";\n\nexport interface MediaCaptionProps {\n title?: string;\n caption?: string;\n}\n\n/** The lines under a picture or a video: the title (card title, bold) over a muted caption; nothing when both are empty. */\nexport const MediaCaption = (props: MediaCaptionProps) => {\n const { title, caption } = props;\n if (!title && !caption) return null;\n return (\n <span className={styles.caption}>\n {title ? (\n <ModelText role=\"body\" weight=\"bold\" className={styles.wrap}>\n {title}\n </ModelText>\n ) : null}\n {caption ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-light)\" className={styles.wrap}>\n {caption}\n </ModelText>\n ) : null}\n </span>\n );\n};\n","import { useCallback, useState } from \"react\";\n\nexport type ImageLoadState = \"loading\" | \"loaded\" | \"failed\";\n\ninterface ImageLoadRecord {\n src: string | undefined;\n state: ImageLoadState;\n}\n\n/**\n * The load state of one `<img>`, bound to its `src`: a new source reads as `loading` without an effect (an effect that\n * resets after the commit would undo the `onLoad` of a cached picture that already fired), and the ref marks a picture\n * that is already complete when it mounts — a cached or lazily loaded one fires no `onLoad` React could still see.\n */\nexport const useImageLoadState = (src: string | undefined) => {\n const [loadRecord, setLoadRecord] = useState<ImageLoadRecord>({ src, state: \"loading\" });\n const loadState: ImageLoadState = loadRecord.src === src ? loadRecord.state : \"loading\";\n const markLoaded = useCallback(() => setLoadRecord({ src, state: \"loaded\" }), [src]);\n const markFailed = useCallback(() => setLoadRecord({ src, state: \"failed\" }), [src]);\n const imageRef = useCallback(\n (imageElement: HTMLImageElement | null) => {\n if (imageElement?.complete && imageElement.naturalWidth > 0) setLoadRecord({ src, state: \"loaded\" });\n },\n [src],\n );\n return { loadState, imageRef, markLoaded, markFailed };\n};\n","import { Icon, InteractiveSurface, Skeleton, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { translateText } from \"../../../provider/environment\";\nimport { ModelText } from \"../../ModelText/ModelText\";\nimport type { MediaAspectRatio, MediaImage, MediaImageFit } from \"./media-values\";\nimport styles from \"./MediaImageTile.module.scss\";\nimport { useImageLoadState } from \"./use-image-load-state\";\n\nexport interface MediaImageTileProps {\n image: MediaImage;\n aspectRatio: MediaAspectRatio;\n fit?: MediaImageFit;\n /** Load at once instead of lazily — the e-mail capture, which shoots the whole widget. */\n isEager?: boolean;\n /** Opens the lightbox at this picture; without it the tile is a plain picture (the e-mail capture). */\n onOpen?: () => void;\n /** The pictures the gallery does not show — counted on this tile as \"+N\". */\n hiddenImageCount?: number;\n /** The compact radius and no source chip — a thumbnail in a compact slot or a dense grid. */\n isCompact?: boolean;\n /** Called once when the picture fails to load; the tile then shows its alt text instead. */\n onLoadFailed?: () => void;\n testId?: string;\n}\n\nconst ASPECT_RATIO_CLASS_NAMES: Readonly<Record<MediaAspectRatio, string>> = {\n \"1:1\": styles.ratioSquare,\n \"4:3\": styles.ratioFourByThree,\n \"3:2\": styles.ratioThreeByTwo,\n \"5:4\": styles.ratioFiveByFour,\n \"16:9\": styles.ratioSixteenByNine,\n \"3:4\": styles.ratioThreeByFour,\n};\n\n/**\n * One picture of the media kit: a frame in the picture's aspect ratio on `--agents-bg-disabled`, a\n * skeleton in the frame's shape until the picture painted, the picture lazily loaded (`object-fit` cover or contain),\n * the source as a dark chip over its corner and, on the last visible tile of a gallery, the count of the hidden rest.\n * A picture that fails to load is replaced by its alt text — no broken image, and the e-mail capture never waits on a\n * missing asset. A tile that opens the lightbox is a native button inside the hoverable surface.\n */\nexport const MediaImageTile = (props: MediaImageTileProps) => {\n const {\n image,\n aspectRatio,\n fit = \"cover\",\n isEager = false,\n onOpen,\n hiddenImageCount = 0,\n isCompact = false,\n onLoadFailed,\n testId,\n } = props;\n const { loadState, imageRef, markLoaded, markFailed: markImageFailed } = useImageLoadState(image.src);\n\n const markFailed = () => {\n markImageFailed();\n onLoadFailed?.();\n };\n\n const frameClassName = classNames(\n styles.frame,\n ASPECT_RATIO_CLASS_NAMES[aspectRatio],\n isCompact && styles.frameCompact,\n );\n\n const frameContent = (\n <>\n {loadState === \"failed\" ? (\n <span className={styles.fallback}>\n <Icon color=\"var(--agents-fg-light)\" name=\"image\" />\n <ModelText role=\"caption\" color=\"var(--agents-fg)\" className={styles.fallbackText}>\n {image.alt}\n </ModelText>\n </span>\n ) : (\n <img\n ref={imageRef}\n className={classNames(styles.image, fit === \"contain\" && styles.imageContain)}\n src={image.src}\n alt={image.alt}\n loading={isEager ? \"eager\" : \"lazy\"}\n decoding=\"async\"\n onLoad={markLoaded}\n onError={markFailed}\n />\n )}\n {loadState === \"loading\" ? <Skeleton className={styles.skeleton} /> : null}\n {image.source && !isCompact ? (\n <span className={styles.sourceChip}>\n <ModelText role=\"caption\" color=\"var(--agents-fg-on-dark)\" ellipsis>\n {image.source.name}\n </ModelText>\n </span>\n ) : null}\n {hiddenImageCount > 0 ? (\n <span className={styles.hiddenCountChip}>\n <Icon color=\"var(--agents-fg-on-dark)\" name=\"photo\" />\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {`+${hiddenImageCount}`}\n </Text>\n </span>\n ) : null}\n </>\n );\n\n if (!onOpen) {\n return (\n <span className={frameClassName} data-testid={testId}>\n {frameContent}\n </span>\n );\n }\n const openLabel =\n hiddenImageCount > 0\n ? translateText(\n \"Open the gallery at %alt%, %count% more picture\",\n { alt: image.alt, count: hiddenImageCount },\n hiddenImageCount === 1 ? \"one\" : \"other\",\n )\n : translateText(\"Open the picture %alt% full size\", { alt: image.alt });\n return (\n <InteractiveSurface hoverable className={frameClassName}>\n {frameContent}\n <button\n type=\"button\"\n className={styles.openButton}\n aria-label={openLabel}\n onClick={onOpen}\n data-testid={testId ? `${testId}-open` : undefined}\n />\n </InteractiveSurface>\n );\n};\n","import { openImageGallery } from \"../../../provider/environment\";\n\n/**\n * The values the media kit components (`Image`, `ImageGroup`, `Video`) read from their resolved props.\n * Every reader is total: a value that does not fit is `undefined` (or dropped from a list and counted), never a throw —\n * the component reports what it lost and renders the rest.\n */\n\n/** Where a picture or a video was found — the chip over an image, the source line under a video. */\nexport interface MediaSource {\n name: string;\n url?: string;\n}\n\n/** One picture of an `Image` node or of an `ImageGroup` list. */\nexport interface MediaImage {\n src: string;\n alt: string;\n title?: string;\n caption?: string;\n source?: MediaSource;\n}\n\n/** The pictures of a list prop: the usable ones, how many were dropped (no `src` / `alt`) and how many past the row cap. */\nexport interface MediaImageList {\n images: MediaImage[];\n droppedCount: number;\n cappedCount: number;\n}\n\nconst readText = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** An `http(s)` URL, unchanged; anything else (a `javascript:` link, a relative path, a typo) is `undefined`. */\nexport const readHttpUrl = (value: unknown): string | undefined => {\n const text = readText(value);\n if (!text) return undefined;\n try {\n const url = new URL(text);\n return url.protocol === \"https:\" || url.protocol === \"http:\" ? text : undefined;\n } catch {\n return undefined;\n }\n};\n\n/** An image address: an `http(s)` URL or an inline `data:image/…` URI (the fixtures, a generated picture). */\nexport const readImageUrl = (value: unknown): string | undefined => {\n const text = readText(value);\n if (text && /^data:image\\/[a-z0-9.+-]+[;,]/i.test(text)) return text;\n return readHttpUrl(value);\n};\n\n/** `{\"name\",\"url\"}`; a source with only a URL is named by its host. */\nexport const readMediaSource = (value: unknown): MediaSource | undefined => {\n if (!isRecord(value)) return undefined;\n const url = readHttpUrl(value.url);\n const name = readText(value.name) ?? (url ? new URL(url).hostname.replace(/^www\\./, \"\") : undefined);\n if (!name) return undefined;\n return url ? { name, url } : { name };\n};\n\n/** One picture from a record carrying `src` and `alt` (an `Image` node's props or one entry of an `ImageGroup`). */\nexport const readMediaImage = (value: unknown): MediaImage | undefined => {\n if (!isRecord(value)) return undefined;\n const src = readImageUrl(value.src);\n const alt = readText(value.alt);\n if (!src || !alt) return undefined;\n const title = readText(value.title);\n const caption = readText(value.caption);\n const source = readMediaSource(value.source);\n return {\n src,\n alt,\n ...(title ? { title } : {}),\n ...(caption ? { caption } : {}),\n ...(source ? { source } : {}),\n };\n};\n\n/** The pictures of a list prop, at most `maxImages` (the schema's `maxRepeatRows`). Not a list = no pictures. */\nexport const readMediaImageList = (value: unknown, maxImages: number): MediaImageList => {\n const entries = Array.isArray(value) ? value : [];\n const usableImages = entries.map(readMediaImage).filter((image): image is MediaImage => image !== undefined);\n const images = usableImages.slice(0, maxImages);\n return {\n images,\n droppedCount: entries.length - usableImages.length,\n cappedCount: usableImages.length - images.length,\n };\n};\n\n/** The frames of the node schema (`ImageComposedViewNode::ASPECT_RATIOS`); each has its class in `MediaImageTile.module.scss`. */\nexport const MEDIA_ASPECT_RATIOS = [\"1:1\", \"4:3\", \"3:2\", \"5:4\", \"16:9\", \"3:4\"] as const;\n\nexport type MediaAspectRatio = (typeof MEDIA_ASPECT_RATIOS)[number];\n\n/** The frame a prop names, or `fallbackAspectRatio` when it names none of the schema's frames. */\nexport const readAspectRatio = (value: unknown, fallbackAspectRatio: MediaAspectRatio): MediaAspectRatio =>\n MEDIA_ASPECT_RATIOS.find((aspectRatio) => aspectRatio === value) ?? fallbackAspectRatio;\n\n/** How a picture fills its frame: `cover` crops a photo, `contain` shows a logo whole. */\nexport type MediaImageFit = \"cover\" | \"contain\";\n\nexport const readImageFit = (value: unknown): MediaImageFit => (value === \"contain\" ? \"contain\" : \"cover\");\n\n/** A positive whole number prop (`maxVisible`), or the fallback. */\nexport const readPositiveCount = (value: unknown, fallbackCount: number): number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallbackCount;\n\n/**\n * Opens the app's image lightbox over `images`, starting at `startIndex` — the same lightbox the chat's image and logo\n * galleries open. Every entry carries its position as its id.\n */\nexport const openMediaImagesLightbox = (images: MediaImage[], startIndex: number): void => {\n if (images.length === 0) return;\n const gallery = images.map((image, imageIndex) => ({\n id: `composed-view-image-${imageIndex}`,\n url: image.src,\n name: image.title ?? image.alt,\n }));\n openImageGallery(gallery, Math.min(Math.max(startIndex, 0), gallery.length - 1));\n};\n\n/** `1418` → `23:38`, `3725` → `1:02:05`; no length for a missing, negative or non-finite value. */\nexport const formatVideoDuration = (durationSeconds: unknown): string | undefined => {\n if (typeof durationSeconds !== \"number\" || !Number.isFinite(durationSeconds) || durationSeconds < 0) return undefined;\n const wholeSeconds = Math.floor(durationSeconds);\n const hours = Math.floor(wholeSeconds / 3600);\n const minutes = Math.floor((wholeSeconds % 3600) / 60);\n const paddedSeconds = String(wholeSeconds % 60).padStart(2, \"0\");\n return hours > 0 ? `${hours}:${String(minutes).padStart(2, \"0\")}:${paddedSeconds}` : `${minutes}:${paddedSeconds}`;\n};\n\n/**\n * A video id of the video connector (YouTube): letters, digits, `-` and `_` only — so it goes into the embed,\n * watch and thumbnail URLs without escaping.\n */\nexport const readVideoId = (value: unknown): string | undefined => {\n const text = readText(value);\n return text && /^[A-Za-z0-9_-]{6,32}$/.test(text) ? text : undefined;\n};\n\nconst YOUTUBE_WATCH_HOSTS = [\"youtube.com\", \"www.youtube.com\", \"m.youtube.com\", \"music.youtube.com\"];\n\n/**\n * The video id of a YouTube link the model wrote as `url` (`youtube.com/watch?v=…`, `youtu.be/…`, `/shorts/…`,\n * `/embed/…`), so such a video plays in place like a connector video; any other link is `undefined`.\n */\nexport const readYouTubeVideoIdFromUrl = (url: string | undefined): string | undefined => {\n if (!url) return undefined;\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch {\n return undefined;\n }\n const host = parsedUrl.hostname.toLowerCase();\n if (host === \"youtu.be\") return readVideoId(parsedUrl.pathname.split(\"/\")[1]);\n if (!YOUTUBE_WATCH_HOSTS.includes(host)) return undefined;\n if (parsedUrl.pathname === \"/watch\") return readVideoId(parsedUrl.searchParams.get(\"v\"));\n const pathMatch = parsedUrl.pathname.match(/^\\/(?:shorts|embed|live)\\/([^/]+)/);\n return pathMatch ? readVideoId(pathMatch[1]) : undefined;\n};\n\n/** The privacy-enhanced embed of a connector video; it autoplays, because the owner pressed play to load it. */\nexport const buildVideoEmbedUrl = (videoId: string): string =>\n `https://www.youtube-nocookie.com/embed/${videoId}?autoplay=1&rel=0`;\n\nexport const buildVideoWatchUrl = (videoId: string): string => `https://www.youtube.com/watch?v=${videoId}`;\n\nexport const buildVideoThumbnailUrl = (videoId: string): string => `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`;\n","import { Skeleton } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { MediaCaption } from \"./MediaCaption\";\nimport { MediaImageTile } from \"./MediaImageTile\";\nimport { openMediaImagesLightbox, readAspectRatio, readImageFit, readMediaImage } from \"./media-values\";\nimport styles from \"./Image.module.scss\";\n\n/**\n * The `Image` node (`ImageComposedViewNode.php`): one picture with its\n * title and caption under it and its source as a chip over it, lazily loaded, opening the component library's lightbox on click. In\n * a compact slot (a table cell) it is a 4:3 thumbnail without text. A picture whose `src` is no http(s) or data:image\n * address reports `failed` and renders nothing; a picture that does not load shows its alt text and reports `failed`.\n */\nconst ImageNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const image = useMemo(() => readMediaImage(nodeProps), [nodeProps]);\n const aspectRatio = readAspectRatio(nodeProps.aspectRatio, \"4:3\");\n const isCompact = sizeClass === \"compact\";\n const [hasLoadFailed, setHasLoadFailed] = useState(false);\n const { reportNodeStatus } = runtime;\n\n useEffect(() => {\n setHasLoadFailed(false);\n }, [image?.src]);\n\n useEffect(() => {\n if (isPending) return;\n if (!image) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the Image has no http(s) or data:image src, or no alt text\");\n return;\n }\n if (hasLoadFailed) {\n reportNodeStatus(\"failed\", \"RENDER_FAILED\", `the picture \"${image.alt}\" did not load`);\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, image, hasLoadFailed, reportNodeStatus]);\n\n if (isPending) {\n return (\n <span\n className={classNames(styles.pendingFrame, isCompact && styles.pendingFrameCompact)}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n <Skeleton className={styles.pendingSkeleton} />\n </span>\n );\n }\n if (!image) return null;\n const openLightbox = runtime.isEmailRender ? undefined : () => openMediaImagesLightbox([image], 0);\n return (\n <figure className={classNames(styles.image, isCompact && styles.imageCompact)} data-testid={testId}>\n <MediaImageTile\n testId={`${testId}-tile`}\n image={image}\n aspectRatio={isCompact ? \"4:3\" : aspectRatio}\n fit={readImageFit(nodeProps.fit)}\n isEager={runtime.isEmailRender}\n isCompact={isCompact}\n onOpen={openLightbox}\n onLoadFailed={() => setHasLoadFailed(true)}\n />\n {isCompact ? null : <MediaCaption title={image.title} caption={image.caption} />}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Image\", component: ImageNode };\n","import { Icon, InteractiveSurface, Skeleton, Text, type AgentsIconName } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { KeyboardEvent, useEffect, useMemo, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { MediaCaption } from \"./MediaCaption\";\nimport { MediaImageTile } from \"./MediaImageTile\";\nimport {\n MediaAspectRatio,\n MediaImage,\n openMediaImagesLightbox,\n readAspectRatio,\n readMediaImageList,\n readPositiveCount,\n} from \"./media-values\";\nimport styles from \"./ImageGroup.module.scss\";\n\n/** Tiles a grid shows before its last tile counts the hidden rest (`maxVisible`); a compact strip shows three. */\nconst DEFAULT_MAX_VISIBLE_TILES = 4;\nconst COMPACT_MAX_VISIBLE_TILES = 3;\n/** Skeleton tiles while the bound pictures are pending. */\nconst PENDING_TILE_COUNT = 4;\n\ntype ImageGroupLayout = \"grid\" | \"carousel\" | \"magazine\";\n\nconst readImageGroupLayout = (value: unknown): ImageGroupLayout =>\n value === \"carousel\" || value === \"magazine\" ? value : \"grid\";\n\ninterface ImageGroupLayoutProps {\n images: MediaImage[];\n aspectRatio: MediaAspectRatio;\n isEmailRender: boolean;\n onImageLoadFailed: (imageIndex: number) => void;\n testId: string;\n}\n\nconst buildOpenImageHandler = (images: MediaImage[], imageIndex: number, isEmailRender: boolean) =>\n isEmailRender ? undefined : () => openMediaImagesLightbox(images, imageIndex);\n\n/** The grid (ChatGPT 44): up to `maxVisible` tiles, the last one counting the hidden rest; every tile opens the lightbox. */\nconst ImageGroupGrid = (props: ImageGroupLayoutProps & { maxVisibleTiles: number; isCompact: boolean }) => {\n const { images, aspectRatio, isEmailRender, onImageLoadFailed, maxVisibleTiles, isCompact, testId } = props;\n const visibleImages = images.slice(0, maxVisibleTiles);\n const hiddenImageCount = images.length - visibleImages.length;\n return (\n <div className={classNames(styles.grid, isCompact && styles.gridCompact)} data-testid={testId}>\n {visibleImages.map((image, imageIndex) => (\n <figure key={`${imageIndex}:${image.src}`} className={styles.tile}>\n <MediaImageTile\n testId={`${testId}-tile-${imageIndex}`}\n image={image}\n aspectRatio={aspectRatio}\n isEager={isEmailRender}\n isCompact={isCompact}\n hiddenImageCount={imageIndex === visibleImages.length - 1 ? hiddenImageCount : 0}\n onOpen={buildOpenImageHandler(images, imageIndex, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(imageIndex)}\n />\n {isCompact ? null : <MediaCaption title={image.title} caption={image.caption} />}\n </figure>\n ))}\n </div>\n );\n};\n\n/** The magazine (ChatGPT 15): the first picture as a 16:9 hero, the others as tiles under it, each with its text. */\nconst ImageGroupMagazine = (props: ImageGroupLayoutProps & { heroAspectRatio: MediaAspectRatio }) => {\n const { images, aspectRatio, heroAspectRatio, isEmailRender, onImageLoadFailed, testId } = props;\n const [heroImage, ...tileImages] = images;\n return (\n <div className={styles.magazine} data-testid={testId}>\n <figure className={styles.tile}>\n <MediaImageTile\n testId={`${testId}-tile-0`}\n image={heroImage}\n aspectRatio={heroAspectRatio}\n isEager={isEmailRender}\n onOpen={buildOpenImageHandler(images, 0, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(0)}\n />\n <MediaCaption title={heroImage.title} caption={heroImage.caption} />\n </figure>\n {tileImages.length > 0 ? (\n <div className={styles.grid}>\n {tileImages.map((image, tileIndex) => (\n <figure key={`${tileIndex}:${image.src}`} className={styles.tile}>\n <MediaImageTile\n testId={`${testId}-tile-${tileIndex + 1}`}\n image={image}\n aspectRatio={aspectRatio}\n isEager={isEmailRender}\n onOpen={buildOpenImageHandler(images, tileIndex + 1, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(tileIndex + 1)}\n />\n <MediaCaption title={image.title} caption={image.caption} />\n </figure>\n ))}\n </div>\n ) : null}\n </div>\n );\n};\n\ninterface CarouselStepButtonProps {\n label: string;\n icon: AgentsIconName;\n className: string;\n isDisabled: boolean;\n onStep: () => void;\n testId: string;\n}\n\n/** Previous / next of the carousel: a round dark control over the picture, the hover layer from GlobalStateComponent. */\nconst CarouselStepButton = (props: CarouselStepButtonProps) => {\n const { label, icon, className, isDisabled, onStep, testId } = props;\n return (\n <InteractiveSurface\n hoverable={!isDisabled}\n className={classNames(styles.carouselButton, className, isDisabled && styles.carouselButtonDisabled)}\n >\n <button\n type=\"button\"\n className={styles.carouselButtonTarget}\n aria-label={label}\n data-testid={testId}\n disabled={isDisabled}\n onClick={onStep}\n >\n <Icon color=\"var(--agents-fg-on-dark)\" name={icon} />\n </button>\n </InteractiveSurface>\n );\n};\n\n/**\n * The carousel (ChatGPT 09): one large picture at a time with its text, previous / next over its sides, the position\n * as \"2 / 5\" and the arrow keys. The e-mail capture shows the first picture without the controls.\n */\nconst ImageGroupCarousel = (props: ImageGroupLayoutProps) => {\n const { images, aspectRatio, isEmailRender, onImageLoadFailed, testId } = props;\n const [shownImageIndex, setShownImageIndex] = useState(0);\n const lastImageIndex = images.length - 1;\n const currentImageIndex = Math.min(shownImageIndex, lastImageIndex);\n const currentImage = images[currentImageIndex];\n const hasControls = !isEmailRender && images.length > 1;\n const showImage = (imageIndex: number) => setShownImageIndex(Math.min(Math.max(imageIndex, 0), lastImageIndex));\n const showImageForKey = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"ArrowLeft\") showImage(currentImageIndex - 1);\n if (event.key === \"ArrowRight\") showImage(currentImageIndex + 1);\n };\n return (\n <div\n className={styles.carousel}\n data-testid={testId}\n role=\"group\"\n aria-roledescription=\"carousel\"\n tabIndex={hasControls ? 0 : undefined}\n onKeyDown={hasControls ? showImageForKey : undefined}\n >\n <div className={styles.carouselStage}>\n <MediaImageTile\n key={`${currentImageIndex}:${currentImage.src}`}\n testId={`${testId}-tile-${currentImageIndex}`}\n image={currentImage}\n aspectRatio={aspectRatio}\n isEager\n onOpen={buildOpenImageHandler(images, currentImageIndex, isEmailRender)}\n onLoadFailed={() => onImageLoadFailed(currentImageIndex)}\n />\n {hasControls ? (\n <>\n <CarouselStepButton\n label={translateText(\"Previous picture\")}\n icon=\"arrowLeft\"\n className={styles.carouselButtonPrevious}\n isDisabled={currentImageIndex === 0}\n onStep={() => showImage(currentImageIndex - 1)}\n testId={`${testId}-previous`}\n />\n <CarouselStepButton\n label={translateText(\"Next picture\")}\n icon=\"arrowRight\"\n className={styles.carouselButtonNext}\n isDisabled={currentImageIndex === lastImageIndex}\n onStep={() => showImage(currentImageIndex + 1)}\n testId={`${testId}-next`}\n />\n <span className={styles.carouselPosition} aria-live=\"polite\" data-testid={`${testId}-position`}>\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {`${currentImageIndex + 1} / ${images.length}`}\n </Text>\n </span>\n </>\n ) : null}\n </div>\n <MediaCaption title={currentImage.title} caption={currentImage.caption} />\n </div>\n );\n};\n\n/**\n * The `ImageGroup` node (`ImageGroupComposedViewNode.php`): a gallery as a grid, a carousel or a\n * magazine; every picture opens the component library's lightbox over the whole gallery at its place. The pictures are capped at the\n * schema's `maxRepeatRows`; an entry without an http(s) / data:image `src` or an `alt` is dropped. It reports `failed`\n * for dropped, capped or unloadable pictures (the rest still shows), `empty` for a gallery with no picture (one muted\n * line), and nothing while its bound pictures are pending (the renderer reports the pending dataset; skeleton tiles).\n */\nconst ImageGroupNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n const { images, droppedCount, cappedCount } = useMemo(\n () => readMediaImageList(nodeProps.images, maxRepeatRows),\n [nodeProps.images, maxRepeatRows],\n );\n const layout = readImageGroupLayout(nodeProps.layout);\n const isCompact = sizeClass === \"compact\";\n const [failedImageIndexes, setFailedImageIndexes] = useState<number[]>([]);\n const { reportNodeStatus } = runtime;\n const imageSourcesKey = images.map((image) => image.src).join(\"\\n\");\n\n useEffect(() => {\n setFailedImageIndexes([]);\n }, [imageSourcesKey]);\n\n useEffect(() => {\n if (isPending) return;\n if (droppedCount > 0) {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n `${droppedCount} of ${droppedCount + images.length + cappedCount} pictures dropped: each needs an http(s) or data:image src and an alt text`,\n );\n return;\n }\n if (cappedCount > 0) {\n reportNodeStatus(\"failed\", \"BUDGET_EXCEEDED\", `ImageGroup shows the first ${maxRepeatRows} pictures only`);\n return;\n }\n if (images.length === 0) {\n reportNodeStatus(\"empty\", \"NO_DATA\", \"the ImageGroup has no pictures\");\n return;\n }\n if (failedImageIndexes.length > 0) {\n reportNodeStatus(\n \"failed\",\n \"RENDER_FAILED\",\n `${failedImageIndexes.length} of ${images.length} pictures did not load`,\n );\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, droppedCount, cappedCount, images.length, failedImageIndexes.length, maxRepeatRows, reportNodeStatus]);\n\n const markImageLoadFailed = (imageIndex: number) =>\n setFailedImageIndexes((currentIndexes) =>\n currentIndexes.includes(imageIndex) ? currentIndexes : [...currentIndexes, imageIndex],\n );\n\n if (isPending) {\n return (\n <div\n className={classNames(styles.grid, isCompact && styles.gridCompact)}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n {Array.from({ length: isCompact ? COMPACT_MAX_VISIBLE_TILES : PENDING_TILE_COUNT }, (unused, tileIndex) => (\n <span key={tileIndex} className={classNames(styles.pendingTile, isCompact && styles.pendingTileCompact)}>\n <Skeleton className={styles.pendingSkeleton} />\n </span>\n ))}\n </div>\n );\n }\n if (images.length === 0) {\n return (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={`${testId}-empty`}>\n {\"No pictures to show.\"}\n </Text>\n );\n }\n const layoutProps: ImageGroupLayoutProps = {\n images,\n aspectRatio: readAspectRatio(nodeProps.aspectRatio, layout === \"magazine\" ? \"1:1\" : \"4:3\"),\n isEmailRender: runtime.isEmailRender,\n onImageLoadFailed: markImageLoadFailed,\n testId,\n };\n // A compact slot has no room for a carousel or a hero: every layout becomes the thumbnail strip there.\n if (isCompact) {\n return <ImageGroupGrid {...layoutProps} aspectRatio=\"4:3\" maxVisibleTiles={COMPACT_MAX_VISIBLE_TILES} isCompact />;\n }\n if (layout === \"carousel\") {\n return <ImageGroupCarousel {...layoutProps} aspectRatio={readAspectRatio(nodeProps.aspectRatio, \"16:9\")} />;\n }\n if (layout === \"magazine\") {\n return <ImageGroupMagazine {...layoutProps} heroAspectRatio=\"16:9\" />;\n }\n return (\n <ImageGroupGrid\n {...layoutProps}\n maxVisibleTiles={readPositiveCount(nodeProps.maxVisible, DEFAULT_MAX_VISIBLE_TILES)}\n isCompact={false}\n />\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"ImageGroup\",\n component: ImageGroupNode,\n};\n","import { Icon, InteractiveSurface, Skeleton, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { translateText } from \"../../../provider/environment\";\nimport { ModelText } from \"../../ModelText/ModelText\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n buildVideoEmbedUrl,\n buildVideoThumbnailUrl,\n buildVideoWatchUrl,\n formatVideoDuration,\n readHttpUrl,\n readImageUrl,\n readMediaSource,\n readVideoId,\n readYouTubeVideoIdFromUrl,\n} from \"./media-values\";\nimport styles from \"./Video.module.scss\";\nimport { useImageLoadState } from \"./use-image-load-state\";\n\nconst readTitle = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\n/**\n * The `Video` node (`VideoComposedViewNode.php`): one video\n * as a card — the 16:9 thumbnail with its length, the title, the channel and the source, and \"Open video\" to the watch\n * page. A connector video (`videoId`) plays in place: the play button swaps the thumbnail for the\n * privacy-enhanced embed, and so does a YouTube watch link written as `url`; any other `url` opens in a new tab. Without a thumbnail a connector video takes its id's\n * thumbnail; a thumbnail that fails falls back to the play glyph on the empty frame. The e-mail capture shows the card\n * without play button and link. A video with neither a `videoId` nor an http(s) `url` reports `failed` and shows its\n * text only.\n */\nconst VideoNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const title = readTitle(nodeProps.title);\n const url = readHttpUrl(nodeProps.url);\n const videoId = readVideoId(nodeProps.videoId) ?? readYouTubeVideoIdFromUrl(url);\n const watchUrl = url ?? (videoId ? buildVideoWatchUrl(videoId) : undefined);\n const thumbnailUrl = readImageUrl(nodeProps.thumbnail) ?? (videoId ? buildVideoThumbnailUrl(videoId) : undefined);\n const duration = formatVideoDuration(nodeProps.durationSeconds);\n const channel = readTitle(nodeProps.channel);\n const source = useMemo(() => readMediaSource(nodeProps.source), [nodeProps.source]);\n const isCompact = sizeClass === \"compact\";\n const [isPlaying, setIsPlaying] = useState(false);\n const {\n loadState: thumbnailLoadState,\n imageRef: thumbnailRef,\n markLoaded: markThumbnailLoaded,\n markFailed: markThumbnailFailed,\n } = useImageLoadState(thumbnailUrl);\n\n useEffect(() => {\n if (isPending) return;\n if (!title) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the Video has no title\");\n return;\n }\n if (!watchUrl) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `the video \"${title}\" has neither a videoId nor an http(s) url`);\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, title, watchUrl, reportNodeStatus]);\n\n if (isPending) {\n return (\n <span\n className={classNames(styles.video, isCompact && styles.videoCompact)}\n aria-busy=\"true\"\n data-testid={`${testId}-skeleton`}\n >\n <span className={styles.frame}>\n <Skeleton className={styles.frameSkeleton} />\n </span>\n </span>\n );\n }\n if (!title) return null;\n\n const canPlayInPlace = videoId !== undefined && !isEmailRender && !isCompact;\n const canOpen = watchUrl !== undefined && !isEmailRender;\n const showThumbnail = thumbnailUrl !== undefined && thumbnailLoadState !== \"failed\";\n const playVideo = () => {\n if (canPlayInPlace) {\n setIsPlaying(true);\n return;\n }\n if (watchUrl) window.open(watchUrl, \"_blank\", \"noopener,noreferrer\");\n };\n const metaLine = [channel, duration].filter((metaPart): metaPart is string => metaPart !== undefined).join(\" · \");\n const sourceName = source && source.name !== channel ? source.name : undefined;\n\n const frame =\n isPlaying && videoId ? (\n <span className={styles.frame}>\n <iframe\n className={styles.player}\n data-testid={`${testId}-player`}\n src={buildVideoEmbedUrl(videoId)}\n title={title}\n allow=\"autoplay; encrypted-media; picture-in-picture; fullscreen\"\n allowFullScreen\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n </span>\n ) : (\n <InteractiveSurface hoverable={canOpen} className={styles.frame}>\n {showThumbnail ? (\n <img\n ref={thumbnailRef}\n className={styles.thumbnail}\n src={thumbnailUrl}\n alt=\"\"\n loading={isEmailRender ? \"eager\" : \"lazy\"}\n decoding=\"async\"\n onLoad={markThumbnailLoaded}\n onError={markThumbnailFailed}\n />\n ) : null}\n {showThumbnail && thumbnailLoadState === \"loading\" ? <Skeleton className={styles.frameSkeleton} /> : null}\n <span className={classNames(styles.playBadge, isCompact && styles.playBadgeCompact)} aria-hidden=\"true\">\n <Icon color=\"var(--agents-fg-on-dark)\" name=\"play\" />\n </span>\n {duration ? (\n <span className={styles.durationChip}>\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {duration}\n </Text>\n </span>\n ) : null}\n {canOpen ? (\n <button\n type=\"button\"\n className={styles.playButton}\n data-testid={`${testId}-play`}\n aria-label={translateText(\"Play the video %title%\", { title })}\n onClick={playVideo}\n />\n ) : null}\n </InteractiveSurface>\n );\n\n if (isCompact) {\n return (\n <span className={classNames(styles.video, styles.videoCompact)} data-testid={testId}>\n {frame}\n <ModelText role=\"caption\" ellipsis>\n {title}\n </ModelText>\n </span>\n );\n }\n return (\n <figure className={styles.video} data-testid={testId}>\n {frame}\n <span className={styles.text}>\n <ModelText role=\"body\" weight=\"bold\" className={styles.wrap}>\n {title}\n </ModelText>\n {metaLine ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-light)\">\n {metaLine}\n </ModelText>\n ) : null}\n {sourceName ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-lightest)\">\n {sourceName}\n </ModelText>\n ) : null}\n </span>\n {canOpen && watchUrl ? (\n <a\n className={styles.openLink}\n href={watchUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n data-testid={`${testId}-open-link`}\n >\n <Text role=\"help\" weight=\"medium\" color=\"var(--agents-fg-cta)\">\n {\"Open video\"}\n </Text>\n <Icon color=\"var(--agents-fg-cta)\" name=\"arrowRight\" />\n </a>\n ) : null}\n </figure>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Video\", component: VideoNode };\n","/**\n * The values the `VideoCard` node reads from its resolved props, each reader total: a value that\n * does not fit is `undefined`, never a throw.\n */\n\n/** A view count: a finite whole number of zero or more. */\nexport const readViewCount = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined;\n\n/** A view count in the locale's compact notation: `18234` → `18K` (en), `18.234` (de), `1.2M` (en). */\nexport const formatViewCount = (viewCount: number, locale: string): string =>\n new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }).format(viewCount);\n\nconst PUBLISHED_DAY = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** A `Y-m-d` publish day in the locale's short form (`Feb 8, 2025`, `8. Feb. 2025`); anything else is `undefined`. */\nexport const formatPublishedDay = (value: unknown, locale: string): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n const dayParts = PUBLISHED_DAY.exec(value.trim());\n if (!dayParts) return undefined;\n const monthIndex = Number(dayParts[2]) - 1;\n const publishedDay = new Date(Number(dayParts[1]), monthIndex, Number(dayParts[3]));\n if (Number.isNaN(publishedDay.getTime()) || publishedDay.getMonth() !== monthIndex) return undefined;\n return new Intl.DateTimeFormat(locale, { day: \"numeric\", month: \"short\", year: \"numeric\" }).format(publishedDay);\n};\n","import { Icon, InteractiveSurface, Skeleton, Text } from \"../../../../provider/components\";\nimport { classNames } from \"../../../../provider/class-names\";\nimport { useEffect, useState } from \"react\";\nimport { translateText } from \"../../../../provider/environment\";\nimport { ModelText } from \"../../../ModelText/ModelText\";\nimport type {\n ComposedViewComponentDefinition,\n ComposedViewComponentProps,\n} from \"../../../composed-view-component-types\";\nimport {\n buildVideoEmbedUrl,\n buildVideoThumbnailUrl,\n buildVideoWatchUrl,\n formatVideoDuration,\n readImageUrl,\n readVideoId,\n} from \"../media-values\";\nimport { useNumberLocale } from \"../../data/use-number-locale\";\nimport { useLayoutNesting } from \"../../layout/layout-nesting-context\";\nimport { formatPublishedDay, formatViewCount, readViewCount } from \"./video-card-values\";\nimport styles from \"./VideoCard.module.scss\";\nimport { useImageLoadState } from \"../use-image-load-state\";\n\nconst readTitle = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\n/**\n * The `VideoCard` node (backend `VideoCardComposedViewNode.php`): one YouTube\n * search result as a card — the 16:9 thumbnail with the length on a dark chip and the play glyph, the title, and\n * \"channel · views · date\" under it. Play swaps the thumbnail for the privacy-enhanced embed in place; \"Open on YouTube\"\n * opens the watch page in a new tab. A thumbnail that does not load leaves the play glyph on the empty frame. The\n * e-mail capture shows the card without play button and link. Without a title or a valid videoId the node reports\n * `failed` and shows its title only.\n */\nconst VideoCardNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const { isInsideSurface, isInsidePressable } = useLayoutNesting();\n const numberLocale = useNumberLocale();\n const title = readTitle(nodeProps.title);\n const videoId = readVideoId(nodeProps.videoId);\n const thumbnailUrl = readImageUrl(nodeProps.thumbnail) ?? (videoId ? buildVideoThumbnailUrl(videoId) : undefined);\n const duration = formatVideoDuration(nodeProps.durationSeconds);\n const channel = readTitle(nodeProps.channel);\n const viewCount = readViewCount(nodeProps.viewCount);\n const publishedDay = formatPublishedDay(nodeProps.publishedAt, numberLocale);\n const isCompact = sizeClass === \"compact\";\n const [isPlaying, setIsPlaying] = useState(false);\n const {\n loadState: thumbnailLoadState,\n imageRef: thumbnailRef,\n markLoaded: markThumbnailLoaded,\n markFailed: markThumbnailFailed,\n } = useImageLoadState(thumbnailUrl);\n\n useEffect(() => {\n if (isPending) return;\n if (!title) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the VideoCard has no title\");\n return;\n }\n if (!videoId) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `the VideoCard \"${title}\" has no valid YouTube videoId`);\n return;\n }\n reportNodeStatus(\"mounted\");\n }, [isPending, title, videoId, reportNodeStatus]);\n\n const cardClassName = classNames(\n styles.card,\n isInsideSurface ? styles.cardFlat : styles.cardElevated,\n isCompact && styles.cardCompact,\n );\n\n if (isPending) {\n return (\n <span className={cardClassName} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <span className={styles.frame}>\n <Skeleton className={styles.frameSkeleton} />\n </span>\n <span className={styles.text}>\n <Skeleton className={styles.titleSkeleton} />\n <Skeleton className={styles.metaSkeleton} />\n </span>\n </span>\n );\n }\n if (!title) return null;\n if (!videoId) {\n return (\n <span className={cardClassName} data-testid={testId}>\n <ModelText role=\"body\" weight=\"bold\" className={styles.wrap}>\n {title}\n </ModelText>\n </span>\n );\n }\n\n const watchUrl = videoId ? buildVideoWatchUrl(videoId) : undefined;\n const hasControls = videoId !== undefined && !isEmailRender && !isInsidePressable;\n const canPlayInPlace = hasControls && !isCompact;\n const showThumbnail = thumbnailUrl !== undefined && thumbnailLoadState !== \"failed\";\n const playVideo = () => {\n if (canPlayInPlace) {\n setIsPlaying(true);\n return;\n }\n if (watchUrl) window.open(watchUrl, \"_blank\", \"noopener,noreferrer\");\n };\n\n const frame =\n isPlaying && videoId ? (\n <span className={styles.frame}>\n <iframe\n className={styles.player}\n data-testid={`${testId}-player`}\n src={buildVideoEmbedUrl(videoId)}\n title={title}\n allow=\"autoplay; encrypted-media; picture-in-picture; fullscreen\"\n allowFullScreen\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n </span>\n ) : (\n <InteractiveSurface hoverable={hasControls} className={styles.frame}>\n {showThumbnail ? (\n <img\n ref={thumbnailRef}\n className={styles.thumbnail}\n src={thumbnailUrl}\n alt=\"\"\n loading={isEmailRender ? \"eager\" : \"lazy\"}\n decoding=\"async\"\n onLoad={markThumbnailLoaded}\n onError={markThumbnailFailed}\n />\n ) : null}\n {showThumbnail && thumbnailLoadState === \"loading\" ? <Skeleton className={styles.frameSkeleton} /> : null}\n <span className={classNames(styles.playBadge, isCompact && styles.playBadgeCompact)} aria-hidden=\"true\">\n <Icon color=\"var(--agents-fg-on-dark)\" name=\"play\" />\n </span>\n {duration ? (\n <span className={styles.durationChip}>\n <Text role=\"caption\" color=\"var(--agents-fg-on-dark)\" translate={false}>\n {duration}\n </Text>\n </span>\n ) : null}\n {hasControls ? (\n <button\n type=\"button\"\n className={styles.playButton}\n data-testid={`${testId}-play`}\n aria-label={translateText(\"Play the video %title%\", { title })}\n onClick={playVideo}\n />\n ) : null}\n </InteractiveSurface>\n );\n\n if (isCompact) {\n return (\n <span className={cardClassName} data-testid={testId}>\n {frame}\n <ModelText role=\"caption\" weight=\"medium\" className={styles.compactTitle}>\n {title}\n </ModelText>\n </span>\n );\n }\n\n // YouTube's own card layout: the channel on its line, \"views · date\" under it — a wrapped line never starts with a dot.\n const statisticPhrases = [\n viewCount !== undefined ? (\n <Text\n key=\"views\"\n role=\"caption\"\n color=\"var(--agents-fg-light)\"\n replacements={{ count: formatViewCount(viewCount, numberLocale) }}\n context={viewCount === 1 ? \"one\" : \"other\"}\n >\n {\"%count% view\"}\n </Text>\n ) : null,\n publishedDay ? (\n <Text key=\"published\" role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {publishedDay}\n </Text>\n ) : null,\n ].filter((statisticPhrase) => statisticPhrase !== null);\n\n return (\n <article className={cardClassName} data-testid={testId}>\n {frame}\n <span className={styles.text}>\n <span className={styles.title} title={title}>\n <ModelText role=\"body\" weight=\"bold\" className={styles.titleText}>\n {title}\n </ModelText>\n </span>\n {channel ? (\n <ModelText role=\"caption\" color=\"var(--agents-fg-light)\" className={styles.wrap}>\n {channel}\n </ModelText>\n ) : null}\n {statisticPhrases.length > 0 ? (\n <span className={styles.metaLine}>\n {statisticPhrases.map((statisticPhrase, phraseIndex) => (\n <span key={phraseIndex} className={styles.metaPhrase}>\n {phraseIndex > 0 ? (\n <Text role=\"caption\" color=\"var(--agents-fg-lightest)\" translate={false}>\n {\"·\"}\n </Text>\n ) : null}\n {statisticPhrase}\n </span>\n ))}\n </span>\n ) : null}\n </span>\n {hasControls && watchUrl ? (\n <a\n className={styles.openLink}\n href={watchUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n data-testid={`${testId}-open-link`}\n >\n <Text role=\"help\" weight=\"medium\" color=\"var(--agents-fg-cta)\">\n {\"Open on YouTube\"}\n </Text>\n <Icon color=\"var(--agents-fg-cta)\" name=\"arrowRight\" />\n </a>\n ) : null}\n </article>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"VideoCard\",\n component: VideoCardNode,\n};\n","import type { HLJSApi, LanguageFn } from \"highlight.js\";\nimport type KatexModule from \"katex\";\nimport type { Mermaid } from \"mermaid\";\nimport type { DOMPurify } from \"dompurify\";\n\n/**\n * The renderer libraries of the rich kit components, each behind a dynamic `import()`: the kit's\n * component files are imported eagerly by the folder registry, so a static import here would put KaTeX, highlight.js,\n * Mermaid and DOMPurify into the chat bundle. Each library loads once per page, on the first node that needs it, as\n * its own chunk; a failed load is forgotten so the next node retries.\n */\n\ntype Katex = typeof KatexModule;\n\nlet katexPromise: Promise<Katex> | undefined;\nlet highlighterPromise: Promise<HLJSApi> | undefined;\nlet mermaidPromise: Promise<Mermaid> | undefined;\nlet domPurifyPromise: Promise<DOMPurify> | undefined;\nconst highlightLanguagePromises: Record<string, Promise<boolean>> = {};\n\n/** KaTeX with its stylesheet (the stylesheet loads the fonts it needs on demand). */\nexport const loadKatex = (): Promise<Katex> => {\n katexPromise ??= Promise.all([import(\"katex\"), import(\"katex/dist/katex.min.css\")])\n .then(([katexModule]) => katexModule.default)\n .catch((error: unknown) => {\n katexPromise = undefined;\n throw error;\n });\n return katexPromise;\n};\n\n/** Mermaid (its diagram-type chunks load inside it, per diagram type). */\nexport const loadMermaid = (): Promise<Mermaid> => {\n mermaidPromise ??= import(\"mermaid\")\n .then((mermaidModule) => mermaidModule.default)\n .catch((error: unknown) => {\n mermaidPromise = undefined;\n throw error;\n });\n return mermaidPromise;\n};\n\n/** DOMPurify as a factory: each caller builds its own instance, so hooks never leak from one caller to another. */\nexport const loadDomPurify = (): Promise<DOMPurify> => {\n domPurifyPromise ??= import(\"dompurify\")\n .then((domPurifyModule) => domPurifyModule.default)\n .catch((error: unknown) => {\n domPurifyPromise = undefined;\n throw error;\n });\n return domPurifyPromise;\n};\n\n/**\n * The highlight.js grammars the `Code` node can load, by grammar name. A closed list of static imports: each grammar\n * is its own chunk, and no name outside the list can be requested.\n */\nconst HIGHLIGHT_LANGUAGE_LOADERS: Record<string, () => Promise<{ default: LanguageFn }>> = {\n bash: () => import(\"highlight.js/lib/languages/bash\"),\n c: () => import(\"highlight.js/lib/languages/c\"),\n cpp: () => import(\"highlight.js/lib/languages/cpp\"),\n csharp: () => import(\"highlight.js/lib/languages/csharp\"),\n css: () => import(\"highlight.js/lib/languages/css\"),\n diff: () => import(\"highlight.js/lib/languages/diff\"),\n dockerfile: () => import(\"highlight.js/lib/languages/dockerfile\"),\n go: () => import(\"highlight.js/lib/languages/go\"),\n graphql: () => import(\"highlight.js/lib/languages/graphql\"),\n ini: () => import(\"highlight.js/lib/languages/ini\"),\n java: () => import(\"highlight.js/lib/languages/java\"),\n javascript: () => import(\"highlight.js/lib/languages/javascript\"),\n json: () => import(\"highlight.js/lib/languages/json\"),\n kotlin: () => import(\"highlight.js/lib/languages/kotlin\"),\n markdown: () => import(\"highlight.js/lib/languages/markdown\"),\n php: () => import(\"highlight.js/lib/languages/php\"),\n plaintext: () => import(\"highlight.js/lib/languages/plaintext\"),\n python: () => import(\"highlight.js/lib/languages/python\"),\n ruby: () => import(\"highlight.js/lib/languages/ruby\"),\n rust: () => import(\"highlight.js/lib/languages/rust\"),\n scss: () => import(\"highlight.js/lib/languages/scss\"),\n shell: () => import(\"highlight.js/lib/languages/shell\"),\n sql: () => import(\"highlight.js/lib/languages/sql\"),\n swift: () => import(\"highlight.js/lib/languages/swift\"),\n typescript: () => import(\"highlight.js/lib/languages/typescript\"),\n xml: () => import(\"highlight.js/lib/languages/xml\"),\n yaml: () => import(\"highlight.js/lib/languages/yaml\"),\n};\n\n/** The names a model writes for a language, mapped to the grammar name. */\nconst HIGHLIGHT_LANGUAGE_ALIASES: Record<string, string> = {\n \"c++\": \"cpp\",\n \"c#\": \"csharp\",\n cs: \"csharp\",\n docker: \"dockerfile\",\n html: \"xml\",\n js: \"javascript\",\n jsx: \"javascript\",\n md: \"markdown\",\n py: \"python\",\n rb: \"ruby\",\n rs: \"rust\",\n sh: \"bash\",\n svg: \"xml\",\n text: \"plaintext\",\n toml: \"ini\",\n ts: \"typescript\",\n tsx: \"typescript\",\n txt: \"plaintext\",\n yml: \"yaml\",\n zsh: \"bash\",\n};\n\n/** The grammar name for what the model wrote (`\"PHP\"`, `\"ts\"`, `\"html\"`), or undefined when no grammar fits. */\nexport const resolveHighlightLanguage = (language: unknown): string | undefined => {\n if (typeof language !== \"string\") return undefined;\n const lowercasedLanguage = language.trim().toLowerCase();\n const grammarName = Object.prototype.hasOwnProperty.call(HIGHLIGHT_LANGUAGE_ALIASES, lowercasedLanguage)\n ? HIGHLIGHT_LANGUAGE_ALIASES[lowercasedLanguage]\n : lowercasedLanguage;\n return Object.prototype.hasOwnProperty.call(HIGHLIGHT_LANGUAGE_LOADERS, grammarName) ? grammarName : undefined;\n};\n\n/** The highlight.js core, without any grammar. */\nconst loadHighlighter = (): Promise<HLJSApi> => {\n highlighterPromise ??= import(\"highlight.js/lib/core\")\n .then((highlighterModule) => highlighterModule.default)\n .catch((error: unknown) => {\n highlighterPromise = undefined;\n throw error;\n });\n return highlighterPromise;\n};\n\n/** The highlight.js core with the grammar `grammarName` registered (a name {@link resolveHighlightLanguage} returned). */\nexport const loadHighlighterWithLanguage = async (grammarName: string): Promise<HLJSApi> => {\n const highlighter = await loadHighlighter();\n if (!Object.prototype.hasOwnProperty.call(highlightLanguagePromises, grammarName)) {\n highlightLanguagePromises[grammarName] = HIGHLIGHT_LANGUAGE_LOADERS[grammarName]()\n .then((grammarModule) => {\n highlighter.registerLanguage(grammarName, grammarModule.default);\n return true;\n })\n .catch((error: unknown) => {\n delete highlightLanguagePromises[grammarName];\n throw error;\n });\n }\n await highlightLanguagePromises[grammarName];\n return highlighter;\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport type { ComposedSizeClass } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport { WidgetSurface } from \"../../../widgets/_shared/modern\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport styles from \"./RichNodeFrame.module.scss\";\n\nexport interface RichNodeFrameProps {\n /** The room the node has: at the root (`full`) the node is the widget and sits on its own elevated surface. */\n sizeClass: ComposedSizeClass;\n /** The model-written heading (business content, never translated). */\n title?: string;\n /** The model-written line under the heading. */\n caption?: string;\n /** A short technical label on the right of the header (\"LaTeX\", \"PHP\"), shown as written. */\n badge?: ReactNode;\n /** The header's controls (copy, wrap), right-aligned. */\n actions?: ReactNode;\n /** A node that is a tile wherever it sits (a code block); otherwise a nested node renders without a surface. */\n isTileWhenNested?: boolean;\n /** The muted line under the content (Math's example line), divided by a hairline. */\n footer?: ReactNode;\n children: ReactNode;\n testId?: string;\n}\n\n/**\n * The frame every rich kit node shares: on the chat (the tree's root) an elevated card with the\n * heading, the caption and the header controls; nested in another node, the same parts without a surface of their own\n * (the parent is the card) — a code block keeps a tile there, flat inside a surface and elevated outside one. The title is `textIntro` bold at the root and\n * `text` bold inside a parent.\n */\nexport const RichNodeFrame = (props: RichNodeFrameProps) => {\n const { sizeClass, title, caption, badge, actions, isTileWhenNested = false, footer, children, testId } = props;\n const isRoot = sizeClass === \"full\";\n const hasHeader = Boolean(title) || badge !== undefined || actions !== undefined;\n const content = (\n <>\n {hasHeader ? (\n <div className={styles.header}>\n <div className={styles.heading}>\n {title ? (\n <Text\n role={isRoot ? \"intro\" : \"body\"}\n weight=\"bold\"\n translate={false}\n className={styles.wrappingText}\n >\n {escapePlainTextForText(title)}\n </Text>\n ) : null}\n {caption ? (\n <Text\n role=\"help\"\n color=\"var(--agents-fg-light)\"\n translate={false}\n className={styles.wrappingText}\n >\n {escapePlainTextForText(caption)}\n </Text>\n ) : null}\n </div>\n {badge !== undefined || actions !== undefined ? (\n <div className={styles.headerEnd}>\n {badge}\n {actions}\n </div>\n ) : null}\n </div>\n ) : null}\n {children}\n {footer ? <div className={styles.footer}>{footer}</div> : null}\n </>\n );\n if (isRoot)\n return (\n <WidgetSurface level=\"elevated\" testId={testId}>\n {content}\n </WidgetSurface>\n );\n // A code block keeps a tile of its own: elevated when its parents draw no surface (a Stack on the chat), flat inside\n // a surface — the stylesheet reads WidgetSurface's `data-surface-level` on an ancestor.\n if (isTileWhenNested)\n return (\n <div className={styles.tile} data-testid={testId}>\n {content}\n </div>\n );\n return (\n <div className={classNames(styles.nested, sizeClass === \"compact\" && styles.compact)} data-testid={testId}>\n {content}\n </div>\n );\n};\n\nexport interface RichNodeContentSkeletonProps {\n /** The height of the content block it stands for, in CSS pixels. */\n height: number;\n testId?: string;\n}\n\n/** The loading block of a rich node: the content's own shape (the heading stays real text), marked busy. */\nexport const RichNodeContentSkeleton = (props: RichNodeContentSkeletonProps) => {\n const { height, testId } = props;\n return (\n <div className={styles.skeleton} aria-busy=\"true\" data-testid={testId}>\n <SkeletonLine width=\"100%\" height={height} radius={12} />\n </div>\n );\n};\n\nexport interface RichNodeBadgeProps {\n /** A technical name shown as written (\"LaTeX\", \"PHP\", \"Mermaid\"). */\n children: string;\n}\n\n/** The quiet label in a rich node's header that names the notation (ChatGPT's \"LaTeX\" badge). */\nexport const RichNodeBadge = (props: RichNodeBadgeProps) => {\n const { children } = props;\n return (\n <span className={styles.badge}>\n <Text role=\"caption\" weight=\"medium\" color=\"var(--agents-fg-light)\" translate={false}>\n {escapePlainTextForText(children)}\n </Text>\n </span>\n );\n};\n","import { Button } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useState } from \"react\";\nimport { ConversationWidgetActions } from \"../../../renderer/ConversationWidgetActions/ConversationWidgetActions\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadHighlighterWithLanguage, resolveHighlightLanguage } from \"./rich-libraries\";\nimport { RichNodeBadge, RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport styles from \"./Code.module.scss\";\n\n/** Lines shown before \"Show all lines\"; the rest stays one click away. */\nexport const CODE_COLLAPSED_LINE_COUNT = 24;\n\nconst COPIED_CONFIRMATION_MS = 2000;\n\n/** How a language name reads in the header — the common names in their usual spelling, the rest as written. */\nconst LANGUAGE_DISPLAY_NAMES: Record<string, string> = {\n bash: \"Bash\",\n cpp: \"C++\",\n csharp: \"C#\",\n css: \"CSS\",\n dockerfile: \"Dockerfile\",\n graphql: \"GraphQL\",\n html: \"HTML\",\n javascript: \"JavaScript\",\n js: \"JavaScript\",\n json: \"JSON\",\n kotlin: \"Kotlin\",\n markdown: \"Markdown\",\n php: \"PHP\",\n python: \"Python\",\n scss: \"SCSS\",\n sql: \"SQL\",\n ts: \"TypeScript\",\n typescript: \"TypeScript\",\n xml: \"XML\",\n yaml: \"YAML\",\n};\n\nconst readLanguageDisplayName = (language: unknown): string | undefined => {\n if (typeof language !== \"string\" || language.trim() === \"\") return undefined;\n const writtenLanguage = language.trim();\n const lowercasedLanguage = writtenLanguage.toLowerCase();\n return Object.prototype.hasOwnProperty.call(LANGUAGE_DISPLAY_NAMES, lowercasedLanguage)\n ? LANGUAGE_DISPLAY_NAMES[lowercasedLanguage]\n : writtenLanguage;\n};\n\ntype CodeHighlighting = { status: \"plain\" } | { status: \"highlighted\"; html: string };\n\n/**\n * The `Code` node (`CodeComposedViewNode.php`): source code in a tile with the\n * language (or the title) in its header, a copy button and a line-wrap toggle. The plain code shows at once; the\n * highlight.js grammar of the language loads on first use and colours it (highlight.js escapes the source, so the\n * coloured markup holds no markup of the code's own). An unknown language stays plain text. Long code shows its first\n * {@link CODE_COLLAPSED_LINE_COUNT} lines with \"Show all lines\". The e-mail capture shows no controls and wraps lines.\n */\nconst CodeNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const code = typeof nodeProps.code === \"string\" ? nodeProps.code.replace(/\\n+$/, \"\") : \"\";\n const grammarName = resolveHighlightLanguage(nodeProps.language);\n const languageDisplayName = readLanguageDisplayName(nodeProps.language);\n const title = typeof nodeProps.title === \"string\" && nodeProps.title.trim() !== \"\" ? nodeProps.title : undefined;\n const [highlighting, setHighlighting] = useState<CodeHighlighting>({ status: \"plain\" });\n const [isWrapped, setIsWrapped] = useState(nodeProps.wrap === true);\n const [isExpanded, setIsExpanded] = useState(false);\n const [isCopied, setIsCopied] = useState(false);\n const lineCount = code === \"\" ? 0 : code.split(\"\\n\").length;\n const isCollapsible = lineCount > CODE_COLLAPSED_LINE_COUNT;\n\n useEffect(() => {\n setHighlighting({ status: \"plain\" });\n if (grammarName === undefined || code === \"\") return;\n let isCurrent = true;\n loadHighlighterWithLanguage(grammarName)\n .then((highlighter) => {\n if (!isCurrent) return;\n const highlightedHtml = highlighter.highlight(code, { language: grammarName, ignoreIllegals: true }).value;\n setHighlighting({ status: \"highlighted\", html: highlightedHtml });\n })\n // A grammar that does not load leaves the plain code, which is complete — nothing is lost but the colours.\n .catch(() => undefined);\n return () => {\n isCurrent = false;\n };\n }, [code, grammarName]);\n\n useEffect(() => {\n if (isPending) reportNodeStatus(\"pending\");\n else if (code === \"\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the code block is empty\");\n else reportNodeStatus(\"mounted\");\n }, [code, isPending, reportNodeStatus]);\n\n useEffect(() => {\n if (!isCopied) return;\n const confirmationTimer = setTimeout(() => setIsCopied(false), COPIED_CONFIRMATION_MS);\n return () => clearTimeout(confirmationTimer);\n }, [isCopied]);\n\n const copyCode = () => {\n void navigator.clipboard\n ?.writeText(code)\n .then(() => setIsCopied(true))\n .catch(() => undefined);\n };\n\n // The code is bound to data that has not arrived yet: the tile with its header and a code-shaped skeleton.\n if (isPending) {\n return (\n <RichNodeFrame sizeClass={sizeClass} title={title ?? languageDisplayName} isTileWhenNested testId={testId}>\n <RichNodeContentSkeleton height={160} testId={`${testId}-skeleton`} />\n </RichNodeFrame>\n );\n }\n // No code: the node renders nothing and reports `empty` (one muted line or nothing).\n if (code === \"\") return null;\n\n const linesWrap = isWrapped || isEmailRender;\n const isClipped = isCollapsible && !isExpanded;\n const actions = isEmailRender ? undefined : (\n <ConversationWidgetActions>\n <div className={styles.actions}>\n <Button\n variant=\"muted\"\n size=\"small\"\n icon=\"text\"\n pressed={isWrapped}\n testId={`${testId}-wrap`}\n onClick={() => setIsWrapped((wasWrapped) => !wasWrapped)}\n >\n {\"Wrap lines\"}\n </Button>\n <Button\n variant=\"muted\"\n size=\"small\"\n icon={isCopied ? \"check\" : \"duplicate\"}\n onClick={copyCode}\n testId={`${testId}-copy`}\n >\n {isCopied ? \"Copied\" : \"Copy\"}\n </Button>\n </div>\n </ConversationWidgetActions>\n );\n\n return (\n <RichNodeFrame\n sizeClass={sizeClass}\n title={title ?? languageDisplayName ?? undefined}\n badge={title && languageDisplayName ? <RichNodeBadge>{languageDisplayName}</RichNodeBadge> : undefined}\n actions={actions}\n isTileWhenNested\n testId={testId}\n >\n <div className={classNames(styles.codeArea, isClipped && styles.clipped)}>\n {highlighting.status === \"highlighted\" ? (\n <pre className={classNames(styles.code, linesWrap && styles.wrapped)}>\n <code className=\"hljs\" dangerouslySetInnerHTML={{ __html: highlighting.html }} />\n </pre>\n ) : (\n <pre className={classNames(styles.code, linesWrap && styles.wrapped)}>\n <code>{code}</code>\n </pre>\n )}\n </div>\n {isCollapsible && !isEmailRender ? (\n <div className={styles.expandRow}>\n <Button\n variant=\"muted\"\n size=\"small\"\n rounded\n icon={isExpanded ? \"caretUp\" : \"caretDown\"}\n replacements={{ lineCount }}\n testId={`${testId}-expand`}\n onClick={() => setIsExpanded((wasExpanded) => !wasExpanded)}\n >\n {isExpanded ? \"Show fewer lines\" : \"Show all %lineCount% lines\"}\n </Button>\n </div>\n ) : null}\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Code\", component: CodeNode };\n","import type { DOMPurify } from \"dompurify\";\n\n/**\n * Sanitises SVG markup for the rich kit components: the `Svg` node's model-written graphic and the\n * SVG Mermaid draws for a `Diagram`. DOMPurify's SVG profile, plus:\n *\n * - no `script`, `foreignObject`, link (`a`), `image` / `feImage`, `use`, animation (`animate`, `set`, …) or embedding\n * element (DOMPurify's SVG profile leaves out `use` itself);\n * - no `style` element for a model-written graphic (Mermaid's own scoped stylesheet stays, its CSS is Mermaid's);\n * - a reference (`href`, `xlink:href`) only to an element of the same graphic (`#id`), a paint `url(…)` only as\n * `url(#id)` — nothing that loads from outside the graphic;\n * - exactly one `<svg>` element at the root; a root without a `viewBox` gets one from its `width` / `height`, and the\n * fixed size is dropped so the graphic scales with its box.\n *\n * Each call builds its own DOMPurify instance, so the hooks never reach another caller of the library.\n */\n\nexport interface SanitizedSvgMarkup {\n /** The safe markup of the one `<svg>` element, or null when nothing safe is left to draw. */\n markup: string | null;\n /** The names of the elements and attributes that were removed (`script`, `onload`, `href`, …), deduplicated. */\n removedPartNames: string[];\n}\n\nexport interface SanitizeSvgMarkupOptions {\n /** Keep a `<style>` element (Mermaid's scoped stylesheet); false for a model-written graphic. */\n keepStyleElement: boolean;\n /** The accessible name of the graphic (`role=\"img\"` + `aria-label`); without one the graphic keeps its own. */\n label?: string;\n}\n\nconst FORBIDDEN_ELEMENT_NAMES = [\n \"a\",\n \"animate\",\n \"animateColor\",\n \"animateMotion\",\n \"animateTransform\",\n \"discard\",\n \"embed\",\n \"feImage\",\n \"foreignObject\",\n \"iframe\",\n \"image\",\n \"object\",\n \"script\",\n \"set\",\n];\n\nconst REFERENCE_ATTRIBUTE_NAMES = new Set([\"href\", \"xlink:href\"]);\n\nconst DOCUMENT_WRAPPER_ELEMENT_NAMES = new Set([\"html\", \"head\", \"body\"]);\n\n/** Every `url(…)` in the value points into the graphic (`url(#id)`). */\nconst usesOnlyInternalUrls = (attributeValue: string): boolean => {\n const urlPattern = /url\\s*\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/gi;\n let urlMatch = urlPattern.exec(attributeValue);\n while (urlMatch !== null) {\n if (!urlMatch[2].trim().startsWith(\"#\")) return false;\n urlMatch = urlPattern.exec(attributeValue);\n }\n return true;\n};\n\nconst readNumericLength = (lengthValue: string | null): number | null => {\n if (lengthValue === null) return null;\n const length = Number.parseFloat(lengthValue);\n return Number.isFinite(length) && length > 0 && /^\\s*[\\d.]+(px)?\\s*$/.test(lengthValue) ? length : null;\n};\n\nexport const sanitizeSvgMarkup = (\n domPurifyFactory: DOMPurify,\n svgMarkup: string,\n options: SanitizeSvgMarkupOptions,\n): SanitizedSvgMarkup => {\n const domPurify = domPurifyFactory(window);\n const hookRemovedPartNames: string[] = [];\n domPurify.addHook(\"uponSanitizeAttribute\", (attributeOwner, hookEvent) => {\n const attributeName = hookEvent.attrName.toLowerCase();\n const attributeValue = hookEvent.attrValue ?? \"\";\n const isExternalReference = REFERENCE_ATTRIBUTE_NAMES.has(attributeName) && !attributeValue.trim().startsWith(\"#\");\n const loadsFromOutside = /url\\s*\\(/i.test(attributeValue) && !usesOnlyInternalUrls(attributeValue);\n const isStyleExpression = attributeName === \"style\" && /@import|expression\\s*\\(|javascript:/i.test(attributeValue);\n if (isExternalReference || loadsFromOutside || isStyleExpression) {\n hookEvent.keepAttr = false;\n hookRemovedPartNames.push(attributeName);\n }\n });\n const sanitizedFragment = domPurify.sanitize(svgMarkup, {\n USE_PROFILES: { svg: true, svgFilters: true },\n // `role` is an accessibility attribute, not a script or a reference: Mermaid writes `role=\"graphics-document\n // document\"` on every drawing, and removing it reported every valid diagram as unsafe.\n ADD_ATTR: [\"role\"],\n FORBID_TAGS: options.keepStyleElement ? FORBIDDEN_ELEMENT_NAMES : [...FORBIDDEN_ELEMENT_NAMES, \"style\"],\n RETURN_DOM_FRAGMENT: true,\n });\n const removedPartNames = new Set<string>(hookRemovedPartNames);\n for (const removedPart of domPurify.removed) {\n if (\"element\" in removedPart && removedPart.element) {\n const removedElementName = removedPart.element.nodeName.toLowerCase();\n // The document wrapper DOMPurify parses into is listed as removed when it returns a fragment — not a part.\n if (!DOCUMENT_WRAPPER_ELEMENT_NAMES.has(removedElementName)) removedPartNames.add(removedElementName);\n } else if (\"attribute\" in removedPart && removedPart.attribute) {\n removedPartNames.add(removedPart.attribute.name.toLowerCase());\n }\n }\n domPurify.removeAllHooks();\n\n const rootElements = Array.from(sanitizedFragment.children);\n const svgElement =\n rootElements.length === 1 && rootElements[0].nodeName.toLowerCase() === \"svg\" ? rootElements[0] : null;\n if (svgElement === null) return { markup: null, removedPartNames: [...removedPartNames] };\n\n if (!svgElement.hasAttribute(\"viewBox\")) {\n const width = readNumericLength(svgElement.getAttribute(\"width\"));\n const height = readNumericLength(svgElement.getAttribute(\"height\"));\n if (width !== null && height !== null) svgElement.setAttribute(\"viewBox\", `0 0 ${width} ${height}`);\n }\n if (svgElement.hasAttribute(\"viewBox\")) {\n svgElement.removeAttribute(\"width\");\n svgElement.removeAttribute(\"height\");\n }\n svgElement.setAttribute(\"focusable\", \"false\");\n if (options.label) {\n svgElement.setAttribute(\"role\", \"img\");\n svgElement.setAttribute(\"aria-label\", options.label);\n }\n if (!svgElement.hasChildNodes()) return { markup: null, removedPartNames: [...removedPartNames] };\n return { markup: svgElement.outerHTML, removedPartNames: [...removedPartNames] };\n};\n","import { useEffect, useState } from \"react\";\n\n/**\n * The colours a Mermaid diagram is drawn in: the theme's functional tokens, resolved to concrete\n * colours on the diagram's own element at draw time — Mermaid computes shades from them, so it needs real colours, not\n * `var(…)` references — and the revision that changes when the colour scheme or theme switches, so the diagram is\n * redrawn in the new colours.\n */\n\nconst resolveTokenColor = (probeParent: HTMLElement, cssColorValue: string): string => {\n const colorProbe = document.createElement(\"span\");\n colorProbe.style.color = cssColorValue;\n colorProbe.style.display = \"none\";\n probeParent.appendChild(colorProbe);\n const resolvedColor = getComputedStyle(colorProbe).color;\n colorProbe.remove();\n return resolvedColor;\n};\n\n/** Relative luminance (0 dark … 1 light) of an `rgb(…)` colour, or 1 when it cannot be read. */\nconst readLuminance = (rgbColor: string): number => {\n const channelMatch = rgbColor.match(/\\d+(\\.\\d+)?/g);\n if (!channelMatch || channelMatch.length < 3) return 1;\n const [red, green, blue] = channelMatch.slice(0, 3).map((channel) => Number(channel) / 255);\n return 0.2126 * red + 0.7152 * green + 0.0722 * blue;\n};\n\n/** Mermaid's `base` theme variables from the theme tokens around `probeParent`. */\nexport const readDiagramThemeVariables = (probeParent: HTMLElement): Record<string, string | boolean> => {\n const surfaceColor = resolveTokenColor(probeParent, \"var(--agents-bg-surface)\");\n const nodeColor = resolveTokenColor(probeParent, \"var(--agents-bg-var)\");\n const textColor = resolveTokenColor(probeParent, \"var(--agents-fg)\");\n const lineColor = resolveTokenColor(probeParent, \"var(--agents-fg-lightest)\");\n const borderColor = resolveTokenColor(probeParent, \"var(--agents-divider-gl)\");\n const fontFamily = getComputedStyle(probeParent).fontFamily;\n return {\n darkMode: readLuminance(surfaceColor) < 0.5,\n background: surfaceColor,\n fontFamily,\n primaryColor: nodeColor,\n primaryTextColor: textColor,\n primaryBorderColor: borderColor,\n secondaryColor: nodeColor,\n secondaryTextColor: textColor,\n secondaryBorderColor: borderColor,\n tertiaryColor: surfaceColor,\n tertiaryTextColor: textColor,\n tertiaryBorderColor: borderColor,\n mainBkg: nodeColor,\n nodeBorder: borderColor,\n clusterBkg: surfaceColor,\n clusterBorder: borderColor,\n lineColor,\n textColor,\n titleColor: textColor,\n edgeLabelBackground: nodeColor,\n noteBkgColor: nodeColor,\n noteTextColor: textColor,\n noteBorderColor: borderColor,\n actorBkg: nodeColor,\n actorBorder: borderColor,\n actorTextColor: textColor,\n signalColor: lineColor,\n signalTextColor: textColor,\n };\n};\n\nconst COLOR_SCHEME_ATTRIBUTES = [\"data-color-scheme\", \"data-theme\", \"class\", \"style\"];\n\n/** A number that grows whenever the page's colour scheme or theme may have changed. */\nexport const useColorSchemeRevision = (): number => {\n const [colorSchemeRevision, setColorSchemeRevision] = useState(0);\n useEffect(() => {\n const bumpRevision = () => setColorSchemeRevision((revision) => revision + 1);\n const attributeObserver = new MutationObserver(bumpRevision);\n attributeObserver.observe(document.documentElement, { attributes: true, attributeFilter: COLOR_SCHEME_ATTRIBUTES });\n const darkSchemeQuery = window.matchMedia?.(\"(prefers-color-scheme: dark)\");\n darkSchemeQuery?.addEventListener?.(\"change\", bumpRevision);\n return () => {\n attributeObserver.disconnect();\n darkSchemeQuery?.removeEventListener?.(\"change\", bumpRevision);\n };\n }, []);\n return colorSchemeRevision;\n};\n","import { Text } from \"../../../provider/components\";\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadDomPurify, loadMermaid } from \"./rich-libraries\";\nimport { sanitizeSvgMarkup } from \"./sanitize-svg-markup\";\nimport { RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport { readDiagramThemeVariables, useColorSchemeRevision } from \"./diagram-theme\";\nimport styles from \"./Diagram.module.scss\";\n\ntype DiagramRendering =\n | { status: \"loading\" }\n | { status: \"empty\" }\n | { status: \"rendered\"; svgMarkup: string; removedPartNames: string[] }\n | { status: \"failed\"; detail: string };\n\n/** The longest Mermaid parse message the report carries. */\nconst MAX_ERROR_DETAIL_LENGTH = 300;\n\nconst readMermaidErrorMessage = (error: unknown): string => {\n const message = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"unknown error\";\n return message.replace(/\\s+/g, \" \").trim().slice(0, MAX_ERROR_DETAIL_LENGTH);\n};\n\n/**\n * The `Diagram` node (`DiagramComposedViewNode.php`): a Mermaid diagram,\n * Mermaid loaded on first use as its own chunk. Mermaid runs at `securityLevel: \"strict\"` with SVG labels (no HTML in\n * labels, no click handlers), its colours are the theme's tokens resolved at draw time (redrawn when the colour scheme\n * changes), and the drawn SVG is sanitised again before it is shown. Source Mermaid cannot read renders one muted line\n * and is reported `failed` with Mermaid's message.\n */\nconst DiagramNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const source = typeof nodeProps.source === \"string\" ? nodeProps.source : \"\";\n const title = typeof nodeProps.title === \"string\" ? nodeProps.title : undefined;\n const caption = typeof nodeProps.caption === \"string\" ? nodeProps.caption : undefined;\n const [rendering, setRendering] = useState<DiagramRendering>({ status: \"loading\" });\n const themeProbeRef = useRef<HTMLDivElement>(null);\n const colorSchemeRevision = useColorSchemeRevision();\n // Mermaid needs a document-unique element id per drawing; React's id carries colons, which a CSS id selector refuses.\n const renderIdBase = `composed-diagram-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n\n useEffect(() => {\n if (isPending) {\n setRendering({ status: \"loading\" });\n return;\n }\n if (source.trim() === \"\") {\n setRendering({ status: \"empty\" });\n return;\n }\n let isCurrent = true;\n const themeProbe = themeProbeRef.current;\n setRendering({ status: \"loading\" });\n const drawDiagram = async (): Promise<DiagramRendering> => {\n const [mermaid, domPurifyFactory] = await Promise.all([loadMermaid(), loadDomPurify()]);\n const themeVariables = themeProbe ? readDiagramThemeVariables(themeProbe) : {};\n mermaid.initialize({\n startOnLoad: false,\n securityLevel: \"strict\",\n theme: \"base\",\n themeVariables,\n htmlLabels: false,\n // A short step name stays on one line (\"Widget auswählen\"); only a long one wraps.\n flowchart: { htmlLabels: false, useMaxWidth: true, wrappingWidth: 260 },\n maxTextSize: 4000,\n suppressErrorRendering: true,\n });\n try {\n await mermaid.parse(source);\n } catch (parseError) {\n return {\n status: \"failed\",\n detail: `Mermaid could not read the diagram — ${readMermaidErrorMessage(parseError)}`,\n };\n }\n const { svg } = await mermaid.render(`${renderIdBase}-${colorSchemeRevision}`, source);\n const sanitizedSvg = sanitizeSvgMarkup(domPurifyFactory, svg, { keepStyleElement: true, label: title });\n if (sanitizedSvg.markup === null)\n return { status: \"failed\", detail: \"the drawn diagram held nothing safe to show\" };\n return { status: \"rendered\", svgMarkup: sanitizedSvg.markup, removedPartNames: sanitizedSvg.removedPartNames };\n };\n drawDiagram()\n .then((diagramRendering) => {\n if (isCurrent) setRendering(diagramRendering);\n })\n .catch((drawError: unknown) => {\n if (isCurrent)\n setRendering({\n status: \"failed\",\n detail: `the diagram could not be drawn — ${readMermaidErrorMessage(drawError)}`,\n });\n });\n return () => {\n isCurrent = false;\n };\n }, [source, title, isPending, renderIdBase, colorSchemeRevision]);\n\n useEffect(() => {\n if (rendering.status === \"loading\") reportNodeStatus(\"pending\");\n if (rendering.status === \"empty\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the diagram source is empty\");\n if (rendering.status === \"failed\") reportNodeStatus(\"failed\", \"RENDER_FAILED\", rendering.detail);\n if (rendering.status === \"rendered\") {\n if (rendering.removedPartNames.length === 0) reportNodeStatus(\"mounted\");\n else {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n `unsafe parts of the drawn diagram were removed (${rendering.removedPartNames.join(\", \")}) — the rest is shown`,\n );\n }\n }\n }, [rendering, reportNodeStatus]);\n\n // No source: the node renders nothing and reports `empty` (one muted line or nothing).\n if (rendering.status === \"empty\") return null;\n return (\n <RichNodeFrame sizeClass={sizeClass} title={title} caption={caption} testId={testId}>\n <div ref={themeProbeRef} className={styles.diagramArea}>\n {rendering.status === \"rendered\" ? (\n <div className={styles.diagram} dangerouslySetInnerHTML={{ __html: rendering.svgMarkup }} />\n ) : null}\n {rendering.status === \"loading\" ? <RichNodeContentSkeleton height={240} testId={`${testId}-skeleton`} /> : null}\n {rendering.status === \"failed\" ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={`${testId}-error`}>\n {\"This diagram could not be drawn.\"}\n </Text>\n ) : null}\n </div>\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Diagram\", component: DiagramNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadKatex } from \"./rich-libraries\";\nimport { RichNodeBadge, RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport styles from \"./Math.module.scss\";\n\ntype MathRendering =\n | { status: \"loading\" }\n | { status: \"empty\" }\n | { status: \"rendered\"; html: string }\n | { status: \"failed\"; detail: string };\n\n/** KaTeX's own safety and size limits: no `\\href` / `\\url` / `\\includegraphics` / HTML extensions, bounded macros. */\nconst KATEX_OPTIONS = {\n throwOnError: false,\n trust: false,\n strict: \"ignore\",\n output: \"htmlAndMathml\",\n maxSize: 20,\n maxExpand: 500,\n} as const;\n\n/** The parse message KaTeX writes into its error element when `throwOnError` is off, or null for a valid formula. */\nconst readKatexErrorMessage = (renderedHtml: string): string | null => {\n if (!renderedHtml.includes(\"katex-error\")) return null;\n const template = document.createElement(\"template\");\n template.innerHTML = renderedHtml;\n return template.content.querySelector(\".katex-error\")?.getAttribute(\"title\") ?? \"KaTeX could not read the formula\";\n};\n\n/**\n * The `Math` node (`MathComposedViewNode.php`): a LaTeX formula typeset by\n * KaTeX, loaded on first use. A block formula sits centred under an optional heading with the \"LaTeX\" badge and an\n * optional caption line under a hairline; an inline formula flows in its line. A formula KaTeX cannot read shows its\n * source and one muted line, and is reported `failed` with KaTeX's parse message.\n */\nconst MathNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const latex = typeof nodeProps.latex === \"string\" ? nodeProps.latex : \"\";\n const isInline = nodeProps.display === \"inline\";\n const title = typeof nodeProps.title === \"string\" ? nodeProps.title : undefined;\n const caption = typeof nodeProps.caption === \"string\" ? nodeProps.caption : undefined;\n const [rendering, setRendering] = useState<MathRendering>({ status: \"loading\" });\n\n useEffect(() => {\n if (isPending) {\n setRendering({ status: \"loading\" });\n return;\n }\n if (latex.trim() === \"\") {\n setRendering({ status: \"empty\" });\n return;\n }\n let isCurrent = true;\n setRendering({ status: \"loading\" });\n loadKatex()\n .then((katex) => {\n if (!isCurrent) return;\n const renderedHtml = katex.renderToString(latex, { ...KATEX_OPTIONS, displayMode: !isInline });\n const errorMessage = readKatexErrorMessage(renderedHtml);\n setRendering(\n errorMessage === null\n ? { status: \"rendered\", html: renderedHtml }\n : { status: \"failed\", detail: `the formula is not valid LaTeX — ${errorMessage}` },\n );\n })\n .catch(() => {\n if (isCurrent) setRendering({ status: \"failed\", detail: \"the formula renderer could not be loaded\" });\n });\n return () => {\n isCurrent = false;\n };\n }, [latex, isInline, isPending]);\n\n useEffect(() => {\n if (rendering.status === \"loading\") reportNodeStatus(\"pending\");\n if (rendering.status === \"empty\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the formula is empty\");\n if (rendering.status === \"rendered\") reportNodeStatus(\"mounted\");\n if (rendering.status === \"failed\") reportNodeStatus(\"failed\", \"RENDER_FAILED\", rendering.detail);\n }, [rendering, reportNodeStatus]);\n\n // Nothing to typeset: the node renders nothing and reports `empty` (one muted line or nothing).\n if (rendering.status === \"empty\") return null;\n if (isInline) {\n if (rendering.status === \"rendered\") {\n return (\n <span\n className={styles.inlineFormula}\n data-testid={testId}\n dangerouslySetInnerHTML={{ __html: rendering.html }}\n />\n );\n }\n if (rendering.status === \"loading\") {\n return (\n <span className={styles.inlineSkeleton} aria-busy=\"true\" data-testid={`${testId}-skeleton`}>\n <SkeletonLine width={64} height={14} radius={4} />\n </span>\n );\n }\n return (\n <Text role=\"body\" translate={false} className={styles.source} testId={`${testId}-error`}>\n {escapePlainTextForText(latex)}\n </Text>\n );\n }\n\n const footer = caption ? (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false} className={styles.caption}>\n {escapePlainTextForText(caption)}\n </Text>\n ) : undefined;\n return (\n <RichNodeFrame\n sizeClass={sizeClass}\n title={title}\n badge={title ? <RichNodeBadge>LaTeX</RichNodeBadge> : undefined}\n footer={footer}\n testId={testId}\n >\n {rendering.status === \"rendered\" ? (\n <div className={styles.blockFormula} dangerouslySetInnerHTML={{ __html: rendering.html }} />\n ) : null}\n {rendering.status === \"loading\" ? <RichNodeContentSkeleton height={48} testId={`${testId}-skeleton`} /> : null}\n {rendering.status === \"failed\" ? (\n <div className={styles.failure} data-testid={`${testId}-error`}>\n <Text role=\"help\" color=\"var(--agents-fg-light)\">\n {\"This formula could not be rendered.\"}\n </Text>\n <Text role=\"help\" translate={false} className={styles.source}>\n {escapePlainTextForText(latex)}\n </Text>\n </div>\n ) : null}\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Math\", component: MathNode };\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { useEffect, useState } from \"react\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { loadDomPurify } from \"./rich-libraries\";\nimport { sanitizeSvgMarkup } from \"./sanitize-svg-markup\";\nimport { RichNodeContentSkeleton, RichNodeFrame } from \"./RichNodeFrame\";\nimport styles from \"./Svg.module.scss\";\n\ntype SvgRendering =\n | { status: \"loading\" }\n | { status: \"empty\" }\n | { status: \"rendered\"; svgMarkup: string; removedPartNames: string[] }\n | { status: \"failed\"; detail: string; removedPartNames: string[] };\n\n/**\n * The `Svg` node (`SvgComposedViewNode.php`): a vector graphic the model drew,\n * shown only after DOMPurify (loaded on first use) reduced it to safe SVG — no scripts, no event attributes, no\n * `foreignObject`, no `style` element, no link and no reference outside the graphic ({@link sanitizeSvgMarkup}). The\n * markup may be a computed text over the tree's state, so the drawing follows the inputs (the radar whose shape moves\n * with its sliders); each change is sanitised again. Removed parts are reported `failed` with their names while the\n * rest is drawn; markup with nothing safe left renders one muted line.\n */\nconst SvgNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus } = runtime;\n const markup = typeof nodeProps.markup === \"string\" ? nodeProps.markup : \"\";\n const label = typeof nodeProps.label === \"string\" && nodeProps.label.trim() !== \"\" ? nodeProps.label : undefined;\n const title = typeof nodeProps.title === \"string\" ? nodeProps.title : undefined;\n const caption = typeof nodeProps.caption === \"string\" ? nodeProps.caption : undefined;\n const [rendering, setRendering] = useState<SvgRendering>({ status: \"loading\" });\n\n useEffect(() => {\n if (isPending) {\n setRendering({ status: \"loading\" });\n return;\n }\n if (markup.trim() === \"\") {\n setRendering({ status: \"empty\" });\n return;\n }\n let isCurrent = true;\n loadDomPurify()\n .then((domPurifyFactory) => {\n if (!isCurrent) return;\n const sanitizedSvg = sanitizeSvgMarkup(domPurifyFactory, markup, {\n keepStyleElement: false,\n label: label ?? title,\n });\n setRendering(\n sanitizedSvg.markup === null\n ? {\n status: \"failed\",\n detail: \"the markup holds no single <svg> element with safe content\",\n removedPartNames: sanitizedSvg.removedPartNames,\n }\n : { status: \"rendered\", svgMarkup: sanitizedSvg.markup, removedPartNames: sanitizedSvg.removedPartNames },\n );\n })\n .catch(() => {\n if (isCurrent)\n setRendering({ status: \"failed\", detail: \"the SVG sanitiser could not be loaded\", removedPartNames: [] });\n });\n return () => {\n isCurrent = false;\n };\n }, [markup, label, title, isPending]);\n\n useEffect(() => {\n if (rendering.status === \"loading\") reportNodeStatus(\"pending\");\n if (rendering.status === \"empty\") reportNodeStatus(\"empty\", \"NO_DATA\", \"the SVG markup is empty\");\n if (rendering.status === \"failed\") {\n const removedPartsDetail =\n rendering.removedPartNames.length > 0 ? ` (removed: ${rendering.removedPartNames.join(\", \")})` : \"\";\n reportNodeStatus(\"failed\", \"RENDER_FAILED\", `${rendering.detail}${removedPartsDetail}`);\n }\n if (rendering.status === \"rendered\") {\n if (rendering.removedPartNames.length === 0) reportNodeStatus(\"mounted\");\n else {\n reportNodeStatus(\n \"failed\",\n \"INVALID_PROP\",\n `unsafe SVG parts were removed (${rendering.removedPartNames.join(\", \")}) — the rest is drawn`,\n );\n }\n }\n }, [rendering, reportNodeStatus]);\n\n // No markup: the node renders nothing and reports `empty` (one muted line or nothing).\n if (rendering.status === \"empty\") return null;\n const graphic =\n rendering.status === \"rendered\" ? (\n <div\n className={classNames(styles.graphic, sizeClass === \"compact\" && styles.compactGraphic)}\n dangerouslySetInnerHTML={{ __html: rendering.svgMarkup }}\n />\n ) : rendering.status === \"loading\" ? (\n <RichNodeContentSkeleton height={sizeClass === \"compact\" ? 48 : 200} testId={`${testId}-skeleton`} />\n ) : (\n <Text role=\"help\" color=\"var(--agents-fg-light)\" testId={`${testId}-error`}>\n {\"This graphic could not be shown.\"}\n </Text>\n );\n\n return (\n <RichNodeFrame sizeClass={sizeClass} title={title} caption={caption} testId={testId}>\n {graphic}\n </RichNodeFrame>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Svg\", component: SvgNode };\n","import { escapePlainTextForText } from \"../../../provider/environment\";\nimport { StatusBadge, type AgentsStatusBadgeStatus } from \"../../../provider/components\";\nimport { SkeletonPill } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n ComposedViewTone,\n readComposedViewTone,\n} from \"../../composed-view-tones\";\nimport { readTextNodeContent, readTextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\nimport styles from \"./Badge.module.scss\";\n\n/** The status colour of a tone: `muted` has no status of its own and reads as the neutral badge. */\nconst STATUS_OF_TONE: Readonly<Record<ComposedViewTone, AgentsStatusBadgeStatus>> = {\n neutral: \"neutral\",\n muted: \"neutral\",\n success: \"success\",\n warning: \"warning\",\n danger: \"danger\",\n info: \"info\",\n};\n\n/**\n * The `Badge` node (`BadgeComposedViewNode.php`): a short status with a judgement tone, as the design's\n * small status badge (the component library's `StatusBadge variant=\"small\"`, no icon). The status text\n * is the model's, so the badge is told not to translate it and the text is escaped (`model-text.ts`).\n */\nconst BadgeNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const tone = readComposedViewTone(nodeProps.tone);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Badge\");\n if (isPending) return <SkeletonPill width={72} height={20} />;\n if (content.kind !== \"text\") return null;\n return (\n <span className={styles.badge} data-tone={tone} data-testid={testId}>\n <StatusBadge\n status={STATUS_OF_TONE[tone]}\n text={escapePlainTextForText(content.text)}\n translate={false}\n size=\"small\"\n hideIcon\n />\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Badge\", component: BadgeNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readTextNodeContent, readTextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\nimport styles from \"./Caption.module.scss\";\n\n/**\n * The `Caption` node (`CaptionComposedViewNode.php`): muted secondary text — the sub-line under a title, a\n * unit, a date, a method note (`textCaption` in `--agents-fg-light`). A block of its own, or inline in a compact slot.\n */\nconst CaptionNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Caption\");\n if (isPending) return <SkeletonLine width=\"30%\" height={10} radius={4} />;\n if (content.kind !== \"text\") return null;\n return (\n <Text\n role=\"caption\"\n translate={false}\n color=\"--agents-fg-light\"\n display={sizeClass === \"compact\" ? \"inline\" : \"block\"}\n className={styles.caption}\n testId={testId}\n >\n {escapePlainTextForText(content.text)}\n </Text>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Caption\", component: CaptionNode };\n","import { Icon } from \"../../../../provider/components\";\nimport { useState } from \"react\";\nimport { buildFaviconUrl } from \"./text-node-values\";\nimport styles from \"./SiteFavicon.module.scss\";\n\nexport interface SiteFaviconProps {\n /** The site, or null when the value named none (the link glyph shows). */\n hostname: string | null;\n /** The site's name for the accessible label and the hover; the host name when absent. */\n siteName?: string;\n /** The e-mail capture fails on a broken image, and a favicon is an outside request: the capture shows the glyph. */\n isEmailRender: boolean;\n}\n\n/**\n * A site's favicon for the kit's text components (`Favicon`, `SourceRef`): the Google favicon service by host name, the\n * generic link glyph when there is no site, the image fails to load, or the e-mail capture renders — never a broken image.\n */\nexport const SiteFavicon = (props: SiteFaviconProps) => {\n const { hostname, siteName, isEmailRender } = props;\n const [hasFailedToLoad, setHasFailedToLoad] = useState(false);\n const accessibleName = siteName ?? hostname ?? undefined;\n if (hostname === null || hasFailedToLoad || isEmailRender) {\n return (\n <span\n className={styles.favicon}\n role={accessibleName ? \"img\" : undefined}\n aria-label={accessibleName}\n title={accessibleName}\n >\n <Icon color=\"var(--agents-fg-light)\" pixelSize={14} name=\"link\" />\n </span>\n );\n }\n return (\n <img\n className={styles.favicon}\n src={buildFaviconUrl(hostname)}\n alt={accessibleName ?? \"\"}\n title={accessibleName}\n loading=\"lazy\"\n onError={() => setHasFailedToLoad(true)}\n />\n );\n};\n","import { SiteFavicon } from \"./shared/SiteFavicon\";\nimport { SkeletonCircle } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readSiteHostname, TextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\n\n/**\n * The `Favicon` node (`FaviconComposedViewNode.php`): the small icon of the site of `url` (a page address or\n * a bare domain). A url that names no site shows the generic link glyph and reports `failed INVALID_PROP`.\n */\nconst FaviconNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime } = props;\n const hostname = readSiteHostname(nodeProps.url);\n const siteName = typeof nodeProps.name === \"string\" && nodeProps.name.trim() !== \"\" ? nodeProps.name : undefined;\n let renderState: TextNodeRenderState = \"shown\";\n if (isPending) renderState = \"pending\";\n else if (hostname === null) renderState = \"invalid\";\n useReportTextNodeRenderState(runtime, renderState, \"Favicon\", \"the Favicon url names no http(s) site\");\n if (isPending) return <SkeletonCircle size={16} />;\n return <SiteFavicon hostname={hostname} siteName={siteName} isEmailRender={runtime.isEmailRender} />;\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Favicon\", component: FaviconNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readTextNodeContent, readTextNodeRenderState, useReportTextNodeRenderState } from \"./shared/text-node-values\";\nimport styles from \"./Label.module.scss\";\n\n/**\n * The `Label` node (`LabelComposedViewNode.php`): the short name above a value, an input or a group — the\n * design's section label (muted, medium, uppercase, letter-spaced; the look of `widgets/_shared/WidgetLabel`, whose copy\n * is a translation key, while a label here is the model's words and stays untranslated).\n */\nconst LabelNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Label\");\n if (isPending) return <SkeletonLine width={120} height={10} radius={4} />;\n if (content.kind !== \"text\") return null;\n return (\n <Text\n role=\"help\"\n weight=\"medium\"\n translate={false}\n color=\"--agents-fg-light\"\n className={styles.label}\n testId={testId}\n >\n {escapePlainTextForText(content.text)}\n </Text>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Label\", component: LabelNode };\n","import { Icon, Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n readSafeHttpUrl,\n readTextNodeContent,\n TextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Link.module.scss\";\n\n/**\n * The `Link` node (`LinkComposedViewNode.php`): the model's text that opens an http(s) page in a new tab\n * (`target=\"_blank\" rel=\"noopener noreferrer\"`), with the new-tab glyph. A url with another scheme\n * (`javascript:`, `data:`, `mailto:`, a relative path) is no link: the text shows alone and the node reports\n * `failed INVALID_PROP`. A link never sends a chat message.\n */\nconst LinkNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const safeUrl = readSafeHttpUrl(nodeProps.url);\n let renderState: TextNodeRenderState = \"shown\";\n if (isPending) renderState = \"pending\";\n else if (content.kind === \"invalid\" || (content.kind === \"text\" && safeUrl === null)) renderState = \"invalid\";\n else if (content.kind === \"missing\") renderState = \"empty\";\n useReportTextNodeRenderState(\n runtime,\n renderState,\n \"Link\",\n content.kind === \"invalid\" ? undefined : \"the Link has no http(s) url — its text is shown without a link\",\n );\n if (isPending) return <SkeletonLine width=\"8em\" height={12} radius={4} />;\n if (content.kind !== \"text\") return null;\n if (safeUrl === null) {\n return (\n <Text role=\"body\" translate={false} display=\"inline\" className={styles.unlinked} testId={testId}>\n {escapePlainTextForText(content.text)}\n </Text>\n );\n }\n return (\n <a className={styles.link} href={safeUrl} target=\"_blank\" rel=\"noopener noreferrer\" data-testid={testId}>\n <Text role=\"body\" translate={false} display=\"inline\" className={styles.linkText}>\n {escapePlainTextForText(content.text)}\n </Text>\n <Icon color=\"var(--agents-fg-light)\" className={styles.newTabIcon} pixelSize={14} name=\"newTab\" />\n </a>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Link\", component: LinkNode };\n","import { Markdown, Text, type AgentsMarkdownProps } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n readSafeHttpUrl,\n readTextNodeContent,\n readTextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Markdown.module.scss\";\n\ninterface MarkdownElementProps {\n children?: ReactNode;\n /** The hast element react-markdown renders (its text is what a heading shows). */\n node?: MarkdownHastNode;\n}\n\ninterface MarkdownHastNode {\n type: string;\n value?: string;\n children?: MarkdownHastNode[];\n}\n\n/** The plain text of a hast element — a heading's inline formatting is not kept (see the heading renderer). */\nconst readHastText = (node: MarkdownHastNode | undefined): string => {\n if (!node) return \"\";\n if (node.type === \"text\") return node.value ?? \"\";\n return (node.children ?? []).map(readHastText).join(\"\");\n};\n\n/**\n * Every heading level as a section title (`text` bold). The component library's `Text` re-parses element children (a link inside\n * would lose its `href`), so a heading shows its plain text.\n */\nconst renderHeading = (props: MarkdownElementProps) => (\n <Text\n role=\"body\"\n weight=\"bold\"\n translate={false}\n display=\"block\"\n className={styles.heading}\n headingLevel={4}\n >\n {escapePlainTextForText(readHastText(props.node))}\n </Text>\n);\n\n/**\n * The safe subset: no images (an outside request, and a tracking pixel in a model's text), headings no\n * larger than a section title, links only to http(s) pages in a new tab — another scheme renders its text alone. Raw\n * HTML never reaches the DOM: the shared renderer has no raw-HTML plugin, so react-markdown drops it.\n */\nconst SAFE_MARKDOWN_COMPONENTS = {\n img: () => null,\n h1: renderHeading,\n h2: renderHeading,\n h3: renderHeading,\n h4: renderHeading,\n h5: renderHeading,\n h6: renderHeading,\n a: (props: MarkdownElementProps & { href?: string }) => {\n const safeUrl = readSafeHttpUrl(props.href);\n if (safeUrl === null) return <span>{props.children}</span>;\n return (\n <a className={styles.link} href={safeUrl} target=\"_blank\" rel=\"noopener noreferrer\">\n {props.children}\n </a>\n );\n },\n} as NonNullable<AgentsMarkdownProps[\"components\"]>;\n\n/**\n * The `Markdown` node (`MarkdownComposedViewNode.php`): the model's formatted text — paragraphs, emphasis,\n * lists, quotes, tables, headings — through the shared conversation Markdown renderer, held to the safe subset above\n * and never translated.\n */\nconst MarkdownNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.markdown);\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Markdown\");\n if (isPending) {\n return (\n <div className={styles.skeleton} data-testid={`${testId}-skeleton`}>\n <SkeletonLine width=\"90%\" height={14} radius={4} />\n <SkeletonLine width=\"70%\" height={14} radius={4} />\n </div>\n );\n }\n if (content.kind !== \"text\") return null;\n return (\n <div className={styles.markdown} data-testid={testId}>\n <Markdown markdown={content.text} translate={false} components={SAFE_MARKDOWN_COMPONENTS} />\n </div>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Markdown\", component: MarkdownNode };\n","import type { ExpressionValue } from \"../../../../renderer/widget-tree/expression/evaluate-expression\";\nimport { readSafeHttpUrl, readSiteHostname, readTextNodeContent } from \"./text-node-values\";\n\n/** One source of a `SourceRef`, read from its wire object: a name always, the rest only when it can be shown safely. */\nexport interface SourceRefEntry {\n /** The publisher or site (\"WDR\", \"Wikimedia Commons\"). */\n name: string;\n /** The http(s) page; null = the source is shown without a link. */\n url: string | null;\n /** The site of `url`, for its favicon; null = the link glyph. */\n hostname: string | null;\n /** The work's title (an image, an article), for the attribution line. */\n title: string | null;\n author: string | null;\n /** The licence name (\"CC BY-SA 4.0\"). */\n license: string | null;\n /** The licence's http(s) page; null = the licence is shown as text. */\n licenseUrl: string | null;\n}\n\nexport interface SourceRefEntries {\n /** The sources that can be shown, at most `maxEntries`. */\n entries: SourceRefEntry[];\n /** Wire items left out because they have no name (or are no object). */\n skippedCount: number;\n /** Items past `maxEntries` (the kit's `maxRepeatRows`). */\n cutCount: number;\n /** Whether `sources` was a list at all. */\n isList: boolean;\n}\n\nconst readOptionalText = (value: ExpressionValue): string | null => {\n const content = readTextNodeContent(value);\n return content.kind === \"text\" ? content.text : null;\n};\n\n/** The `sources` prop read into entries — never throws: what cannot be shown is counted, the rest is kept in order. */\nexport const readSourceRefEntries = (sourcesValue: ExpressionValue, maxEntries: number): SourceRefEntries => {\n // Nothing bound yet (a dataset still loading, an unset state) is an empty list, not a wrong one.\n if (sourcesValue === undefined || sourcesValue === null)\n return { entries: [], skippedCount: 0, cutCount: 0, isList: true };\n if (!Array.isArray(sourcesValue)) return { entries: [], skippedCount: 0, cutCount: 0, isList: false };\n const entries: SourceRefEntry[] = [];\n let skippedCount = 0;\n let cutCount = 0;\n for (const sourceValue of sourcesValue) {\n if (typeof sourceValue !== \"object\" || sourceValue === null || Array.isArray(sourceValue)) {\n skippedCount += 1;\n continue;\n }\n const name = readOptionalText(sourceValue.name);\n if (name === null) {\n skippedCount += 1;\n continue;\n }\n if (entries.length >= maxEntries) {\n cutCount += 1;\n continue;\n }\n const url = readSafeHttpUrl(sourceValue.url);\n entries.push({\n name,\n url,\n hostname: url === null ? null : readSiteHostname(url),\n title: readOptionalText(sourceValue.title),\n author: readOptionalText(sourceValue.author),\n license: readOptionalText(sourceValue.license),\n licenseUrl: readSafeHttpUrl(sourceValue.licenseUrl),\n });\n }\n return { entries, skippedCount, cutCount, isList: true };\n};\n\n/** Whether the entry carries an attribution beyond its name (an image licence, an author). */\nexport const hasAttribution = (entry: SourceRefEntry): boolean => entry.license !== null || entry.author !== null;\n","import { Icon, Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { Fragment, useEffect, useId, useState } from \"react\";\nimport { composedNodeSchema } from \"../../../renderer/widget-tree/composed-node-schema\";\nimport { SkeletonPill } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { SiteFavicon } from \"./shared/SiteFavicon\";\nimport { hasAttribution, readSourceRefEntries, SourceRefEntry } from \"./shared/source-ref-entries\";\nimport styles from \"./SourceRef.module.scss\";\n\ninterface SourceChipProps {\n entry: SourceRefEntry;\n isEmailRender: boolean;\n testId: string;\n}\n\n/** One source as a chip: its favicon and name, a link to its page when it has one (new tab). */\nconst SourceChip = (props: SourceChipProps) => {\n const { entry, isEmailRender, testId } = props;\n const chipContent = (\n <>\n <SiteFavicon hostname={entry.hostname} siteName={entry.name} isEmailRender={isEmailRender} />\n <Text role=\"caption\" weight=\"medium\" translate={false} className={styles.chipName}>\n {escapePlainTextForText(entry.name)}\n </Text>\n </>\n );\n if (entry.url === null)\n return (\n <span className={styles.chip} data-testid={testId}>\n {chipContent}\n </span>\n );\n return (\n <a\n className={classNames(styles.chip, styles.linkedChip)}\n href={entry.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n title={entry.title ?? entry.name}\n data-testid={testId}\n >\n {chipContent}\n </a>\n );\n};\n\ninterface AttributionPart {\n text: string;\n /** The http(s) page of this part (the licence); null = plain text. */\n url: string | null;\n}\n\n/**\n * The attribution of one source: title · author · licence (linked when it has a page) · source name. Each part is its\n * own `Text` and the licence link sits outside it — the component library's `Text` re-parses element children and drops a link's\n * `href`, `target` and `rel`.\n */\nconst SourceAttribution = (props: { entry: SourceRefEntry }) => {\n const { entry } = props;\n const parts: AttributionPart[] = [];\n if (entry.title !== null) parts.push({ text: entry.title, url: null });\n if (entry.author !== null) parts.push({ text: entry.author, url: null });\n if (entry.license !== null) parts.push({ text: entry.license, url: entry.licenseUrl });\n parts.push({ text: entry.name, url: null });\n return (\n <span className={styles.attribution}>\n {parts.map((part, partIndex) => {\n const partText = (\n <Text\n role=\"caption\"\n translate={false}\n display=\"inline\"\n color=\"--agents-fg-light\"\n className={styles.attributionText}\n >\n {escapePlainTextForText(part.text)}\n </Text>\n );\n return (\n <Fragment key={partIndex}>\n {partIndex > 0 ? (\n <Text\n role=\"caption\"\n translate={false}\n display=\"inline\"\n color=\"--agents-fg-light\"\n className={styles.attributionText}\n >\n {\"·\"}\n </Text>\n ) : null}\n {part.url === null ? (\n partText\n ) : (\n <a className={styles.licenseLink} href={part.url} target=\"_blank\" rel=\"noopener noreferrer\">\n {partText}\n </a>\n )}\n </Fragment>\n );\n })}\n </span>\n );\n};\n\ninterface SourceListProps {\n entries: SourceRefEntry[];\n isEmailRender: boolean;\n testId: string;\n}\n\n/** The full source line (\"Sources\" + one chip per source) and one attribution line per licensed source. */\nconst SourceList = (props: SourceListProps) => {\n const { entries, isEmailRender, testId } = props;\n const attributedEntries = entries.filter(hasAttribution);\n return (\n <span className={styles.sourceList}>\n <span className={styles.sourceLine}>\n <Text\n role=\"caption\"\n color=\"--agents-fg-light\"\n className={styles.sourceLabel}\n context={entries.length === 1 ? \"one\" : \"other\"}\n >\n {\"Source\"}\n </Text>\n <span role=\"list\" className={styles.chips}>\n {entries.map((entry, entryIndex) => (\n <span role=\"listitem\" key={`${entryIndex}-${entry.name}`} className={styles.chipItem}>\n <SourceChip entry={entry} isEmailRender={isEmailRender} testId={`${testId}-chip-${entryIndex}`} />\n </span>\n ))}\n </span>\n </span>\n {attributedEntries.map((entry, entryIndex) => (\n <SourceAttribution key={`${entryIndex}-${entry.name}`} entry={entry} />\n ))}\n </span>\n );\n};\n\n/**\n * The `SourceRef` node (`SourceRefComposedViewNode.php`): where the shown values come from. In a\n * regular slot one line \"Sources\" with a chip per source (favicon, name, link to its page in a new tab) and, per source\n * with a licence or an author (an image from Wikimedia Commons), an attribution line. In a compact slot\n * (inside a `Text`, a table cell) one chip \"WDR +2\" that unfolds the full list — an effect-free toggle. Sources\n * without a name are left out and reported; at most `maxRepeatRows` sources are shown.\n */\nconst SourceRefNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, sizeClass, runtime, testId } = props;\n const { reportNodeStatus, isEmailRender } = runtime;\n const maxEntries = composedNodeSchema.budgets.maxRepeatRows;\n const { entries, skippedCount, cutCount, isList } = readSourceRefEntries(nodeProps.sources, maxEntries);\n const [isExpanded, setIsExpanded] = useState(false);\n const expandedListId = useId();\n\n useEffect(() => {\n if (isPending) reportNodeStatus(\"pending\");\n else if (!isList) reportNodeStatus(\"failed\", \"INVALID_PROP\", \"the SourceRef sources are not a list\");\n else if (cutCount > 0) {\n reportNodeStatus(\"failed\", \"BUDGET_EXCEEDED\", `the SourceRef shows the first ${maxEntries} sources only`);\n } else if (skippedCount > 0) {\n reportNodeStatus(\"failed\", \"INVALID_PROP\", `${skippedCount} source(s) without a name were left out`);\n } else if (entries.length === 0) reportNodeStatus(\"empty\", \"NO_DATA\", \"the SourceRef has no source to show\");\n else reportNodeStatus(\"mounted\");\n }, [reportNodeStatus, isPending, isList, cutCount, skippedCount, entries.length, maxEntries]);\n\n if (isPending) return <SkeletonPill width={120} height={24} />;\n if (entries.length === 0) return null;\n if (sizeClass !== \"compact\") {\n return (\n <span className={styles.sourceRef} data-testid={testId}>\n <SourceList entries={entries} isEmailRender={isEmailRender} testId={testId} />\n </span>\n );\n }\n const [firstEntry] = entries;\n const otherSourcesCount = entries.length - 1;\n if (otherSourcesCount === 0 && !hasAttribution(firstEntry)) {\n return (\n <span className={styles.sourceRef} data-testid={testId}>\n <SourceChip entry={firstEntry} isEmailRender={isEmailRender} testId={`${testId}-chip-0`} />\n </span>\n );\n }\n return (\n <span className={styles.sourceRef} data-testid={testId}>\n <button\n type=\"button\"\n className={classNames(styles.chip, styles.toggleChip)}\n aria-expanded={isExpanded}\n aria-controls={expandedListId}\n disabled={isEmailRender}\n data-testid={`${testId}-toggle`}\n onClick={() => setIsExpanded((wasExpanded) => !wasExpanded)}\n >\n <SiteFavicon hostname={firstEntry.hostname} siteName={firstEntry.name} isEmailRender={isEmailRender} />\n <Text\n role=\"caption\"\n weight=\"medium\"\n translate={false}\n className={styles.chipName}\n >\n {escapePlainTextForText(firstEntry.name)}\n </Text>\n {otherSourcesCount > 0 ? (\n <Text role=\"caption\" translate={false} color=\"--agents-fg-light\" className={styles.moreCount}>\n {`+${otherSourcesCount}`}\n </Text>\n ) : null}\n <Icon color=\"var(--agents-fg-light)\" pixelSize={12} name={isExpanded ? \"caretUp\" : \"caretDown\"} />\n </button>\n {isExpanded ? (\n <span id={expandedListId} className={styles.expandedList} data-testid={`${testId}-expanded`}>\n <SourceList entries={entries} isEmailRender={isEmailRender} testId={`${testId}-expanded`} />\n </span>\n ) : null}\n </span>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = {\n nodeType: \"SourceRef\",\n component: SourceRefNode,\n};\n","import { Text } from \"../../../provider/components\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport { readComposedViewTone } from \"../../composed-view-tones\";\nimport {\n readAllowedValue,\n readTextNodeContent,\n TextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Text.module.scss\";\n\nconst TEXT_WEIGHTS = [\"regular\", \"medium\", \"bold\"] as const;\nconst FONT_WEIGHT_BY_TEXT_WEIGHT = {\n regular: \"regular\",\n medium: \"medium\",\n bold: \"bold\",\n} as const;\nconst MAX_CLAMPED_LINES = 10;\n\n/** `maxLines` within 1–10, else no clamp. */\nconst readMaxLines = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 1\n ? Math.min(Math.floor(value), MAX_CLAMPED_LINES)\n : undefined;\n\n/**\n * Whether the clamped run cuts its text off — measured on the element, again whenever its width changes (a narrower pane\n * clamps a text that fit before).\n */\nconst useIsTextCutOff = (isClamped: boolean, clampedText: string | null) => {\n const clampedRunRef = useRef<HTMLSpanElement>(null);\n const [isCutOff, setIsCutOff] = useState(false);\n useEffect(() => {\n const clampedRun = clampedRunRef.current;\n if (!isClamped || clampedText === null || !clampedRun) {\n setIsCutOff(false);\n return undefined;\n }\n const measureCutOff = () => setIsCutOff(clampedRun.scrollHeight > clampedRun.clientHeight + 1);\n measureCutOff();\n if (typeof ResizeObserver === \"undefined\") return undefined;\n const resizeObserver = new ResizeObserver(measureCutOff);\n resizeObserver.observe(clampedRun);\n return () => resizeObserver.disconnect();\n }, [isClamped, clampedText]);\n return { clampedRunRef, isCutOff };\n};\n\n/**\n * The `Text` node (`TextComposedViewNode.php`): plain text — a paragraph, or an inline run when it sits in\n * a compact slot (inside another `Text`, a table cell). Its children are inline nodes that follow the text on the same\n * line (a `Badge`, a `Link`, a `SourceRef` chip). `tone` picks the muted or a judgement colour, `maxLines` clamps a\n * long text, keeps the whole of it on hover and — when the clamp cut something off — offers \"Show more\" / \"Show less\"\n * below the paragraph, so a touch screen reaches the whole text too (the e-mail capture shows the clamp alone). The model's words are never translated and never parsed as markup.\n */\nconst TextNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, slots, sizeClass, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const childNodes = slots.children ?? [];\n const weight = readAllowedValue(nodeProps.weight, TEXT_WEIGHTS, \"regular\");\n const tone = readComposedViewTone(nodeProps.tone);\n const maxLines = readMaxLines(nodeProps.maxLines);\n const isInline = sizeClass === \"compact\";\n const [isExpanded, setIsExpanded] = useState(false);\n const isClamped = maxLines !== undefined && !isExpanded;\n const { clampedRunRef, isCutOff } = useIsTextCutOff(\n isClamped,\n content.kind === \"text\" && !isPending ? content.text : null,\n );\n const isShowingClampToggle =\n !isInline && !runtime.isEmailRender && maxLines !== undefined && (isCutOff || isExpanded);\n let renderState: TextNodeRenderState = \"shown\";\n if (isPending) renderState = \"pending\";\n else if (content.kind === \"invalid\") renderState = \"invalid\";\n else if (content.kind === \"missing\" && childNodes.length === 0) renderState = \"empty\";\n useReportTextNodeRenderState(runtime, renderState, \"Text\");\n\n if (isPending) {\n return isInline ? (\n <span className={styles.inlineSkeleton}>\n <SkeletonLine width=\"6em\" height={12} radius={4} />\n </span>\n ) : (\n <SkeletonLine width=\"80%\" height={14} radius={4} />\n );\n }\n if (renderState !== \"shown\") return null;\n const Wrapper = isInline ? \"span\" : \"div\";\n return (\n <Wrapper\n className={classNames(styles.text, isInline ? styles.inline : styles.paragraph, styles[tone])}\n data-testid={testId}\n >\n {content.kind === \"text\" ? (\n <span\n ref={clampedRunRef}\n className={isClamped ? classNames(styles.clamped, styles[`clampedAt${maxLines}Lines`]) : undefined}\n title={isClamped ? content.text : undefined}\n >\n <Text\n role=\"body\"\n weight={FONT_WEIGHT_BY_TEXT_WEIGHT[weight]}\n translate={false}\n display=\"inline\"\n color=\"--agents-text-node-tone-color\"\n >\n {escapePlainTextForText(content.text)}\n </Text>\n </span>\n ) : null}\n {childNodes.map((childNode, childIndex) => (\n <span key={childIndex} className={styles.inlineChild}>\n {childNode}\n </span>\n ))}\n {isShowingClampToggle ? (\n <button\n type=\"button\"\n className={styles.clampToggle}\n data-testid={`${testId}-toggle`}\n aria-expanded={isExpanded}\n onClick={() => setIsExpanded((wasExpanded) => !wasExpanded)}\n >\n <Text role=\"caption\" weight=\"medium\" color=\"var(--agents-fg-light)\">\n {isExpanded ? \"Show less\" : \"Show more\"}\n </Text>\n </button>\n ) : null}\n </Wrapper>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Text\", component: TextNode };\n","import { Text } from \"../../../provider/components\";\nimport { escapePlainTextForText } from \"../../../provider/environment\";\nimport { SkeletonLine } from \"../../../widgets/_shared/skeleton-primitives\";\nimport type { ComposedViewComponentDefinition, ComposedViewComponentProps } from \"../../composed-view-component-types\";\nimport {\n readAllowedValue,\n readTextNodeContent,\n readTextNodeRenderState,\n useReportTextNodeRenderState,\n} from \"./shared/text-node-values\";\nimport styles from \"./Title.module.scss\";\n\nconst TITLE_LEVELS = [\"widget\", \"section\"] as const;\n\n/**\n * The `Title` node (`TitleComposedViewNode.php`): the heading of the view (`widget`, the card title —\n * `textIntro` bold) or of one part of it (`section`, `text` bold). The model's words, never\n * translated; a skeleton while a bound text waits for its data.\n */\nconst TitleNode = (props: ComposedViewComponentProps) => {\n const { props: nodeProps, isPending, runtime, testId } = props;\n const content = readTextNodeContent(nodeProps.text);\n const level = readAllowedValue(nodeProps.level, TITLE_LEVELS, \"widget\");\n useReportTextNodeRenderState(runtime, readTextNodeRenderState(isPending, content), \"Title\");\n if (isPending) return <SkeletonLine width=\"40%\" height={level === \"widget\" ? 20 : 16} radius={4} />;\n if (content.kind !== \"text\") return null;\n return (\n <Text\n role={level === \"widget\" ? \"intro\" : \"body\"}\n weight=\"bold\"\n translate={false}\n className={styles.title}\n testId={testId}\n headingLevel={level === \"widget\" ? 3 : 4}\n >\n {escapePlainTextForText(content.text)}\n </Text>\n );\n};\n\nexport const composedViewComponent: ComposedViewComponentDefinition = { nodeType: \"Title\", component: TitleNode };\n","import { createContext, useContext } from \"react\";\nimport type { ComposedViewComponentDefinition } from \"./composed-view-component-types\";\n\n/**\n * The kit's component registry: every `components/**\\/*.composed.tsx` that exports\n * `composedViewComponent` registers itself by folder glob — a component is added with one new file and edits no list.\n * A second component for one node type is a build error (thrown at module load, caught by the spec).\n */\nconst componentModules = import.meta.glob<{ composedViewComponent?: ComposedViewComponentDefinition }>(\n \"./components/**/*.composed.tsx\",\n { eager: true },\n);\n\nexport const buildComposedViewComponentRegistry = (\n definitions: ComposedViewComponentDefinition[],\n): Readonly<Record<string, ComposedViewComponentDefinition>> => {\n const registry: Record<string, ComposedViewComponentDefinition> = {};\n for (const definition of definitions) {\n if (Object.prototype.hasOwnProperty.call(registry, definition.nodeType)) {\n throw new Error(`Two ComposedView components register the node type \"${definition.nodeType}\".`);\n }\n registry[definition.nodeType] = definition;\n }\n return registry;\n};\n\n/** Node type → component, from the folder. */\nexport const composedViewComponents = buildComposedViewComponentRegistry(\n Object.values(componentModules)\n .map((componentModule) => componentModule.composedViewComponent)\n .filter((definition): definition is ComposedViewComponentDefinition => definition !== undefined),\n);\n\n/** The registry the renderer uses — the folder's by default; a story or a spec may provide its own stub components. */\nexport const ComposedViewComponentsContext =\n createContext<Readonly<Record<string, ComposedViewComponentDefinition>>>(composedViewComponents);\n\nexport const useComposedViewComponents = () => useContext(ComposedViewComponentsContext);\n","import React from \"react\";\n\ninterface ComposedViewSlotErrorBoundaryProps {\n /** Where the node sits in the tree (`view.children[2]`), for the report. */\n nodePath: string;\n nodeType: string;\n onRenderFailed: (nodePath: string, nodeType: string) => void;\n children: React.ReactNode;\n}\n\ninterface ComposedViewSlotErrorBoundaryState {\n hasFailed: boolean;\n}\n\n/**\n * One node of a `ComposedView` tree inside its own error boundary (per-slot context): a node that throws\n * renders nothing and is reported `failed` (`RENDER_FAILED`), the rest of the tree stays. React error boundaries\n * require a class.\n */\nexport class ComposedViewSlotErrorBoundary extends React.Component<\n ComposedViewSlotErrorBoundaryProps,\n ComposedViewSlotErrorBoundaryState\n> {\n state: ComposedViewSlotErrorBoundaryState = { hasFailed: false };\n\n static getDerivedStateFromError(): ComposedViewSlotErrorBoundaryState {\n return { hasFailed: true };\n }\n\n componentDidCatch(error: Error): void {\n console.error(`[ComposedView] node ${this.props.nodeType} at ${this.props.nodePath} crashed`, error);\n this.props.onRenderFailed(this.props.nodePath, this.props.nodeType);\n }\n\n render(): React.ReactNode {\n return this.state.hasFailed ? null : this.props.children;\n }\n}\n","import { useEffect, useState } from \"react\";\n\n/** The value as it was `delayMs` after its last change. */\nexport const useDebouncedValue = <T>(value: T, delayMs: number): T => {\n const [debouncedValue, setDebouncedValue] = useState(value);\n useEffect(() => {\n const timer = setTimeout(() => setDebouncedValue(value), delayMs);\n return () => clearTimeout(timer);\n }, [value, delayMs]);\n return debouncedValue;\n};\n","import { useEffect, useMemo, useState } from \"react\";\nimport { useDebouncedValue } from \"./hooks/use-debounced-value\";\nimport { useWidgetHydration } from \"../renderer/widget-hydration\";\nimport {\n composedViewDataSourceHydrationType,\n ComposedViewDataSourcePayload,\n ComposedViewSourceBinding,\n hasComposedViewDataSourceFetcher,\n resolveComposedViewSourceParams,\n} from \"../renderer/widget-tree/composed-view-data-sources\";\nimport type { ExpressionValue } from \"../renderer/widget-tree/expression/evaluate-expression\";\nimport type { ComposedViewSourceValue } from \"../renderer/widget-tree/resolve-composed-view-values\";\n\n/** State-bound parameters settle for this long before the source is read again (a dragged slider reads once). */\nconst PARAM_DEBOUNCE_MS = 300;\n\ninterface ComposedViewDataSourceLoaderProps {\n sourceBinding: ComposedViewSourceBinding;\n state: Record<string, ExpressionValue>;\n agentSpaceKey: number | undefined;\n /** Whether this tree may start another read (the per-tree budget); a refused change keeps the last parameters. */\n mayRead: () => boolean;\n onValue: (bindingKey: string, sourceValue: ComposedViewSourceValue) => void;\n}\n\n/**\n * Reads ONE `$source` binding of a tree through the widget-hydration mechanism and hands the rows up.\n * Renders nothing; one component per binding, so the number of hooks never depends on the tree. The hydration reads\n * again whenever the payload changes, so a parameter change is first debounced, then counted against the tree's budget\n * (`maxSourceRequestsPerTreePerMinute`); a refused change keeps the rows of the last accepted parameters. A source\n * without a registered frontend fetcher fails at once (`UNRESOLVED_BINDING` in the report).\n */\nexport const ComposedViewDataSourceLoader = (props: ComposedViewDataSourceLoaderProps) => {\n const { sourceBinding, state, agentSpaceKey, mayRead, onValue } = props;\n const resolvedParams = useMemo(\n () => resolveComposedViewSourceParams(sourceBinding.writtenParams, state),\n [sourceBinding.writtenParams, state],\n );\n const debouncedParams = useDebouncedValue(resolvedParams, PARAM_DEBOUNCE_MS);\n const debouncedParamsJson = JSON.stringify(debouncedParams);\n const [acceptedPayload, setAcceptedPayload] = useState<ComposedViewDataSourcePayload>(() => ({\n params: resolvedParams,\n agentSpaceKey,\n }));\n\n useEffect(() => {\n const isUnchanged =\n JSON.stringify(acceptedPayload.params) === debouncedParamsJson && acceptedPayload.agentSpaceKey === agentSpaceKey;\n if (isUnchanged || !mayRead()) return;\n setAcceptedPayload({ params: JSON.parse(debouncedParamsJson) as Record<string, ExpressionValue>, agentSpaceKey });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- reacts to the settled parameters only\n }, [debouncedParamsJson, agentSpaceKey]);\n\n const isRegistered = hasComposedViewDataSourceFetcher(sourceBinding.dataSourceName);\n const hydration = useWidgetHydration<ExpressionValue[], ComposedViewDataSourcePayload>(\n composedViewDataSourceHydrationType(isRegistered ? sourceBinding.dataSourceName : \"unregistered\"),\n acceptedPayload,\n { showLastDataWhileRefreshing: true },\n );\n\n useEffect(() => {\n if (!isRegistered || hydration.isError) {\n onValue(sourceBinding.bindingKey, { status: \"failed\", value: undefined });\n } else if (hydration.data !== null) {\n onValue(sourceBinding.bindingKey, { status: \"resolved\", value: hydration.data });\n } else {\n onValue(sourceBinding.bindingKey, { status: \"pending\", value: undefined });\n }\n }, [isRegistered, hydration.isError, hydration.data, sourceBinding.bindingKey, onValue]);\n\n return null;\n};\n","import {\n ComposedViewTree,\n getComposedViewSubtreeNodes,\n readComposedViewBinding,\n} from \"../renderer/widget-tree/composed-view-tree\";\n\n/**\n * Which data paths of a `ComposedView` tree carry a time the report e-mail must state: the turn-time\n * `$from` snapshots (the tool results the backend wrote into the block when the report message was stored) and the\n * mail-time reads (a `$source` binding or an embedded domain widget, both read live while the e-mail is captured).\n * Inline data carries its own source line and no time.\n */\nexport interface ComposedViewDataTimes {\n /** The tree binds at least one `$from` tool result. */\n hasTurnTimeSnapshot: boolean;\n /**\n * The newest `resolvedAt` (ISO 8601) the persist-time resolution wrote into a resolved `$from` snapshot, when it\n * wrote one; otherwise undefined and the caption names the report time without a clock time.\n */\n turnTimeResolvedAt: string | undefined;\n /** The tree reads at least one `$source` or embeds a self-hydrating domain widget. */\n hasMailTimeRead: boolean;\n}\n\ninterface DataTimesCollection {\n hasTurnTimeSnapshot: boolean;\n newestResolvedAtMs: number | undefined;\n hasMailTimeRead: boolean;\n}\n\n/** The moment of a resolved `$from` snapshot, or undefined (no `resolvedAt`, or not a readable ISO moment). */\nconst readSnapshotResolvedAtMs = (fromBindingObject: unknown): number | undefined => {\n if (typeof fromBindingObject !== \"object\" || fromBindingObject === null || Array.isArray(fromBindingObject)) {\n return undefined;\n }\n const snapshot = fromBindingObject as Record<string, unknown>;\n if (snapshot.state !== \"resolved\" || typeof snapshot.resolvedAt !== \"string\") return undefined;\n const resolvedAtMs = Date.parse(snapshot.resolvedAt);\n return Number.isFinite(resolvedAtMs) ? resolvedAtMs : undefined;\n};\n\nconst collectDataTimesFromValue = (value: unknown, collection: DataTimesCollection): void => {\n const binding = readComposedViewBinding(value);\n if (binding !== null) {\n if (binding.kind === \"from\") {\n collection.hasTurnTimeSnapshot = true;\n const resolvedAtMs = readSnapshotResolvedAtMs(binding.wireValue.$from);\n if (resolvedAtMs !== undefined) {\n collection.newestResolvedAtMs = Math.max(collection.newestResolvedAtMs ?? resolvedAtMs, resolvedAtMs);\n }\n }\n if (binding.kind === \"source\") collection.hasMailTimeRead = true;\n return;\n }\n if (Array.isArray(value)) value.forEach((element) => collectDataTimesFromValue(element, collection));\n else if (typeof value === \"object\" && value !== null) {\n Object.values(value).forEach((nested) => collectDataTimesFromValue(nested, collection));\n }\n};\n\n/** The data paths with a time of a checked tree: its datasets and every node's props, embedded widgets included. */\nexport const readComposedViewDataTimes = (tree: ComposedViewTree): ComposedViewDataTimes => {\n const collection: DataTimesCollection = {\n hasTurnTimeSnapshot: false,\n newestResolvedAtMs: undefined,\n hasMailTimeRead: false,\n };\n collectDataTimesFromValue(tree.data, collection);\n const nodes = tree.view ? getComposedViewSubtreeNodes(tree.view) : [];\n for (const node of nodes) {\n if (node.type === \"Widget\") collection.hasMailTimeRead = true;\n collectDataTimesFromValue(node.props, collection);\n }\n return {\n hasTurnTimeSnapshot: collection.hasTurnTimeSnapshot,\n turnTimeResolvedAt:\n collection.newestResolvedAtMs === undefined ? undefined : new Date(collection.newestResolvedAtMs).toISOString(),\n hasMailTimeRead: collection.hasMailTimeRead,\n };\n};\n","import { Text } from \"../../provider/components\";\nimport { useMemo, useState } from \"react\";\nimport { useAgentsOwnerSettings } from \"../../provider/AgentsProvider\";\nimport { translateText } from \"../../provider/environment\";\nimport type { ComposedViewTree } from \"../../renderer/widget-tree/composed-view-tree\";\nimport { readComposedViewDataTimes } from \"../composed-view-data-times\";\nimport styles from \"./ComposedViewEmailDataTimes.module.scss\";\n\nconst FALLBACK_DATE_LOCALE = \"en-GB\";\n\n/** A moment in the owner's date locale and zone (`25.10.2026, 08:00`); without a usable zone, the capture's own. */\nexport const formatDataTime = (moment: Date, dateLocale: string, timeZone: string | null | undefined): string => {\n const formatOptions: Intl.DateTimeFormatOptions = { dateStyle: \"medium\", timeStyle: \"short\" };\n try {\n return new Intl.DateTimeFormat(dateLocale, timeZone ? { ...formatOptions, timeZone } : formatOptions).format(\n moment,\n );\n } catch {\n return new Intl.DateTimeFormat(FALLBACK_DATE_LOCALE, formatOptions).format(moment);\n }\n};\n\nexport interface ComposedViewEmailDataTimesProps {\n tree: ComposedViewTree;\n}\n\n/**\n * The time of each data path of an e-mailed `ComposedView`, as ONE caption line under the tree: a report\n * mail mixes the tool results written into the block at turn time (`$from`) with data read live while the mail is\n * captured (`$source`, embedded domain widgets) — the reader must know which numbers are from when. The turn time is\n * the `resolvedAt` the resolution wrote into the snapshot; the mail time is the capture moment, fixed at the first\n * render. Each phrase is its own translation key; the phrases are joined by a middle dot. A tree with inline data only\n * shows no line.\n */\nexport const ComposedViewEmailDataTimes = (props: ComposedViewEmailDataTimesProps) => {\n const { tree } = props;\n const dataTimes = useMemo(() => readComposedViewDataTimes(tree), [tree]);\n const [captureMoment] = useState(() => new Date());\n // The owner's settings come from the app, read defensively: the capture store is a partial copy of the app's.\n const { dateLocale: ownerDateLocale, locale: ownerLocale, timeZone } = useAgentsOwnerSettings();\n const dateLocale = ownerDateLocale || ownerLocale || FALLBACK_DATE_LOCALE;\n\n const phrases: string[] = [];\n if (dataTimes.hasTurnTimeSnapshot) {\n phrases.push(\n dataTimes.turnTimeResolvedAt === undefined\n ? translateText(\"Conversation data as of the time of the report\")\n : translateText(\"Conversation data as of %dataTime%\", {\n dataTime: formatDataTime(new Date(dataTimes.turnTimeResolvedAt), dateLocale, timeZone),\n }),\n );\n }\n if (dataTimes.hasMailTimeRead) {\n phrases.push(\n translateText(\"Live data as of %dataTime%\", {\n dataTime: formatDataTime(captureMoment, dateLocale, timeZone),\n }),\n );\n }\n if (phrases.length === 0) return null;\n return (\n <div className={styles.dataTimes} data-testid=\"composed-view-email-data-times\">\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {phrases.join(\" · \")}\n </Text>\n </div>\n );\n};\n","import { Text } from \"../provider/components\";\nimport React, { useCallback, useEffect, useMemo, useReducer, useRef } from \"react\";\nimport { stringifyWithinLimit } from \"../renderer/widget-tree/bounded-json\";\nimport {\n composedNodeSchema,\n ComposedSizeClass,\n getComposedNodeSchema,\n resolveComposedSlotForNodeProps,\n} from \"../renderer/widget-tree/composed-node-schema\";\nimport {\n ComposedViewAction,\n ComposedViewLiftedWidget,\n ComposedViewNode,\n ComposedViewTree,\n isComposedViewWithoutContent,\n} from \"../renderer/widget-tree/composed-view-tree\";\nimport {\n isRowBoundOpenEntityAction,\n readOpenEntityActionTarget,\n} from \"../renderer/canvas/entity-detail-instance\";\nimport {\n computeComposedViewValues,\n ExpressionValue,\n} from \"../renderer/widget-tree/expression/evaluate-expression\";\nimport { useComposedViewState } from \"../renderer/widget-tree/use-composed-view-state\";\nimport { collectComposedViewSourceBindings } from \"../renderer/widget-tree/composed-view-data-sources\";\nimport {\n ComposedViewSourceValue,\n ComposedViewValueScope,\n resolveComposedViewDatasets,\n resolveComposedViewValue,\n ResolvedBindingStatus,\n} from \"../renderer/widget-tree/resolve-composed-view-values\";\nimport type {\n WidgetRenderReportCode,\n WidgetRenderReportEntry,\n WidgetRenderStatus,\n} from \"../renderer/render-report/widget-render-report\";\nimport type { ComposedViewRuntime } from \"./composed-view-component-types\";\nimport { useComposedViewComponents } from \"./composed-view-components\";\nimport { ComposedViewSlotErrorBoundary } from \"./ComposedViewSlotErrorBoundary\";\nimport { ComposedViewDataSourceLoader } from \"./ComposedViewDataSourceLoader\";\nimport { EmbeddedConversationWidget } from \"./components/embedding/EmbeddedConversationWidget\";\nimport { ModelText } from \"./ModelText/ModelText\";\nimport { ComposedViewEmailDataTimes } from \"../image-render/ComposedViewEmailDataTimes/ComposedViewEmailDataTimes\";\nimport styles from \"./ComposedViewConversationWidget.module.scss\";\n\n/**\n * Renders a checked `ComposedView` tree: one state store per instance, the datasets and computed\n * values for the current state, then the node tree — each node through its registered component, each slot node in its\n * own error boundary, the slot's size class handed down. The renderer folds the tree's findings, the expression\n * errors, the nodes' own reports and the pending bindings into ONE block status for the render report. A finding that\n * drops nothing (the schema's `noteFindingCodes`: figures without a source, a choice state outside its choices, a set\n * state nothing reads, an `$item` field the rows lack, a slot under its minimum) never fails the block: a block that rendered reports `mounted`\n * with that code as a note, which the chat tells the model.\n */\n\nexport interface ComposedViewRendererProps {\n tree: ComposedViewTree;\n interactive: boolean;\n isEmailRender: boolean;\n messageId?: string | number;\n agentSpaceKey?: string | number;\n /** The block status, whenever it changes. */\n onReport: (entry: WidgetRenderReportEntry) => void;\n /**\n * Runs an `openEntity` action — the `entityDetail` canvas. A platform-minted reference carries the entity the backend\n * resolved it to; a row-bound action (`ref: {\"$item\":\"entityRef\"}`) comes with `currentRow`, the row it fired in,\n * whose `entity` it opens (`readOpenEntityActionTarget(action, currentRow)`).\n */\n onOpenEntity?: (action: ComposedViewAction, currentRow?: ExpressionValue) => void;\n testId?: string;\n}\n\ntype NodeReportAction = {\n nodePath: string;\n status: WidgetRenderStatus;\n code?: WidgetRenderReportCode;\n detail?: string;\n};\ntype NodeReports = Record<string, Omit<NodeReportAction, \"nodePath\">>;\n\nconst nodeReportsReducer = (nodeReports: NodeReports, action: NodeReportAction): NodeReports => {\n const current = nodeReports[action.nodePath];\n if (current && current.status === action.status && current.code === action.code && current.detail === action.detail) {\n return nodeReports;\n }\n return { ...nodeReports, [action.nodePath]: { status: action.status, code: action.code, detail: action.detail } };\n};\n\ntype SourceValueAction = { bindingKey: string; sourceValue: ComposedViewSourceValue };\ntype SourceValues = Record<string, ComposedViewSourceValue>;\n\nconst sourceValuesReducer = (sourceValues: SourceValues, action: SourceValueAction): SourceValues => {\n const current = sourceValues[action.bindingKey];\n if (current && current.status === action.sourceValue.status && current.value === action.sourceValue.value) {\n return sourceValues;\n }\n return { ...sourceValues, [action.bindingKey]: action.sourceValue };\n};\n\nconst SOURCE_BUDGET_WINDOW_MS = 60_000;\n\nconst MAX_DETAIL_FINDINGS = 5;\n\n/**\n * The first node report of `status`, its detail prefixed with the node's path (`view.children[1]: ExampleWidget: …`)\n * unless the detail names it already — the model learns WHICH cell of a dashboard failed or showed nothing.\n */\nconst findNodeReportWithItsPath = (\n nodeReports: NodeReports,\n status: WidgetRenderStatus,\n): WidgetRenderReportEntry | undefined => {\n const nodeReportEntry = Object.entries(nodeReports).find(([, nodeReport]) => nodeReport.status === status);\n if (!nodeReportEntry) return undefined;\n const [nodePath, nodeReport] = nodeReportEntry;\n const detail = nodeReport.detail ?? \"\";\n return { ...nodeReport, detail: detail.includes(nodePath) ? detail : `${nodePath}: ${detail}`.replace(/: $/, \"\") };\n};\n\n/** The finding codes that drop nothing (`ComposedViewValidationFinding::NOTE_CODES`): the block mounts with a note. */\nconst NOTE_FINDING_CODES: readonly string[] = composedNodeSchema.noteFindingCodes ?? [\"INLINE_VALUE_WITHOUT_SOURCE\"];\n\n/**\n * The rendered-node budget of ONE render pass (`maxRenderedNodes`): every node view counts itself; past the budget a\n * node renders nothing and the renderer reports `BUDGET_EXCEEDED` once the pass is committed. A `Repeat` multiplies its\n * template, so this — not the node count of the tree — is what bounds the DOM.\n */\ninterface RenderedNodeBudget {\n renderedNodeCount: number;\n isExceeded: boolean;\n}\n\ninterface ComposedViewNodeViewProps {\n node: ComposedViewNode;\n nodePath: string;\n sizeClass: ComposedSizeClass;\n scope: ComposedViewValueScope;\n runtime: ComposedViewRuntime;\n reportNodeStatus: (\n nodePath: string,\n status: WidgetRenderStatus,\n code?: WidgetRenderReportCode,\n detail?: string,\n ) => void;\n /** Reports a node that threw (from its slot boundary). */\n onRenderFailed: (nodePath: string, nodeType: string) => void;\n renderedNodeBudget: RenderedNodeBudget;\n testId: string;\n}\n\nconst toTestIdSegment = (rawSegment: string) => rawSegment.replace(/[^a-zA-Z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n\nconst ComposedViewNodeView = (props: ComposedViewNodeViewProps) => {\n const { node, nodePath, sizeClass, scope, runtime, reportNodeStatus, onRenderFailed, renderedNodeBudget, testId } =\n props;\n const components = useComposedViewComponents();\n const maxRepeatRows = composedNodeSchema.budgets.maxRepeatRows;\n let isOverRepeatRows = false;\n renderedNodeBudget.renderedNodeCount += 1;\n const isOverRenderedNodes = renderedNodeBudget.renderedNodeCount > composedNodeSchema.budgets.maxRenderedNodes;\n if (isOverRenderedNodes) renderedNodeBudget.isExceeded = true;\n const definition = Object.prototype.hasOwnProperty.call(components, node.type) ? components[node.type] : undefined;\n const nodeTypeSchema = getComposedNodeSchema().nodeTypes[node.type];\n\n useEffect(() => {\n if (!definition)\n reportNodeStatus(nodePath, \"failed\", \"INVALID_NODE\", `no component renders the node type ${node.type}`);\n }, [definition, node.type, nodePath, reportNodeStatus]);\n // Runs after the component rendered its items, so it sees whether it asked for more than `maxRepeatRows`.\n useEffect(() => {\n if (isOverRepeatRows) {\n reportNodeStatus(\n nodePath,\n \"failed\",\n \"BUDGET_EXCEEDED\",\n `${node.type} shows the first ${maxRepeatRows} rows only`,\n );\n }\n });\n\n const currentRow = scope.item;\n const nodeRuntime = useMemo<ComposedViewRuntime>(\n () => ({\n ...runtime,\n currentRow,\n // An event of a node in an item scope fires in that scope's row, unless the node names the row itself (a Map point).\n runEvent: (eventWireValue: unknown, eventValue?: unknown, eventRow?: ExpressionValue) =>\n runtime.runEvent(eventWireValue, eventValue, eventRow !== undefined ? eventRow : currentRow),\n reportNodeStatus: (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n reportNodeStatus(nodePath, status, code, detail),\n }),\n [runtime, currentRow, reportNodeStatus, nodePath],\n );\n\n let isPending = false;\n const markBindingStatus = (status: ResolvedBindingStatus) => {\n if (status === \"pending\") isPending = true;\n };\n const resolvedProps: Record<string, ExpressionValue> = {};\n for (const [propName, propValue] of Object.entries(node.props)) {\n resolvedProps[propName] = resolveComposedViewValue(propValue, scope, markBindingStatus);\n }\n\n const renderSlotNodes = (slotName: string, slotScope: ComposedViewValueScope, keySuffix = \"\"): React.ReactNode[] => {\n // The slot of this node: a Grid's cells narrow with its `columns` (1 full, 2 regular, 3–4 compact).\n const declaredSlot = nodeTypeSchema?.slots.find((slot) => slot.name === slotName);\n const slotSizeClass = (\n declaredSlot ? resolveComposedSlotForNodeProps(declaredSlot, node.props).sizeClass : \"regular\"\n ) as ComposedSizeClass;\n const slotPathSegment = slotName === \"children\" ? \"children\" : `slots.${slotName}`;\n return (node.nodesBySlotName[slotName] ?? []).map((slotNode, slotPosition) => {\n const slotNodePath = `${nodePath}.${slotPathSegment}[${slotPosition}]${keySuffix}`;\n return (\n <ComposedViewSlotErrorBoundary\n key={slotNodePath}\n nodePath={slotNodePath}\n nodeType={slotNode.type}\n onRenderFailed={onRenderFailed}\n >\n <ComposedViewNodeView\n node={slotNode}\n nodePath={slotNodePath}\n sizeClass={slotSizeClass}\n scope={slotScope}\n runtime={runtime}\n reportNodeStatus={reportNodeStatus}\n onRenderFailed={onRenderFailed}\n renderedNodeBudget={renderedNodeBudget}\n testId={testId}\n />\n </ComposedViewSlotErrorBoundary>\n );\n });\n };\n\n if (!definition || isOverRenderedNodes) return null;\n const providesItemScope = nodeTypeSchema?.providesItemScope ?? false;\n const slots: Record<string, React.ReactNode[]> = {};\n if (!providesItemScope) {\n for (const slotName of Object.keys(node.nodesBySlotName)) slots[slotName] = renderSlotNodes(slotName, scope);\n }\n // A repeating node renders at most `maxRepeatRows` items, whatever its component asks for (enforced here, not per component).\n const renderSlotForItem = (slotName: string, item: ExpressionValue, itemIndex: number) => {\n if (itemIndex >= maxRepeatRows) {\n isOverRepeatRows = true;\n return [];\n }\n return renderSlotNodes(slotName, { ...scope, item }, `#${itemIndex}`);\n };\n const Component = definition.component;\n return (\n <Component\n node={node}\n props={resolvedProps}\n isPending={isPending}\n slots={slots}\n sizeClass={sizeClass}\n renderSlotForItem={renderSlotForItem}\n runtime={nodeRuntime}\n testId={`${testId}-${toTestIdSegment(node.type).toLowerCase()}-${toTestIdSegment(node.id ?? nodePath).toLowerCase()}`}\n />\n );\n};\n\ninterface ComposedViewLiftedWidgetViewProps {\n liftedWidget: ComposedViewLiftedWidget;\n interactive: boolean;\n messageId?: string | number;\n agentSpaceKey?: string | number;\n reportNodeStatus: ComposedViewNodeViewProps[\"reportNodeStatus\"];\n}\n\n/**\n * A widget the reader LIFTED out of the tree: shown after the view as its own widget, at full\n * width, reporting into the block at `lifted <path>`. A stored row lifts nothing — the backend rewrites the row before\n * it is stored — so this renders the trees of rows stored before the lift and of a reply still on its way.\n */\nconst ComposedViewLiftedWidgetView = (props: ComposedViewLiftedWidgetViewProps) => {\n const { liftedWidget, interactive, messageId, agentSpaceKey, reportNodeStatus } = props;\n const liftedPath = `lifted ${liftedWidget.path}`;\n const reportStatus = useCallback(\n (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n reportNodeStatus(liftedPath, status, code, detail),\n [reportNodeStatus, liftedPath],\n );\n return (\n <EmbeddedConversationWidget\n widgetName={liftedWidget.widget}\n fields={liftedWidget.fields}\n agentSpaceKey={agentSpaceKey}\n interactive={interactive}\n messageId={messageId}\n reportStatus={reportStatus}\n />\n );\n};\n\n/** The one muted line of a view left with nothing to show — never a title over an empty Grid. */\nconst ComposedViewNothingToShow = () => (\n <Text role=\"help\" color=\"var(--agents-fg-light)\">\n This view has nothing to show right now.\n </Text>\n);\n\n/** The `ComposedView` tree, rendered. */\nexport const ComposedViewRenderer = (props: ComposedViewRendererProps) => {\n const {\n tree,\n interactive,\n isEmailRender,\n messageId,\n agentSpaceKey,\n onReport,\n onOpenEntity,\n testId = \"composed-view-widget\",\n } = props;\n const budgets = composedNodeSchema.budgets;\n const { state, setStateValue, resetState } = useComposedViewState(tree, budgets);\n const [nodeReports, dispatchNodeReport] = useReducer(nodeReportsReducer, {});\n const [sourceValues, dispatchSourceValue] = useReducer(sourceValuesReducer, {});\n const renderedNodeBudget: RenderedNodeBudget = { renderedNodeCount: 0, isExceeded: false };\n useEffect(() => {\n if (renderedNodeBudget.isExceeded) {\n dispatchNodeReport({\n nodePath: \"view\",\n status: \"failed\",\n code: \"BUDGET_EXCEEDED\",\n detail: `more than ${budgets.maxRenderedNodes} rendered nodes — the rest is not shown`,\n });\n }\n });\n const sourceBindings = useMemo(() => collectComposedViewSourceBindings(tree), [tree]);\n const sourceReadTimesRef = useRef<number[]>([]);\n\n /** The per-tree read budget: every source read after the first one of each binding counts against it. */\n const mayReadSource = useCallback(() => {\n const now = Date.now();\n sourceReadTimesRef.current = sourceReadTimesRef.current.filter(\n (readTime) => now - readTime < SOURCE_BUDGET_WINDOW_MS,\n );\n if (sourceReadTimesRef.current.length >= budgets.maxSourceRequestsPerTreePerMinute) return false;\n sourceReadTimesRef.current.push(now);\n return true;\n }, [budgets.maxSourceRequestsPerTreePerMinute]);\n const onSourceValue = useCallback(\n (bindingKey: string, sourceValue: ComposedViewSourceValue) => dispatchSourceValue({ bindingKey, sourceValue }),\n [],\n );\n const sourceAgentSpaceKey = agentSpaceKey === undefined || agentSpaceKey === \"\" ? undefined : Number(agentSpaceKey);\n\n const resolvedDatasets = useMemo(\n () => resolveComposedViewDatasets(tree.data, sourceValues),\n [tree.data, sourceValues],\n );\n const computedValues = useMemo(\n () => computeComposedViewValues(tree.computed, state, resolvedDatasets.datasets, budgets),\n [tree.computed, state, resolvedDatasets.datasets, budgets],\n );\n\n const writeStateValue = useCallback(\n (stateName: string, value: unknown) => {\n if (!isEmailRender) setStateValue(stateName, value);\n },\n [isEmailRender, setStateValue],\n );\n\n const runAction = useCallback(\n (actionName: string, eventRow?: ExpressionValue) => {\n const action = Object.prototype.hasOwnProperty.call(tree.actions, actionName)\n ? tree.actions[actionName]\n : undefined;\n if (!action || isEmailRender) return;\n if (action.type === \"resetState\") resetState();\n if (action.type === \"openUrl\" && typeof action.url === \"string\") {\n window.open(action.url, \"_blank\", \"noopener,noreferrer\");\n }\n if (action.type === \"openEntity\" && isRowBoundOpenEntityAction(action)) {\n // The entity is the row's own — never one written on the action; a row without one opens nothing.\n if (readOpenEntityActionTarget(action, eventRow) === undefined) {\n dispatchNodeReport({\n nodePath: `actions.${actionName}`,\n status: \"failed\",\n code: \"UNRESOLVED_REF\",\n detail: `the openEntity action \"${actionName}\" fired in a row without a resolved entity — nothing opened`,\n });\n return;\n }\n onOpenEntity?.(action, eventRow);\n } else if (action.type === \"openEntity\" && typeof action.ref === \"string\") onOpenEntity?.(action);\n if (action.type === \"copy\") {\n const copiedValue = resolveComposedViewValue(action.value, {\n state,\n computed: computedValues.values,\n datasets: resolvedDatasets.datasets,\n datasetStatuses: resolvedDatasets.statusByDatasetName,\n sources: sourceValues,\n });\n // Bounded BEFORE it is built: a value shared many times over can be far larger as text than as a structure.\n const copiedText =\n typeof copiedValue === \"string\" ? copiedValue : stringifyWithinLimit(copiedValue, budgets.maxSourceBytes);\n if (copiedText === undefined) {\n dispatchNodeReport({\n nodePath: `actions.${actionName}`,\n status: \"failed\",\n code: \"BUDGET_EXCEEDED\",\n detail: `the value to copy is larger than ${budgets.maxSourceBytes} characters`,\n });\n return;\n }\n void navigator.clipboard?.writeText(copiedText);\n }\n },\n [\n tree.actions,\n isEmailRender,\n resetState,\n onOpenEntity,\n state,\n computedValues.values,\n resolvedDatasets.datasets,\n resolvedDatasets.statusByDatasetName,\n sourceValues,\n budgets.maxSourceBytes,\n ],\n );\n\n const reportNodeStatus = useCallback(\n (nodePath: string, status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n dispatchNodeReport({ nodePath, status, code, detail }),\n [],\n );\n const onRenderFailed = useCallback(\n (nodePath: string, nodeType: string) =>\n dispatchNodeReport({\n nodePath,\n status: \"failed\",\n code: \"RENDER_FAILED\",\n detail: `the ${nodeType} at ${nodePath} threw`,\n }),\n [],\n );\n\n const runtime = useMemo<ComposedViewRuntime>(\n () => ({\n state,\n setStateValue: writeStateValue,\n runEvent: (eventWireValue: unknown, eventValue?: unknown, eventRow?: ExpressionValue) => {\n if (typeof eventWireValue !== \"object\" || eventWireValue === null) return;\n const event = eventWireValue as { set?: unknown; action?: unknown };\n if (typeof event.set === \"string\") writeStateValue(event.set, eventValue);\n if (typeof event.action === \"string\") runAction(event.action, eventRow);\n },\n interactive,\n isEmailRender,\n messageId,\n agentSpaceKey,\n findAction: (actionName: string) =>\n Object.prototype.hasOwnProperty.call(tree.actions, actionName)\n ? (tree.actions[actionName] as Record<string, unknown>)\n : undefined,\n reportNodeStatus: (status: WidgetRenderStatus, code?: WidgetRenderReportCode, detail?: string) =>\n reportNodeStatus(\"view\", status, code, detail),\n }),\n [\n state,\n writeStateValue,\n runAction,\n interactive,\n isEmailRender,\n messageId,\n agentSpaceKey,\n tree.actions,\n reportNodeStatus,\n ],\n );\n\n const blockReport = useMemo<WidgetRenderReportEntry>(() => {\n const droppingFindings = tree.findings.filter((finding) => !NOTE_FINDING_CODES.includes(finding.code));\n // a view the lift took entirely leaves its lifted widgets: the block reports their notes, not \"no view\"\n if (tree.view === null && tree.liftedWidgets.length === 0) {\n return {\n status: \"failed\",\n code: droppingFindings[0]?.code ?? \"INVALID_NODE\",\n detail: \"the tree has no view to render\",\n };\n }\n if (droppingFindings.length > 0) {\n const findingLines = droppingFindings\n .slice(0, MAX_DETAIL_FINDINGS)\n .map((finding) => `${finding.code} at ${finding.path}: ${finding.message}`);\n return {\n status: \"failed\",\n code: droppingFindings[0].code,\n detail: `${droppingFindings.length} part(s) dropped, the rest rendered — ${findingLines.join(\"; \")}`,\n };\n }\n const expressionErrors = Object.entries(computedValues.errors);\n if (expressionErrors.length > 0) {\n const [computedName, expressionError] = expressionErrors[0];\n return {\n status: \"failed\",\n code: expressionError.errorCode,\n detail: `computed \"${computedName}\": ${expressionError.message}`,\n };\n }\n const failedNodeReport = findNodeReportWithItsPath(nodeReports, \"failed\");\n if (failedNodeReport) return failedNodeReport;\n const failedDataset = Object.entries(resolvedDatasets.statusByDatasetName).find(\n ([, status]) => status === \"failed\",\n );\n if (failedDataset) {\n return {\n status: \"failed\",\n code: \"UNRESOLVED_BINDING\",\n detail: `the dataset \"${failedDataset[0]}\" did not resolve`,\n };\n }\n const isPending =\n Object.values(resolvedDatasets.statusByDatasetName).includes(\"pending\") ||\n Object.values(nodeReports).some((nodeReport) => nodeReport.status === \"pending\");\n if (isPending) return { status: \"pending\" };\n const emptyNodeReport = findNodeReportWithItsPath(nodeReports, \"empty\");\n if (emptyNodeReport) return emptyNodeReport;\n // Rendered — but figures without a source are a NOTE the model reads, so its next tree names them.\n const unsourcedFindings = tree.findings.filter((finding) => finding.code === \"INLINE_VALUE_WITHOUT_SOURCE\");\n if (unsourcedFindings.length > 0) {\n return {\n status: \"mounted\",\n code: \"INLINE_VALUE_WITHOUT_SOURCE\",\n detail: `rendered, but ${unsourcedFindings.length} part(s) show figures without a source — ${unsourcedFindings\n .slice(0, MAX_DETAIL_FINDINGS)\n .map((finding) => `${finding.path}: ${finding.message}`)\n .join(\"; \")}`,\n };\n }\n // The other notes (a choice state outside its choices, a set state nothing reads, an `$item` field the rows lack).\n const noteFindings = tree.findings.filter((finding) => NOTE_FINDING_CODES.includes(finding.code));\n if (noteFindings.length > 0) {\n return {\n status: \"mounted\",\n code: noteFindings[0].code,\n detail: `rendered, but ${noteFindings.length} part(s) do not work as written — ${noteFindings\n .slice(0, MAX_DETAIL_FINDINGS)\n .map((finding) => `${finding.code} at ${finding.path}: ${finding.message}`)\n .join(\"; \")}`,\n };\n }\n return { status: \"mounted\" };\n }, [\n tree.findings,\n tree.view,\n tree.liftedWidgets.length,\n computedValues.errors,\n nodeReports,\n resolvedDatasets.statusByDatasetName,\n ]);\n\n useEffect(() => {\n onReport(blockReport);\n }, [blockReport, onReport]);\n\n const sourceLoaders = sourceBindings.map((sourceBinding) => (\n <ComposedViewDataSourceLoader\n key={sourceBinding.bindingKey}\n sourceBinding={sourceBinding}\n state={state}\n agentSpaceKey={sourceAgentSpaceKey}\n mayRead={mayReadSource}\n onValue={onSourceValue}\n />\n ));\n const liftedWidgetViews = tree.liftedWidgets.map((liftedWidget) => (\n <ComposedViewLiftedWidgetView\n key={liftedWidget.path}\n liftedWidget={liftedWidget}\n interactive={interactive}\n messageId={messageId}\n agentSpaceKey={agentSpaceKey}\n reportNodeStatus={reportNodeStatus}\n />\n ));\n if (tree.view === null) {\n // the lift took the whole view: only its widgets stand; nothing at all: one explicit line, never a blank block\n return (\n <div className={styles.root}>\n {sourceLoaders}\n {liftedWidgetViews.length > 0 ? liftedWidgetViews : <ComposedViewNothingToShow />}\n </div>\n );\n }\n // a layout that LOST all its content to the reader (a dropped or lifted node) shows the explicit line, never an\n // empty Grid; a layout written empty on purpose renders and reports `empty` itself\n const lostAllItsContent =\n isComposedViewWithoutContent(tree.view) &&\n tree.findings.some((finding) => !NOTE_FINDING_CODES.includes(finding.code) || finding.code === \"WIDGET_LIFTED\");\n const rootScope: ComposedViewValueScope = {\n state,\n computed: computedValues.values,\n datasets: resolvedDatasets.datasets,\n datasetStatuses: resolvedDatasets.statusByDatasetName,\n sources: sourceValues,\n };\n return (\n <div className={styles.root} data-testid={testId}>\n {sourceLoaders}\n {tree.title ? (\n <ModelText role=\"intro\" weight=\"bold\">\n {tree.title}\n </ModelText>\n ) : null}\n {lostAllItsContent ? (\n <ComposedViewNothingToShow />\n ) : (\n <ComposedViewSlotErrorBoundary nodePath=\"view\" nodeType={tree.view.type} onRenderFailed={onRenderFailed}>\n <ComposedViewNodeView\n node={tree.view}\n nodePath=\"view\"\n sizeClass=\"full\"\n scope={rootScope}\n runtime={runtime}\n reportNodeStatus={reportNodeStatus}\n onRenderFailed={onRenderFailed}\n renderedNodeBudget={renderedNodeBudget}\n testId={testId}\n />\n </ComposedViewSlotErrorBoundary>\n )}\n {liftedWidgetViews}\n {/* The e-mail states when each data path was read: turn-time `$from` vs mail-time `$source`. */}\n {isEmailRender ? <ComposedViewEmailDataTimes tree={tree} /> : null}\n </div>\n );\n};\n","import { useCallback, useMemo, useState } from \"react\";\nimport type { PayloadConversationWidgetProps } from \"../renderer/conversation-widget-props\";\nimport { useIsEmailWidgetRender } from \"../renderer/ConversationWidgetRenderContext\";\nimport { useConversationWidgetContext } from \"../renderer/ConversationWidgetCallbacksContext\";\nimport { readWidgetAgentSpaceKeyAttribute } from \"../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport { messageAnchor } from \"../renderer/canvas/canvas-state\";\nimport {\n canvasInstanceIdForEntityDetail,\n readOpenEntityActionTarget,\n} from \"../renderer/canvas/entity-detail-instance\";\nimport {\n ComposedViewAction,\n parseComposedViewTree,\n} from \"../renderer/widget-tree/composed-view-tree\";\nimport {\n useReportWidgetRenderStatus,\n WidgetRenderReportEntry,\n} from \"../renderer/render-report/widget-render-report\";\nimport type { ExpressionValue } from \"../renderer/widget-tree/expression/evaluate-expression\";\nimport { ComposedViewRenderer } from \"./ComposedViewRenderer\";\n\n/**\n * The composable widget kit: the model composes a TREE of kit components — layout, text, data,\n * media, inputs — with local state, computed values and a closed list of actions, in one ```widget fence of type\n * `ComposedView`. The payload is read into typed objects and checked against the generated node schema\n * (`widget-tree/composed-view-tree.ts`, the twin of the backend reader); what is invalid is dropped and reported, the\n * rest renders. Inputs change local state only (no chat turn, no write), so a replay stays usable; the e-mail capture\n * freezes them at their initial state.\n *\n * The kit's components register themselves by folder (`components/**\\/*.composed.tsx`); this widget only parses,\n * renders, reports and opens the `entityDetail` canvas for an `openEntity` action whose reference the backend resolved\n * (a reference still unresolved opens nothing; without a message id — a streaming reply — nothing opens either).\n */\nexport const ComposedViewConversationWidget = (props: PayloadConversationWidgetProps) => {\n const { payload, interactive = false, messageId } = props;\n const agentSpaceKey = readWidgetAgentSpaceKeyAttribute(props);\n const isEmailRender = useIsEmailWidgetRender();\n const tree = useMemo(() => parseComposedViewTree(payload), [payload]);\n const [blockReport, setBlockReport] = useState<WidgetRenderReportEntry>({ status: \"pending\" });\n const onReport = useCallback((entry: WidgetRenderReportEntry) => setBlockReport(entry), []);\n const { openCanvas } = useConversationWidgetContext();\n const numericMessageId = messageId === undefined ? Number.NaN : Number(messageId);\n const onOpenEntity = useCallback(\n (action: ComposedViewAction, currentRow?: ExpressionValue) => {\n const target = readOpenEntityActionTarget(action, currentRow);\n if (target === undefined || !Number.isFinite(numericMessageId)) return;\n openCanvas({\n canvasId: \"entityDetail\",\n instanceId: canvasInstanceIdForEntityDetail(target),\n anchor: messageAnchor(numericMessageId),\n origin: \"cardClick\",\n justDelivered: false,\n });\n },\n [openCanvas, numericMessageId],\n );\n\n useReportWidgetRenderStatus(blockReport.status, blockReport.code, blockReport.detail);\n\n return (\n <ComposedViewRenderer\n tree={tree}\n interactive={interactive}\n isEmailRender={isEmailRender}\n messageId={messageId}\n agentSpaceKey={agentSpaceKey}\n onReport={onReport}\n onOpenEntity={onOpenEntity}\n />\n );\n};\n","import type { ConversationWidgetEntry } from \"../renderer/conversationWidgetRegistry\";\nimport { ComposedViewConversationWidget } from \"./ComposedViewConversationWidget\";\n\n/**\n * The composable widget kit: a component tree the model composes; deliberately UNGATED — the data\n * it shows carries its own gates (the tools and data sources behind its bindings, an embedded widget's own feature\n * gate). It opens the `entityDetail` canvas (an `openEntity` action) and the `mapFullScreen` canvas (a `Map` node's\n * full-screen control). A canvas an embedded widget opens on a click is that widget's own: the embedded widget lists it\n * in its registry entry, and `findWidgetFencesInMarkdown` reads every embedded widget as a fence of its own, so the\n * reload restore finds it there.\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"ComposedView\",\n component: ComposedViewConversationWidget,\n opensCanvases: [\"entityDetail\", \"mapFullScreen\"],\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { ClockConversationWidget } from \"./ClockConversationWidget\";\n\n/**\n * The live clock / world clock — deliberately UNGATED: it shows no business data and needs no\n * capability (the time is computed in the browser).\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"Clock\",\n component: ClockConversationWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { ConceptExplainerConversationWidget } from \"./ConceptExplainerConversationWidget\";\n\n/**\n * The interactive explainer — deliberately UNGATED: the frame serves the explainer types an app\n * declares in several of its domains; a domain flag would hide every type for an owner missing that one domain, and\n * an explainer shows no data a feature flag protects. Opens no canvas.\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"ConceptExplainer\",\n component: ConceptExplainerConversationWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { CurrencyConverterConversationWidget } from \"./CurrencyConverterConversationWidget\";\n\n/** The currency converter: ungated — currency conversion belongs to no feature domain. */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"CurrencyConverter\",\n component: CurrencyConverterConversationWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { CustomVisualizationConversationWidget } from \"./CustomVisualizationConversationWidget\";\n\n/**\n * The sandboxed custom visualization — deliberately UNGATED: it shows no product data of one\n * domain, only what the block itself carries. Opens no canvas.\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"CustomVisualization\",\n component: CustomVisualizationConversationWidget,\n};\n","import { Button, Icon, Text } from \"../../../provider/components\";\nimport { ModelText } from \"../../../kit/ModelText/ModelText\";\nimport type { EntityMentionFields } from \"../shared/entity-mention\";\nimport styles from \"./EntityMentionChip.module.scss\";\n\nexport interface EntityMentionChipProps {\n mention: EntityMentionFields;\n /** The composer's ✕; omitted → no remove button. */\n onRemove?: () => void;\n testId?: string;\n}\n\n/**\n * ONE mentioned entity as a chip — in the chat input ({@link EntityMentionComposerWidget}): the detail glyph, the label \"About:\" and the name.\n * The name is what the panel showed — business content through `ModelText` (never translated, never parsed as\n * markup; a `replacements` value is parsed by the component library, so it is not used for it); without one the chip says \"About\n * this entry\".\n */\nexport const EntityMentionChip = (props: EntityMentionChipProps) => {\n const { mention, onRemove, testId = \"entity-mention-chip\" } = props;\n return (\n <span className={styles.chip} data-testid={testId}>\n <Icon color=\"var(--agents-fg-light)\" className={styles.icon} pixelSize={14} name=\"details\" />\n {mention.label !== null ? (\n <>\n <Text className={styles.prefix} role=\"help\" color=\"var(--agents-fg-light)\" textWrap=\"nowrap\">\n {\"About:\"}\n </Text>\n <ModelText className={styles.label} role=\"help\" textWrap=\"nowrap\">\n {mention.label}\n </ModelText>\n </>\n ) : (\n <Text className={styles.label} role=\"help\" textWrap=\"nowrap\">\n {\"About this entry\"}\n </Text>\n )}\n {onRemove && (\n <Button\n className={styles.remove}\n variant=\"muted\"\n size=\"small\"\n icon=\"close\"\n onClick={onRemove}\n testId={`${testId}-remove`}\n rounded\n />\n )}\n </span>\n );\n};\n","import { useMemo } from \"react\";\nimport type { ComposerConversationWidgetProps } from \"../../renderer/conversation-widget-props\";\nimport { EntityMentionChip } from \"./EntityMentionChip/EntityMentionChip\";\nimport { normalizeEntityMentionFields } from \"./shared/entity-mention\";\n\n/**\n * The registry `composerComponent` of `EntityMention`: the entity chip in the chat input until the owner\n * sends — its ✕ (or Backspace on an empty input) takes the mention out. Fields that name no entity render nothing.\n */\nexport const EntityMentionComposerWidget = (props: ComposerConversationWidgetProps) => {\n const { fields, remove, testId = \"entity-mention\" } = props;\n const mention = useMemo(() => normalizeEntityMentionFields(fields), [fields]);\n if (mention === null) return null;\n return <EntityMentionChip mention={mention} onRemove={remove} testId={`${testId}-chip`} />;\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { EntityMentionConversationWidget } from \"./EntityMentionConversationWidget\";\nimport { EntityMentionComposerWidget } from \"./EntityMentionComposerWidget\";\n\n/**\n * `EntityMention`: composed by the OWNER — the detail panel's \"Ask about this\" puts it into the chat\n * input (`composerComponent`), it travels in the owner's message as a fence and echoes read-only above its prose\n * (`component`). Ungated: it names an entity the owner could already open. Backspace removes the whole chip (one\n * entity per widget, so no `removeLastPartFromComposerWidgetFields`).\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"EntityMention\",\n component: EntityMentionConversationWidget,\n composerComponent: EntityMentionComposerWidget,\n};\n","import type { ConversationWidgetEntry } from \"../../renderer/conversationWidgetRegistry\";\nimport { WritingDraftConversationWidget } from \"./WritingDraftConversationWidget\";\n\n/**\n * The editable text draft — deliberately UNGATED: it carries only the text the model wrote, reads no\n * business data and needs no capability; every action stays in the browser (copy, the owner's own mail program).\n */\nexport const conversationWidgetRegistration: ConversationWidgetEntry = {\n name: \"WritingDraft\",\n component: WritingDraftConversationWidget,\n};\n","import type React from \"react\";\nimport type { ConversationWidgetUpsellProps } from \"./_access/ConversationWidgetFeatureGate\";\nimport type { CanvasId } from \"./canvas/canvas-behaviours\";\nimport type { ComposerConversationWidgetProps } from \"./conversation-widget-props\";\nimport { SuggestedActions } from \"../widgets/SuggestedActions/SuggestedActions\";\nimport { MultiChoiceConversationWidget } from \"../widgets/MultiChoiceConversationWidget/MultiChoiceConversationWidget\";\nimport { QuickRepliesConversationWidget } from \"../widgets/QuickRepliesConversationWidget/QuickRepliesConversationWidget\";\nimport { ToolTraceConversationWidget } from \"../widgets/ToolTraceConversationWidget/ToolTraceConversationWidget\";\nimport { ConversationSearchResultsConversationWidget } from \"../widgets/ConversationSearchResultsConversationWidget/ConversationSearchResultsConversationWidget\";\nimport { WebSearchResultsConversationWidget } from \"../widgets/WebSearchResultsConversationWidget/WebSearchResultsConversationWidget\";\n\nexport interface ConversationWidgetEntry {\n /**\n * The CANONICAL wire name — short, never ending in `Directive` (that suffix is reserved as the legacy marker; see\n * `widget-name-resolver.ts`). Stored messages that carry the old `<Name>Directive` form resolve onto this one.\n */\n name: string;\n component: React.ComponentType<any>;\n /**\n * The app's requirement name (a feature flag) that gates this widget — opaque to the package, checked by the app's\n * `WidgetFeatureGate`. Omit to render unconditionally (default).\n */\n featureFlag?: string;\n /**\n * May this widget be mounted by NAME from outside a conversation — the `?agentWidget=<name>` deep-link a page uses to\n * open the chat with this widget's canvas already up, and the restore of a pinned canvas after a reload\n * (`resolve-deep-linkable-widget.ts`). Opt-in per widget because a URL is untrusted input: everything else is mounted\n * only from a message the agent wrote. Default false.\n */\n deepLinkable?: boolean;\n /**\n * The canvases (by canvas id, `canvas/canvas-behaviours.ts`) this widget may open. Documentation and the restore's\n * validation: a stored canvas pointer is re-opened only when its anchor message carries a widget that lists the\n * canvas. `_registry-wire-names.spec.ts` asserts every listed id is a declared canvas.\n */\n opensCanvases?: readonly CanvasId[];\n /** Optional custom upgrade offer for the gated widget; defaults to the app gate's own. */\n upsellTrigger?: React.ComponentType<ConversationWidgetUpsellProps>;\n /**\n * Renders this widget INSIDE the chat input (editable: per-part ✕ etc.). Present = the widget may be composed by\n * the customer (see `ConversationComposerWidget`). An entry declaring this MUST also declare `component` (asserted\n * in `_registry-wire-names.spec.ts`) — the message rendering.\n */\n composerComponent?: React.ComponentType<ComposerConversationWidgetProps>;\n /**\n * Backspace on an empty input removes the LAST removable part of the last composer widget. Returns the fields\n * without that part, or `null` when nothing is left (the widget is then removed entirely). Omitted → Backspace\n * removes the whole widget.\n */\n removeLastPartFromComposerWidgetFields?: (fields: Record<string, unknown>) => Record<string, unknown> | null;\n}\n\n/**\n * The package's widgets that register themselves by FILE: every `*.widget-registration.ts` below the\n * package's `widgets/` and `kit/` that exports `conversationWidgetRegistration` joins the list. An app registers its\n * own widgets with `registerConversationWidgets` (its folder globs stay in its own code).\n */\nconst widgetRegistrationModules = import.meta.glob<{ conversationWidgetRegistration?: ConversationWidgetEntry }>(\n [\"../widgets/**/*.widget-registration.ts\", \"../kit/**/*.widget-registration.ts\"],\n { eager: true },\n);\n\n/** The entries of a set of registration modules (`*.widget-registration.ts` files an app or the package globbed). */\nexport const readConversationWidgetRegistrations = (\n registrationModules: Record<string, { conversationWidgetRegistration?: ConversationWidgetEntry }>,\n): ConversationWidgetEntry[] =>\n Object.values(registrationModules)\n .map((registrationModule) => registrationModule.conversationWidgetRegistration)\n .filter((entry): entry is ConversationWidgetEntry => entry !== undefined);\n\n/** The package's own widgets registered by file. */\nexport const readFolderRegisteredConversationWidgets = (): ConversationWidgetEntry[] =>\n readConversationWidgetRegistrations(widgetRegistrationModules);\n\n/** Throws on a wire name registered twice — the written list and the registration files together. */\nexport const assertUniqueConversationWidgetNames = (widgets: readonly ConversationWidgetEntry[]): void => {\n const seenNames = new Set<string>();\n for (const widget of widgets) {\n if (seenNames.has(widget.name)) throw new Error(`The conversation widget \"${widget.name}\" is registered twice.`);\n seenNames.add(widget.name);\n }\n};\n\n/** The package's own widgets: the written entries and every package widget registered by file. */\nexport const packageConversationWidgets: readonly ConversationWidgetEntry[] = [\n { name: \"SuggestedActions\", component: SuggestedActions },\n { name: \"MultiChoice\", component: MultiChoiceConversationWidget },\n { name: \"QuickReplies\", component: QuickRepliesConversationWidget },\n { name: \"ToolTrace\", component: ToolTraceConversationWidget },\n {\n name: \"ConversationSearchResults\",\n component: ConversationSearchResultsConversationWidget,\n opensCanvases: [\"conversationSearchResults\"],\n },\n { name: \"WebSearchResults\", component: WebSearchResultsConversationWidget, opensCanvases: [\"webSearchResults\"] },\n // Every package widget with a `<Name>ConversationWidget.widget-registration.ts` file joins below.\n ...readFolderRegisteredConversationWidgets(),\n];\n\n/**\n * ONE list — every registered widget, in no particular order. There are no kinds of widget here: inline vs canvas vs\n * mount-time is the component's own choice, not a registry bucket. A widget that opens a canvas lists the canvas ids\n * (`opensCanvases`); the canvas's behaviour lives in `canvas/canvas-behaviours.ts`, its body in `canvas/canvasBodies.tsx`.\n * It starts with the package's own widgets; an app adds its widgets with `registerConversationWidgets` before the\n * first render (outside React). The array is filled in place, so a reader that holds it sees every registration.\n */\nexport const conversationWidgetRegistry: {\n widgets: ConversationWidgetEntry[];\n} = {\n widgets: [...packageConversationWidgets],\n};\n\nassertUniqueConversationWidgetNames(conversationWidgetRegistry.widgets);\n\nlet registryRevision = 0;\n\n/**\n * Counts the registrations: a reader that caches something derived from the registry (a name set, a component map)\n * rebuilds it when the revision moved.\n */\nexport const getConversationWidgetRegistryRevision = (): number => registryRevision;\n\n/**\n * Adds an app's widgets to the registry. Runs outside React, before the first render; throws when a wire name is\n * registered twice (with the package's own or an earlier registration).\n */\nexport const registerConversationWidgets = (widgets: readonly ConversationWidgetEntry[]): void => {\n assertUniqueConversationWidgetNames([...conversationWidgetRegistry.widgets, ...widgets]);\n conversationWidgetRegistry.widgets.push(...widgets);\n registryRevision += 1;\n};\n\n/**\n * Puts `widgets` in place of every registered entry and returns the entries the registry held, so a spec renders\n * against widgets of its own and puts the registry back afterwards (`installTestConversationWidgets`, the\n * `client/testing` subpath). Fills the same array in place, so a reader that holds it sees the swap; moves the revision.\n */\nexport const replaceConversationWidgetRegistryEntries = (\n widgets: readonly ConversationWidgetEntry[],\n): ConversationWidgetEntry[] => {\n assertUniqueConversationWidgetNames(widgets);\n const previousWidgets = conversationWidgetRegistry.widgets.splice(0, conversationWidgetRegistry.widgets.length, ...widgets);\n registryRevision += 1;\n return previousWidgets;\n};\n","import { conversationWidgetRegistry, getConversationWidgetRegistryRevision } from \"./conversationWidgetRegistry\";\n\n/**\n * WIRE LAYER — this file owns the ONE rule that maps a name off the wire onto a registered widget.\n *\n * CANONICAL names are SHORT: `QuickReplies`, `MultiChoice`, `WebSearchResults`. That is what the registry holds, what the\n * agent emits in a ```widget fence `type`, and what every doc and FE-generated message writes today.\n *\n * LEGACY names carry a trailing `Directive`: stored conversation messages in the database contain\n * `::QuickRepliesDirective{payload='…'}` and ```widget fences with `\"type\": \"QuickRepliesDirective\"`. Those rows are\n * permanent — the database is not rewritten.\n *\n * THE RULE (in `resolveCanonicalWidgetName`, and nowhere else):\n * 1. exact match against the canonical names;\n * 2. ONLY if the requested name ends in `Directive` — strip that suffix ONCE and retry the exact match;\n * 3. otherwise undefined (unknown widget).\n *\n * Consequence: the `Directive` suffix is RESERVED as the legacy marker. Never register a new widget under a name\n * ending in `Directive` — `_registry-wire-names.spec.ts` asserts no canonical name does, and asserts that every legacy\n * long name still resolves to the canonical one, so old conversations keep rendering forever.\n */\n\n/** The suffix every pre-canonicalization wire name carried. Reserved as the legacy marker — see the file header. */\nconst LEGACY_NAME_SUFFIX = \"Directive\";\n\nlet widgetNameSet: ReadonlySet<string> | undefined;\nlet widgetNameSetRevision = -1;\n\n/**\n * Every registered widget name, canonical (short) — the runtime source of truth for what renders. Read LAZILY: the\n * registry imports every widget, and a widget can import AgentChat, which imports this file — a module-scope read\n * would run before the registry finished initializing whenever a widget is the first module loaded (a story). Rebuilt\n * when an app registered more widgets since (`registerConversationWidgets`).\n */\nconst getWidgetNameSet = (): ReadonlySet<string> => {\n if (widgetNameSet === undefined || widgetNameSetRevision !== getConversationWidgetRegistryRevision()) {\n widgetNameSet = new Set(conversationWidgetRegistry.widgets.map((widget) => widget.name));\n widgetNameSetRevision = getConversationWidgetRegistryRevision();\n }\n return widgetNameSet;\n};\n\n/**\n * THE resolution rule (see the file header): exact canonical match, else — only for a name ending in `Directive` —\n * strip that legacy suffix once and match again. Undefined = no such widget. Every lookup in the pipeline goes through\n * this function (the fence plugin, the AST plugin, the drawer-reset scan, the unrendered-widget detector), so a name\n * that renders in one place renders in all of them.\n */\nexport const resolveCanonicalWidgetName = (\n requestedName: string,\n canonicalNames: ReadonlySet<string>,\n): string | undefined => {\n if (canonicalNames.has(requestedName)) return requestedName;\n if (!requestedName.endsWith(LEGACY_NAME_SUFFIX)) return undefined;\n const withoutLegacySuffix = requestedName.slice(0, -LEGACY_NAME_SUFFIX.length);\n return canonicalNames.has(withoutLegacySuffix) ? withoutLegacySuffix : undefined;\n};\n\n/**\n * Resolve a model-supplied ```widget `type` — or the name on a stored message's `::<Name>` node — to a registered\n * widget name. `QuickReplies` matches exactly; the legacy `QuickRepliesDirective` resolves to the same canonical\n * `QuickReplies`. Shared by the render plugin (which DROPS an unresolved block) and the unrendered-widget detector\n * (which REPORTS it), so both agree exactly on what counts as a valid widget.\n */\nexport const resolveWidgetName = (type: string): string | undefined =>\n resolveCanonicalWidgetName(type, getWidgetNameSet());\n\n/** Normalize a widget name / type for fuzzy comparison: lowercase, drop a trailing `Directive`. */\nconst normalizeWidgetName = (value: string): string => value.toLowerCase().replace(/directive$/, \"\");\n\n/** Split a PascalCase / camelCase widget name into lowercase word tokens (`WebSearchResults` → [web, search, results]). */\nconst wordTokens = (value: string): string[] =>\n value\n .replace(/directive$/i, \"\")\n .split(/(?=[A-Z])/)\n .map((token) => token.toLowerCase())\n .filter(Boolean);\n\n/** Levenshtein edit distance — the fine tiebreaker for the closest-widget shortlist (dependency-free). */\nconst editDistance = (a: string, b: string): number => {\n const rows = a.length + 1;\n const cols = b.length + 1;\n const dist: number[][] = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));\n for (let i = 0; i < rows; i++) dist[i][0] = i;\n for (let j = 0; j < cols; j++) dist[0][j] = j;\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n dist[i][j] = Math.min(\n dist[i - 1][j] + 1,\n dist[i][j - 1] + 1,\n dist[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),\n );\n }\n }\n return dist[rows - 1][cols - 1];\n};\n\n/**\n * The closest VALID widget names to an unknown `type` the model emitted — a deterministic similarity shortlist (no\n * LLM): substring containment + shared PascalCase tokens + edit-distance proximity as the tiebreaker. A candidate is\n * kept only when it genuinely resembles the type (containment, a shared word, or a very close spelling) — proximity\n * alone is too loose across ~60 widget names. Returned as the canonical (short) names, which is what a corrected\n * emission should use; empty when nothing is close.\n */\nexport const closestWidgetNames = (type: string, limit = 3): string[] => {\n const target = normalizeWidgetName(type);\n if (target === \"\") return [];\n const targetTokens = new Set(wordTokens(type));\n return [...getWidgetNameSet()]\n .map((name) => {\n const candidate = normalizeWidgetName(name);\n const candidateTokens = wordTokens(name);\n const contains = candidate.includes(target) || target.includes(candidate) ? 3 : 0;\n const overlap = candidateTokens.filter((token) => targetTokens.has(token)).length;\n // Proximity against the WHOLE name and against each word token (so a single-word typo like `conections` still\n // matches the `connections` token of a multi-word widget), best of the two.\n const nameProximity = 1 - editDistance(target, candidate) / Math.max(target.length, candidate.length);\n const tokenProximity = Math.max(\n 0,\n ...candidateTokens.map((token) => 1 - editDistance(target, token) / Math.max(target.length, token.length)),\n );\n const proximity = Math.max(nameProximity, tokenProximity);\n return {\n name,\n keep: contains > 0 || overlap > 0 || proximity >= 0.6,\n score: contains + overlap + proximity,\n };\n })\n .filter((entry) => entry.keep)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map((entry) => entry.name);\n};\n"],"names":["value","pending","nested","text","hasOwn","isPlainObject","entry","row","code","fields","categories","source","arrow","budgets","left","list","toStateValue","rows","fallback","readFiniteNumber","readText","delta","field","heatCell","styles","stage","readHttpUrl","SourceChip","caption","title","composedViewComponent","label","icon","compact","marker","description","trailing","column","bar","heat","content","tableStyles","headerItems","COPIED_CONFIRMATION_MS","labelText","FALLBACK_DATE_LOCALE","readFieldText","typedText","readChoiceId","readScrollEdges","track","slide","prefersReducedMotion","ALIGNMENTS","ALIGNMENT_CLASS_NAMES","embeddableWidgets","cell","attribution","sourceLabel","readImageUrl","COMPOSED_VIEW_WIDGET_NAME","markdown","AgentsMap","routeChip","image","readTitle","metaLine","frame","badge","actions","footer","graphic","Fragment","__vite_glob_0_0","__vite_glob_0_1","__vite_glob_0_2","__vite_glob_0_3","__vite_glob_0_4","__vite_gl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