@widgentic/designer 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../core/src/contract/validate.ts", "../../../core/src/contract/urls.ts", "../../../core/src/catalog/node.ts", "../../../core/src/catalog/descriptors.ts", "../../../core/src/catalog/schema.ts", "../../../core/src/catalog/widgets/format.ts", "../../../core/src/catalog/widgets/images.ts", "../../../core/src/catalog/widgets/card.ts", "../../../core/src/catalog/widgets/table.ts", "../../../core/src/catalog/widgets/tree.ts", "../../../core/src/catalog/widgets/custom.ts", "../../../core/src/catalog/widgets/group.ts", "../../../core/src/catalog/registry.ts", "../../../core/src/catalog/styles.ts", "../../../core/src/theming/tokens.ts", "../../../core/src/theming/stylesheet.ts", "../../../core/src/theming/apply.ts", "../../../core/src/shared/plain-object.ts", "../../../core/src/templates/guards.ts", "../../../core/src/templates/paths.ts", "../../../core/src/actions/types.ts", "../../../core/src/actions/validate.ts", "../../../core/src/templates/validate.ts", "../../../core/src/templates/locate.ts", "../../../core/src/templates/compile.ts", "../../../core/src/reactive/build.ts", "../../../core/src/reactive/diff.ts", "../../../core/src/reactive/mount.ts", "../../src/chrome-defaults.ts", "../../src/dom.ts", "../../src/internal.ts", "../../src/highlight.ts", "../../src/io.ts", "../../src/json-tree-editor.ts", "../../src/schema-builder.ts", "../../src/record-editor.ts", "../../src/schema-form.ts", "../../src/styles-editor.ts", "../../src/schema-paths.ts", "../../src/action-editor.ts", "../../src/validate.ts", "../../src/template-panel.ts", "../../src/theme-panel.ts", "../../src/panels.ts", "../../src/preview.ts", "../../src/store.ts", "../../src/shell.ts", "../../src/schema-designer.ts", "../../src/theme-designer.ts", "../../src/action-designer.ts", "../../src/element.ts", "../../src/browser.ts"],
4
- "sourcesContent": ["import type { WidgetPayload } from \"./types.js\";\nimport type { WidgetContractError } from \"./errors.js\";\n\nexport interface ValidateOptions {\n /**\n * If provided and non-empty, payloads whose `kind` is not in the set fail\n * with `UNKNOWN_KIND`. When omitted or empty, kind membership is not\n * checked (kind format is still validated).\n */\n knownKinds?: ReadonlySet<string>;\n}\n\nexport type ValidateResult =\n | { ok: true; payload: WidgetPayload }\n | { ok: false; error: WidgetContractError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Validate an unknown input against the widget contract.\n *\n * Returns a discriminated result. The `payload` returned on success is the\n * original input (unknown top-level fields are preserved for forward\n * compatibility).\n */\nexport function validateWidgetPayload(\n input: unknown,\n options: ValidateOptions = {}\n): ValidateResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"\",\n message: \"Payload must be a plain object.\"\n }\n };\n }\n\n if (!(\"kind\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Payload is missing required field 'kind'.\"\n }\n };\n }\n\n const kind = input.kind;\n if (typeof kind !== \"string\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"kind\",\n message: \"Field 'kind' must be a string.\"\n }\n };\n }\n if (kind.length === 0) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Field 'kind' must be a non-empty string.\"\n }\n };\n }\n\n if (!(\"data\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data\",\n message: \"Payload is missing required field 'data'.\"\n }\n };\n }\n\n if (\"hints\" in input && input.hints !== undefined && !isPlainObject(input.hints)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"hints\",\n message: \"Field 'hints' must be an object when present.\"\n }\n };\n }\n\n if (\"meta\" in input && input.meta !== undefined && !isPlainObject(input.meta)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"meta\",\n message: \"Field 'meta' must be an object when present.\"\n }\n };\n }\n\n const { knownKinds } = options;\n if (knownKinds && knownKinds.size > 0 && !knownKinds.has(kind)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${kind}'.`\n }\n };\n }\n\n // Preserve unknown top-level fields by returning the original input.\n return { ok: true, payload: input as WidgetPayload };\n}\n", "/**\n * URL safety primitives shared by the template DSL and the catalog's image\n * rendering. They live in the contract layer \u2014 the zero-dependency base\n * both consumers sit on \u2014 so the strict and lenient layers can never drift\n * (`templates` imports from `catalog`, so `catalog` cannot import back).\n */\n\n/** Schemes allowed in URL-bearing attributes (plus relative references). */\nexport const ALLOWED_SCHEMES = new Set([\"http\", \"https\", \"mailto\", \"tel\"]);\n\n/**\n * Strip control characters and whitespace before scheme inspection,\n * mirroring how browsers parse URLs (defeats `java\\nscript:` obfuscation).\n */\nfunction cleanUrl(value: string): string {\n return value.replace(/[\\u0000-\\u0020]+/g, \"\");\n}\n\n/**\n * True when a URL value is safe for a URL-bearing attribute: an allowed\n * scheme or a relative reference.\n */\nexport function isSafeUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return true;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/**\n * True only for an EXPLICITLY-schemed allowed URL \u2014 unlike {@link isSafeUrl},\n * relative references do not qualify: as anchor targets they are dead\n * clicks inside the app frame and junk navigation on served pages.\n */\nexport function isLinkableUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return false;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/** `data:image/<subtype>;base64,<payload>` \u2014 the only `data:` form images accept. */\nconst DATA_IMAGE = /^data:image\\/[a-z0-9.+-]+;base64,[a-z0-9+/=]*$/i;\n\n/** Absolute http(s) \u2014 image sources are fetched, so relative refs are useless. */\nconst HTTP_URL = /^https?:\\/\\//i;\n\n/**\n * True when a value is acceptable as an image source: an absolute http(s)\n * URL or a base64 `data:image/*` URI. Broader `data:` stays banned here and\n * everywhere else \u2014 data-URI navigation is an XSS vector; data-URI images\n * are not.\n */\nexport function isSafeImageSrc(value: string): boolean {\n const cleaned = cleanUrl(value);\n return DATA_IMAGE.test(cleaned) || HTTP_URL.test(cleaned);\n}\n\nconst IMAGE_EXTENSION = /\\.(png|jpe?g|gif|webp|avif|svg)$/i;\n\n/**\n * Auto-detection predicate for the built-in renderers: a safe image source\n * that self-identifies as an image \u2014 `data:image/*`, or an http(s) URL\n * whose pathname ends in an image extension (query strings tolerated).\n * Extensionless image URLs need a `hints.images` entry instead.\n */\nexport function looksLikeImageUrl(value: string): boolean {\n const cleaned = cleanUrl(value);\n if (!isSafeImageSrc(cleaned)) return false;\n if (cleaned.toLowerCase().startsWith(\"data:image/\")) return true;\n try {\n return IMAGE_EXTENSION.test(new URL(cleaned).pathname);\n } catch {\n return false;\n }\n}\n", "/**\n * Pure render tree produced by widget renderers.\n *\n * Plain, JSON-serializable data \u2014 no DOM or framework types \u2014 so renderers\n * are testable anywhere and the output layers (`renderToHtml`, `mountNode`)\n * stay thin and swappable. There is deliberately no raw-HTML node type: all\n * text is escaped at the output boundary.\n */\nimport type { WidgetPayload } from \"../contract/types.js\";\n\n/** Attribute map. Values are plain strings (escaped by output layers). */\nexport type WidgetNodeAttrs = Record<string, string>;\n\n/** A tagged element in the render tree. */\nexport interface WidgetElementNode {\n tag: string;\n attrs?: WidgetNodeAttrs;\n children?: WidgetNode[];\n}\n\n/** An element in the render tree: a text node or a tagged element. */\nexport type WidgetNode = string | WidgetElementNode;\n\n/** A widget renderer: pure function from payload to render tree. */\nexport type WidgetRenderer = (payload: WidgetPayload) => WidgetNode;\n\n/** Convenience node constructor (omits empty attrs/children). */\nexport function el(\n tag: string,\n attrs?: WidgetNodeAttrs,\n children?: WidgetNode[]\n): WidgetElementNode {\n const node: WidgetElementNode = { tag };\n if (attrs && Object.keys(attrs).length > 0) node.attrs = attrs;\n if (children && children.length > 0) node.children = children;\n return node;\n}\n", "import type { WidgetKind } from \"../contract/types.js\";\nimport type { DataSchema } from \"./schema.js\";\nimport type { WidgetStyles } from \"./styles.js\";\n\n/**\n * Agent-facing documentation for a widget kind. Descriptors make the\n * catalog reflectable: tooling (e.g. the widgentic MCP server's\n * `list_widgets`) lists them so agents can pick a widget and shape their\n * `data` without reading source.\n */\nexport interface WidgetDescriptor {\n kind: WidgetKind;\n /** What the widget is for. */\n description: string;\n /** Human-readable description of the expected `data` input. */\n dataShape: string;\n /** Small example `data` value an agent can imitate. */\n dataExample?: unknown;\n /** Supported hint keys and what they do. */\n hints?: Record<string, string>;\n /**\n * Optional JSON-Schema subset for `data` (see schema.ts). When present,\n * `catalog.render` validates data against it before rendering; kinds\n * without one keep their lenient fallback behavior.\n */\n dataSchema?: DataSchema;\n /**\n * Optional CSS-as-data for the kind's `.wg-` classes (see styles.ts).\n * Included in `page` output and exposable by hosts; guarded like themes.\n */\n styles?: WidgetStyles;\n}\n\n/** Descriptor as supplied at registration; `kind` is filled by the catalog. */\nexport type WidgetDescriptorInput = Omit<WidgetDescriptor, \"kind\">;\n\n/**\n * Honest documentation of the built-ins' actual (lenient) behavior. Every\n * `dataExample` is asserted by tests to render successfully.\n */\nexport const BUILTIN_DESCRIPTORS: Record<\n \"card\" | \"table\" | \"tree\" | \"custom\" | \"group\",\n WidgetDescriptorInput\n> = {\n card: {\n description:\n \"Key/value details for a single entity, with optional title and subtitle.\",\n dataShape:\n \"A plain object. `title`, `subtitle`, and `fields` are used when present; \" +\n \"other entries become field key/value pairs. Primitives render as a single \" +\n \"value line. `meta.title`/`meta.subtitle` fill in missing chrome. Send \" +\n \"field values typed (e.g. price: 9.99, not '$9.99') and use \" +\n \"hints.fieldFormat for display formatting \u2014 the payload keeps the \" +\n \"typed value while the render gets its unit. Field values that are \" +\n \"image URLs render as images (see hints.images).\",\n dataExample: {\n title: \"Essence Mascara\",\n subtitle: \"beauty\",\n fields: { price: 9.99, rating: 2.56, stock: 99 }\n },\n hints: {\n fieldFormat:\n \"Record<fieldKey, pattern> \u2014 formats matching field values by \" +\n \"substituting {value} in the pattern (e.g. { price: '${value}', \" +\n \"rating: '{value} / 5' }); a pattern without {value} is prefixed \" +\n \"to the value. Output is escaped like any text.\",\n images:\n \"Record<fieldKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"field values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: thumb); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text; image treatment wins over \" +\n \"fieldFormat for the same key.\",\n links:\n \"Record<fieldKey, boolean | prefix> \u2014 true links a field whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same key. Links are never \" +\n \"automatic \u2014 opt in per field.\"\n }\n },\n table: {\n description: \"Rows and columns for arrays of records.\",\n dataShape:\n \"An array of records (plain objects). Columns are the union of record keys \" +\n \"in first-seen order; missing cells render empty; non-array data becomes a \" +\n \"single row. Cell values that are image URLs render as avatars (see \" +\n \"hints.images). meta.title/meta.subtitle render as the table's caption. \" +\n \"Send cell values typed (e.g. total: 11471334.78, not '11,471,334.78') \" +\n \"and use hints.fieldFormat for display formatting \u2014 the payload keeps \" +\n \"the typed value while the render gets its unit.\",\n dataExample: [\n { name: \"Ada\", role: \"eng\", avatar: \"https://picsum.photos/id/64/64/64.jpg\" },\n { name: \"Lin\", role: \"ops\", avatar: \"https://picsum.photos/id/65/64/64.jpg\" }\n ],\n hints: {\n columns: \"string[] \u2014 overrides column selection and order\",\n fieldFormat:\n \"Record<columnKey, pattern> \u2014 formats matching cell values by \" +\n \"substituting {value} in the pattern (e.g. { total: '${value}' }); \" +\n \"a pattern without {value} is prefixed to the value. Output is \" +\n \"escaped like any text; image treatment wins for the same column.\",\n links:\n \"Record<columnKey, boolean | prefix> \u2014 true links cells whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same column. Links are never \" +\n \"automatic \u2014 opt in per column.\",\n images:\n \"Record<columnKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"cell values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: avatar); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text.\"\n }\n },\n tree: {\n description: \"Collapsible hierarchy of labeled nodes.\",\n dataShape:\n \"Nested `{ label, children[] }` nodes \u2014 a single root object or an array of \" +\n \"them. Nodes without a usable `label` get a JSON fallback label. \" +\n \"meta.title renders as a title line above the tree.\",\n dataExample: {\n label: \"root\",\n children: [{ label: \"leaf\", children: [] }]\n },\n hints: {\n expandDepth:\n \"number \u2014 branches at depth < value start expanded (default: \" +\n \"unlimited). Presentational only: the full subtree is always in the \" +\n \"markup; `data-expanded` appears only on nodes with children, and \" +\n \"the widgentic base stylesheet hides collapsed children via CSS.\"\n }\n },\n custom: {\n description:\n \"Generic escape hatch: renders any data as pretty-printed JSON. Best \" +\n \"for raw inspection and debugging \u2014 for human-legible output, reshape \" +\n \"the data and use card, table, or tree instead (e.g. join values with \" +\n \"their units: '24.4 \u00B0C').\",\n dataShape: \"Any JSON value, rendered verbatim (value-exact, not byte-exact).\",\n dataExample: { anything: [\"goes\", 42] }\n },\n group: {\n description:\n \"Several widgets in one response \u2014 mixed kinds in a single layout \" +\n \"container. Use ONE group render instead of repeated render calls \" +\n \"when showing multiple widgets together.\",\n dataShape:\n \"{ items: [{ kind, data, hints?, meta? }, ...] } \u2014 each item is a \" +\n \"full sub-widget rendered exactly as a top-level call would be \" +\n \"(any listed kind except 'group'; groups do not nest). At most 20 \" +\n \"items per group.\",\n dataExample: {\n items: [\n { kind: \"card\", data: { title: \"Ada\", fields: { role: \"eng\" } } },\n { kind: \"card\", data: { title: \"Lin\", fields: { role: \"ops\" } } }\n ]\n },\n hints: {\n layout:\n \"'stack' | 'row' | 'grid' \u2014 how items sit together (default: \" +\n \"stack). 'row' wraps; 'grid' uses equal columns.\",\n gap: \"'none' | 'sm' | 'md' | 'lg' \u2014 spacing between items (default: md).\",\n columns: \"number 1-4 \u2014 column count for layout: 'grid' (default: 2).\"\n }\n }\n};\n", "import type { WidgetContractError } from \"../contract/errors.js\";\n\n/**\n * A JSON-Schema *subset* for widget `data`: `type`, `properties`,\n * `required`, `items`, `enum`, `pattern`. Unknown keywords are ignored\n * (forward compatible), never misinterpreted \u2014 and that policy extends to\n * `pattern` values this module refuses to run (see the ReDoS bounds\n * below). Violations map to the existing contract vocabulary with dotted\n * paths into the data.\n */\nexport type DataSchema = Record<string, unknown>;\n\n// `pattern` bounds: schemas arrive from descriptor authors, but the strings\n// they test arrive from agents \u2014 an exponential-backtracking pattern over\n// attacker-lengthened input is a denial of service. Overlong patterns,\n// nested-quantifier shapes, and RegExp-invalid sources are IGNORED (never\n// misinterpreted as passing or failing); tested strings are capped.\n/** Longest `pattern` the validator will compile. */\nexport const PATTERN_MAX_LENGTH = 256;\nconst TESTED_STRING_MAX = 10_000;\nconst NESTED_QUANTIFIER = /(\\([^)]*[+*][^)]*\\)|\\[[^\\]]*\\][+*])[+*{]/;\n\nfunction compileSafePattern(pattern: unknown): RegExp | undefined {\n if (typeof pattern !== \"string\" || pattern.length > PATTERN_MAX_LENGTH) {\n return undefined;\n }\n if (NESTED_QUANTIFIER.test(pattern)) return undefined;\n try {\n return new RegExp(pattern);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction matchesSingleType(type: string, data: unknown): boolean {\n switch (type) {\n case \"object\":\n return isPlainObject(data);\n case \"array\":\n return Array.isArray(data);\n case \"string\":\n return typeof data === \"string\";\n case \"number\":\n return typeof data === \"number\";\n case \"integer\":\n return typeof data === \"number\" && Number.isInteger(data);\n case \"boolean\":\n return typeof data === \"boolean\";\n case \"null\":\n return data === null;\n default:\n // Unknown type keyword: ignore rather than reject.\n return true;\n }\n}\n\nfunction matchesType(type: unknown, data: unknown): boolean {\n if (typeof type === \"string\") return matchesSingleType(type, data);\n if (Array.isArray(type)) {\n return type.some(\n (candidate) =>\n typeof candidate === \"string\" && matchesSingleType(candidate, data)\n );\n }\n return true;\n}\n\nfunction enumMatches(allowed: unknown[], data: unknown): boolean {\n return allowed.some((value) => {\n if (value === data) return true;\n try {\n return JSON.stringify(value) === JSON.stringify(data);\n } catch {\n return false;\n }\n });\n}\n\nfunction formatType(type: unknown): string {\n return Array.isArray(type) ? type.join(\" | \") : String(type);\n}\n\n/**\n * Validate `data` against a subset schema. Returns the first violation as a\n * contract-vocabulary error (`MISSING_FIELD` for required, `INVALID_TYPE`\n * for type/enum) with a dotted path, or `undefined` when valid. Never\n * throws.\n */\nexport function validateDataAgainstSchema(\n schema: DataSchema,\n data: unknown,\n path = \"data\"\n): WidgetContractError | undefined {\n if (Array.isArray(schema.enum) && !enumMatches(schema.enum, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must be one of the enumerated options.`\n };\n }\n\n if (schema.type !== undefined && !matchesType(schema.type, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must have type ${formatType(schema.type)}.`\n };\n }\n\n // Pattern applies to string data only \u2014 type mismatches are `type`'s job.\n if (typeof data === \"string\" && schema.pattern !== undefined) {\n const regex = compileSafePattern(schema.pattern);\n if (regex !== undefined && !regex.test(data.slice(0, TESTED_STRING_MAX))) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must match pattern ${String(schema.pattern)}.`\n };\n }\n }\n\n if (isPlainObject(data)) {\n if (Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && !(key in data)) {\n return {\n code: \"MISSING_FIELD\",\n path: `${path}.${key}`,\n message: `Missing required property '${key}'.`\n };\n }\n }\n }\n if (isPlainObject(schema.properties)) {\n for (const [key, subschema] of Object.entries(schema.properties)) {\n if (key in data && isPlainObject(subschema)) {\n const error = validateDataAgainstSchema(\n subschema,\n data[key],\n `${path}.${key}`\n );\n if (error) return error;\n }\n }\n }\n }\n\n if (Array.isArray(data) && isPlainObject(schema.items)) {\n for (let i = 0; i < data.length; i++) {\n const error = validateDataAgainstSchema(\n schema.items as DataSchema,\n data[i],\n `${path}.${i}`\n );\n if (error) return error;\n }\n }\n\n return undefined;\n}\n", "/** Shared helpers for the built-in renderers. */\nimport { isLinkableUrl } from \"../../contract/urls.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\n\n/** Same plain-object definition as the contract validator. */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Render any value as display text. Strings pass through; primitives\n * stringify; structured values fall back to compact JSON. Never throws.\n */\nexport function formatValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"\";\n if (\n value === null ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\"\n ) {\n return String(value);\n }\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\n/** Apply a `fieldFormat` pattern: substitute `{value}`, or append when absent. */\nexport function applyPattern(pattern: string, value: string): string {\n return pattern.includes(\"{value}\")\n ? pattern.split(\"{value}\").join(value)\n : pattern + value;\n}\n\n/**\n * Wrap display text in an anchor when the caller opted this key into\n * `hints.links` AND the raw value is an explicitly-schemed safe URL.\n * Built-ins construct nodes directly (they never pass the template\n * compiler's URL guard), so the scheme check lives here \u2014 mirroring\n * `isSafeImageSrc` in the image path. Everything else stays plain text.\n */\nexport function linkOrText(\n key: string,\n raw: unknown,\n hints: unknown,\n display: string\n): WidgetNode {\n const links =\n isPlainObject(hints) && isPlainObject(hints.links) ? hints.links : undefined;\n const hint = links?.[key];\n if (typeof raw !== \"string\" || raw === \"\") return display;\n // true: the value IS the URL. String: an author-supplied prefix composed\n // with the value (e.g. \"mailto:\") \u2014 the display stays the clean value,\n // and the COMPOSED href faces the guard, so a hostile value can never\n // smuggle a scheme past an author prefix.\n const href =\n hint === true ? raw : typeof hint === \"string\" ? hint + raw : undefined;\n if (href === undefined || !isLinkableUrl(href)) return display;\n return el(\n \"a\",\n { class: \"wg-link\", href, rel: \"noopener noreferrer\" },\n [display]\n );\n}\n", "import { isSafeImageSrc, looksLikeImageUrl } from \"../../contract/urls.js\";\nimport type { WidgetElementNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Image presentation variants; each maps to a `wg-img-<shape>` class. */\nexport type ImageShape = \"avatar\" | \"thumb\" | \"hero\";\n\nconst SHAPES = new Set<string>([\"avatar\", \"thumb\", \"hero\"]);\n\n/**\n * Decide whether a card-field / table-cell value renders as an image.\n * `hints.images` (keyed by field/column name) overrides auto-detection:\n * a shape string forces that shape, `true` forces the context default,\n * `false` suppresses. Hints never bypass safety \u2014 an unsafe source always\n * renders as text (`null` here). Auto-detection requires the value to\n * self-identify as an image (`looksLikeImageUrl`).\n */\nexport function resolveImage(\n key: string,\n value: unknown,\n hints: Record<string, unknown> | undefined,\n defaultShape: ImageShape\n): { src: string; shape: ImageShape } | null {\n if (typeof value !== \"string\") return null;\n const images = isPlainObject(hints?.images) ? hints.images : undefined;\n const hint = images?.[key];\n if (hint === false) return null;\n if (typeof hint === \"string\" && SHAPES.has(hint)) {\n return isSafeImageSrc(value)\n ? { src: value, shape: hint as ImageShape }\n : null;\n }\n if (hint === true) {\n return isSafeImageSrc(value) ? { src: value, shape: defaultShape } : null;\n }\n return looksLikeImageUrl(value) ? { src: value, shape: defaultShape } : null;\n}\n\n/** The standard image element: stable classes, key as alt, lazy loading. */\nexport function imageNode(\n key: string,\n src: string,\n shape: ImageShape\n): WidgetElementNode {\n return el(\"img\", {\n class: `wg-img wg-img-${shape}`,\n src,\n alt: key,\n loading: \"lazy\",\n decoding: \"async\"\n });\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\n\n/**\n * `card` renderer.\n *\n * Uses `data.title`/`data.subtitle`/`data.fields` when present; other\n * plain-object entries become field key/value pairs; primitives and `null`\n * render as a single value line. `meta.title`/`meta.subtitle` fill in when\n * `data` does not provide them. Total: never throws.\n */\nexport function renderCard(payload: WidgetPayload): WidgetNode {\n const { data, meta } = payload;\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n\n let title: unknown;\n let subtitle: unknown;\n let fieldEntries: [string, unknown][] = [];\n let value: string | undefined;\n\n if (isPlainObject(data)) {\n title = data.title;\n subtitle = data.subtitle;\n if (isPlainObject(data.fields)) {\n fieldEntries = Object.entries(data.fields);\n } else {\n fieldEntries = Object.entries(data).filter(\n ([key]) => key !== \"title\" && key !== \"subtitle\"\n );\n }\n } else {\n value = formatValue(data);\n }\n\n if (title === undefined) title = meta?.title;\n if (subtitle === undefined) subtitle = meta?.subtitle;\n\n const children: WidgetNode[] = [];\n if (title !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n children.push(\n el(\"div\", { class: \"wg-card-subtitle\" }, [formatValue(subtitle)])\n );\n }\n if (value !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-value\" }, [value]));\n }\n if (fieldEntries.length > 0) {\n children.push(\n el(\n \"dl\",\n { class: \"wg-card-fields\" },\n fieldEntries.map(([key, fieldValue]) => {\n // Image treatment wins over fieldFormat for the same key.\n const image = resolveImage(key, fieldValue, payload.hints, \"thumb\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(key, image.src, image.shape);\n } else {\n const raw = formatValue(fieldValue);\n const pattern = fieldFormat?.[key];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(key, fieldValue, payload.hints, text);\n }\n return el(\"div\", { class: \"wg-card-field\" }, [\n el(\"dt\", { class: \"wg-card-field-key\" }, [key]),\n el(\"dd\", { class: \"wg-card-field-value\" }, [display])\n ]);\n })\n )\n );\n }\n return el(\"div\", { class: \"wg-card\" }, children);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\n\n/**\n * `table` renderer.\n *\n * One row per record; columns are the union of record keys in first-seen\n * order, overridable via `hints.columns`. Non-array data becomes a\n * single-record array; non-object rows are wrapped as `{ value }`. Missing\n * cells render empty. Total: never throws.\n */\nexport function renderTable(payload: WidgetPayload): WidgetNode {\n const rows = Array.isArray(payload.data) ? payload.data : [payload.data];\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n const records: Record<string, unknown>[] = rows.map((row) =>\n isPlainObject(row) ? row : { value: row }\n );\n\n const hintColumns = payload.hints?.columns;\n let columns: string[];\n if (\n Array.isArray(hintColumns) &&\n hintColumns.every((column): column is string => typeof column === \"string\")\n ) {\n columns = hintColumns;\n } else {\n columns = [];\n const seen = new Set<string>();\n for (const record of records) {\n for (const key of Object.keys(record)) {\n if (!seen.has(key)) {\n seen.add(key);\n columns.push(key);\n }\n }\n }\n }\n\n // Caption chrome from meta \u2014 a table's data has no title slot, so meta\n // is the only source; absence means no caption. <caption> must be the\n // table's first child per the HTML content model.\n const chrome: WidgetNode[] = [];\n const title = payload.meta?.title;\n const subtitle = payload.meta?.subtitle;\n if (title !== undefined || subtitle !== undefined) {\n const parts: WidgetNode[] = [];\n if (title !== undefined) {\n parts.push(el(\"span\", { class: \"wg-table-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n parts.push(\n el(\"span\", { class: \"wg-table-subtitle\" }, [formatValue(subtitle)])\n );\n }\n chrome.push(el(\"caption\", { class: \"wg-table-caption\" }, parts));\n }\n\n return el(\"table\", { class: \"wg-table\" }, [\n ...chrome,\n el(\"thead\", { class: \"wg-table-head\" }, [\n el(\n \"tr\",\n undefined,\n columns.map((column) =>\n el(\"th\", { class: \"wg-table-header\" }, [column])\n )\n )\n ]),\n el(\n \"tbody\",\n { class: \"wg-table-body\" },\n records.map((record) =>\n el(\n \"tr\",\n { class: \"wg-table-row\" },\n columns.map((column) => {\n if (!(column in record)) {\n return el(\"td\", { class: \"wg-table-cell\" }, [\"\"]);\n }\n const value = record[column];\n // Precedence per column: image > link > formatted text.\n const image = resolveImage(column, value, payload.hints, \"avatar\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(column, image.src, image.shape);\n } else {\n const raw = formatValue(value);\n const pattern = fieldFormat?.[column];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(column, value, payload.hints, text);\n }\n return el(\"td\", { class: \"wg-table-cell\" }, [display]);\n })\n )\n )\n )\n ]);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode, WidgetNodeAttrs } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { formatValue, isPlainObject } from \"./format.js\";\n\n/**\n * `tree` renderer.\n *\n * Renders nested `{ label, children[] }` nodes; nodes without a usable\n * `label` get a JSON-snippet fallback (excluding `children`). Recurses only\n * into array-valued `children`. `hints.expandDepth` (default unlimited)\n * marks nodes at depth < value as expanded via `data-expanded` \u2014 state only,\n * no behavior. Total: never throws.\n */\nexport function renderTree(payload: WidgetPayload): WidgetNode {\n const depthHint = payload.hints?.expandDepth;\n const expandDepth =\n typeof depthHint === \"number\" && depthHint >= 0 ? depthHint : Infinity;\n const roots = Array.isArray(payload.data) ? payload.data : [payload.data];\n const list = el(\n \"ul\",\n { class: \"wg-tree\" },\n roots.map((node) => renderNode(node, 0, expandDepth))\n );\n // Title chrome from meta \u2014 tree data has no title slot, so meta is the\n // only source; absence means no title line.\n const title = payload.meta?.title;\n if (title === undefined) return list;\n return el(\"div\", { class: \"wg-tree-titled\" }, [\n el(\"div\", { class: \"wg-tree-title\" }, [formatValue(title)]),\n list\n ]);\n}\n\nfunction nodeLabel(node: unknown): string {\n if (isPlainObject(node)) {\n if (node.label !== undefined) return formatValue(node.label);\n const { children: _children, ...rest } = node;\n if (Object.keys(rest).length > 0) return formatValue(rest);\n }\n return formatValue(node);\n}\n\nfunction renderNode(\n node: unknown,\n depth: number,\n expandDepth: number\n): WidgetNode {\n const hasChildren =\n isPlainObject(node) &&\n Array.isArray(node.children) &&\n node.children.length > 0;\n\n // The expansion attribute marks expandable branches only \u2014 its presence\n // identifies a branch, its value the initial state. Leaves carry none.\n const attrs: WidgetNodeAttrs = hasChildren\n ? {\n class: \"wg-tree-node\",\n \"data-expanded\": depth < expandDepth ? \"true\" : \"false\"\n }\n : { class: \"wg-tree-node\" };\n\n const children: WidgetNode[] = [\n el(\"span\", { class: \"wg-tree-label\" }, [nodeLabel(node)])\n ];\n if (hasChildren) {\n children.push(\n el(\n \"ul\",\n { class: \"wg-tree-children\" },\n (node.children as unknown[]).map((child) =>\n renderNode(child, depth + 1, expandDepth)\n )\n )\n );\n }\n return el(\"li\", attrs, children);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\n\n/**\n * Built-in `custom` renderer \u2014 the generic escape hatch.\n *\n * Renders `data` as pretty-printed JSON in a preformatted block, falling\n * back to `String(data)` when serialization fails (circular data, bigint).\n * Hosts register richer kinds via the catalog's registration API.\n */\nexport function renderCustom(payload: WidgetPayload): WidgetNode {\n let text: string;\n try {\n text = JSON.stringify(payload.data, null, 2) ?? String(payload.data);\n } catch {\n text = String(payload.data);\n }\n return el(\"pre\", { class: \"wg-custom\" }, [text]);\n}\n", "/**\n * `group` built-in \u2014 several widgets in one render.\n *\n * The renderer here only builds the layout container; item rendering is\n * the catalog dispatch's job (items re-enter `catalog.render`, so\n * registered and composed kinds participate and per-item errors keep\n * their structured codes with `data.items[<i>]`-prefixed paths).\n */\nimport type { WidgetContractError } from \"../../contract/errors.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Hard cap on `data.items` \u2014 bounds total render work per call. */\nexport const GROUP_MAX_ITEMS = 20;\n\nexport const GROUP_LAYOUTS = [\"stack\", \"row\", \"grid\"] as const;\nexport const GROUP_GAPS = [\"none\", \"sm\", \"md\", \"lg\"] as const;\n/** `columns` is clamped into this range (grid only). */\nexport const GROUP_MAX_COLUMNS = 4;\n\nexport interface GroupItem {\n kind: string;\n data: unknown;\n hints?: unknown;\n meta?: unknown;\n}\n\nexport type GroupEnvelopeResult =\n | { ok: true; items: GroupItem[] }\n | { ok: false; error: WidgetContractError };\n\n/**\n * Validate the group envelope: `data.items` is an array of sub-widget\n * objects with string kinds, no nested groups, within the item cap.\n * Item *content* is not judged here \u2014 each item faces the full contract\n * and schema validation when it re-enters the catalog.\n */\nexport function checkGroupEnvelope(data: unknown): GroupEnvelopeResult {\n if (!isPlainObject(data) || data.items === undefined) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data.items\",\n message: \"'group' data must be an object with an 'items' array.\"\n }\n };\n }\n const items = data.items;\n if (!Array.isArray(items)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: \"'items' must be an array of sub-widgets.\"\n }\n };\n }\n if (items.length > GROUP_MAX_ITEMS) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: `'items' holds ${items.length} sub-widgets; a group renders at most ${GROUP_MAX_ITEMS}.`\n }\n };\n }\n const checked: GroupItem[] = [];\n for (let i = 0; i < items.length; i++) {\n const item: unknown = items[i];\n if (!isPlainObject(item)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}]`,\n message: \"each item must be an object: { kind, data, hints?, meta? }.\"\n }\n };\n }\n if (typeof item.kind !== \"string\" || item.kind === \"\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"each item needs a widget kind (non-empty string).\"\n }\n };\n }\n if (item.kind === \"group\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"a 'group' cannot contain another 'group'.\"\n }\n };\n }\n const entry: GroupItem = { kind: item.kind, data: item.data };\n if (item.hints !== undefined) entry.hints = item.hints;\n if (item.meta !== undefined) entry.meta = item.meta;\n checked.push(entry);\n }\n return { ok: true, items: checked };\n}\n\n/**\n * Build the layout container. Hints only ever SELECT from the fixed\n * class names below \u2014 no hint or data value contributes characters to\n * the class list. Unknown values fall back to the defaults (hint\n * diagnostics, not renderers, tell the caller).\n */\nexport function renderGroupContainer(\n hints: unknown,\n children: WidgetNode[]\n): WidgetNode {\n const h = isPlainObject(hints) ? hints : {};\n const layout = GROUP_LAYOUTS.some((known) => known === h.layout)\n ? (h.layout as string)\n : \"stack\";\n const gap = GROUP_GAPS.some((known) => known === h.gap)\n ? (h.gap as string)\n : \"md\";\n const classes = [`wg-group`, `wg-group-${layout}`, `wg-gap-${gap}`];\n if (layout === \"grid\") {\n const raw = typeof h.columns === \"number\" && Number.isFinite(h.columns) ? h.columns : 2;\n const columns = Math.min(GROUP_MAX_COLUMNS, Math.max(1, Math.trunc(raw)));\n classes.push(`wg-cols-${columns}`);\n }\n return el(\"div\", { class: classes.join(\" \") }, children);\n}\n", "import { validateWidgetPayload } from \"../contract/validate.js\";\nimport type { WidgetContractError } from \"../contract/errors.js\";\nimport type { WidgetKind } from \"../contract/types.js\";\nimport type { WidgetNode, WidgetRenderer } from \"./node.js\";\nimport type { WidgetDescriptor, WidgetDescriptorInput } from \"./descriptors.js\";\nimport { BUILTIN_DESCRIPTORS } from \"./descriptors.js\";\nimport { validateDataAgainstSchema } from \"./schema.js\";\nimport { renderCard } from \"./widgets/card.js\";\nimport { renderTable } from \"./widgets/table.js\";\nimport { renderTree } from \"./widgets/tree.js\";\nimport { renderCustom } from \"./widgets/custom.js\";\nimport { checkGroupEnvelope, renderGroupContainer } from \"./widgets/group.js\";\n\n/**\n * Group composition: an item's action descriptors were compiled against\n * the ITEM's template, so they name the item's kind (`widget`) but not\n * where the item sits in the group payload. Stamping `at` lets the server\n * fold an action's result back into the right item and re-render the whole\n * group. Returns a NEW tree \u2014 renderers may hand back cached nodes, and\n * composition must not mutate what a pure renderer returned. Groups do not\n * nest, so the location is always one level: `data.items.<i>`.\n */\nfunction stampActionLocation(node: WidgetNode, location: string): WidgetNode {\n if (typeof node === \"string\") return node;\n const raw = node.attrs?.[\"data-wg-action\"];\n let attrs = node.attrs;\n if (typeof raw === \"string\") {\n try {\n const descriptor = JSON.parse(raw) as Record<string, unknown>;\n if (typeof descriptor === \"object\" && descriptor !== null) {\n attrs = { ...node.attrs, \"data-wg-action\": JSON.stringify({ ...descriptor, at: location }) };\n }\n } catch {\n /* not a descriptor */\n }\n }\n const children = node.children?.map((child) => stampActionLocation(child, location));\n return {\n tag: node.tag,\n ...(attrs !== undefined ? { attrs } : {}),\n ...(children !== undefined ? { children } : {})\n };\n}\n\n/**\n * Thrown when a widget kind is registered twice on the same catalog.\n * Double registration is a host programming error, surfaced loudly at\n * setup time \u2014 unlike render-time errors, which are structured results.\n */\nexport class DuplicateKindError extends Error {\n readonly code: \"DUPLICATE_KIND\" = \"DUPLICATE_KIND\";\n readonly kind: string;\n\n constructor(kind: string) {\n super(`Widget kind '${kind}' is already registered.`);\n this.name = \"DuplicateKindError\";\n this.kind = kind;\n }\n}\n\n/** Discriminated result of `catalog.render` (mirrors the contract pattern). */\nexport type RenderResult =\n | { ok: true; node: WidgetNode }\n | { ok: false; error: WidgetContractError };\n\nexport interface WidgetCatalog {\n /**\n * Register a renderer for a new kind, optionally with agent-facing\n * documentation. Throws {@link DuplicateKindError} on duplicates\n * (built-ins included). Without a descriptor, a minimal one is generated\n * so every renderable kind stays listable.\n */\n register(\n kind: WidgetKind,\n renderer: WidgetRenderer,\n descriptor?: WidgetDescriptorInput\n ): void;\n has(kind: WidgetKind): boolean;\n resolve(kind: WidgetKind): WidgetRenderer | undefined;\n /** Currently registered kinds, as a fresh array. */\n kinds(): WidgetKind[];\n /** Descriptor for a kind, or undefined when the kind is unknown. */\n describe(kind: WidgetKind): WidgetDescriptor | undefined;\n /** All descriptors, as a fresh array. */\n list(): WidgetDescriptor[];\n /** Validate a payload against the contract (with this catalog's kinds) and render it. Never throws. */\n render(payload: unknown): RenderResult;\n}\n\n/**\n * Create an independent catalog instance with the built-ins (`card`,\n * `table`, `tree`, `custom`) pre-registered.\n */\nexport function createCatalog(): WidgetCatalog {\n const renderers = new Map<WidgetKind, WidgetRenderer>();\n const descriptors = new Map<WidgetKind, WidgetDescriptor>();\n\n const catalog: WidgetCatalog = {\n register(kind, renderer, descriptor) {\n if (renderers.has(kind)) throw new DuplicateKindError(kind);\n renderers.set(kind, renderer);\n descriptors.set(kind, {\n kind,\n description: descriptor?.description ?? `Custom widget kind '${kind}'.`,\n dataShape: descriptor?.dataShape ?? \"Defined by the registered renderer.\",\n ...(descriptor?.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {}),\n ...(descriptor?.hints ? { hints: descriptor.hints } : {}),\n ...(descriptor?.dataSchema ? { dataSchema: descriptor.dataSchema } : {}),\n ...(descriptor?.styles ? { styles: descriptor.styles } : {})\n });\n },\n has: (kind) => renderers.has(kind),\n resolve: (kind) => renderers.get(kind),\n kinds: () => [...renderers.keys()],\n describe: (kind) => descriptors.get(kind),\n list: () => [...descriptors.values()],\n render(payload) {\n const validated = validateWidgetPayload(payload, {\n knownKinds: new Set(renderers.keys())\n });\n if (!validated.ok) return validated;\n // Opt-in structural validation: kinds with a dataSchema fail fast\n // with a dotted data path instead of rendering a lenient fallback.\n const schema = descriptors.get(validated.payload.kind)?.dataSchema;\n if (schema) {\n const schemaError = validateDataAgainstSchema(\n schema,\n validated.payload.data\n );\n if (schemaError) return { ok: false, error: schemaError };\n }\n // `group` recurses through this same entry so registered and\n // composed kinds participate and per-item failures keep their\n // structured codes, re-pathed under `data.items[<i>]`. Renderers\n // stay pure `(payload) => WidgetNode`; composition is dispatch work.\n if (validated.payload.kind === \"group\") {\n const envelope = checkGroupEnvelope(validated.payload.data);\n if (!envelope.ok) return envelope;\n const children: WidgetNode[] = [];\n for (let i = 0; i < envelope.items.length; i++) {\n const item = envelope.items[i]!;\n const sub = catalog.render({\n kind: item.kind,\n data: item.data,\n ...(item.hints !== undefined ? { hints: item.hints } : {}),\n ...(item.meta !== undefined ? { meta: item.meta } : {})\n });\n if (!sub.ok) {\n const subPath = sub.error.path;\n return {\n ok: false,\n error: {\n ...sub.error,\n path: `data.items[${i}]${subPath ? `.${subPath}` : \"\"}`\n }\n };\n }\n children.push(stampActionLocation(sub.node, `data.items.${i}`));\n }\n return {\n ok: true,\n node: renderGroupContainer(validated.payload.hints, children)\n };\n }\n const renderer = renderers.get(validated.payload.kind);\n if (renderer === undefined) {\n // Unreachable while knownKinds is non-empty; kept for totality.\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${validated.payload.kind}'.`\n }\n };\n }\n // Built-ins are total by construction; this guards the extension\n // point \u2014 a registered renderer that throws must surface as a\n // structured error, never a propagated exception.\n try {\n return { ok: true, node: renderer(validated.payload) };\n } catch (thrown) {\n return {\n ok: false,\n error: {\n code: \"RENDER_FAILED\",\n path: \"widget\",\n message: `Renderer for kind '${validated.payload.kind}' threw: ${\n thrown instanceof Error ? thrown.message : String(thrown)\n }`\n }\n };\n }\n }\n };\n\n // Built-ins go through register() so they get the same duplicate\n // protection and hosts cannot silently override them.\n catalog.register(\"card\", renderCard, BUILTIN_DESCRIPTORS.card);\n catalog.register(\"table\", renderTable, BUILTIN_DESCRIPTORS.table);\n catalog.register(\"tree\", renderTree, BUILTIN_DESCRIPTORS.tree);\n catalog.register(\"custom\", renderCustom, BUILTIN_DESCRIPTORS.custom);\n // `render()` intercepts 'group' before renderer lookup, so this renderer\n // only serves direct `resolve()` callers (e.g. designer previews); it\n // delegates back through the dispatch so items render for them too.\n catalog.register(\n \"group\",\n (payload) => {\n const result = catalog.render(payload);\n if (result.ok) return result.node;\n throw new Error(result.error.message);\n },\n BUILTIN_DESCRIPTORS.group\n );\n\n return catalog;\n}\n", "/**\n * Registered widget styles: custom kinds ship their look as data alongside\n * their template/renderer. Same trust model as themes \u2014 designer-authored,\n * so selectors, properties, and values are all guarded, and unsafe entries\n * are skipped rather than emitted.\n */\nexport type WidgetStyles = Record<string, Record<string, string>>;\n\n/** Substrings that disqualify a selector, property or value. Exported\n * so the authoring guide derives the rule instead of restating it. */\nexport const UNSAFE = /[;{}<>@\\\\]/;\n/** The property-name allowlist: not merely \"no banned characters\". */\nexport const PROPERTY_NAME = /^-?[a-zA-Z][a-zA-Z-]*$/;\n\n/** Every comma-separated selector part must target a .wg- class. */\nfunction isSafeSelector(selector: string): boolean {\n if (UNSAFE.test(selector)) return false;\n const parts = selector.split(\",\").map((part) => part.trim());\n return parts.length > 0 && parts.every((part) => part.includes(\".wg-\"));\n}\n\nfunction isSafeValue(value: string): boolean {\n return (\n !UNSAFE.test(value) &&\n !/url\\s*\\(/i.test(value) &&\n !/expression\\s*\\(/i.test(value)\n );\n}\n\n/**\n * Generate CSS from a styles map, emitting only guarded entries. Values may\n * reference theme tokens via `var(--wg-*)`. Never throws.\n */\nexport function widgetStylesToCss(styles: WidgetStyles): string {\n const rules: string[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (!isSafeSelector(selector)) continue;\n if (typeof declarations !== \"object\" || declarations === null) continue;\n const lines: string[] = [];\n for (const [property, value] of Object.entries(declarations)) {\n if (!PROPERTY_NAME.test(property)) continue;\n if (typeof value !== \"string\" || !isSafeValue(value)) continue;\n lines.push(` ${property}: ${value};`);\n }\n if (lines.length > 0) {\n rules.push(`${selector} {\\n${lines.join(\"\\n\")}\\n}`);\n }\n }\n return rules.join(\"\\n\");\n}\n", "/**\n * Theme token registry. Tokens are the only theming surface: the base\n * stylesheet reads them via `var(--wg-<token>, <default>)` and themes are\n * plain maps of bare token names to values. The defaults table is the\n * single source of truth for the light look.\n */\n/**\n * The token table: every token's default, its VALUE TYPE, and what it is\n * for. Type metadata is not decoration \u2014 tooling reads it (the theme\n * designer picks a color picker vs a text field from `type`, never by\n * guessing at the default's shape) and `list_theme_tokens` tells agents\n * what kind of value each token expects. `use` doubles as the\n * documentation that earns a token its place when the base stylesheet\n * cannot consume it.\n */\nexport type TokenType =\n | \"color\"\n | \"dimension\"\n | \"number\"\n | \"font-family\"\n | \"font-weight\"\n | \"shadow\";\n\nexport interface TokenSpec {\n default: string;\n type: TokenType;\n use: string;\n /**\n * Token this one inherits from when a theme leaves it unset. Declared\n * here rather than special-cased in the stylesheet because a literal\n * default at `:root` would sever that inheritance: a `var()` fallback\n * applies only when the property is UNSET, so defining\n * `--wg-surface: #ffffff` makes `var(--wg-surface, var(--wg-bg, \u2026))`\n * unreachable. The defaults block emits a chain for these instead.\n */\n fallback?: string;\n}\n\nexport const TOKEN_SPECS = {\n bg: { default: \"#ffffff\", type: \"color\", use: \"Page background behind widgets.\" },\n surface: {\n default: \"#ffffff\",\n type: \"color\",\n fallback: \"bg\",\n use: \"Widget panel background (cards, tables); falls back to bg when unset.\"\n },\n fg: { default: \"#1f2430\", type: \"color\", use: \"Primary text.\" },\n muted: { default: \"#6b7280\", type: \"color\", use: \"Secondary text: labels, captions, keys.\" },\n accent: { default: \"#2563eb\", type: \"color\", use: \"Emphasis: titles, links, filled badges.\" },\n \"accent-fg\": {\n default: \"#ffffff\",\n type: \"color\",\n use: \"Text drawn on an accent fill (filled badges and buttons).\"\n },\n border: { default: \"#e2e8f0\", type: \"color\", use: \"Hairlines: panel edges, row rules.\" },\n \"border-width\": { default: \"1px\", type: \"dimension\", use: \"Width of those hairlines.\" },\n radius: { default: \"6px\", type: \"dimension\", use: \"Default corner rounding.\" },\n \"radius-sm\": { default: \"3px\", type: \"dimension\", use: \"Tight rounding: pills, chips, inline marks.\" },\n \"radius-lg\": { default: \"12px\", type: \"dimension\", use: \"Generous rounding: hero media, large panels.\" },\n spacing: { default: \"8px\", type: \"dimension\", use: \"Base spacing step.\" },\n \"spacing-sm\": { default: \"4px\", type: \"dimension\", use: \"Half step: inline gaps inside a row.\" },\n \"spacing-lg\": { default: \"16px\", type: \"dimension\", use: \"Double step: section separation.\" },\n \"font-family\": {\n default: \"system-ui, -apple-system, 'Segoe UI', sans-serif\",\n type: \"font-family\",\n use: \"Body text family.\"\n },\n \"font-mono\": {\n default: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n type: \"font-family\",\n use: \"Monospace family for code and raw JSON (the custom kind).\"\n },\n \"font-size\": { default: \"14px\", type: \"dimension\", use: \"Body text size.\" },\n \"font-size-sm\": { default: \"12px\", type: \"dimension\", use: \"Small text: captions, stats, pills.\" },\n \"font-size-lg\": { default: \"18px\", type: \"dimension\", use: \"Large text: widget titles.\" },\n \"font-weight-bold\": {\n default: \"600\",\n type: \"font-weight\",\n use: \"Weight for titles and emphasized labels.\"\n },\n \"line-height\": { default: \"1.45\", type: \"number\", use: \"Text density.\" },\n shadow: {\n default: \"0 1px 3px rgba(0, 0, 0, 0.12)\",\n type: \"shadow\",\n use: \"Panel elevation.\"\n },\n danger: { default: \"#b91c1c\", type: \"color\", use: \"Error status: fills and text (see .wg-status-danger).\" },\n \"danger-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a danger fill.\" },\n success: { default: \"#15803d\", type: \"color\", use: \"Success status (see .wg-status-success).\" },\n \"success-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a success fill.\" },\n warning: { default: \"#b45309\", type: \"color\", use: \"Warning status (see .wg-status-warning).\" },\n \"warning-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a warning fill.\" },\n info: { default: \"#0369a1\", type: \"color\", use: \"Informational status (see .wg-status-info).\" },\n \"info-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on an info fill.\" },\n \"avatar-size\": { default: \"32px\", type: \"dimension\", use: \"Box of .wg-img-avatar images.\" },\n \"thumb-size\": { default: \"48px\", type: \"dimension\", use: \"Box of .wg-img-thumb images.\" }\n} as const satisfies Record<string, TokenSpec>;\n\n/** Default value per token \u2014 derived, so the table stays the one source. */\nexport const TOKEN_DEFAULTS = Object.fromEntries(\n Object.entries(TOKEN_SPECS).map(([name, spec]) => [name, spec.default])\n) as { [K in keyof typeof TOKEN_SPECS]: (typeof TOKEN_SPECS)[K][\"default\"] };\n\nexport type ThemeToken = keyof typeof TOKEN_SPECS;\n\n/** All theme token names, in defaults-table order. */\nexport const THEME_TOKENS: readonly ThemeToken[] = Object.keys(\n TOKEN_SPECS\n) as ThemeToken[];\n\n/**\n * A theme: bare token names to CSS values. Bare keys make unknown-token\n * validation trivial and structurally prevent setting arbitrary custom\n * properties \u2014 the `--wg-` prefix is always applied by this module.\n */\nexport type WidgetTheme = Partial<Record<ThemeToken, string>>;\n\n/**\n * A theme plus author-defined `x-*` variables (emitted as `--wg-x-<name>`).\n * Kept as a separate type on purpose: `WidgetTheme` has only optional\n * properties, which is what makes TypeScript reject `{ sneaky: \"red\" }` via\n * weak-type detection \u2014 an index signature here would silently disable that\n * protection for every consumer. Functions accept this wider input; the\n * runtime validator is the authority on which keys are legal.\n */\nexport type WidgetThemeInput = WidgetTheme &\n Partial<Record<`x-${string}`, string>>;\n\nexport type ThemeErrorCode =\n | \"INVALID_THEME\"\n | \"UNKNOWN_TOKEN\"\n | \"INVALID_TOKEN_VALUE\";\n\nexport interface ThemeError {\n code: ThemeErrorCode;\n message: string;\n /** Offending token name, when applicable. */\n token?: string;\n}\n\n/**\n * Value guard shared by validation (strict) and application (lenient\n * defense in depth). Rejects exfiltration and execution vectors \u2014 not\n * invalid CSS: declaration/HTML escapes, `url()` (resource fetching), and\n * `expression()` (legacy script execution in old embedded webviews).\n */\nexport function isSafeTokenValue(value: string): boolean {\n return (\n !/[;{}<>]/.test(value) &&\n !/url\\s*\\(/i.test(value) &&\n !/expression\\s*\\(/i.test(value)\n );\n}\n", "import type { ThemeToken } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_DEFAULTS } from \"./tokens.js\";\n\n/** `var(--wg-<token>, <light default>)` \u2014 every themeable knob goes through this. */\nfunction v(token: ThemeToken): string {\n return `var(--wg-${token}, ${TOKEN_DEFAULTS[token]})`;\n}\n\n/**\n * Every registry token DEFINED at :root with its default, so custom\n * widget styles may reference bare `var(--wg-<token>)` and always\n * resolve. The built-in rules below carry their own fallbacks and never\n * needed this; custom authors write plain references (per the authoring\n * guide), and before this block an applied theme was the only thing that\n * defined tokens \u2014 every token it didn't set silently collapsed the\n * author's declaration (observed live: a valid widget rendered jammed\n * because `--wg-spacing-lg` was \"not defined\"). Themes override these\n * (later style elements and element-level applyTheme both win).\n *\n * Literals only \u2014 a chain here would NOT work: `--wg-surface:\n * var(--wg-bg, \u2026)` substitutes against `:root`'s own `--wg-bg` at\n * computed-value time and inherits that resolved value, so a descendant\n * overriding `--wg-bg` never reaches it. Tokens declaring a `fallback`\n * are resolved where the theme is applied instead (see `withFallbacks`\n * in apply.ts); this block only guarantees a bare `var(--wg-<token>)`\n * always resolves to something.\n */\nconst tokenDefaultsBlock = `:root {\n${THEME_TOKENS.map((token) => ` --wg-${token}: ${TOKEN_DEFAULTS[token]};`).join(\"\\n\")}\n}`;\n\n/**\n * Predefined styles for the built-in `wg-*` classes. Generated from the\n * token defaults table, so the light theme lives in exactly one place and\n * every visual knob is overridable by a theme.\n */\nexport const baseStylesheet = `\n${tokenDefaultsBlock}\n.wg-card, .wg-table, .wg-tree, .wg-custom, .wg-template {\n font-family: ${v(\"font-family\")};\n font-size: ${v(\"font-size\")};\n line-height: ${v(\"line-height\")};\n color: ${v(\"fg\")};\n}\n.wg-card {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius-lg\")};\n box-shadow: ${v(\"shadow\")};\n padding: ${v(\"spacing-lg\")};\n}\n.wg-card-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-subtitle {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-fields {\n margin: 0;\n}\n.wg-card-field {\n display: flex;\n gap: ${v(\"spacing\")};\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-card-field-key {\n color: ${v(\"muted\")};\n}\n.wg-card-field-value {\n margin: 0;\n}\n.wg-table {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n border-collapse: collapse;\n}\n.wg-table-header {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n text-align: left;\n border-bottom: calc(${v(\"border-width\")} * 2) solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-table-cell {\n border-bottom: ${v(\"border-width\")} solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-tree {\n list-style: none;\n margin: 0;\n padding-left: 0;\n}\n.wg-tree-children {\n list-style: none;\n padding-left: ${v(\"spacing-lg\")};\n border-left: ${v(\"border-width\")} solid ${v(\"border\")};\n}\n.wg-tree-node {\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-tree-node[data-expanded=\"false\"] > .wg-tree-children {\n display: none;\n}\n.wg-custom {\n font-family: ${v(\"font-mono\")};\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n padding: ${v(\"spacing\")};\n overflow: auto;\n}\n.wg-status {\n display: inline-block;\n padding: 0 ${v(\"spacing-sm\")};\n border-radius: ${v(\"radius-sm\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n}\n.wg-status-danger { background: ${v(\"danger\")}; color: ${v(\"danger-fg\")}; }\n.wg-status-success { background: ${v(\"success\")}; color: ${v(\"success-fg\")}; }\n.wg-status-warning { background: ${v(\"warning\")}; color: ${v(\"warning-fg\")}; }\n.wg-status-info { background: ${v(\"info\")}; color: ${v(\"info-fg\")}; }\n.wg-status-accent { background: ${v(\"accent\")}; color: ${v(\"accent-fg\")}; }\n.wg-img {\n object-fit: cover;\n vertical-align: middle;\n background: ${v(\"border\")};\n}\n.wg-img-avatar {\n width: ${v(\"avatar-size\")};\n height: ${v(\"avatar-size\")};\n border-radius: 50%;\n}\n.wg-img-thumb {\n width: ${v(\"thumb-size\")};\n height: ${v(\"thumb-size\")};\n border-radius: ${v(\"radius\")};\n}\n.wg-img-hero {\n display: block;\n width: 100%;\n max-width: 100%;\n height: auto;\n border-radius: ${v(\"radius\")};\n}\n.wg-table-caption {\n caption-side: top;\n text-align: left;\n padding-bottom: ${v(\"spacing\")};\n}\n.wg-table-title {\n display: block;\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing-sm\")};\n}\n.wg-table-subtitle {\n display: block;\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n}\n.wg-tree-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-link {\n color: ${v(\"accent\")};\n text-decoration: underline;\n}\n.wg-group {\n display: flex;\n flex-direction: column;\n}\n.wg-group-row {\n flex-direction: row;\n flex-wrap: wrap;\n}\n.wg-group-row > * {\n flex: 1 1 240px;\n min-width: 0;\n}\n.wg-group-grid {\n display: grid;\n}\n.wg-group-grid > * {\n min-width: 0;\n}\n.wg-cols-1 { grid-template-columns: 1fr; }\n.wg-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }\n.wg-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }\n.wg-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }\n.wg-gap-none { gap: 0; }\n.wg-gap-sm { gap: ${v(\"spacing-sm\")}; }\n.wg-gap-md { gap: ${v(\"spacing\")}; }\n.wg-gap-lg { gap: ${v(\"spacing-lg\")}; }\n`.trim();\n\nconst STYLE_MARKER = \"data-widgentic\";\n\n/**\n * Append the base stylesheet to the document head as a marked `<style>`\n * element. Idempotent: repeated calls leave exactly one element.\n */\nexport function injectBaseStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"base\");\n style.textContent = baseStylesheet;\n doc.head.appendChild(style);\n}\n", "import type { ThemeError, TokenSpec, WidgetTheme, WidgetThemeInput } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_SPECS, isSafeTokenValue } from \"./tokens.js\";\n\nexport type ValidateThemeResult =\n | { ok: true; theme: WidgetThemeInput }\n | { ok: false; error: ThemeError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst KNOWN_TOKENS: ReadonlySet<string> = new Set(THEME_TOKENS);\n\n/**\n * Author-defined variables: `x-<name>` keys are accepted alongside registry\n * tokens and emitted as `--wg-x-<name>`. This is the sanctioned escape\n * hatch for custom widgets that need their own knobs, so the registry does\n * not have to grow for every one-off. Names are lowercase/kebab so the\n * generated custom property is always a valid CSS identifier. Exported so\n * tooling states this rule by reading it, never by restating it.\n */\nexport const CUSTOM_VARIABLE = /^x-[a-z0-9][a-z0-9-]*$/;\n\n/** Custom-variable keys carried by a theme, in declaration order. */\nfunction customKeys(theme: WidgetThemeInput): string[] {\n return Object.keys(theme).filter((key) => CUSTOM_VARIABLE.test(key));\n}\n\n/** The `--wg-*` property name a theme key maps to. */\nfunction propertyName(key: string): string {\n return `--wg-${key}`;\n}\n\n/** Validate an unknown value as a theme. Never throws. */\nexport function validateTheme(input: unknown): ValidateThemeResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: { code: \"INVALID_THEME\", message: \"Theme must be a plain object.\" }\n };\n }\n for (const [token, value] of Object.entries(input)) {\n if (!KNOWN_TOKENS.has(token) && !CUSTOM_VARIABLE.test(token)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_TOKEN\",\n message:\n `Unknown theme token '${token}'. Use a registry token, or a ` +\n `custom variable named 'x-<lowercase-kebab>'.`,\n token\n }\n };\n }\n if (typeof value !== \"string\" || !isSafeTokenValue(value)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TOKEN_VALUE\",\n message: `Token '${token}' has an invalid or unsafe value.`,\n token\n }\n };\n }\n }\n return { ok: true, theme: input as WidgetThemeInput };\n}\n\n/**\n * Fill in tokens a theme left unset that declare a `fallback`, using the\n * fallback token's value FROM THIS THEME.\n *\n * This cannot live in the base stylesheet: a `:root` chain\n * (`--wg-surface: var(--wg-bg, \u2026)`) substitutes against `:root`'s own\n * `--wg-bg` at computed-value time and then inherits that resolved\n * value, so a descendant overriding `--wg-bg` never reaches it. Resolving\n * where the theme is applied puts both declarations on the same element,\n * which is the only place the relationship holds (observed live at v24: a\n * bg-only dark theme painted white cards).\n */\nfunction withFallbacks(theme: WidgetThemeInput): WidgetThemeInput {\n const source = theme as Record<string, unknown>;\n let filled: Record<string, unknown> | undefined;\n for (const token of THEME_TOKENS) {\n const { fallback } = TOKEN_SPECS[token] as TokenSpec;\n if (fallback === undefined) continue;\n if (typeof source[token] === \"string\") continue; // theme set it explicitly\n const inherited = source[fallback];\n if (typeof inherited !== \"string\") continue; // nothing to inherit from\n filled ??= { ...source };\n filled[token] = inherited;\n }\n return (filled ?? theme) as WidgetThemeInput;\n}\n\n/**\n * Apply a theme to a container as inline `--wg-*` custom properties\n * (scoped: descendants inherit them; siblings are unaffected). Replace\n * semantics \u2014 previously applied tokens are removed first, so\n * `applyTheme(el, {})` resets to the stylesheet defaults. Invalid entries\n * are skipped; the CSSOM path (`setProperty`) parses no stylesheet text,\n * so declaration escape is structurally impossible here.\n */\nexport function applyTheme(container: Element, input: WidgetThemeInput): void {\n const theme = withFallbacks(input);\n const style = (container as Partial<ElementCSSInlineStyle>).style;\n if (!style) return;\n // Replace semantics: clear every property this module could have set,\n // custom variables included (they are removed by name from the inline\n // style, which is the only place applyTheme writes).\n for (const token of THEME_TOKENS) {\n style.removeProperty(propertyName(token));\n }\n for (let i = style.length - 1; i >= 0; i--) {\n const property = style.item(i);\n if (property.startsWith(\"--wg-x-\")) style.removeProperty(property);\n }\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n style.setProperty(propertyName(key), value);\n }\n }\n}\n\n/**\n * Generate a CSS rule assigning the theme's tokens under `selector`\n * (default `:root`). Only entries passing the safety guard are emitted.\n */\nexport function themeToCss(input: WidgetThemeInput, selector = \":root\"): string {\n const theme = withFallbacks(input);\n const declarations: string[] = [];\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n declarations.push(` ${propertyName(key)}: ${value};`);\n }\n }\n return `${selector} {\\n${declarations.join(\"\\n\")}\\n}`;\n}\n\n/** Dark preset \u2014 ordinary theme data, a starting point for custom themes. */\nexport const darkTheme: WidgetTheme = {\n bg: \"#0f131c\",\n surface: \"#161b26\",\n fg: \"#e5e9f0\",\n muted: \"#8b93a7\",\n accent: \"#7aa2f7\",\n \"accent-fg\": \"#0f131c\",\n border: \"#2a3140\",\n shadow: \"0 1px 3px rgba(0, 0, 0, 0.6)\",\n danger: \"#f0a3a3\",\n success: \"#8fd19e\",\n warning: \"#e8b878\",\n info: \"#7cc4e8\"\n};\n", "/**\n * The one `isPlainObject`. Every entry imports it relatively, so the\n * zero-dependency entries stay zero-dependency and the source-scan tests\n * keep passing.\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "/**\n * Safety constants shared by validation (strict) and interpretation\n * (lenient defense in depth). Both layers MUST consult these \u2014 keeping them\n * in one module is what prevents the two from drifting. URL safety itself\n * lives in the contract layer (`contract/urls.ts`) so the catalog's image\n * rendering shares the exact same rules; re-exported here to keep this\n * module the single import point for template safety.\n */\nexport {\n ALLOWED_SCHEMES,\n isSafeUrl,\n isSafeImageSrc\n} from \"../contract/urls.js\";\n\n/**\n * Attributes that are code or embedded documents: event handlers (`on*`)\n * and `srcdoc`, which smuggles a whole document past the tag policy.\n */\nexport const FORBIDDEN_ATTR = /^(?:on.*|srcdoc)$/i;\n\n/**\n * Tags that introduce active or foreign content into the frame. A template\n * is data, never a program: these fail validation and render as nothing\n * when validation was bypassed \u2014 the same two-layer stance as `on*`.\n */\nexport const FORBIDDEN_TAGS: ReadonlySet<string> = new Set([\n \"script\", \"iframe\", \"frame\", \"frameset\", \"object\", \"embed\", \"style\",\n \"link\", \"meta\", \"base\", \"template\", \"noscript\"\n]);\n\n/**\n * Renderer-owned attributes (`data-wg-*`): action descriptors and render\n * markers. Authors cannot write them \u2014 only a validated `action` binding\n * produces one \u2014 so a hand-written descriptor never reaches a tree.\n */\nexport const RESERVED_ATTR = /^data-wg-/i;\n\n/** Attributes whose values are URLs and can smuggle script schemes. */\nexport const URL_ATTRS = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"data\",\n \"poster\",\n \"ping\"\n]);\n\n/** Maximum template nesting depth accepted by validation. */\nexport const MAX_TEMPLATE_DEPTH = 64;\n", "/**\n * The template path grammar, shared by validation (strict) and\n * interpretation (lenient) so the two never drift:\n *\n * \".\" the current scope itself\n * \"$index\" zero-based position in the innermost `each`\n * \"$meta.<segments>\" reads payload.meta\n * \"$root[.<segments>]\" reads payload.data regardless of `each` nesting\n * \"$parent\"+ [.<rest>] steps out of one enclosing `each` per token;\n * <rest> is segments, \"$index\", or nothing\n * \"<segments>\" dot path against the current scope\n *\n * Reserved tokens (`$meta`, `$root`, `$parent`, `$index`) are only valid in\n * the positions above; anywhere else the path is invalid.\n */\nexport interface ParsedPath {\n base: \"scope\" | \"meta\" | \"root\";\n /** Enclosing-scope hops (`$parent` count). */\n up: number;\n /** The path names the current index rather than a value. */\n index: boolean;\n segments: string[];\n}\n\nconst RESERVED = new Set([\"$meta\", \"$root\", \"$parent\", \"$index\"]);\n\n/** Parse a path; `undefined` when the syntax is invalid. Never throws. */\nexport function parsePath(value: string): ParsedPath | undefined {\n if (value === \".\") return { base: \"scope\", up: 0, index: false, segments: [] };\n const tokens = value.split(\".\");\n let i = 0;\n let base: ParsedPath[\"base\"] = \"scope\";\n let up = 0;\n if (tokens[0] === \"$meta\") {\n base = \"meta\";\n i = 1;\n } else if (tokens[0] === \"$root\") {\n base = \"root\";\n i = 1;\n } else {\n while (tokens[i] === \"$parent\") {\n up++;\n i++;\n }\n }\n const rest = tokens.slice(i);\n if (rest.length === 1 && rest[0] === \"$index\") {\n if (base !== \"scope\") return undefined;\n return { base, up, index: true, segments: [] };\n }\n if (rest.length === 0) {\n if (base === \"meta\") return undefined;\n return { base, up, index: false, segments: [] };\n }\n if (rest.some((segment) => segment === \"\" || RESERVED.has(segment))) return undefined;\n return { base, up, index: false, segments: rest };\n}\n", "/**\n * The action model: what a widget can ask for when a person activates a\n * bound element. Two kinds \u2014 `prompt` proposes a user message through the\n * host, `http` performs a server-side request against an author-declared\n * URL \u2014 both plain JSON data, storable and validatable, never code.\n *\n * Zero-dependency by design: this module is shared by the template\n * compiler (which resolves bindings into descriptors at render time), the\n * store (which validates stored actions), the server (which executes) and\n * the designers (which edit).\n */\nimport type { DataSchema } from \"../catalog/index.js\";\n\n/** A prompt's text: literals and `{ bind }` segments resolved at render time. */\nexport type PromptSegment = string | { bind: string };\n\nexport interface PromptActionDefinition {\n kind: \"prompt\";\n text: PromptSegment[];\n}\n\n/** A by-name reference to one of the principal's secrets. */\nexport interface SecretRef {\n secret: string;\n}\n\n/** Header and query values: author literals or secret references. */\nexport type HeaderValue = string | SecretRef;\n\nexport type HttpMethod = \"GET\" | \"POST\";\n\nexport interface HttpActionDefinition {\n kind: \"http\";\n method: HttpMethod;\n /** Absolute https URL, fixed by the author \u2014 bindings never reach it. */\n url: string;\n /** JSON Schema (`type: \"object\"`) of the arguments. */\n input: DataSchema;\n /** JSON Schema the response body must satisfy. */\n output: DataSchema;\n headers?: Record<string, HeaderValue>;\n query?: Record<string, HeaderValue>;\n}\n\nexport type ActionDefinition = PromptActionDefinition | HttpActionDefinition;\n\n/** A shared, named action a principal owns. */\nexport interface StoredAction {\n name: string;\n label?: string;\n description?: string;\n definition: ActionDefinition;\n}\n\n/** Input mapping: input-schema field \u2192 template path or literal. */\nexport type InputMapping = Record<string, string | { const: unknown }>;\n\nexport type OutputMode = \"replace\" | \"merge\" | \"patch\";\n\nexport interface OutputBinding {\n /** Default `merge`. */\n mode?: OutputMode;\n /** Required for `patch`: the dotted data path the response is written at. */\n path?: string;\n /** Projection applied first: target data path \u2192 source response path. */\n map?: Record<string, string>;\n}\n\n/**\n * A binding names an action \u2014 a shared one by `ref`, or an inline one\n * under `definition` (nested so the definition's `input`/`output` schemas\n * never collide with the binding's `input` mapping and `output` mode) \u2014\n * plus how data flows.\n */\nexport type ActionBinding = ({ ref: string } | { definition: ActionDefinition }) & {\n input?: InputMapping;\n output?: OutputBinding;\n};\n\n/** Why an action renders unavailable. */\nexport type ActionDisabledReason = \"scope\" | \"unresolved\";\n\n/**\n * What a rendered element carries in `data-wg-action`: everything the\n * bridge needs, nothing it must evaluate.\n */\nexport interface ActionDescriptor {\n /** Binding identifier: the element's dotted template path, or \"load\". */\n id: string;\n kind?: ActionDefinition[\"kind\"];\n /** Resolved http arguments. */\n args?: Record<string, unknown>;\n /** Resolved prompt text. */\n text?: string;\n disabled?: ActionDisabledReason;\n /** The kind whose template declared the binding (set when registered). */\n widget?: string;\n /**\n * Inside a `group` render: the dotted path of the item payload within the\n * root payload (e.g. `data.items.2`), stamped by the group composition.\n */\n at?: string;\n}\n\n/** Structured validation error; `path` is dotted, relative to the caller's root. */\nexport interface ActionError {\n code: \"INVALID_ACTION\";\n message: string;\n path: string;\n}\n\n/** Upper bound on a resolved prompt message. */\nexport const PROMPT_TEXT_MAX = 2_000;\n\n/** Secret names: short, lowercase, URL- and header-safe. */\nexport const SECRET_NAME = /^[a-z][a-z0-9-]{0,63}$/;\n\n/** Action names share the secret-name discipline. */\nexport const ACTION_NAME = SECRET_NAME;\n\nexport const OUTPUT_MODES: readonly OutputMode[] = [\"replace\", \"merge\", \"patch\"];\n\nexport const HTTP_METHODS: readonly HttpMethod[] = [\"GET\", \"POST\"];\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type {\n ActionDefinition,\n ActionError\n} from \"./types.js\";\nimport {\n HTTP_METHODS,\n OUTPUT_MODES,\n PROMPT_TEXT_MAX,\n SECRET_NAME\n} from \"./types.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction fail(message: string, path: string): ActionError {\n return { code: \"INVALID_ACTION\", message, path };\n}\n\n/** RFC 7230 token: what a header or query parameter NAME may be. */\nconst HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\n/** Header names the transport owns; an author must not set them. */\nconst RESERVED_HEADERS: ReadonlySet<string> = new Set([\n \"host\", \"content-length\", \"transfer-encoding\", \"connection\"\n]);\n\n/** Segments that would reach the prototype chain or the template grammar's reserved tokens. */\nconst FORBIDDEN_SEGMENTS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * The dotted-path grammar for output `path` and `map` entries: non-empty\n * segments, no `$`-tokens, nothing that addresses a prototype.\n */\nexport function isDataPath(value: string): boolean {\n if (value === \"\") return false;\n return value.split(\".\").every(\n (segment) => segment !== \"\" && !segment.startsWith(\"$\") && !FORBIDDEN_SEGMENTS.has(segment)\n );\n}\n\n/** A header/query value: literal string or `{ secret: name }`. */\nfunction checkHeaderValue(value: unknown, path: string): ActionError | undefined {\n if (typeof value === \"string\") return undefined;\n if (isPlainObject(value) && typeof value.secret === \"string\") {\n if (!SECRET_NAME.test(value.secret)) {\n return fail(`Secret reference '${value.secret}' is not a valid secret name.`, path);\n }\n if (Object.keys(value).length !== 1) {\n return fail(\"A secret reference carries only 'secret'.\", path);\n }\n return undefined;\n }\n return fail(\"Value must be a string or a { secret } reference.\", path);\n}\n\n/** Does any nested value look like a secret reference? */\nfunction containsSecretRef(value: unknown): boolean {\n if (!isPlainObject(value) && !Array.isArray(value)) return false;\n if (isPlainObject(value) && typeof value.secret === \"string\") return true;\n const entries = Array.isArray(value) ? value : Object.values(value);\n return entries.some(containsSecretRef);\n}\n\nfunction checkUrl(url: unknown, path: string): ActionError | undefined {\n if (typeof url !== \"string\" || url.length === 0) {\n return fail(\"'url' must be a non-empty string.\", path);\n }\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return fail(`'url' must be an absolute URL (got '${url}').`, path);\n }\n if (parsed.protocol !== \"https:\") return fail(\"'url' must use https.\", path);\n if (parsed.username !== \"\" || parsed.password !== \"\") {\n return fail(\"'url' must not carry userinfo.\", path);\n }\n if (parsed.hash !== \"\") return fail(\"'url' must not carry a fragment.\", path);\n return undefined;\n}\n\n/**\n * Validate an action definition. `path` locates it for the caller (an\n * element's `action`, a stored action's `definition`). Never throws.\n */\nexport interface DefinitionCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n}\n\nexport function validateActionDefinition(\n input: unknown,\n path = \"\",\n options: DefinitionCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action definition must be an object.\", path);\n if (input.kind === \"prompt\") {\n if (!Array.isArray(input.text)) {\n return fail(\"'text' must be an array of literals and { bind } segments.\", join(path, \"text\"));\n }\n let literal = 0;\n for (let i = 0; i < input.text.length; i++) {\n const segment = input.text[i];\n if (typeof segment === \"string\") {\n literal += segment.length;\n continue;\n }\n if (isPlainObject(segment) && typeof segment.bind === \"string\" && Object.keys(segment).length === 1) {\n if (options.isPath && !options.isPath(segment.bind)) {\n return fail(`Invalid data path '${segment.bind}'.`, join(path, `text.${i}`));\n }\n continue;\n }\n return fail(\"Prompt segments are strings or { bind } objects.\", join(path, `text.${i}`));\n }\n if (literal > PROMPT_TEXT_MAX) {\n return fail(`Prompt text exceeds ${PROMPT_TEXT_MAX} characters.`, join(path, \"text\"));\n }\n return undefined;\n }\n if (input.kind === \"http\") {\n if (!HTTP_METHODS.some((m) => m === input.method)) {\n return fail(\"'method' must be GET or POST.\", join(path, \"method\"));\n }\n const urlError = checkUrl(input.url, join(path, \"url\"));\n if (urlError) return urlError;\n if (!isPlainObject(input.input) || input.input.type !== \"object\") {\n return fail(\"'input' must be a JSON Schema with type \\\"object\\\".\", join(path, \"input\"));\n }\n if (containsSecretRef(input.input)) {\n return fail(\"Secret references are allowed only in headers and query.\", join(path, \"input\"));\n }\n if (!isPlainObject(input.output)) {\n return fail(\"'output' must be a JSON Schema object.\", join(path, \"output\"));\n }\n for (const field of [\"headers\", \"query\"] as const) {\n const map = input[field];\n if (map === undefined) continue;\n if (!isPlainObject(map)) return fail(`'${field}' must be an object.`, join(path, field));\n for (const [name, value] of Object.entries(map)) {\n const namePath = join(path, `${field}.${name}`);\n if (!HEADER_TOKEN.test(name)) {\n return fail(`'${name}' is not a valid ${field === \"headers\" ? \"header\" : \"parameter\"} name.`, namePath);\n }\n if (field === \"headers\" && RESERVED_HEADERS.has(name.toLowerCase())) {\n return fail(`Header '${name}' is set by the transport and cannot be declared.`, namePath);\n }\n const error = checkHeaderValue(value, namePath);\n if (error) return error;\n }\n }\n return undefined;\n }\n return fail(\"'kind' must be \\\"prompt\\\" or \\\"http\\\".\", join(path, \"kind\"));\n}\n\nexport interface BindingCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n /** Resolve a `ref` to its definition when the caller knows the catalog. */\n resolve?: (ref: string) => ActionDefinition | undefined;\n /** `load` bindings: http GET only. */\n loadOnly?: boolean;\n}\n\nfunction definitionOf(\n binding: Record<string, unknown>,\n options: BindingCheckOptions\n): ActionDefinition | undefined {\n if (typeof binding.ref === \"string\") return options.resolve?.(binding.ref);\n return binding.definition as ActionDefinition | undefined;\n}\n\n/**\n * Validate a binding: `{ ref }` or an inline definition, plus `input` and\n * `output`. When the definition is known (inline, or resolved through\n * `options.resolve`), input keys are checked against its input schema and\n * `load` bindings are held to http GET. Never throws.\n */\nexport function validateActionBinding(\n input: unknown,\n path = \"\",\n options: BindingCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action binding must be an object.\", path);\n const hasRef = \"ref\" in input;\n if (hasRef) {\n if (typeof input.ref !== \"string\" || input.ref.length === 0) {\n return fail(\"'ref' must name a shared action.\", join(path, \"ref\"));\n }\n if (\"definition\" in input) return fail(\"A binding is either a { ref } or a { definition }, not both.\", path);\n if (options.resolve && options.resolve(input.ref) === undefined) {\n return fail(`Unknown action '${input.ref}'.`, join(path, \"ref\"));\n }\n } else if (\"definition\" in input) {\n const definitionError = validateActionDefinition(input.definition, join(path, \"definition\"), {\n ...(options.isPath ? { isPath: options.isPath } : {})\n });\n if (definitionError) return definitionError;\n } else {\n return fail(\"A binding names a shared action ({ ref }) or carries an inline { definition }.\", path);\n }\n const definition = definitionOf(input, options);\n\n if (options.loadOnly && definition !== undefined) {\n if (definition.kind !== \"http\" || definition.method !== \"GET\") {\n return fail(\"'load' accepts only http GET actions.\", path);\n }\n }\n\n if (input.input !== undefined) {\n if (!isPlainObject(input.input)) return fail(\"'input' must be an object.\", join(path, \"input\"));\n if (definition?.kind === \"prompt\") {\n return fail(\"Prompt actions take no input mapping.\", join(path, \"input\"));\n }\n const declared = definition?.kind === \"http\" && isPlainObject(definition.input.properties)\n ? definition.input.properties\n : undefined;\n for (const [field, value] of Object.entries(input.input)) {\n const fieldPath = join(path, `input.${field}`);\n if (declared !== undefined && !(field in declared)) {\n return fail(`Input field '${field}' is not declared by the action's input schema.`, fieldPath);\n }\n if (typeof value === \"string\") {\n if (options.isPath && !options.isPath(value)) {\n return fail(`Invalid data path '${value}'.`, fieldPath);\n }\n continue;\n }\n if (isPlainObject(value) && \"const\" in value && Object.keys(value).length === 1) {\n if (containsSecretRef(value.const)) {\n return fail(\"Secret references are allowed only in headers and query.\", fieldPath);\n }\n continue;\n }\n return fail(\"Input values are data paths or { const } literals.\", fieldPath);\n }\n }\n\n if (input.output !== undefined) {\n const outPath = join(path, \"output\");\n if (!isPlainObject(input.output)) return fail(\"'output' must be an object.\", outPath);\n if (definition?.kind === \"prompt\") return fail(\"Prompt actions have no output.\", outPath);\n const { mode, path: target, map } = input.output;\n if (mode !== undefined && !OUTPUT_MODES.some((m) => m === mode)) {\n return fail(\"'mode' must be replace, merge or patch.\", join(outPath, \"mode\"));\n }\n if (mode === \"patch\") {\n if (typeof target !== \"string\" || !isDataPath(target)) {\n return fail(\"'patch' requires a valid data 'path'.\", join(outPath, \"path\"));\n }\n } else if (target !== undefined) {\n return fail(\"'path' is only meaningful with mode \\\"patch\\\".\", join(outPath, \"path\"));\n }\n if (map !== undefined) {\n if (!isPlainObject(map)) return fail(\"'map' must be an object of data paths.\", join(outPath, \"map\"));\n const entries = Object.entries(map);\n if (entries.length === 0) return fail(\"'map' must not be empty (omit it to take the whole response).\", join(outPath, \"map\"));\n for (const [key, value] of entries) {\n const entryPath = join(outPath, `map.${key}`);\n if (key === \".\") {\n if (entries.length > 1) return fail(\"A '.' target takes the whole projection and must be the only entry.\", entryPath);\n } else if (!isDataPath(key)) {\n return fail(`'${key}' is not a valid data path.`, entryPath);\n }\n if (typeof value !== \"string\" || (value !== \".\" && !isDataPath(value))) {\n return fail(\"Map values are data paths into the response ('.' for the whole response).\", entryPath);\n }\n }\n }\n }\n return undefined;\n}\n\n/** A widget's `load` binding: http GET only (see `BindingCheckOptions.loadOnly`). */\nexport function validateLoadBinding(\n input: unknown,\n path = \"load\",\n options: Omit<BindingCheckOptions, \"loadOnly\"> = {}\n): ActionError | undefined {\n return validateActionBinding(input, path, { ...options, loadOnly: true });\n}\n\n/** Secret names an http definition references in its headers and query. */\nexport function collectSecretRefs(definition: unknown): string[] {\n if (!isPlainObject(definition) || definition.kind !== \"http\") return [];\n const names = new Set<string>();\n for (const field of [\"headers\", \"query\"] as const) {\n const map = definition[field];\n if (!isPlainObject(map)) continue;\n for (const value of Object.values(map)) {\n if (isPlainObject(value) && typeof value.secret === \"string\") names.add(value.secret);\n }\n }\n return [...names];\n}\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type { TemplateError, WidgetTemplate } from \"./types.js\";\nimport { FORBIDDEN_ATTR, FORBIDDEN_TAGS, MAX_TEMPLATE_DEPTH, RESERVED_ATTR } from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { validateActionBinding } from \"../actions/validate.js\";\n\nexport type ValidateTemplateResult =\n | { ok: true; template: WidgetTemplate }\n | { ok: false; error: TemplateError };\n\n/**\n * Thrown by `registerTemplate` when the template fails validation \u2014\n * registration is host setup, where failing loudly is the convention.\n * Carries the structured error for programmatic handling.\n */\nexport class InvalidTemplateError extends Error {\n readonly templateError: TemplateError;\n\n constructor(kind: string, error: TemplateError) {\n super(\n `Invalid widget template for kind '${kind}' at '${error.path}': ${error.message} (${error.code})`\n );\n this.name = \"InvalidTemplateError\";\n this.templateError = error;\n }\n}\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction nodeError(message: string, path: string): TemplateError {\n return { code: \"INVALID_TEMPLATE_NODE\", message, path };\n}\n\n/** Path syntax per paths.ts: \".\", \"$index\", \"$meta.\"/\"$root.\"/\"$parent.\"-prefixed, or dot segments. */\nfunction checkPathSyntax(value: string, path: string): TemplateError | undefined {\n if (parsePath(value) !== undefined) return undefined;\n return {\n code: \"INVALID_PATH\",\n message: `Invalid data path '${value}'.`,\n path\n };\n}\n\nfunction check(node: unknown, path: string, depth: number): TemplateError | undefined {\n if (depth > MAX_TEMPLATE_DEPTH) {\n return {\n code: \"TEMPLATE_TOO_DEEP\",\n message: `Template exceeds the maximum nesting depth of ${MAX_TEMPLATE_DEPTH}.`,\n path\n };\n }\n if (typeof node === \"string\") return undefined;\n if (!isPlainObject(node)) {\n return nodeError(\"Template node must be a string or a plain object.\", path);\n }\n\n if (\"bind\" in node) {\n if (typeof node.bind !== \"string\") {\n return nodeError(\"'bind' must be a string path.\", path);\n }\n return checkPathSyntax(node.bind, path);\n }\n\n if (\"each\" in node) {\n if (typeof node.each !== \"string\") {\n return nodeError(\"'each' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.each, path);\n if (pathError) return pathError;\n if (!(\"template\" in node)) {\n return nodeError(\"'each' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"empty\" in node && node.empty !== undefined) {\n return check(node.empty, join(path, \"empty\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"when\" in node) {\n if (typeof node.when !== \"string\") {\n return nodeError(\"'when' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.when, path);\n if (pathError) return pathError;\n if (!(\"template\" in node)) {\n return nodeError(\"'when' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"else\" in node && node.else !== undefined) {\n return check(node.else, join(path, \"else\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"tag\" in node) {\n if (typeof node.tag !== \"string\" || node.tag.length === 0) {\n return nodeError(\"'tag' must be a non-empty string.\", path);\n }\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) {\n return {\n code: \"FORBIDDEN_TAG\",\n message: `Element '${node.tag}' is not allowed in templates (active or foreign content).`,\n path\n };\n }\n if (\"attrs\" in node && node.attrs !== undefined) {\n if (!isPlainObject(node.attrs)) {\n return nodeError(\"'attrs' must be an object.\", path);\n }\n for (const [name, value] of Object.entries(node.attrs)) {\n const attrPath = join(path, `attrs.${name}`);\n if (FORBIDDEN_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is not allowed in templates (event handlers and srcdoc).`,\n path: attrPath\n };\n }\n if (RESERVED_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is reserved for the renderer (data-wg-*); use an 'action' binding.`,\n path: attrPath\n };\n }\n if (typeof value === \"string\") continue;\n if (isPlainObject(value) && typeof value.bind === \"string\") {\n const pathError = checkPathSyntax(value.bind, attrPath);\n if (pathError) return pathError;\n // One transform per value: map selects an authored literal,\n // prefix glues one in front \u2014 combining them has no use case\n // and every combination would need teaching forever.\n const hasMap = value.map !== undefined;\n const hasPrefix = value.prefix !== undefined;\n if (hasMap && hasPrefix) {\n return nodeError(\n `Attribute '${name}' carries both 'map' and 'prefix' \u2014 one transform per value.`,\n attrPath\n );\n }\n if (hasMap) {\n if (\n !isPlainObject(value.map) ||\n Object.values(value.map).some((entry) => typeof entry !== \"string\")\n ) {\n return nodeError(\n `Attribute '${name}': 'map' must be an object of string values.`,\n attrPath\n );\n }\n if (value.default !== undefined && typeof value.default !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'default' must be a string.`,\n attrPath\n );\n }\n } else if (value.default !== undefined) {\n return nodeError(\n `Attribute '${name}': 'default' requires 'map'.`,\n attrPath\n );\n }\n if (hasPrefix && typeof value.prefix !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'prefix' must be a string.`,\n attrPath\n );\n }\n continue;\n }\n return nodeError(\n `Attribute '${name}' must be a string, { bind }, { bind, map, default? } or { bind, prefix } value.`,\n attrPath\n );\n }\n }\n if (\"action\" in node && node.action !== undefined) {\n // An element is a link OR an action \u2014 both would leave the bridge\n // guessing which the author meant.\n const hasHref =\n isPlainObject(node.attrs) &&\n Object.keys(node.attrs).some((name) => name.toLowerCase() === \"href\");\n if (hasHref) {\n return {\n code: \"CONFLICTING_ATTRIBUTES\",\n message: \"An element carries 'href' or an 'action' binding, never both.\",\n path\n };\n }\n const actionError = validateActionBinding(node.action, join(path, \"action\"), {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (actionError) {\n return { code: \"INVALID_ACTION\", message: actionError.message, path: actionError.path };\n }\n }\n if (\"children\" in node && node.children !== undefined) {\n if (!Array.isArray(node.children)) {\n return nodeError(\"'children' must be an array.\", path);\n }\n for (let i = 0; i < node.children.length; i++) {\n const childError = check(\n node.children[i],\n join(path, `children.${i}`),\n depth + 1\n );\n if (childError) return childError;\n }\n }\n return undefined;\n }\n\n return nodeError(\n \"Unknown template node form (expected text, bind, tag, each, or when).\",\n path\n );\n}\n\n/** Validate an unknown value as a widget template. Never throws. */\nexport function validateTemplate(input: unknown): ValidateTemplateResult {\n const error = check(input, \"\", 0);\n if (error) return { ok: false, error };\n return { ok: true, template: input as WidgetTemplate };\n}\n", "/**\n * Addressing nodes inside a template by the validator's dotted path\n * convention (`children.2.template`, `else`, \u2026) \u2014 the identifier an action\n * binding is known by \u2014 and enumerating the shared actions a template\n * references, so stores can enforce referential integrity without a\n * second grammar.\n */\nimport { isPlainObject } from \"../shared/plain-object.js\";\nimport type { ActionBinding } from \"../actions/types.js\";\n\n/** The template node at a dotted path (\"\" is the root); `undefined` when absent. */\nexport function findTemplateNode(template: unknown, path: string): unknown {\n if (path === \"\") return template;\n let current: unknown = template;\n for (const segment of path.split(\".\")) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/** The element's `action` binding at a dotted path, when that node is a bound element. */\nexport function findActionBinding(template: unknown, path: string): ActionBinding | undefined {\n const node = findTemplateNode(template, path);\n if (isPlainObject(node) && typeof node.tag === \"string\" && isPlainObject(node.action)) {\n return node.action as ActionBinding;\n }\n return undefined;\n}\n\n/** Visit every binding object a template (and an optional `load`) carries. */\nfunction eachBinding(template: unknown, load: unknown, onBinding: (binding: Record<string, unknown>) => void): void {\n const visit = (node: unknown): void => {\n if (!isPlainObject(node)) return;\n if (isPlainObject(node.action)) onBinding(node.action);\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (node[key] !== undefined) visit(node[key]);\n }\n if (Array.isArray(node.children)) for (const child of node.children) visit(child);\n };\n visit(template);\n if (isPlainObject(load)) onBinding(load);\n}\n\n/** Every shared-action name a template (and an optional `load`) references by `ref`. */\nexport function collectActionRefs(template: unknown, load?: unknown): string[] {\n const refs = new Set<string>();\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref === \"string\") refs.add(binding.ref);\n });\n return [...refs];\n}\n\n/** Every inline action definition in a template (and `load`), for secret-reference scans. */\nexport function collectInlineActions(template: unknown, load?: unknown): unknown[] {\n const out: unknown[] = [];\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref !== \"string\" && binding.definition !== undefined) out.push(binding.definition);\n });\n return out;\n}\n\n/** Does the template (or `load`) carry any action binding at all? */\nexport function hasActionBindings(template: unknown, load?: unknown): boolean {\n if (load !== undefined) return true;\n return collectActionRefs(template).length > 0 || collectInlineActions(template).length > 0;\n}\n", "import type { WidgetPayload } from \"../contract/types.js\";\nimport type {\n WidgetCatalog,\n WidgetDescriptorInput,\n WidgetElementNode,\n WidgetNode,\n WidgetNodeAttrs,\n WidgetRenderer\n} from \"../catalog/index.js\";\nimport type {\n ActionBinding,\n ActionDefinition,\n ActionDescriptor,\n ActionDisabledReason\n} from \"../actions/types.js\";\nimport { PROMPT_TEXT_MAX } from \"../actions/types.js\";\nimport type { WidgetTemplate } from \"./types.js\";\nimport {\n FORBIDDEN_ATTR,\n FORBIDDEN_TAGS,\n RESERVED_ATTR,\n URL_ATTRS,\n isSafeImageSrc,\n isSafeUrl\n} from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { InvalidTemplateError, validateTemplate } from \"./validate.js\";\nimport { formatValue } from \"../catalog/widgets/format.js\";\nimport { isPlainObject } from \"../shared/plain-object.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\n/**\n * One scope frame: the root frame holds `payload.data`; every `each`\n * pushes the current item with its position. `$parent` walks the stack,\n * `$root` reads the bottom, `$index` reads the top's position.\n */\ninterface Frame {\n scope: unknown;\n index?: number;\n}\n\n/**\n * Resolve a path against the scope chain (see paths.ts for the grammar).\n * Missing, non-traversable or malformed paths resolve to `undefined` \u2014\n * never throws.\n */\nfunction resolvePath(path: string, frames: Frame[], meta: unknown): unknown {\n const parsed = parsePath(path);\n if (parsed === undefined) return undefined;\n let current: unknown;\n if (parsed.base === \"meta\") {\n current = meta;\n } else if (parsed.base === \"root\") {\n current = frames[0]?.scope;\n } else {\n const depth = frames.length - 1 - parsed.up;\n if (depth < 0) return undefined;\n const frame = frames[depth];\n if (frame === undefined) return undefined;\n if (parsed.index) return frame.index;\n current = frame.scope;\n }\n for (const segment of parsed.segments) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/**\n * Interpretation budget. `each` multiplies template nodes by the length of\n * AGENT-supplied data, so template size bounds nothing on its own \u2014 a\n * stored template driven by a large payload could otherwise spend the\n * process. Counting work (nodes emitted, plus one unit per `each`\n * iteration so empty iterations are not free) rather than watching a\n * clock keeps the bound reproducible: the same template and data always\n * truncate at the same place.\n */\nexport const DEFAULT_MAX_NODES = 50_000;\n\ninterface Budget {\n remaining: number;\n truncated: boolean;\n}\n\n/** Render-time knowledge about actions the caller supplies. */\n/** The compile options the action layer reads; the options object itself serves. */\ntype ActionContext = Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\">;\n\n/**\n * Resolve a binding into the descriptor an element carries. Everything the\n * bridge needs is decided here, in scope, at render time: the prompt's\n * text, the http arguments, and whether the action is available at all.\n */\nfunction buildDescriptor(\n binding: ActionBinding,\n id: string,\n frames: Frame[],\n meta: unknown,\n ctx: ActionContext\n): ActionDescriptor {\n const definition: ActionDefinition | undefined =\n \"ref\" in binding && typeof binding.ref === \"string\"\n ? ctx.actions?.(binding.ref)\n : \"definition\" in binding && isPlainObject(binding.definition)\n ? (binding.definition as ActionDefinition)\n : undefined;\n if (definition === undefined || (definition.kind !== \"prompt\" && definition.kind !== \"http\")) {\n const unresolved: ActionDescriptor = { id, disabled: \"unresolved\" };\n if (ctx.kind !== undefined) unresolved.widget = ctx.kind;\n return unresolved;\n }\n if (definition.kind === \"prompt\") {\n let text = \"\";\n const segments = Array.isArray(definition.text) ? definition.text : [];\n for (const segment of segments) {\n if (typeof segment === \"string\") text += segment;\n else if (isPlainObject(segment) && typeof segment.bind === \"string\") {\n text += formatValue(resolvePath(segment.bind, frames, meta));\n }\n if (text.length >= PROMPT_TEXT_MAX) break;\n }\n // Cap by code point so a surrogate pair is never split.\n const prompt: ActionDescriptor = { id, kind: \"prompt\", text: Array.from(text).slice(0, PROMPT_TEXT_MAX).join(\"\") };\n if (ctx.kind !== undefined) prompt.widget = ctx.kind;\n return prompt;\n }\n const args: Record<string, unknown> = {};\n if (isPlainObject(binding.input)) {\n for (const [field, value] of Object.entries(binding.input)) {\n let resolved: unknown;\n if (typeof value === \"string\") resolved = resolvePath(value, frames, meta);\n else if (isPlainObject(value) && \"const\" in value) resolved = value.const;\n if (resolved !== undefined) args[field] = resolved;\n }\n }\n const descriptor: ActionDescriptor = { id, kind: \"http\", args };\n if (ctx.httpDisabled !== undefined) descriptor.disabled = ctx.httpDisabled;\n if (ctx.kind !== undefined) descriptor.widget = ctx.kind;\n return descriptor;\n}\n\n/**\n * Interpret a template node into zero or more render-tree nodes.\n * Lenient by design: validation is the strict layer, so unknown or\n * malformed forms render as nothing rather than throwing (defense in\n * depth for templates that bypassed validation). `tpath` is the node's\n * dotted position in the TEMPLATE (the validator's path convention) \u2014 the\n * identifier an action binding is known by.\n */\nfunction interpretNode(\n node: unknown,\n frames: Frame[],\n meta: unknown,\n budget: Budget,\n tpath: string,\n ctx: ActionContext\n): WidgetNode[] {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n return [];\n }\n if (typeof node === \"string\") {\n budget.remaining--;\n return [node];\n }\n if (!isPlainObject(node)) return [];\n\n if (typeof node.bind === \"string\") {\n budget.remaining--;\n return [formatValue(resolvePath(node.bind, frames, meta))];\n }\n\n if (typeof node.each === \"string\") {\n const value = resolvePath(node.each, frames, meta);\n const items = Array.isArray(value) ? value : [];\n if (items.length === 0) {\n return node.empty === undefined\n ? []\n : interpretNode(node.empty, frames, meta, budget, join(tpath, \"empty\"), ctx);\n }\n const out: WidgetNode[] = [];\n const itemPath = join(tpath, \"template\");\n for (let i = 0; i < items.length; i++) {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n break;\n }\n budget.remaining--; // the iteration itself costs, even when it renders nothing\n frames.push({ scope: items[i], index: i });\n out.push(...interpretNode(node.template, frames, meta, budget, itemPath, ctx));\n frames.pop();\n }\n return out;\n }\n\n if (typeof node.when === \"string\") {\n const truthy = Boolean(resolvePath(node.when, frames, meta));\n const branch = truthy ? node.template : node.else;\n return branch === undefined\n ? []\n : interpretNode(branch, frames, meta, budget, join(tpath, truthy ? \"template\" : \"else\"), ctx);\n }\n\n if (typeof node.tag === \"string\" && node.tag.length > 0) {\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) return []; // active content never reaches a tree\n budget.remaining--;\n const attrs: WidgetNodeAttrs = {};\n if (isPlainObject(node.attrs)) {\n for (const [name, raw] of Object.entries(node.attrs)) {\n // Handlers are code; data-wg-* is the renderer's own vocabulary.\n if (FORBIDDEN_ATTR.test(name) || RESERVED_ATTR.test(name)) continue;\n let value: string | undefined;\n if (typeof raw === \"string\") {\n value = raw;\n } else if (isPlainObject(raw) && typeof raw.bind === \"string\") {\n const resolved = resolvePath(raw.bind, frames, meta);\n if (isPlainObject(raw.map)) {\n // The resolved value SELECTS a key; every emitted character\n // is an author-written literal. A miss falls to `default`,\n // or empty \u2014 an unanticipated status degrades, never breaks.\n const key = formatValue(resolved);\n const hit = Object.prototype.hasOwnProperty.call(raw.map, key)\n ? raw.map[key]\n : undefined;\n value =\n typeof hit === \"string\"\n ? hit\n : typeof raw.default === \"string\"\n ? raw.default\n : \"\";\n } else if (typeof raw.prefix === \"string\") {\n // The prefix is never emitted alone: no dead mailto: hrefs.\n // The composed value still faces the URL guard below.\n const text = formatValue(resolved);\n value = text === \"\" ? \"\" : raw.prefix + text;\n } else {\n value = formatValue(resolved);\n }\n }\n if (value === undefined) continue;\n const lower = name.toLowerCase();\n if (URL_ATTRS.has(lower)) {\n // Image sources additionally accept data:image/*; every other\n // URL attribute keeps the strict scheme set (data-URI\n // navigation is an XSS vector; data-URI images are not).\n const imageContext = lower === \"src\" && node.tag.toLowerCase() === \"img\";\n const allowed =\n isSafeUrl(value) || (imageContext && isSafeImageSrc(value));\n if (!allowed) continue;\n }\n attrs[name] = value;\n }\n }\n if (isPlainObject(node.action)) {\n attrs[\"data-wg-action\"] = JSON.stringify(\n buildDescriptor(node.action as ActionBinding, tpath, frames, meta, ctx)\n );\n }\n const children = Array.isArray(node.children)\n ? node.children.flatMap((child, i) =>\n interpretNode(child, frames, meta, budget, join(tpath, `children.${i}`), ctx)\n )\n : [];\n const element: WidgetElementNode = { tag: node.tag };\n if (Object.keys(attrs).length > 0) element.attrs = attrs;\n if (children.length > 0) element.children = children;\n return [element];\n }\n\n return [];\n}\n\n/** Count the nodes a template's STRUCTURE contains (not its output). */\nexport function countTemplateNodes(template: unknown): number {\n if (typeof template === \"string\") return 1;\n if (!isPlainObject(template)) return 0;\n if (typeof template.bind === \"string\") return 1;\n let total = 1;\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (template[key] !== undefined) total += countTemplateNodes(template[key]);\n }\n if (Array.isArray(template.children)) {\n for (const child of template.children) total += countTemplateNodes(child);\n }\n return total;\n}\n\nexport interface CompileOptions {\n /** Node budget for one render (default {@link DEFAULT_MAX_NODES}). */\n maxNodes?: number;\n /**\n * Resolve `{ ref }` action bindings to their definitions (the\n * principal's shared actions). Unresolvable refs render disabled.\n */\n actions?: (ref: string) => ActionDefinition | undefined;\n /**\n * Render every http action disabled with this reason \u2014 the server sets\n * `\"scope\"` when the caller's key cannot execute.\n */\n httpDisabled?: ActionDisabledReason;\n /** The kind this template is registered as \u2014 stamped into descriptors. */\n kind?: string;\n}\n\n/**\n * Compile a template into an ordinary widget renderer. The renderer is pure\n * and total; when the root interprets to anything other than exactly one\n * node, the output is wrapped in a `div.wg-template`. Renders are bounded\n * by a node budget \u2014 an exhausted budget stops interpretation and marks\n * the output with `data-truncated`, so the outcome is visible rather than\n * silently short.\n */\nexport function compileTemplate(\n template: WidgetTemplate,\n options: CompileOptions = {}\n): WidgetRenderer {\n const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;\n const ctx: ActionContext = options;\n return (payload: WidgetPayload): WidgetNode => {\n const budget: Budget = { remaining: maxNodes, truncated: false };\n const frames: Frame[] = [{ scope: payload.data }];\n const nodes = interpretNode(template, frames, payload.meta, budget, \"\", ctx);\n if (!budget.truncated && nodes.length === 1) {\n const only = nodes[0];\n if (only !== undefined) return only;\n }\n const attrs: WidgetNodeAttrs = { class: \"wg-template\" };\n if (budget.truncated) attrs[\"data-truncated\"] = \"true\";\n return { tag: \"div\", attrs, children: nodes };\n };\n}\n\n/**\n * Resolve a binding outside the tree \u2014 the widget-level `load` binding,\n * whose descriptor rides `structuredContent.load` rather than an element.\n * Resolved against the payload's root scope.\n */\nexport function resolveActionDescriptor(\n binding: ActionBinding,\n id: string,\n payload: WidgetPayload,\n options: Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\"> = {}\n): ActionDescriptor {\n const ctx: ActionContext = options;\n return buildDescriptor(binding, id, [{ scope: payload.data }], payload.meta, ctx);\n}\n\n/**\n * Validate, compile, and register a template as a widget kind. Throws\n * {@link InvalidTemplateError} on invalid templates and the catalog's\n * `DuplicateKindError` on duplicate kinds \u2014 registration is host setup.\n */\nexport function registerTemplate(\n catalog: WidgetCatalog,\n kind: string,\n template: unknown,\n descriptor?: WidgetDescriptorInput,\n options?: CompileOptions\n): void {\n const validated = validateTemplate(template);\n if (!validated.ok) {\n throw new InvalidTemplateError(kind, validated.error);\n }\n catalog.register(kind, compileTemplate(validated.template, { ...options, kind }), descriptor);\n}\n", "import type { WidgetNode } from \"../catalog/index.js\";\n\n/**\n * Materialize a render tree as fresh DOM. Text becomes text nodes (no HTML\n * parsing), matching the catalog DOM layer's safety discipline. Private to\n * the reactive module \u2014 the catalog's builder stays private to its own.\n */\nexport function buildDom(node: WidgetNode, doc: Document): Node {\n if (typeof node === \"string\") return doc.createTextNode(node);\n const element = doc.createElement(node.tag);\n if (node.attrs) {\n for (const [name, value] of Object.entries(node.attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (node.children) {\n for (const child of node.children) {\n element.appendChild(buildDom(child, doc));\n }\n }\n return element;\n}\n", "import type { WidgetElementNode, WidgetNode } from \"../catalog/index.js\";\nimport { buildDom } from \"./build.js\";\n\n/**\n * Patch `dom` in place so it reflects `next`, given that it currently\n * reflects `prev`. Returns the node now representing `next` \u2014 the same node\n * when patched in place, a freshly built replacement when the shape (tag or\n * node type) changed. Identity is preserved wherever shape matches.\n */\nexport function patchNode(prev: WidgetNode, next: WidgetNode, dom: Node): Node {\n if (typeof prev === \"string\" && typeof next === \"string\") {\n if (prev !== next) dom.nodeValue = next;\n return dom;\n }\n if (\n typeof prev !== \"string\" &&\n typeof next !== \"string\" &&\n prev.tag === next.tag &&\n dom.nodeType === 1\n ) {\n patchElement(prev, next, dom as Element);\n return dom;\n }\n // Shape changed: replace only this subtree.\n const doc = dom.ownerDocument;\n if (!doc || !dom.parentNode) return dom;\n const replacement = buildDom(next, doc);\n dom.parentNode.replaceChild(replacement, dom);\n return replacement;\n}\n\nfunction patchElement(\n prev: WidgetElementNode,\n next: WidgetElementNode,\n element: Element\n): void {\n const prevAttrs = prev.attrs ?? {};\n const nextAttrs = next.attrs ?? {};\n for (const [name, value] of Object.entries(nextAttrs)) {\n if (prevAttrs[name] !== value) element.setAttribute(name, value);\n }\n for (const name of Object.keys(prevAttrs)) {\n if (!(name in nextAttrs)) element.removeAttribute(name);\n }\n patchChildren(prev.children ?? [], next.children ?? [], element);\n}\n\nfunction patchChildren(\n prev: readonly WidgetNode[],\n next: readonly WidgetNode[],\n element: Element\n): void {\n const doc = element.ownerDocument;\n // Snapshot: childNodes is live and patchNode may replace entries.\n const domChildren: Node[] = [];\n for (let i = 0; i < element.childNodes.length; i++) {\n const child = element.childNodes[i];\n if (child) domChildren.push(child);\n }\n\n const shared = Math.min(prev.length, next.length);\n for (let i = 0; i < shared; i++) {\n const prevChild = prev[i];\n const nextChild = next[i];\n const childDom = domChildren[i];\n if (prevChild === undefined || nextChild === undefined) continue;\n if (childDom) {\n patchNode(prevChild, nextChild, childDom);\n } else {\n element.appendChild(buildDom(nextChild, doc));\n }\n }\n for (let i = shared; i < next.length; i++) {\n const extra = next[i];\n if (extra !== undefined) element.appendChild(buildDom(extra, doc));\n }\n for (let i = prev.length - 1; i >= shared; i--) {\n const surplus = domChildren[i];\n if (surplus) element.removeChild(surplus);\n }\n}\n", "import type { WidgetCatalog, WidgetNode } from \"../catalog/index.js\";\nimport { createCatalog } from \"../catalog/index.js\";\nimport type { WidgetContractError } from \"../contract/index.js\";\nimport type { ActionDescriptor } from \"../actions/index.js\";\nimport { buildDom } from \"./build.js\";\nimport { patchNode } from \"./diff.js\";\n\n/** Outcome of a mount or update. Failures leave the DOM untouched. */\nexport type UpdateResult =\n | { ok: true }\n | { ok: false; error: WidgetContractError };\n\n/** An activated element's descriptor, handed to the host untouched. */\nexport type ActionActivation = ActionDescriptor;\n\nexport interface MountOptions {\n /**\n * Catalog used for validation and rendering. Defaults to a fresh\n * `createCatalog()` per mount; pass a shared instance to render custom\n * registered kinds.\n */\n catalog?: WidgetCatalog;\n /**\n * Receives activations of mounted `[data-wg-action]` elements (click, or\n * Enter/Space on non-button hosts) with the parsed descriptor and the\n * currently mounted payload; the default action is prevented. Without\n * it, action elements are inert \u2014 the mount never executes anything.\n */\n onAction?: (activation: ActionActivation, payload: unknown) => void;\n}\n\nexport interface WidgetMount {\n /** Outcome of the initial render performed by `mountWidget`. */\n readonly initial: UpdateResult;\n /**\n * Re-render with a new payload, patching the DOM in place. Returns a\n * structured error (DOM untouched) for invalid payloads. Throws if the\n * mount was disposed \u2014 that is a host programming error.\n */\n update(payload: unknown): UpdateResult;\n /** Currently rendered tree (`undefined` before the first successful render). */\n node(): WidgetNode | undefined;\n /** Empty the container and end this mount. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Mount a widget payload into `container` and keep updating it in place.\n * The first render is just an internal `update`; its outcome is exposed as\n * `initial`, so a failed first payload does not cost the caller the handle.\n */\nexport function mountWidget(\n payload: unknown,\n container: Element,\n options: MountOptions = {}\n): WidgetMount {\n const catalog = options.catalog ?? createCatalog();\n let current: WidgetNode | undefined;\n let root: Node | undefined;\n let disposed = false;\n let mountedPayload: unknown;\n\n // Delegated on the container: descriptors are data the host decides\n // about \u2014 this layer only parses and forwards them.\n const onAction = options.onAction;\n function parseDescriptor(el: Element): ActionDescriptor | undefined {\n try {\n const parsed = JSON.parse(el.getAttribute(\"data-wg-action\") ?? \"\") as unknown;\n if (typeof parsed === \"object\" && parsed !== null && typeof (parsed as { id?: unknown }).id === \"string\") {\n return parsed as ActionDescriptor;\n }\n } catch {\n /* malformed descriptor: inert */\n }\n return undefined;\n }\n function activation(event: Event): void {\n const target = event.target as Element | null;\n const el = target?.closest?.(\"[data-wg-action]\");\n if (!el || !container.contains(el)) return;\n if (event.type === \"keydown\") {\n const key = (event as KeyboardEvent).key;\n if (key !== \"Enter\" && key !== \" \") return;\n if (el.tagName === \"BUTTON\" || el.tagName === \"A\") return; // native keyboard \u2192 click\n }\n event.preventDefault();\n if (onAction === undefined) return;\n const descriptor = parseDescriptor(el);\n if (descriptor !== undefined) onAction(descriptor, mountedPayload);\n }\n container.addEventListener(\"click\", activation);\n container.addEventListener(\"keydown\", activation);\n\n function update(nextPayload: unknown): UpdateResult {\n if (disposed) {\n throw new Error(\n \"Widget mount is disposed; create a new mount instead of updating.\"\n );\n }\n const rendered = catalog.render(nextPayload);\n if (!rendered.ok) return rendered;\n\n if (current === undefined || root === undefined) {\n const built = buildDom(rendered.node, container.ownerDocument);\n container.replaceChildren(built);\n root = built;\n } else {\n root = patchNode(current, rendered.node, root);\n }\n current = rendered.node;\n mountedPayload = nextPayload;\n return { ok: true };\n }\n\n function dispose(): void {\n if (disposed) return;\n disposed = true;\n container.removeEventListener(\"click\", activation);\n container.removeEventListener(\"keydown\", activation);\n container.replaceChildren();\n current = undefined;\n root = undefined;\n mountedPayload = undefined;\n }\n\n return {\n initial: update(payload),\n update,\n node: () => current,\n dispose\n };\n}\n", "/**\n * The chrome tokens and the palettes painted through them.\n *\n * `CHROME_DEFAULTS` is not a description of the defaults \u2014 it IS them: the\n * injected stylesheet's token blocks are generated from this object, so a host\n * that paints its own surfaces from the export cannot drift from the\n * designers. There is deliberately no second palette to fall back to: a host\n * that wants a different look passes its own values through `chrome`, and\n * `chromeCss` renders whatever palette it hands back.\n *\n * Colours and shape carry the product's identity. Typography does not: a\n * library must never default to a webfont it cannot serve, so `font`,\n * `font-mono` and the three sizes stay system values in both palettes and a\n * host with its own typeface passes it through `chrome`.\n */\n\n/**\n * The chrome tokens \u2014 every `--wgd-<token>` the stylesheet paints with.\n * Colours (18) differ between the schemes; typography, shape and shadow are\n * declared per scheme too so each palette stands alone. Public API: a rename\n * is a spec change.\n */\nexport const CHROME_TOKENS = [\n \"bg\", \"panel\", \"border\", \"line\", \"text\", \"muted\",\n \"accent\", \"accent-bg\", \"accent-line\",\n \"danger\", \"danger-bg\", \"danger-line\", \"hover\",\n \"hl-key\", \"hl-str\", \"hl-num\", \"hl-bool\", \"hl-punct\",\n \"font\", \"font-mono\", \"font-size\", \"font-size-sm\", \"font-size-xs\",\n \"radius-sm\", \"radius\", \"radius-lg\", \"gap\", \"shadow\"\n] as const;\n\nexport type ChromeToken = (typeof CHROME_TOKENS)[number];\n\n/** A host's partial chrome: token \u2192 CSS value (`var()` references welcome). */\nexport type ChromeOptions = Partial<Record<ChromeToken, string>>;\n\n/** Every token valued \u2014 what a palette is. */\nexport type ChromeScheme = Record<ChromeToken, string>;\n\n/** A complete palette: both schemes, every token. */\nexport interface ChromePalette {\n light: ChromeScheme;\n dark: ChromeScheme;\n}\n\n/** Shared by both palettes: see the module header on why typography is not branded. */\nconst TYPOGRAPHY = {\n font: \"system-ui, sans-serif\",\n \"font-mono\": \"ui-monospace, monospace\",\n \"font-size\": \"13px\",\n \"font-size-sm\": \"12px\",\n \"font-size-xs\": \"11px\"\n} as const;\n\n/**\n * The widgentic palette \u2014 what the designers render with when a host passes\n * no `chrome`, and what a host paints its own page with to match them.\n *\n * Every colour sits on the logo mark's own hue (197.6deg, from `#40a0c8`).\n * Surfaces, text and accents come from the product's existing palette;\n * `border`, `accent-line` and `danger-line` are DERIVED, not chosen: each is\n * the lightest value on that hue which still clears 3:1 against the surface\n * it sits on, because those edges are what identifies a control, a focused tag\n * and a banner. Minimum weight that complies, so nothing is heavier than\n * accessibility requires. See chrome-contrast.test.ts for the gate.\n */\nexport const CHROME_DEFAULTS: ChromePalette = {\n light: {\n bg: \"#f6fafc\", panel: \"#ffffff\", border: \"#6e95a6\",\n line: \"#e4ecf2\", text: \"#0b1b26\", muted: \"#56707f\",\n accent: \"#1e6f92\", \"accent-bg\": \"#e3f1f7\", \"accent-line\": \"#4b91ae\",\n danger: \"#b42318\", \"danger-bg\": \"#fdf2f2\", \"danger-line\": \"#c97572\",\n hover: \"#eef5f9\",\n \"hl-key\": \"#1e6f92\", \"hl-str\": \"#2e7d5b\", \"hl-num\": \"#96620f\",\n \"hl-bool\": \"#7a4fbf\", \"hl-punct\": \"#56707f\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(11, 27, 38, 0.35)\"\n },\n dark: {\n bg: \"#0b141b\", panel: \"#10202a\", border: \"#437082\",\n line: \"#1b2f3d\", text: \"#e6f0f5\", muted: \"#93a9b6\",\n accent: \"#8acbe6\", \"accent-bg\": \"#14303d\", \"accent-line\": \"#3e7e98\",\n danger: \"#f0a3a3\", \"danger-bg\": \"#2a1a1c\", \"danger-line\": \"#a3524f\",\n hover: \"#152a36\",\n \"hl-key\": \"#8acbe6\", \"hl-str\": \"#6cc79a\", \"hl-num\": \"#e0b25a\",\n \"hl-bool\": \"#bb9af7\", \"hl-punct\": \"#93a9b6\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(0, 0, 0, 0.7)\"\n }\n};\n\nexport interface ChromeCssOptions {\n /** Custom-property prefix, dashes included. Default `--wgd`. */\n prefix?: string;\n /** Selector the light block is written under. Default `:root`. */\n selector?: string;\n /** Selector for the dark block inside `prefers-color-scheme: dark`; defaults to `selector`. */\n darkMediaSelector?: string;\n /** Optional selector for an unconditional dark block \u2014 an explicit host toggle. */\n darkSelector?: string;\n}\n\nfunction declarations(scheme: ChromeScheme, prefix: string, indent: string): string {\n return CHROME_TOKENS.map((token) => `${indent}${prefix}-${token}: ${scheme[token]};`).join(\"\\n\");\n}\n\n/**\n * Render a palette as CSS declaration blocks \u2014 the light values under\n * `selector`, the dark values under `prefers-color-scheme: dark`, and\n * optionally under an explicit selector a host toggles. Every token is\n * declared in every block, so nothing falls back to a browser value.\n *\n * A string builder, deliberately: no injection, no runtime, no dependency.\n * The designers' own stylesheet is built with it, and so is a host page that\n * wants its surfaces to match them.\n */\nexport function chromeCss(palette: ChromePalette, options: ChromeCssOptions = {}): string {\n const prefix = options.prefix ?? \"--wgd\";\n const selector = options.selector ?? \":root\";\n const darkMediaSelector = options.darkMediaSelector ?? selector;\n const blocks = [\n `${selector} {\\n${declarations(palette.light, prefix, \" \")}\\n}`,\n `@media (prefers-color-scheme: dark) {\\n ${darkMediaSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n }\\n}`\n ];\n if (options.darkSelector !== undefined) {\n blocks.push(`${options.darkSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n}`);\n }\n return blocks.join(\"\\n\");\n}\n", "/**\n * Tiny DOM helpers for the designer chrome \u2014 the same hand-rolled\n * discipline as the rest of the project, sized for form-heavy panels.\n * Designer chrome classes are prefixed `wgd-` (widget content inside the\n * preview keeps the normal `wg-` classes).\n */\nimport { CHROME_DEFAULTS, CHROME_TOKENS, chromeCss } from \"./chrome-defaults.js\";\nimport type { ChromeOptions } from \"./chrome-defaults.js\";\n\nexport type Child = Node | string;\n\n/** The first `<selector>` under `parent`, which the caller's own markup guarantees exists. */\nexport function requireChild<K extends keyof HTMLElementTagNameMap>(\n parent: ParentNode,\n selector: K\n): HTMLElementTagNameMap[K] {\n const found = parent.querySelector(selector);\n if (found === null) throw new Error(`Designer chrome is missing a <${selector}> element.`);\n return found;\n}\n\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs?: Record<string, string>,\n children?: Child[]\n): HTMLElementTagNameMap[K];\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement;\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement {\n const element = document.createElement(tag);\n if (attrs) {\n for (const [name, value] of Object.entries(attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (children) {\n for (const child of children) {\n element.append(child);\n }\n }\n return element;\n}\n\n/** Labeled single-line input bound through a callback. */\nexport function textField(\n label: string,\n value: string,\n onInput: (value: string) => void\n): HTMLElement {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = value;\n input.addEventListener(\"input\", () => onInput(input.value));\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n input\n ]);\n}\n\n/** Labeled multi-line textarea bound through a callback. */\nexport function textArea(\n label: string,\n value: string,\n onInput: (value: string) => void,\n rows = 6\n): HTMLElement {\n const area = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: String(rows),\n spellcheck: \"false\"\n });\n area.value = value;\n area.addEventListener(\"input\", () => onInput(area.value));\n // An empty label means the surrounding chrome already names the field \u2014\n // no legend row.\n return h(\"label\", { class: \"wgd-field\" }, [\n ...(label === \"\" ? [] : [h(\"span\", { class: \"wgd-field-label\" }, [label])]),\n area\n ]);\n}\n\n/** Collapsible titled section (open by default). */\nexport function section(title: string, children: Child[], open = true): HTMLElement {\n const attrs: Record<string, string> = { class: \"wgd-section\" };\n if (open) attrs.open = \"\";\n return h(\"details\", attrs, [\n h(\"summary\", { class: \"wgd-section-title\" }, [title]),\n h(\"div\", { class: \"wgd-section-body\" }, children)\n ]);\n}\n\n/**\n * Size a select to its SELECTED label (a bare <select> sizes to its\n * widest option, or to whatever flex hands it), so the caret sits beside\n * the text instead of drifting with leftover row width. ch tracks\n * monospace text exactly; the em term scales with padding, and the px\n * term covers the UA's caret region, which does NOT scale with font size\n * (11px selects clip under a pure em term). Re-fits on change.\n */\nexport function fitSelect(select: HTMLSelectElement): void {\n const fit = (): void => {\n const label = select.options[select.selectedIndex]?.text ?? select.value;\n select.style.width = `calc(${Math.max(label.length, 1)}ch + 1.2em + 18px)`;\n };\n fit();\n select.addEventListener(\"change\", fit);\n}\n\n/**\n * Compact add-menu: one toggle button revealing the options on demand \u2014\n * the tree stays calm instead of carrying a button per option at every\n * level. Closes on pick, outside pointer-down, or Escape.\n */\nexport function menuButton(\n label: string,\n title: string,\n options: string[],\n onPick: (option: string) => void\n): HTMLElement {\n const wrap = h(\"span\", { class: \"wgd-menuwrap\" });\n const toggle = h(\n \"button\",\n { class: \"wgd-icon wgd-menu-toggle\", type: \"button\", title },\n [label]\n );\n const menu = h(\"div\", { class: \"wgd-menu\" });\n menu.hidden = true;\n\n const close = (): void => {\n menu.hidden = true;\n document.removeEventListener(\"pointerdown\", onOutside, true);\n document.removeEventListener(\"keydown\", onKey, true);\n };\n const onOutside = (event: Event): void => {\n if (!wrap.contains(event.target as Node)) close();\n };\n const onKey = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\") close();\n };\n\n toggle.addEventListener(\"click\", () => {\n if (!menu.hidden) {\n close();\n return;\n }\n menu.hidden = false;\n document.addEventListener(\"pointerdown\", onOutside, true);\n document.addEventListener(\"keydown\", onKey, true);\n });\n for (const option of options) {\n const item = h(\n \"button\",\n { class: \"wgd-menu-item\", type: \"button\" },\n [option]\n );\n item.addEventListener(\"click\", () => {\n close();\n onPick(option);\n });\n menu.append(item);\n }\n wrap.append(toggle, menu);\n return wrap;\n}\n\n/** Inline diagnostic line (empty text removes it from the flow). */\nexport function diagnosticLine(text: string | undefined): HTMLElement {\n const el = h(\"div\", { class: \"wgd-diagnostic\" }, text === undefined ? [] : [text]);\n if (text === undefined) el.setAttribute(\"hidden\", \"\");\n return el;\n}\n\n// The token list and the palettes live in chrome-defaults.ts, which the\n// stylesheet below is generated from; re-exported here so the modules that\n// already import chrome types from this one keep working.\nexport { CHROME_TOKENS } from \"./chrome-defaults.js\";\nexport type { ChromeOptions, ChromeToken } from \"./chrome-defaults.js\";\n\nconst CHROME_TOKEN_SET: ReadonlySet<string> = new Set<string>(CHROME_TOKENS);\n\n// On a custom property a CSS-wide keyword acts on the property itself (it\n// inherits/resets the TOKEN, not the consumer), so it never expresses what\n// a host means by it; hosts pass `var(--their-token, fallback)` instead.\nconst CSS_WIDE_KEYWORD = /^(inherit|initial|unset|revert|revert-layer)$/i;\n\n/**\n * Apply a host's chrome on a designer root as inline custom properties \u2014\n * the style attribute outranks every rule in the injected stylesheet, so\n * the host's values win over the light/dark defaults. Unknown tokens,\n * non-string values and CSS-wide keywords are ignored at the door.\n */\nexport function applyChrome(root: HTMLElement, chrome: ChromeOptions | undefined): void {\n if (chrome === undefined) return;\n for (const [token, value] of Object.entries(chrome)) {\n if (!CHROME_TOKEN_SET.has(token)) continue;\n if (typeof value !== \"string\" || CSS_WIDE_KEYWORD.test(value.trim())) continue;\n root.style.setProperty(`--wgd-${token}`, value);\n }\n}\n\n/** The element form of the option: a `chrome` attribute holding JSON; anything else \u2192 nothing. */\nexport function parseChromeAttribute(value: string | null): ChromeOptions | undefined {\n if (value === null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return parsed as ChromeOptions;\n } catch {\n return undefined;\n }\n}\n\nconst STYLE_MARKER = \"data-widgentic-designer\";\n\n/** Designer chrome stylesheet \u2014 injected once per document. */\nexport function injectDesignerStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"chrome\");\n style.textContent = `\n/* Chrome tokens (CHROME_TOKENS), generated from CHROME_DEFAULTS so the\n exported palette IS the applied one. A host overrides any of them through\n options.chrome (inline on the root, which outranks these rules). Widget\n content inside the preview keeps its own --wg-* theme tokens. */\n${chromeCss(CHROME_DEFAULTS, {\n selector: \".wgd-root\",\n darkMediaSelector: '.wgd-root:not([data-wgd-theme=\"light\"])',\n darkSelector: '.wgd-root[data-wgd-theme=\"dark\"]'\n})}\n.wgd-root { display: flex; gap: var(--wgd-gap); font-family: var(--wgd-font); font-size: var(--wgd-font-size); align-items: flex-start; color: var(--wgd-text); background: var(--wgd-bg); }\n/* Any chrome class that sets display would silently defeat the hidden\n attribute (learned live twice: the add menu, then the styles tree as a\n tab pane). hidden always wins \u2014 scoped to the designer's own tree. */\n.wgd-root [hidden] { display: none !important; }\n/* Read-only: editing surfaces are inert (visible, inoperable) and read\n de-emphasized; the preview and its selectors stay full-strength. The\n controls flatten into plain values \u2014 a form that cannot be typed in\n should not look like a form (opacity alone was invisible on dark). */\n.wgd-readonly .wgd-section-body[inert] { opacity: 0.75; }\n/* Empty preview state \u2014 shown only when there has never been a valid\n render to freeze on; a blank pane is the one state the contract bans. */\n.wgd-preview-empty { color: var(--wgd-muted); font-style: italic; font-size: var(--wgd-font-size-sm); }\n.wgd-readonly [inert] .wgd-input,\n.wgd-readonly [inert] .wgd-select,\n.wgd-readonly [inert] .wgd-textarea,\n.wgd-readonly [inert] textarea.wgd-hl-input {\n border-color: transparent; background: transparent; box-shadow: none;\n}\n.wgd-readonly [inert] .wgd-hl { background: transparent; }\n/* Controls that only exist to mutate carry no meaning here. */\n.wgd-readonly [inert] .wgd-button,\n.wgd-readonly [inert] .wgd-icon,\n.wgd-readonly [inert] .wgd-add,\n.wgd-readonly [inert] input[type=\"checkbox\"] { opacity: 0.4; }\n.wgd-panels { flex: 1 1 460px; min-width: 340px; display: flex; flex-direction: column; gap: 8px; }\n.wgd-side { flex: 1 1 420px; min-width: 320px; display: flex; flex-direction: column; gap: 8px; position: sticky; top: 8px; }\n.wgd-preview-pane { display: flex; flex-direction: column; gap: 8px; }\n.wgd-section { border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 6px 10px; background: var(--wgd-panel); }\n.wgd-section-title { cursor: pointer; font-weight: 600; }\n.wgd-section-body { display: flex; flex-direction: column; gap: 8px; padding-top: 8px; }\n.wgd-field { display: flex; flex-direction: column; gap: 2px; }\n.wgd-field-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-input, .wgd-textarea, .wgd-select { font: inherit; padding: 4px 6px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); }\n/* Textareas fill their panel regardless of the intrinsic cols width. */\n.wgd-textarea { font-family: var(--wgd-font-mono); white-space: pre; width: 100%; box-sizing: border-box; min-width: 0; resize: vertical; }\n.wgd-preview .wg-designer-action { position: relative; outline: 1px dashed var(--wgd-muted); outline-offset: 2px; }\n.wgd-preview .wg-designer-action::after { content: \"\u26A1 action\"; position: absolute; top: -0.9em; right: 0; font: calc(var(--wgd-font-size-xs) - 1px) var(--wgd-font); color: var(--wgd-muted); background: var(--wgd-panel); padding: 0 4px; border-radius: var(--wgd-radius-sm); pointer-events: none; }\n.wgd-binding { display: flex; flex-direction: column; gap: 6px; padding: 6px 8px; border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius); margin: 4px 0; }\n.wgd-binding-field { min-width: 8ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-action-definition { display: flex; flex-direction: column; gap: 6px; }\n.wgd-action-schema { display: flex; flex-direction: column; gap: 4px; padding: 4px 0; }\n.wgd-test-output { font: var(--wgd-font-size-sm) var(--wgd-font-mono); white-space: pre-wrap; word-break: break-all; max-height: 240px; overflow: auto; margin: 6px 0 0; }\n.wgd-diagnostic { color: var(--wgd-danger); font-size: var(--wgd-font-size-sm); white-space: pre-wrap; }\n.wgd-banner { border: 1px solid var(--wgd-danger-line); background: var(--wgd-danger-bg); color: var(--wgd-danger); border-radius: var(--wgd-radius-lg); padding: 8px 10px; margin-bottom: 8px; }\n/* The preview is the WIDGET's surface, not chrome: it establishes the\n --wg-* context (like composePage does for page output) so widget content\n \u2014 including custom kinds the base stylesheet doesn't color \u2014 never\n inherits the designer's own text/background. */\n.wgd-preview { border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 16px; background: var(--wg-bg); color: var(--wg-fg); }\n.wgd-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }\n.wgd-button { font: inherit; padding: 4px 10px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); cursor: pointer; }\n.wgd-button:hover { background: var(--wgd-hover); }\n.wgd-tab-active { background: var(--wgd-accent-bg); border-color: var(--wgd-accent); }\n/* Shared tree/editor chrome (JSON tree, schema builder/form, template tree) */\n.wgd-jt-children, .wgd-children { margin-left: 10px; padding-left: 10px; border-left: 2px solid var(--wgd-line); display: flex; flex-direction: column; gap: 4px; }\n.wgd-jt-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }\n.wgd-jt-entry { padding: 2px 0; }\n.wgd-jt-key { font-family: var(--wgd-font-mono); color: var(--wgd-muted); min-width: 2ch; }\n.wgd-jt-keyinput, .wgd-jt-type { max-width: 12ch; }\n.wgd-jt-summary { cursor: pointer; color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-sf-object { border: 1px solid var(--wgd-line); border-radius: var(--wgd-radius-lg); padding: 6px 10px; margin: 4px 0; }\n/* Schema builder: property name + type + required on one row. */\n.wgd-sb-node { margin-left: 8px; padding: 1px 0 1px 8px; border-left: 2px solid var(--wgd-line); }\n.wgd-sb-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; }\n.wgd-sb-constraints { padding-left: 12px; }\n.wgd-sb-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-prop { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); }\n.wgd-sb-type { flex: 0 0 auto; max-width: 11ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-req { display: flex; gap: 2px; align-items: center; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-constraint { flex: 1 1 auto; min-width: 6ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-root { padding: 2px 0 2px 8px; border-left: 2px solid transparent; }\n/* Schema builder: the template tree's flat discipline \u2014 chrome on\n hover/focus only, removal revealed by the row, fitted type selects. */\n.wgd-schemabuilder .wgd-input, .wgd-schemabuilder .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-schemabuilder .wgd-input:hover, .wgd-schemabuilder .wgd-select:hover,\n.wgd-schemabuilder .wgd-input:focus, .wgd-schemabuilder .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-schemabuilder .wgd-sb-type { flex: 0 0 auto; box-sizing: border-box; max-width: none; color: var(--wgd-accent); }\n.wgd-schemabuilder .wgd-sb-prop { font-size: var(--wgd-font-size-sm); color: var(--wgd-hl-key); }\n.wgd-sb-row { border-radius: var(--wgd-radius-sm); }\n.wgd-sb-row:hover { background: var(--wgd-hover); }\n.wgd-sb-row > .wgd-icon { visibility: hidden; }\n.wgd-sb-row:hover > .wgd-icon, .wgd-sb-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-schemabuilder .wgd-button { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-schemabuilder .wgd-button:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n.wgd-remove { color: var(--wgd-danger); }\n/* Breathing room between a tab strip and its active pane. */\n.wgd-tabs > .wgd-row { margin-bottom: 6px; }\n/* Template tree: one node = one slim row; sub-structure indents below.\n Controls stay flat (chrome appears on hover/focus) so a deep template\n reads like the JSON it projects, not like a form. */\n.wgd-node { padding: 0 0 0 4px; }\n.wgd-node-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; border-radius: var(--wgd-radius-sm); }\n.wgd-node-row:hover { background: var(--wgd-hover); }\n.wgd-node-badge { font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border-radius: var(--wgd-radius-sm); padding: 0 5px; flex: 0 0 auto; }\n.wgd-node-icons { display: flex; gap: 2px; margin-left: auto; flex: 0 0 auto; visibility: hidden; }\n.wgd-node-row:hover > .wgd-node-icons, .wgd-node-row:focus-within > .wgd-node-icons { visibility: visible; }\n.wgd-node-value { flex: 1 1 auto; min-width: 4ch; }\n.wgd-icon { font: inherit; font-size: var(--wgd-font-size-xs); line-height: 1.4; padding: 0 5px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); background: var(--wgd-bg); cursor: pointer; color: var(--wgd-muted); }\n.wgd-icon:hover { background: var(--wgd-hover); }\n/* Compact controls: inside tree nodes, and wherever a section opts in with\n .wgd-compact (the Load action editor mirrors an element's binding editor). */\n.wgd-node .wgd-input, .wgd-node .wgd-select,\n.wgd-compact .wgd-input, .wgd-compact .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-node .wgd-input:hover, .wgd-node .wgd-select:hover, .wgd-compact .wgd-input:hover, .wgd-compact .wgd-select:hover,\n.wgd-node .wgd-input:focus, .wgd-node .wgd-select:focus, .wgd-compact .wgd-input:focus, .wgd-compact .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-compact .wgd-binding { border: none; padding: 0; }\n/* Busy controls (the host-supplied Test call): disabled, with a spinner. */\n.wgd-button.wgd-busy { opacity: 0.7; cursor: progress; }\n.wgd-button.wgd-busy::after { content: \"\"; display: inline-block; width: 10px; height: 10px; margin-left: 6px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; vertical-align: -1px; animation: wgd-spin 0.8s linear infinite; }\n@keyframes wgd-spin { to { transform: rotate(360deg); } }\n.wgd-tagwrap, .wgd-pathwrap { display: contents; }\n/* Collapse chevron: every tree row reserves the column so values align. */\n.wgd-chevron { flex: 0 0 auto; width: 16px; padding: 0; border: none; background: none; color: var(--wgd-muted); font-size: calc(var(--wgd-font-size-xs) - 1px); cursor: pointer; }\n.wgd-chevron-none { visibility: hidden; }\n.wgd-node-summary { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n/* Attrs vs children: attributes group under a dotted muted rail with\n key-colored names; children keep the solid accent rail. */\n.wgd-attrs { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 0; }\n.wgd-attr-row > .wgd-icon { visibility: hidden; }\n.wgd-attr-row:hover > .wgd-icon, .wgd-attr-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-attr-name { font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); flex: 0 1 auto; min-width: 5ch; }\n.wgd-attr-prefix { flex: 0 1 auto; min-width: 6ch; max-width: 10ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-str); }\n.wgd-attr { display: flex; flex-direction: column; gap: 1px; }\n/* Transform block under a bind attr: one more dotted level in. */\n.wgd-attr-map { margin-left: 24px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-map-default { flex: 1 1 auto; min-width: 8ch; }\n.wgd-attr-mode { flex: 0 0 auto; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); }\n.wgd-children { margin-left: 14px; padding-left: 8px; border-left: 2px solid var(--wgd-accent-line); gap: 1px; }\n.wgd-slot { display: flex; flex-direction: column; gap: 1px; }\n.wgd-slot-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); font-style: italic; padding-left: 4px; }\n/* Add menu: one toggle, options in a popover. */\n.wgd-menuwrap { position: relative; display: inline-flex; }\n.wgd-menu-toggle { color: var(--wgd-accent); }\n.wgd-menu { position: absolute; top: 100%; left: 0; z-index: 10; min-width: 9ch; display: flex; flex-direction: column; background: var(--wgd-panel); border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); box-shadow: var(--wgd-shadow); padding: 2px; }\n/* An OPEN menu must not inherit the icons' hover-gated visibility:\n visibility (unlike display) lets a child re-assert visible. */\n.wgd-menu:not([hidden]) { visibility: visible; }\n.wgd-menuwrap:has(> .wgd-menu:not([hidden])) { visibility: visible; }\n/* Menus in the right-aligned icons area hang leftward, not off-panel. */\n.wgd-node-icons .wgd-menu { left: auto; right: 0; }\n.wgd-menu-item { font: inherit; font-size: var(--wgd-font-size-sm); text-align: left; padding: 3px 8px; border: none; border-radius: var(--wgd-radius-sm); background: none; color: var(--wgd-text); cursor: pointer; white-space: nowrap; }\n.wgd-menu-item:hover { background: var(--wgd-accent-bg); color: var(--wgd-accent); }\n/* Styles tree: selector rows with declaration rows \u2014 the same flat\n template-tree discipline (flat inputs, hover-revealed icons). */\n.wgd-styles { display: flex; flex-direction: column; gap: 2px; }\n.wgd-st-row { display: flex; gap: 4px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-row:hover { background: var(--wgd-hover); }\n.wgd-st-row:hover > .wgd-node-icons, .wgd-st-row:focus-within > .wgd-node-icons { visibility: visible; }\n.wgd-styles .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); font-family: var(--wgd-font-mono); border-color: transparent; background: transparent; }\n.wgd-styles .wgd-input:hover, .wgd-styles .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-st-selector { flex: 1 1 auto; min-width: 8ch; color: var(--wgd-accent); }\n.wgd-st-decls { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-st-decl { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-decl:hover { background: var(--wgd-hover); }\n.wgd-st-decl > .wgd-icon { visibility: hidden; }\n.wgd-st-decl:hover > .wgd-icon, .wgd-st-decl:focus-within > .wgd-icon { visibility: visible; }\n.wgd-st-prop { flex: 0 1 auto; min-width: 8ch; color: var(--wgd-hl-key); }\n.wgd-st-value { flex: 1 1 auto; min-width: 8ch; }\n.wgd-st-colon { color: var(--wgd-muted); flex: 0 0 auto; }\n.wgd-st-add { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-st-add:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n/* Import and export stack as sibling sections with the column's rhythm. */\n.wgd-io { display: flex; flex-direction: column; gap: 8px; }\n/* Flat string\u2192string record rows (hints): mono keys, prose values. */\n.wgd-record { display: flex; flex-direction: column; gap: 1px; }\n.wgd-rec-row { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-rec-row:hover { background: var(--wgd-hover); }\n.wgd-rec-row > .wgd-icon { visibility: hidden; }\n.wgd-rec-row:hover > .wgd-icon, .wgd-rec-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-record .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-record .wgd-input:hover, .wgd-record .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-rec-key { flex: 0 1 auto; min-width: 8ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); }\n.wgd-rec-value { flex: 1 1 auto; min-width: 8ch; }\n/* The tag select IS the element node's label: flat, accent, monospace.\n Tag and path selects are width-fitted to their SELECTED value by the\n panel (fitSelect), so carets hug the text \u2014 no flex stretching here. */\n.wgd-node .wgd-tag { flex: 0 0 auto; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border: 1px solid transparent; border-radius: var(--wgd-radius-sm); padding: 0 4px; }\n.wgd-node .wgd-tag:hover, .wgd-node .wgd-tag:focus { border-color: var(--wgd-accent-line); }\n.wgd-node .wgd-path { flex: 0 1 auto; min-width: 6ch; max-width: 100%; font-family: var(--wgd-font-mono); }\n.wgd-node .wgd-select { box-sizing: border-box; }\n/* Theme panel: swatch beside each color token. */\n/* Syntax coloring: <pre> layer behind a transparent-text textarea. Every\n metric here must mirror .wgd-textarea or the glyphs drift apart. */\n.wgd-hlwrap { position: relative; }\n.wgd-hl, .wgd-hl-input {\n font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size); line-height: 1.45;\n padding: 4px 6px; border: 1px solid transparent; border-radius: var(--wgd-radius);\n box-sizing: border-box; white-space: pre; tab-size: 2; letter-spacing: normal;\n}\n.wgd-hl {\n position: absolute; inset: 0; margin: 0; overflow: hidden;\n pointer-events: none; z-index: 0; background: var(--wgd-bg);\n color: var(--wgd-text);\n}\ntextarea.wgd-hl-input {\n position: relative; z-index: 1; background: transparent; color: transparent;\n caret-color: var(--wgd-text); border-color: var(--wgd-border);\n}\n.wgd-hl-k { color: var(--wgd-hl-key); }\n.wgd-hl-s { color: var(--wgd-hl-str); }\n.wgd-hl-n { color: var(--wgd-hl-num); }\n.wgd-hl-b { color: var(--wgd-hl-bool); }\n.wgd-hl-p { color: var(--wgd-hl-punct); }\n.wgd-swatch { flex: 0 0 auto; width: 26px; height: 22px; padding: 0; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: none; cursor: pointer; }\n.wgd-token-row { display: flex; gap: 6px; align-items: center; }\n.wgd-token-row .wgd-input { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-token-ref { display: flex; flex-direction: column; gap: 2px; max-height: 220px; overflow-y: auto; margin-top: 4px; }\n.wgd-token-ref-row { display: flex; gap: 6px; align-items: center; font-size: var(--wgd-font-size-xs); }\n.wgd-token-ref-swatch { flex: 0 0 auto; width: 14px; height: 14px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); }\n.wgd-token-ref-noswatch { border-style: dashed; opacity: 0.35; }\n.wgd-token-ref-name { font-family: var(--wgd-font-mono); color: var(--wgd-accent); }\n.wgd-token-ref-value { color: var(--wgd-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.wgd-token-ref-details summary { cursor: pointer; }\n`;\n doc.head.appendChild(style);\n}\n", "/** Package-local helpers (kept here rather than exported from core \u2014 see design D4). */\n\n/** Structural copy of JSON-shaped data; the designers hand out copies, never their state. */\nexport function clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** A caught value's message without asserting it is an Error. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n", "/**\n * Cheap syntax coloring for the JSON textareas: a highlighted <pre> layer\n * sits exactly behind a transparent-text <textarea>, so the browser keeps\n * doing all the real work (typing, selection, undo, IME) and we only paint\n * colors. No editor library, no parsing beyond a tokenizer \u2014 invalid JSON\n * still colors sensibly because the tokenizer is regex-based, never a\n * parser.\n *\n * The two layers must agree on every metric that affects glyph position\n * (font, size, line-height, padding, border width, white-space); the\n * stylesheet keeps them in lockstep.\n */\n\ninterface Token {\n /** Token class suffix: k(ey) s(tring) n(umber) b(oolean/null) p(unctuation). */\n cls: string;\n text: string;\n}\n\nconst JSON_TOKENS =\n /(\"(?:[^\"\\\\]|\\\\.)*\")(\\s*:)?|(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)|\\b(true|false|null)\\b|([{}[\\],:])/g;\n\nexport function tokenizeJson(text: string): Token[] {\n const out: Token[] = [];\n let last = 0;\n let match: RegExpExecArray | null;\n JSON_TOKENS.lastIndex = 0;\n while ((match = JSON_TOKENS.exec(text)) !== null) {\n if (match.index > last) out.push({ cls: \"\", text: text.slice(last, match.index) });\n if (match[1] !== undefined) {\n // A string followed by ':' is an object key.\n if (match[2] !== undefined) {\n out.push({ cls: \"k\", text: match[1] });\n out.push({ cls: \"p\", text: match[2] });\n } else {\n out.push({ cls: \"s\", text: match[1] });\n }\n } else if (match[3] !== undefined) {\n out.push({ cls: \"n\", text: match[3] });\n } else if (match[4] !== undefined) {\n out.push({ cls: \"b\", text: match[4] });\n } else if (match[5] !== undefined) {\n out.push({ cls: \"p\", text: match[5] });\n }\n last = JSON_TOKENS.lastIndex;\n }\n if (last < text.length) out.push({ cls: \"\", text: text.slice(last) });\n return out;\n}\n\n/** Paint tokens into the layer as DOM nodes (never innerHTML). */\nfunction paint(layer: HTMLElement, text: string): void {\n const nodes: Node[] = [];\n for (const token of tokenizeJson(text)) {\n if (token.cls === \"\") {\n nodes.push(document.createTextNode(token.text));\n continue;\n }\n const span = document.createElement(\"span\");\n span.className = `wgd-hl-${token.cls}`;\n span.textContent = token.text;\n nodes.push(span);\n }\n // A trailing newline needs a following glyph box to render as a line.\n nodes.push(document.createTextNode(\"\\n\"));\n layer.replaceChildren(...nodes);\n}\n\n/**\n * Wrap a textarea in the highlight layer. Returns a disposer that restores\n * the original DOM shape.\n */\nexport function attachJsonHighlight(textarea: HTMLTextAreaElement): () => void {\n const parent = textarea.parentNode;\n if (parent === null) return () => undefined;\n\n const wrap = document.createElement(\"div\");\n wrap.className = \"wgd-hlwrap\";\n const layer = document.createElement(\"pre\");\n layer.className = \"wgd-hl\";\n layer.setAttribute(\"aria-hidden\", \"true\");\n\n parent.insertBefore(wrap, textarea);\n wrap.append(layer, textarea);\n textarea.classList.add(\"wgd-hl-input\");\n\n const sync = (): void => {\n paint(layer, textarea.value);\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n const syncScroll = (): void => {\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n // Tab indents instead of moving focus \u2014 these panes hold indented JSON.\n // Shift+Tab keeps its focus-moving default as the keyboard escape.\n const onTab = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\" || event.shiftKey || textarea.readOnly) return;\n event.preventDefault();\n const { selectionStart, selectionEnd, value } = textarea;\n textarea.value = `${value.slice(0, selectionStart)} ${value.slice(selectionEnd)}`;\n textarea.selectionStart = textarea.selectionEnd = selectionStart + 2;\n // The commit path listens for input; a synthetic one keeps the store\n // and the paint layer in step with the inserted spaces.\n textarea.dispatchEvent(new Event(\"input\", { bubbles: true }));\n };\n\n textarea.addEventListener(\"input\", sync);\n textarea.addEventListener(\"scroll\", syncScroll);\n textarea.addEventListener(\"keydown\", onTab);\n sync();\n\n return () => {\n textarea.removeEventListener(\"input\", sync);\n textarea.removeEventListener(\"scroll\", syncScroll);\n textarea.removeEventListener(\"keydown\", onTab);\n textarea.classList.remove(\"wgd-hl-input\");\n wrap.replaceWith(textarea);\n };\n}\n\n/**\n * Repaint after a programmatic value change (store refresh), which fires\n * no input event.\n */\nexport function repaintHighlight(textarea: HTMLTextAreaElement): void {\n const layer = textarea.parentElement?.querySelector(\".wgd-hl\");\n if (layer instanceof HTMLElement) paint(layer, textarea.value);\n}\n", "/**\n * Import/export in the server's shapes: widget JSON is exactly the\n * `CustomWidget` definition (`{ kind, template, descriptor }`) that\n * `examples/mcp-server/widgets/` registers; themes are bare token maps.\n * Imports are untrusted \u2014 everything re-validates, and a failed import\n * never touches the current draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport { parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { } from \"@widgentic/core\";\nimport { diagnosticLine, h, section, textArea, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport interface WidgetDefinition {\n kind: WidgetDraft[\"kind\"];\n template: WidgetDraft[\"template\"];\n descriptor: WidgetDraft[\"descriptor\"];\n load?: ActionBinding;\n}\n\n/** Validate an untrusted definition; errors instead of throws. */\nexport function checkDefinition(definition: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(definition)) return [\"Definition must be an object.\"];\n if (typeof definition.kind !== \"string\" || definition.kind.trim() === \"\") {\n errors.push(\"'kind' must be a non-empty string.\");\n }\n const template = validateTemplate(definition.template);\n if (!template.ok) {\n errors.push(`template: ${template.error.code} \u2014 ${template.error.message}`);\n }\n if (!isPlainObject(definition.descriptor)) {\n errors.push(\"'descriptor' must be an object.\");\n } else if (typeof definition.descriptor.description !== \"string\") {\n errors.push(\"'descriptor.description' must be a string.\");\n }\n if (definition.load !== undefined) {\n const problem = validateLoadBinding(definition.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) errors.push(`load: ${problem.message} (at ${problem.path})`);\n }\n return errors;\n}\n\nexport function exportWidgetJson(draft: WidgetDraft): string {\n const definition: WidgetDefinition = {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n };\n return JSON.stringify(definition, null, 2);\n}\n\nexport function exportThemeJson(draft: WidgetDraft): string {\n return JSON.stringify(draft.theme ?? {}, null, 2);\n}\n\nexport type ImportResult =\n | { ok: true; definition: WidgetDefinition }\n | { ok: false; errors: string[] };\n\nexport function importWidgetJson(text: string): ImportResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n return { ok: false, errors: [`Invalid JSON: ${errorMessage(error)}`] };\n }\n const errors = checkDefinition(parsed);\n if (errors.length > 0) return { ok: false, errors };\n return { ok: true, definition: parsed as unknown as WidgetDefinition };\n}\n\n/** Apply a validated definition to the store, preserving the session theme. */\nexport function applyDefinition(store: DraftStore, definition: WidgetDefinition): void {\n const theme = store.get().theme;\n store.replace({\n kind: definition.kind,\n template: definition.template,\n descriptor: definition.descriptor,\n ...(definition.load !== undefined ? { load: definition.load } : {}),\n ...(theme !== undefined ? { theme } : {})\n });\n}\n\nfunction camelCase(kind: string): string {\n return kind\n .split(/[^a-zA-Z0-9]+/)\n .filter((part) => part.length > 0)\n .map((part, i) => (i === 0 ? part : part[0]?.toUpperCase() + part.slice(1)))\n .join(\"\");\n}\n\n/**\n * Emit a module body compatible with `examples/mcp-server/widgets/` \u2014\n * the manual-registration bridge until wire registration exists.\n */\nexport function toTypeScriptModule(draft: WidgetDraft): string {\n const name = camelCase(draft.kind) || \"custom\";\n return (\n `import type { CustomWidget } from \"./index.js\";\\n\\n` +\n `export const ${name}Widget: CustomWidget = ${JSON.stringify(\n {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n },\n null,\n 2\n )};\\n`\n );\n}\n\nexport function mountIoPanel(store: DraftStore): {\n element: HTMLElement;\n dispose(): void;\n} {\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n\n function button(label: string, produce: () => string): HTMLElement {\n const el = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [label]);\n el.addEventListener(\"click\", () => {\n output.value = produce();\n repaintHighlight(output);\n });\n return el;\n }\n\n const importError = diagnosticLine(undefined);\n const importField = textArea(\"Import widget JSON\", \"\", () => undefined, 5);\n const importArea = requireChild(importField, \"textarea\");\n attachJsonHighlight(importArea);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n const result = importWidgetJson(importArea.value);\n if (!result.ok) {\n importError.hidden = false;\n importError.textContent = result.errors.join(\"\\n\");\n return; // current draft untouched\n }\n importError.hidden = true;\n importError.textContent = \"\";\n applyDefinition(store, result.definition);\n });\n\n // Import and export are independent flows \u2014 two sections, import first\n // (bringing a drafted definition in is the more common entry point).\n const importSection = section(\"Import\", [\n importField,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n // Export copies out what is already on screen, so read-only leaves it\n // operable: the mode restricts editing, not looking.\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-row\" }, [\n button(\"Export widget JSON\", () => exportWidgetJson(store.get())),\n button(\"Export theme JSON\", () => exportThemeJson(store.get())),\n button(\"Copy as TypeScript\", () => toTypeScriptModule(store.get()))\n ]),\n output\n ]);\n exportSection.classList.add(\"wgd-view-only\");\n const element = h(\"div\", { class: \"wgd-io\" }, [importSection, exportSection]);\n // After assembly: the layer wraps the textarea in place, so the element\n // must already have its parent.\n attachJsonHighlight(output);\n\n return { element, dispose: () => element.remove() };\n}\n", "/**\n * Generic JSON value editor: collapsible tree with in-place key/value\n * editing, type switching, and add/remove \u2014 the NanoJSON/JSONTree\n * interaction pattern, built in-house because the general libraries carry\n * far more (and weigh far more) than the designer needs.\n *\n * Structural operations re-render the tree; text edits commit on change\n * (blur/Enter) so typing is never interrupted.\n */\nimport { h } from \"./dom.js\";\n\ntype Path = (string | number)[];\n\nconst TYPE_OPTIONS = [\"string\", \"number\", \"boolean\", \"null\", \"object\", \"array\"] as const;\ntype TypeName = (typeof TYPE_OPTIONS)[number];\n\nfunction typeOf(value: unknown): TypeName {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return (typeof value) as TypeName;\n}\n\nfunction defaultFor(type: TypeName, previous: unknown): unknown {\n switch (type) {\n case \"string\":\n return typeof previous === \"number\" || typeof previous === \"boolean\"\n ? String(previous)\n : \"\";\n case \"number\": {\n const parsed = Number(previous);\n return Number.isFinite(parsed) ? parsed : 0;\n }\n case \"boolean\":\n return previous === \"true\" ? true : Boolean(previous) && previous !== \"false\";\n case \"null\":\n return null;\n case \"object\":\n return {};\n case \"array\":\n return [];\n }\n}\n\nfunction setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n if (typeof root === \"object\" && root !== null) {\n const copy = { ...(root as Record<string, unknown>) };\n if (rest.length === 0 && remove) delete copy[step as string];\n else copy[step as string] = setAt(copy[step as string], rest, value, remove);\n return copy;\n }\n return root;\n}\n\nfunction renameKey(root: unknown, path: Path, from: string, to: string): unknown {\n const holder = path.reduce<unknown>(\n (node, step) =>\n typeof node === \"object\" && node !== null\n ? (node as Record<string, unknown>)[step as string]\n : undefined,\n root\n );\n if (typeof holder !== \"object\" || holder === null || Array.isArray(holder)) return root;\n const entries = Object.entries(holder).map(([k, v]) =>\n k === from ? ([to, v] as const) : ([k, v] as const)\n );\n return setAt(root, path, Object.fromEntries(entries));\n}\n\nexport interface JsonTreeEditor {\n element: HTMLElement;\n getValue(): unknown;\n /** External update (skipped while the user is editing inside the tree). */\n setValue(value: unknown): void;\n}\n\nexport function createJsonTreeEditor(\n initial: unknown,\n onChange: (value: unknown) => void\n): JsonTreeEditor {\n let current: unknown = initial;\n const element = h(\"div\", { class: \"wgd-jsontree\" });\n\n function commit(next: unknown): void {\n current = next;\n render();\n onChange(current);\n }\n\n function commitText(path: Path, type: TypeName, text: string): void {\n const value =\n type === \"number\"\n ? Number.isFinite(Number(text))\n ? Number(text)\n : 0\n : text;\n current = setAt(current, path, value);\n onChange(current); // no re-render: in-place text edit\n }\n\n function typeSelect(value: unknown, path: Path): HTMLSelectElement {\n const select = h(\"select\", { class: \"wgd-select wgd-jt-type\" });\n for (const option of TYPE_OPTIONS) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.value = typeOf(value);\n select.addEventListener(\"change\", () =>\n commit(setAt(current, path, defaultFor(select.value as TypeName, value)))\n );\n return select;\n }\n\n function valueControl(value: unknown, path: Path): Node {\n const type = typeOf(value);\n if (type === \"boolean\") {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value as boolean;\n box.addEventListener(\"change\", () => commit(setAt(current, path, box.checked)));\n return box;\n }\n if (type === \"null\") return h(\"code\", undefined, [\"null\"]);\n if (type === \"string\" || type === \"number\") {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = String(value);\n input.addEventListener(\"change\", () => commitText(path, type, input.value));\n return input;\n }\n return h(\"span\");\n }\n\n function entryRow(\n keyLabel: Node,\n value: unknown,\n path: Path,\n removable: boolean\n ): HTMLElement {\n const row = h(\"div\", { class: \"wgd-jt-row\" }, [keyLabel, typeSelect(value, path)]);\n const type = typeOf(value);\n if (type !== \"object\" && type !== \"array\") {\n row.append(valueControl(value, path));\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => commit(setAt(current, path, undefined, true)));\n row.append(remove);\n }\n const wrap = h(\"div\", { class: \"wgd-jt-entry\" }, [row]);\n if (type === \"object\" || type === \"array\") {\n wrap.append(renderContainer(value, path));\n }\n return wrap;\n }\n\n function renderContainer(value: unknown, path: Path): HTMLElement {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n body.append(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [String(index)]), item, [...path, index], true)\n );\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit(setAt(current, [...path, value.length], \"\"))\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n } else if (typeof value === \"object\" && value !== null) {\n for (const [key, item] of Object.entries(value)) {\n const keyInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n keyInput.value = key;\n keyInput.addEventListener(\"change\", () =>\n commit(renameKey(current, path, key, keyInput.value))\n );\n body.append(entryRow(keyInput, item, [...path, key], true));\n }\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ property\"]);\n add.addEventListener(\"click\", () => {\n const holder = value as Record<string, unknown>;\n let name = \"key\";\n for (let i = 1; name in holder; i++) name = `key${i}`;\n commit(setAt(current, [...path, name], \"\"));\n });\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n const details = h(\"details\", { class: \"wgd-jt-branch\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-jt-summary\" }, [\n Array.isArray(value)\n ? `[ ${value.length} item${value.length === 1 ? \"\" : \"s\"} ]`\n : `{ ${Object.keys(value as object).length} propert${Object.keys(value as object).length === 1 ? \"y\" : \"ies\"} }`\n ]),\n body\n ]);\n return details;\n }\n\n function render(): void {\n element.replaceChildren(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [\"value\"]), current, [], false)\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value;\n render();\n }\n };\n}\n", "/**\n * Structured editor for the dataSchema subset \u2014 the property-card pattern\n * from the React schema-builder ecosystem, sized to widgentic's six\n * keywords (type/properties/required/items/enum/pattern) so it stays a\n * dependency-free couple hundred lines.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h } from \"./dom.js\";\n\nconst TYPES = [\"object\", \"array\", \"string\", \"number\", \"integer\", \"boolean\", \"null\", \"any\"] as const;\n\n/**\n * Types the builder offers `enum` for. The validator accepts `enum` on any\n * type (deep JSON comparison, per JSON Schema), but enumerating whole\n * objects/arrays belongs in the JSON tab, not a form.\n */\nconst ENUM_TYPES = new Set([\"string\", \"number\", \"integer\", \"any\"]);\n\nexport interface SchemaBuilder {\n element: HTMLElement;\n getValue(): DataSchema | undefined;\n setValue(schema: DataSchema | undefined): void;\n}\n\nexport function createSchemaBuilder(\n initial: DataSchema | undefined,\n onChange: (schema: DataSchema | undefined) => void\n): SchemaBuilder {\n let current: DataSchema | undefined = initial;\n const element = h(\"div\", { class: \"wgd-schemabuilder\" });\n\n function commit(next: DataSchema | undefined, rerender = true): void {\n current = next;\n onChange(current);\n if (rerender) render();\n }\n\n /** Rebuild a node with one key changed/removed (undefined removes). */\n function withKey(node: DataSchema, key: string, value: unknown): DataSchema {\n const copy: DataSchema = { ...node };\n if (value === undefined) delete copy[key];\n else copy[key] = value;\n return copy;\n }\n\n /**\n * One schema node. `lead`/`trail` let a parent put the property name and\n * its required/remove controls on the SAME row as the type select.\n */\n function renderNode(\n node: DataSchema,\n apply: (next: DataSchema) => void,\n depth: number,\n lead: (Node | string)[] = [],\n trail: (Node | string)[] = []\n ): HTMLElement {\n const rows: (Node | string)[] = [];\n\n const typeSelect = h(\"select\", { class: \"wgd-select wgd-sb-type\" });\n for (const t of TYPES) typeSelect.append(h(\"option\", { value: t }, [t]));\n // Nullable type arrays ([<type>, \"null\"], either order) present as the\n // PRIMARY type + a nullable toggle \u2014 never collapsing to \"any\", which\n // silently hid pattern/enum for agent-authored nullable fields.\n const rawType = node.type;\n const typeList = Array.isArray(rawType)\n ? rawType.filter((t): t is string => typeof t === \"string\")\n : undefined;\n const nullable = typeList?.includes(\"null\") ?? false;\n const currentType =\n typeof rawType === \"string\"\n ? rawType\n : (typeList?.find((t) => t !== \"null\") ?? (nullable ? \"null\" : \"any\"));\n typeSelect.value = TYPES.some((type) => type === currentType)\n ? currentType\n : \"any\";\n fitSelect(typeSelect);\n const nullBox = h(\"input\", {\n type: \"checkbox\",\n title: \"Also allows null\"\n });\n nullBox.checked = nullable;\n nullBox.disabled = typeSelect.value === \"any\" || typeSelect.value === \"null\";\n /** The `type` value the current controls describe. */\n function typeValue(selected: string, allowNull: boolean): unknown {\n if (selected === \"any\") return undefined;\n return allowNull && selected !== \"null\" ? [selected, \"null\"] : selected;\n }\n nullBox.addEventListener(\"change\", () => {\n apply(withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked)));\n });\n typeSelect.addEventListener(\"change\", () => {\n let next = withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked));\n if (typeSelect.value !== \"object\") {\n next = withKey(withKey(next, \"properties\", undefined), \"required\", undefined);\n }\n if (typeSelect.value !== \"array\") next = withKey(next, \"items\", undefined);\n if (typeSelect.value !== \"string\") next = withKey(next, \"pattern\", undefined);\n if (!ENUM_TYPES.has(typeSelect.value)) next = withKey(next, \"enum\", undefined);\n apply(next);\n });\n // Header row: [name?] [type] [nullable] [required?] [remove?]\n rows.push(\n h(\"div\", { class: \"wgd-sb-row\" }, [\n ...lead,\n typeSelect,\n h(\"label\", { class: \"wgd-sb-req wgd-sb-null\", title: \"Also allows null\" }, [\n nullBox,\n \"null\"\n ]),\n ...trail\n ])\n );\n\n // Constraints row \u2014 only the ones this type can actually use.\n const constraints: (Node | string)[] = [];\n if (typeSelect.value === \"string\") {\n const pattern = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: \"pattern (regex, optional)\"\n });\n pattern.value = typeof node.pattern === \"string\" ? node.pattern : \"\";\n pattern.addEventListener(\"change\", () =>\n apply(withKey(node, \"pattern\", pattern.value === \"\" ? undefined : pattern.value))\n );\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"pattern\"]), pattern);\n }\n const enumError = diagnosticLine(undefined);\n // `enum` is type-agnostic in the validator, but enumerating whole\n // objects/arrays is a JSON-tab affair \u2014 the builder offers it where\n // it is actually useful.\n if (ENUM_TYPES.has(typeSelect.value)) {\n const enumInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: 'enum [\"a\",\"b\"] (optional)'\n });\n enumInput.value = Array.isArray(node.enum) ? JSON.stringify(node.enum) : \"\";\n enumInput.addEventListener(\"change\", () => {\n if (enumInput.value.trim() === \"\") {\n enumError.hidden = true;\n apply(withKey(node, \"enum\", undefined));\n return;\n }\n try {\n const parsed: unknown = JSON.parse(enumInput.value);\n if (!Array.isArray(parsed)) throw new Error(\"must be a JSON array\");\n enumError.hidden = true;\n apply(withKey(node, \"enum\", parsed));\n } catch (error) {\n enumError.hidden = false;\n enumError.textContent = `enum ignored: ${errorMessage(error)}`;\n }\n });\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"enum\"]), enumInput);\n }\n if (constraints.length > 0) {\n rows.push(h(\"div\", { class: \"wgd-sb-row wgd-sb-constraints\" }, constraints), enumError);\n }\n\n // Object: property cards + required toggles\n if (typeSelect.value === \"object\") {\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required)\n ? node.required.filter((k): k is string => typeof k === \"string\")\n : [];\n const cards = h(\"div\", { class: \"wgd-jt-children\" });\n for (const [name, sub] of Object.entries(properties)) {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-prop\",\n placeholder: \"property name\"\n });\n nameInput.value = name;\n nameInput.addEventListener(\"change\", () => {\n const entries = Object.entries(properties).map(([k, v]) =>\n k === name ? ([nameInput.value, v] as const) : ([k, v] as const)\n );\n const nextRequired = required.map((k) => (k === name ? nameInput.value : k));\n apply(\n withKey(\n withKey(node, \"properties\", Object.fromEntries(entries)),\n \"required\",\n nextRequired.length > 0 ? nextRequired : undefined\n )\n );\n });\n const requiredBox = h(\"input\", { type: \"checkbox\", title: \"required\" });\n requiredBox.checked = required.includes(name);\n requiredBox.addEventListener(\"change\", () => {\n const nextRequired = requiredBox.checked\n ? [...required, name]\n : required.filter((k) => k !== name);\n apply(withKey(node, \"required\", nextRequired.length > 0 ? nextRequired : undefined));\n });\n const removeProp = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove property\" }, [\"\u2715\"]);\n removeProp.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = properties;\n apply(\n withKey(\n withKey(node, \"properties\", Object.keys(rest).length > 0 ? rest : undefined),\n \"required\",\n required.filter((k) => k !== name).length > 0\n ? required.filter((k) => k !== name)\n : undefined\n )\n );\n });\n // Name, type, required and remove all share the property's first row.\n cards.append(\n renderNode(\n isPlainObject(sub) ? (sub as DataSchema) : {},\n (nextSub) =>\n apply(withKey(node, \"properties\", { ...properties, [name]: nextSub })),\n depth + 1,\n [nameInput],\n [\n h(\"label\", { class: \"wgd-sb-req\", title: \"required\" }, [requiredBox, \"req\"]),\n removeProp\n ]\n )\n );\n }\n const addProp = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ property\"\n ]);\n addProp.addEventListener(\"click\", () => {\n let name = \"field\";\n for (let i = 1; name in properties; i++) name = `field${i}`;\n apply(withKey(node, \"properties\", { ...properties, [name]: { type: \"string\" } }));\n });\n cards.append(h(\"div\", { class: \"wgd-toolbar\" }, [addProp]));\n rows.push(cards);\n }\n\n // Array: items node\n if (typeSelect.value === \"array\") {\n rows.push(\n h(\"div\", { class: \"wgd-slot\" }, [\n renderNode(\n isPlainObject(node.items) ? (node.items as DataSchema) : {},\n (nextItems) => apply(withKey(node, \"items\", nextItems)),\n depth + 1,\n [h(\"span\", { class: \"wgd-sb-label\" }, [\"items\"])]\n )\n ])\n );\n }\n\n return h(\"div\", { class: depth === 0 ? \"wgd-sb-root\" : \"wgd-sb-node\" }, rows);\n }\n\n function render(): void {\n if (current === undefined) {\n const start = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ add a data schema\"\n ]);\n start.addEventListener(\"click\", () => commit({ type: \"object\" }));\n element.replaceChildren(\n h(\"div\", undefined, [\n h(\"span\", { class: \"wgd-sb-label\" }, [\n \"No schema \u2014 data is accepted leniently.\"\n ]),\n h(\"div\", { class: \"wgd-toolbar\" }, [start])\n ])\n );\n return;\n }\n const clear = h(\"button\", { class: \"wgd-button wgd-add wgd-remove\", type: \"button\" }, [\n \"remove schema\"\n ]);\n clear.addEventListener(\"click\", () => commit(undefined));\n element.replaceChildren(\n renderNode(current, (next) => commit(next), 0),\n h(\"div\", { class: \"wgd-toolbar\" }, [clear])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(schema) {\n if (element.contains(document.activeElement)) return;\n current = schema;\n render();\n }\n };\n}\n", "/**\n * Flat editor for a string\u2192string record (hints: name \u2192 doc), under the\n * same flat discipline as the styles tree \u2014 one slim row per entry,\n * removal revealed by the row. Values are strings by construction, so\n * the tree enforces the exact shape; anything looser is a JSON-tab\n * affair.\n */\nimport { h } from \"./dom.js\";\n\nexport interface RecordEditor {\n element: HTMLElement;\n getValue(): Record<string, string> | undefined;\n setValue(record: Record<string, string> | undefined): void;\n}\n\nexport function createRecordEditor(\n initial: Record<string, string> | undefined,\n placeholders: { key: string; value: string; add: string },\n onChange: (record: Record<string, string> | undefined) => void\n): RecordEditor {\n let current: Record<string, string> | undefined = initial;\n const element = h(\"div\", { class: \"wgd-record\" });\n\n function commit(next: Record<string, string>): void {\n // An emptied record means \"none\" \u2014 the owning key drops entirely.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function render(): void {\n const record = current ?? {};\n const rows = Object.entries(record).map(([key, value]) => {\n const keyInput = changeInput(\n key,\n placeholders.key,\n \"wgd-input wgd-rec-key\",\n (next) => {\n const entries = Object.entries(record).map(([k, v]) =>\n k === key ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const valueInput = changeInput(\n value,\n placeholders.value,\n \"wgd-input wgd-rec-value\",\n (next) => commit({ ...record, [key]: next })\n );\n const remove = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove entry\" },\n [\"\u2715\"]\n );\n remove.addEventListener(\"click\", () => {\n const { [key]: _gone, ...rest } = record;\n commit(rest);\n });\n return h(\"div\", { class: \"wgd-rec-row\" }, [\n keyInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n remove\n ]);\n });\n const add = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [placeholders.add]\n );\n add.addEventListener(\"click\", () => {\n let key = \"\";\n for (let i = 1; key in record; i++) key = `key${i}`;\n commit({ ...record, [key]: \"\" });\n });\n element.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(record) {\n if (element.contains(document.activeElement)) return;\n current = record;\n render();\n }\n };\n}\n", "/**\n * Schema-driven data form: generates controls from widgentic's dataSchema\n * subset (type/properties/required/items/enum/pattern). This is the\n * @json-editor/json-editor interaction model, sized to the six keywords\n * the subset actually has \u2014 which is what makes an in-house generator a\n * few hundred lines instead of a 150 KB dependency.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nfunction firstType(schema: DataSchema): string | undefined {\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n // Nullable arrays pick the PRIMARY type regardless of order.\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n if (type.includes(\"null\")) return \"null\";\n }\n return undefined;\n}\n\nfunction seedFor(schema: DataSchema): unknown {\n if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];\n switch (firstType(schema)) {\n case \"object\": {\n const seed: Record<string, unknown> = {};\n if (isPlainObject(schema.properties) && Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && isPlainObject(schema.properties[key])) {\n seed[key] = seedFor(schema.properties[key] as DataSchema);\n }\n }\n }\n return seed;\n }\n case \"array\":\n return [];\n case \"number\":\n case \"integer\":\n return 0;\n case \"boolean\":\n return false;\n case \"null\":\n return null;\n default:\n return \"\";\n }\n}\n\nexport interface SchemaForm {\n element: HTMLElement;\n getValue(): unknown;\n setValue(value: unknown): void;\n}\n\nexport function createSchemaForm(\n schema: DataSchema,\n initial: unknown,\n onChange: (value: unknown) => void\n): SchemaForm {\n let current: unknown = initial ?? seedFor(schema);\n const element = h(\"div\", { class: \"wgd-schemaform\" });\n\n type Path = (string | number)[];\n\n function setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n const holder = isPlainObject(root) ? { ...root } : {};\n if (rest.length === 0 && remove) delete holder[step as string];\n else holder[step as string] = setAt(holder[step as string], rest, value, remove);\n return holder;\n }\n\n function commit(path: Path, value: unknown, rerender = false): void {\n current = setAt(current, path, value);\n onChange(current);\n if (rerender) render();\n }\n\n function control(node: DataSchema, value: unknown, path: Path, label: string): HTMLElement {\n if (Array.isArray(node.enum)) {\n const select = h(\"select\", { class: \"wgd-select\" });\n for (const option of node.enum) {\n select.append(h(\"option\", { value: JSON.stringify(option) }, [JSON.stringify(option)]));\n }\n select.value = JSON.stringify(value ?? node.enum[0]);\n select.addEventListener(\"change\", () =>\n commit(path, JSON.parse(select.value) as unknown)\n );\n return field(label, select);\n }\n switch (firstType(node)) {\n case \"boolean\": {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value === true;\n box.addEventListener(\"change\", () => commit(path, box.checked));\n return field(label, box);\n }\n case \"number\":\n case \"integer\": {\n const input = h(\"input\", { type: \"number\", class: \"wgd-input\" });\n input.value = typeof value === \"number\" ? String(value) : \"0\";\n input.addEventListener(\"change\", () => {\n const parsed = Number(input.value);\n commit(path, Number.isFinite(parsed) ? parsed : 0);\n });\n return field(label, input);\n }\n case \"object\": {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required) ? node.required : [];\n const holder = isPlainObject(value) ? value : {};\n for (const [name, sub] of Object.entries(properties)) {\n if (!isPlainObject(sub)) continue;\n const isRequired = required.includes(name);\n body.append(\n control(\n sub as DataSchema,\n holder[name] ?? (isRequired ? seedFor(sub as DataSchema) : undefined),\n [...path, name],\n isRequired ? `${name} *` : name\n )\n );\n }\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n case \"array\": {\n const itemsSchema = isPlainObject(node.items) ? (node.items as DataSchema) : {};\n const items = Array.isArray(value) ? value : [];\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n items.forEach((item, index) => {\n const row = h(\"div\", { class: \"wgd-jt-entry\" }, [\n control(itemsSchema, item, [...path, index], `#${index}`)\n ]);\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove item\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n current = setAt(current, [...path, index], undefined, true);\n onChange(current);\n render();\n });\n row.append(remove);\n body.append(row);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit([...path, items.length], seedFor(itemsSchema), true)\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n default: {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n if (typeof node.pattern === \"string\") {\n input.setAttribute(\"placeholder\", `pattern: ${node.pattern}`);\n input.setAttribute(\"title\", `Must match ${node.pattern}`);\n }\n input.value = typeof value === \"string\" ? value : value === undefined ? \"\" : String(value);\n input.addEventListener(\"change\", () => commit(path, input.value));\n return field(label, input);\n }\n }\n }\n\n function field(label: string, controlEl: Node): HTMLElement {\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n controlEl\n ]);\n }\n\n function render(): void {\n element.replaceChildren(control(schema, current, [], \"data\"));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value ?? seedFor(schema);\n render();\n }\n };\n}\n", "/**\n * Structured editor for the descriptor's styles \u2014 selector rows with\n * their declaration rows, under the template tree's flat discipline.\n * The value is `Record<selector, Record<property, value>>` (strings\n * only), so the tree enforces the exact shape the server's style guards\n * expect; anything looser belongs in the JSON tab.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nexport type WidgetStylesValue = Record<string, Record<string, string>>;\n\nexport interface StylesEditor {\n element: HTMLElement;\n getValue(): WidgetStylesValue | undefined;\n setValue(styles: WidgetStylesValue | undefined): void;\n}\n\nexport function createStylesEditor(\n initial: WidgetStylesValue | undefined,\n onChange: (styles: WidgetStylesValue | undefined) => void\n): StylesEditor {\n let current: WidgetStylesValue | undefined = initial;\n const element = h(\"div\", { class: \"wgd-styles\" });\n\n function commit(next: WidgetStylesValue): void {\n // An emptied record means \"no styles\" \u2014 the descriptor drops the key.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function renderSelector(\n selector: string,\n declarations: Record<string, string>,\n styles: WidgetStylesValue\n ): HTMLElement {\n const rename = changeInput(\n selector,\n \".wg-selector\",\n \"wgd-input wgd-st-selector\",\n (next) => {\n const entries = Object.entries(styles).map(([k, v]) =>\n k === selector ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const addDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Add declaration\" },\n [\"+\"]\n );\n addDecl.addEventListener(\"click\", () => {\n commit({ ...styles, [selector]: { ...declarations, \"\": \"\" } });\n });\n const removeSelector = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove selector\" },\n [\"\u2715\"]\n );\n removeSelector.addEventListener(\"click\", () => {\n const { [selector]: _gone, ...rest } = styles;\n commit(rest);\n });\n const declRows = Object.entries(declarations).map(([property, value]) => {\n const propInput = changeInput(\n property,\n \"property\",\n \"wgd-input wgd-st-prop\",\n (next) => {\n const entries = Object.entries(declarations).map(([k, v]) =>\n k === property ? ([next, v] as const) : ([k, v] as const)\n );\n commit({ ...styles, [selector]: Object.fromEntries(entries) });\n }\n );\n const valueInput = changeInput(\n value,\n \"value (no url(...), no ;)\",\n \"wgd-input wgd-st-value\",\n (next) => {\n commit({\n ...styles,\n [selector]: { ...declarations, [property]: next }\n });\n }\n );\n const removeDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove declaration\" },\n [\"\u2715\"]\n );\n removeDecl.addEventListener(\"click\", () => {\n const { [property]: _gone, ...rest } = declarations;\n commit({ ...styles, [selector]: rest });\n });\n return h(\"div\", { class: \"wgd-st-decl\" }, [\n propInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n removeDecl\n ]);\n });\n return h(\"div\", { class: \"wgd-st-rule\" }, [\n h(\"div\", { class: \"wgd-st-row\" }, [\n rename,\n h(\"span\", { class: \"wgd-node-icons\" }, [addDecl, removeSelector])\n ]),\n h(\"div\", { class: \"wgd-st-decls\" }, declRows)\n ]);\n }\n\n function render(): void {\n const styles = current ?? {};\n const addSelector = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [\"+ selector\"]\n );\n addSelector.addEventListener(\"click\", () => {\n let name = \".wg-\";\n for (let i = 1; name in styles; i++) name = `.wg-${i}`;\n commit({ ...styles, [name]: {} });\n });\n element.replaceChildren(\n ...Object.entries(styles).map(([selector, declarations]) =>\n renderSelector(\n selector,\n isPlainObject(declarations)\n ? (declarations as Record<string, string>)\n : {},\n styles\n )\n ),\n h(\"div\", { class: \"wgd-toolbar\" }, [addSelector])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(styles) {\n if (element.contains(document.activeElement)) return;\n current = styles;\n render();\n }\n };\n}\n", "/**\n * Path helpers over widgentic's dataSchema subset, shared by the template\n * panel (bind/each/when completions) and the binding editor (input and\n * output mapping completions, type checks). Nullable type arrays pick the\n * PRIMARY type; `any` (no type) is treated as unknown, never mismatched.\n */\nimport { isPlainObject } from \"@widgentic/core\";\n/** The primary type a schema declares, if any. */\nexport function schemaType(schema: unknown): string | undefined {\n if (!isPlainObject(schema)) return undefined;\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n }\n return undefined;\n}\n\n/**\n * Dotted paths reachable from a schema, with the schema at each path.\n * Arrays are offered as themselves; descending into their items needs an\n * `each` first, so collection stops there.\n */\nexport function collectPaths(\n schema: unknown,\n prefix: string,\n out: { path: string; schema: unknown }[],\n depth = 0\n): void {\n if (!isPlainObject(schema) || depth > 3) return;\n if (schemaType(schema) !== \"object\" || !isPlainObject(schema.properties)) return;\n for (const [name, sub] of Object.entries(schema.properties)) {\n const path = prefix === \"\" ? name : `${prefix}.${name}`;\n out.push({ path, schema: sub });\n collectPaths(sub, path, out, depth + 1);\n }\n}\n\n/** The sub-schema at a dotted path (\"\" or \".\" is the schema itself). */\nexport function schemaAt(schema: unknown, path: string): unknown {\n if (path === \"\" || path === \".\") return schema;\n let current: unknown = schema;\n for (const segment of path.split(\".\")) {\n if (!isPlainObject(current)) return undefined;\n if (schemaType(current) === \"array\") {\n current = isPlainObject(current.items) ? current.items : undefined;\n if (!/^\\d+$/.test(segment)) {\n // A named segment under an array steps into the item schema.\n if (!isPlainObject(current) || !isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n continue;\n }\n if (!isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n return current;\n}\n\n/** Numeric types agree with each other; unknown never mismatches. */\nexport function typesConflict(a: string | undefined, b: string | undefined): boolean {\n if (a === undefined || b === undefined) return false;\n const norm = (t: string) => (t === \"integer\" ? \"number\" : t);\n return norm(a) !== norm(b);\n}\n\n/** All dotted paths under a schema (leaves and branches), for completions. */\nexport function allPaths(schema: unknown): string[] {\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(schema, \"\", entries);\n return entries.map((entry) => entry.path);\n}\n", "/**\n * Shared editors for the action model: an action DEFINITION (prompt or\n * http) and a BINDING (shared ref or inline definition, plus the input\n * mapping and output mode). The standalone action designer edits\n * definitions; the widget designer binds them to elements and to the\n * widget's `load`. Everything is plain DOM over immutable values, and no\n * network I/O happens here \u2014 testing an action is the host's job.\n *\n * Handlers read the editor's live state at event time and a commit\n * re-renders only its own section, so two edits in a row never lose each\n * other and focus survives a commit. Rows without a name (a new header,\n * query parameter or projection) live in editor-local state until they are\n * named; only named rows reach `onChange`.\n */\nimport type { DataSchema } from \"@widgentic/core\";\nimport type {\n ActionBinding,\n ActionDefinition,\n HttpActionDefinition,\n InputMapping,\n OutputBinding,\n OutputMode,\n PromptSegment,\n StoredAction\n} from \"@widgentic/core\";\nimport { HTTP_METHODS, OUTPUT_MODES } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h } from \"./dom.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { allPaths, schemaAt, schemaType, typesConflict } from \"./schema-paths.js\";\n\n/** The path select's escape hatch to free text. */\nconst CUSTOM_PATH = \"__custom__\";\n\ntype HeaderValue = string | { secret: string };\ntype HeaderMap = Record<string, HeaderValue>;\ntype RefBinding = { ref: string } & Pick<ActionBinding, \"input\" | \"output\">;\n\nexport interface ActionEditorContext {\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n}\n\nexport function starterPromptDefinition(): ActionDefinition {\n return { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] };\n}\n\nexport function starterHttpDefinition(): HttpActionDefinition {\n return {\n kind: \"http\",\n method: \"GET\",\n url: \"https://api.example.com/resource\",\n input: { type: \"object\", properties: {} },\n output: { type: \"object\" }\n };\n}\n\nfunction isRefBinding(binding: ActionBinding): binding is RefBinding {\n return \"ref\" in binding && typeof binding.ref === \"string\";\n}\n\nfunction textInput(value: string, className: string, onCommit: (value: string) => void, placeholder = \"\"): HTMLInputElement {\n const el = h(\"input\", { type: \"text\", class: className, placeholder });\n el.value = value;\n el.addEventListener(\"change\", () => onCommit(el.value));\n return el;\n}\n\nfunction select(options: { value: string; label?: string }[], value: string, className: string, onChange: (value: string) => void): HTMLSelectElement {\n const el = h(\"select\", { class: className });\n for (const option of options) el.append(h(\"option\", { value: option.value }, [option.label ?? option.value]));\n el.value = value;\n fitSelect(el);\n el.addEventListener(\"change\", () => onChange(el.value));\n return el;\n}\n\nfunction label(text: string): HTMLElement {\n return h(\"span\", { class: \"wgd-field-label\" }, [text]);\n}\n\nfunction removeButton(onClick: () => void): HTMLElement {\n const button = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n button.addEventListener(\"click\", onClick);\n return button;\n}\n\n/**\n * Path picker: a select over the known paths (plus the current value when\n * it is off-schema) with a \"custom\u2026\" escape to free text \u2014 the template\n * panel's pathControl, for mappings. The placeholder option clears the\n * value. With no known paths it is a text input.\n */\nfunction pathSelect(\n value: string,\n options: string[],\n onCommit: (path: string) => void,\n placeholder: string,\n className = \"wgd-input wgd-rec-value\"\n): HTMLElement {\n if (options.length === 0) return textInput(value, className, onCommit, placeholder);\n const sel = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n const listed = known || value === \"\" ? options : [value, ...options];\n sel.append(h(\"option\", { value: \"\" }, [placeholder]));\n for (const option of listed) {\n sel.append(h(\"option\", { value: option }, [option === value && !known ? `${option} (off-schema)` : option]));\n }\n sel.append(h(\"option\", { value: CUSTOM_PATH }, [\"custom\u2026\"]));\n sel.value = value;\n fitSelect(sel);\n const custom = textInput(value, className, onCommit, placeholder);\n custom.hidden = true;\n sel.addEventListener(\"change\", () => {\n if (sel.value === CUSTOM_PATH) {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(sel.value);\n });\n return h(\"span\", { class: \"wgd-pathwrap\" }, [sel, custom]);\n}\n\n/**\n * Header/query map rows: name, literal-or-secret mode, value. Unnamed rows\n * are editor-local; a rename onto an existing name is flagged, not applied.\n */\nfunction headerMapEditor(\n initial: HeaderMap | undefined,\n secretNames: string[],\n labels: { add: string; name: string },\n onChange: (next: HeaderMap | undefined) => void\n): HTMLElement {\n let current: HeaderMap = clone(initial ?? {});\n const pending: { value: HeaderValue }[] = [];\n const element = h(\"div\", { class: \"wgd-record wgd-headers\" });\n const duplicate = diagnosticLine(undefined);\n\n function commit(next: HeaderMap): void {\n current = next;\n onChange(Object.keys(current).length > 0 ? current : undefined);\n render();\n }\n function flagDuplicate(name: string): void {\n duplicate.hidden = false;\n duplicate.textContent = `'${name}' is already used; pick another ${labels.name} name.`;\n }\n function valueControl(value: HeaderValue, onValue: (next: HeaderValue) => void): HTMLElement[] {\n const isSecret = isPlainObject(value);\n const mode = select(\n [{ value: \"literal\" }, { value: \"secret\" }],\n isSecret ? \"secret\" : \"literal\",\n \"wgd-select wgd-attr-mode\",\n (next) => onValue(next === \"secret\" ? { secret: secretNames[0] ?? \"\" } : \"\")\n );\n if (isSecret) {\n const names = secretNames.includes(value.secret) ? secretNames : [value.secret, ...secretNames];\n const picker = select(\n names.map((n) => ({ value: n, label: n === \"\" ? \"(pick a secret)\" : n })),\n value.secret,\n \"wgd-select wgd-secret\",\n (next) => onValue({ secret: next })\n );\n return [mode, picker];\n }\n return [mode, textInput(value, \"wgd-input wgd-rec-value\", onValue, \"value\")];\n }\n function render(): void {\n element.replaceChildren();\n duplicate.hidden = true;\n for (const [name, value] of Object.entries(current)) {\n const nameInput = textInput(name, \"wgd-input wgd-rec-key\", (next) => {\n if (next === name) return;\n if (next === \"\" || Object.hasOwn(current, next)) { flagDuplicate(next || \"(empty)\"); return; }\n const entries = Object.entries(current).map(([k, v]) => (k === name ? [next, v] : [k, v]));\n commit(Object.fromEntries(entries));\n }, labels.name);\n const controls = valueControl(value, (next) => commit({ ...current, [name]: next }));\n const remove = removeButton(() => {\n const { [name]: _gone, ...rest } = current;\n commit(rest);\n });\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [nameInput, ...controls, remove]));\n }\n pending.forEach((row, index) => {\n const nameInput = textInput(\"\", \"wgd-input wgd-rec-key\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(current, next)) { flagDuplicate(next); return; }\n pending.splice(index, 1);\n commit({ ...current, [next]: row.value });\n }, labels.name);\n const controls = valueControl(row.value, (next) => { row.value = next; render(); });\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n element.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [nameInput, ...controls, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [labels.add]);\n add.addEventListener(\"click\", () => { pending.push({ value: \"\" }); render(); });\n element.append(h(\"div\", { class: \"wgd-row\" }, [add]), duplicate);\n }\n render();\n return element;\n}\n\n/** Prompt text: ordered literal/bind segments. */\nfunction segmentsEditor(initial: PromptSegment[], onChange: (next: PromptSegment[]) => void): HTMLElement {\n let current = clone(initial);\n const element = h(\"div\", { class: \"wgd-record wgd-segments\" });\n function commit(next: PromptSegment[]): void {\n current = next;\n onChange(current);\n render();\n }\n function render(): void {\n element.replaceChildren();\n current.forEach((segment, index) => {\n const isBind = typeof segment !== \"string\";\n const mode = select([{ value: \"text\" }, { value: \"bind\" }], isBind ? \"bind\" : \"text\", \"wgd-select wgd-attr-mode\", (next) => {\n const copy = [...current];\n copy[index] = next === \"bind\" ? { bind: \".\" } : \"\";\n commit(copy);\n });\n const value = textInput(\n isBind ? segment.bind : segment,\n \"wgd-input wgd-rec-value\",\n (next) => {\n const copy = [...current];\n copy[index] = isBind ? { bind: next } : next;\n commit(copy);\n },\n isBind ? \"data path\" : \"text\"\n );\n const remove = removeButton(() => commit(current.filter((_, i) => i !== index)));\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [mode, value, remove]));\n });\n const addText = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ text\"]);\n addText.addEventListener(\"click\", () => commit([...current, \"\"]));\n const addBind = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ bind\"]);\n addBind.addEventListener(\"click\", () => commit([...current, { bind: \".\" }]));\n element.append(h(\"div\", { class: \"wgd-row\" }, [addText, addBind]));\n }\n render();\n return element;\n}\n\nexport interface DefinitionEditor {\n element: HTMLElement;\n getValue(): ActionDefinition;\n setValue(definition: ActionDefinition): void;\n}\n\n/** Editor for one action definition, either kind. */\nexport function createDefinitionEditor(\n initial: ActionDefinition | undefined,\n ctx: ActionEditorContext,\n onChange: (definition: ActionDefinition) => void\n): DefinitionEditor {\n let current: ActionDefinition = clone(initial ?? starterPromptDefinition());\n const headEl = h(\"div\", { class: \"wgd-action-head\" });\n const schemasEl = h(\"div\", { class: \"wgd-action-schemas\" });\n const mapsEl = h(\"div\", { class: \"wgd-action-maps\" });\n const element = h(\"div\", { class: \"wgd-action-definition\" }, [headEl, schemasEl, mapsEl]);\n\n /** The live http definition; handlers call this at event time, never a render-time copy. */\n function http(): HttpActionDefinition {\n return current as HttpActionDefinition;\n }\n\n function commit(next: ActionDefinition, rerender: \"all\" | \"schemas\" | \"none\"): void {\n current = next;\n onChange(clone(current));\n if (rerender === \"all\") render();\n else if (rerender === \"schemas\") renderSchemas();\n }\n\n function schemaSection(title: string, which: \"input\" | \"output\"): HTMLElement {\n const builder = createSchemaBuilder(http()[which] as DataSchema, (schema) => {\n commit({ ...http(), [which]: schema ?? { type: \"object\" } }, \"none\");\n });\n const parts: (Node | string)[] = [label(title), builder.element];\n const shared = ctx.schemas ?? [];\n if (shared.length > 0) {\n // Actions store their schemas INLINE (a contract must not drift when a\n // shared schema is edited), so this is a copy \u2014 and says so.\n const copyFrom = select(\n [{ value: \"\", label: \"copy a shared schema into this action\u2026\" }, ...shared.map((s) => ({ value: s.name }))],\n \"\",\n \"wgd-select\",\n (name) => {\n const entry = shared.find((s) => s.name === name);\n if (entry) commit({ ...http(), [which]: clone(entry.schema) }, \"schemas\");\n }\n );\n parts.push(h(\"div\", { class: \"wgd-row\" }, [copyFrom, label(\"(a copy \u2014 later edits to the shared schema do not follow)\")]));\n }\n return h(\"div\", { class: \"wgd-action-schema\" }, parts);\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const kind = select(\n [{ value: \"prompt\", label: \"prompt \u2014 propose a message\" }, { value: \"http\", label: \"http \u2014 call an API\" }],\n current.kind,\n \"wgd-select wgd-action-kind\",\n (next) => commit(next === \"http\" ? starterHttpDefinition() : starterPromptDefinition(), \"all\")\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [label(\"Kind\"), kind]));\n if (current.kind === \"prompt\") {\n headEl.append(\n label(\"Message (literals and bound values; the user reviews and sends it)\"),\n segmentsEditor(current.text, (text) => commit({ kind: \"prompt\", text }, \"none\"))\n );\n return;\n }\n const method = select(HTTP_METHODS.map((m) => ({ value: m })), current.method, \"wgd-select\", (next) =>\n commit({ ...http(), method: next as HttpActionDefinition[\"method\"] }, \"none\")\n );\n const url = textInput(current.url, \"wgd-input wgd-action-url\", (next) => commit({ ...http(), url: next }, \"none\"), \"https://\u2026\");\n headEl.append(\n h(\"div\", { class: \"wgd-row\" }, [label(\"Method\"), method]),\n h(\"label\", { class: \"wgd-field\" }, [label(\"URL (https, fixed)\"), url])\n );\n }\n\n function renderSchemas(): void {\n schemasEl.replaceChildren();\n if (current.kind !== \"http\") return;\n schemasEl.append(\n schemaSection(\"Input schema (arguments; GET \u2192 query, POST \u2192 JSON body)\", \"input\"),\n schemaSection(\"Output schema (the response must satisfy it)\", \"output\")\n );\n }\n\n function renderMaps(): void {\n mapsEl.replaceChildren();\n if (current.kind !== \"http\") return;\n const secretNames = ctx.secretNames ?? [];\n mapsEl.append(\n label(\"Headers\"),\n headerMapEditor(current.headers, secretNames, { add: \"+ header\", name: \"header\" }, (headers) => {\n const { headers: _h, ...rest } = http();\n commit(headers === undefined ? rest : { ...rest, headers }, \"none\");\n }),\n label(\"Fixed query parameters\"),\n headerMapEditor(current.query, secretNames, { add: \"+ parameter\", name: \"parameter\" }, (query) => {\n const { query: _q, ...rest } = http();\n commit(query === undefined ? rest : { ...rest, query }, \"none\");\n })\n );\n }\n\n function render(): void {\n renderHead();\n renderSchemas();\n renderMaps();\n }\n render();\n return {\n element,\n getValue: () => clone(current),\n setValue(definition) {\n current = clone(definition);\n render();\n }\n };\n}\n\nexport interface BindingEditorContext extends ActionEditorContext {\n /** Shared actions offered by name. */\n actions?: StoredAction[];\n /** Data paths in scope at the bound element, offered as completions. */\n scopePaths?: string[];\n /** The widget's effective data schema (inline or resolved ref) \u2014 drives output-map targets and type checks. */\n getDataSchema?: () => DataSchema | undefined;\n /** `load` bindings: http GET only, no prompt. */\n loadOnly?: boolean;\n}\n\nexport interface BindingEditor {\n element: HTMLElement;\n setValue(binding: ActionBinding | undefined): void;\n}\n\n/** Editor for a binding: none / shared / inline, input mapping, output mode. */\nexport function createBindingEditor(\n initial: ActionBinding | undefined,\n ctx: BindingEditorContext,\n onChange: (binding: ActionBinding | undefined) => void\n): BindingEditor {\n let current: ActionBinding | undefined = initial === undefined ? undefined : clone(initial);\n const headEl = h(\"div\", { class: \"wgd-binding-head\" });\n const inputEl = h(\"div\", { class: \"wgd-binding-input\" });\n const outputEl = h(\"div\", { class: \"wgd-binding-output\" });\n const element = h(\"div\", { class: \"wgd-binding\" }, [headEl, inputEl, outputEl]);\n\n function definitionOf(binding: ActionBinding | undefined): ActionDefinition | undefined {\n if (binding === undefined) return undefined;\n if (isRefBinding(binding)) return (ctx.actions ?? []).find((a) => a.name === binding.ref)?.definition;\n return binding.definition;\n }\n const inputOf = (): InputMapping => clone(current?.input ?? {});\n const outputOf = (): OutputBinding => clone(current?.output ?? {});\n\n function commit(next: ActionBinding | undefined, rerender: \"all\" | \"io\" | \"input\" | \"output\" | \"none\"): void {\n current = next;\n onChange(next === undefined ? undefined : clone(next));\n if (rerender === \"all\") render();\n else if (rerender === \"io\") { renderInput(); renderOutput(); }\n else if (rerender === \"input\") renderInput();\n else if (rerender === \"output\") renderOutput();\n }\n\n function withMapping(binding: ActionBinding, input: InputMapping | undefined, output: OutputBinding | undefined): ActionBinding {\n const head: { ref: string } | { definition: ActionDefinition } = isRefBinding(binding)\n ? { ref: binding.ref }\n : { definition: binding.definition };\n return {\n ...head,\n ...(input !== undefined && Object.keys(input).length > 0 ? { input } : {}),\n ...(output !== undefined && Object.keys(output).length > 0 ? { output } : {})\n };\n }\n\n /** Helper completions are complete paths: the scope markers alone, plus every root path. */\n function helperPaths(): string[] {\n const root = allPaths(ctx.getDataSchema?.()).map((p) => `$root.${p}`);\n return [\"$index\", \"$parent\", \"$root\", ...root];\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const shared = (ctx.actions ?? []).filter((a) => !ctx.loadOnly || (a.definition.kind === \"http\" && a.definition.method === \"GET\"));\n const mode = current === undefined ? \"none\" : isRefBinding(current) ? \"shared\" : \"inline\";\n const modeSelect = select(\n [{ value: \"none\", label: ctx.loadOnly ? \"no load action\" : \"no action\" }, { value: \"shared\", label: \"shared action\" }, { value: \"inline\", label: \"inline definition\" }],\n mode,\n \"wgd-select wgd-binding-mode\",\n (next) => {\n if (next === \"none\") commit(undefined, \"all\");\n else if (next === \"shared\") commit({ ref: shared[0]?.name ?? \"\" }, \"all\");\n else commit({ definition: starterHttpDefinition() }, \"all\");\n }\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [modeSelect]));\n if (current === undefined) return;\n if (isRefBinding(current)) {\n const ref = current.ref;\n const names = shared.map((a) => a.name);\n const options = (names.includes(ref) ? names : [ref, ...names]).map((n) => ({ value: n, label: n === \"\" ? \"(pick an action)\" : names.includes(n) ? n : `${n} (unknown)` }));\n const refSelect = select(options, ref, \"wgd-select wgd-binding-ref\", (next) =>\n commit(withMapping({ ref: next }, inputOf(), outputOf()), \"io\")\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [label(\"Action\"), refSelect]));\n return;\n }\n const editor = createDefinitionEditor(current.definition, ctx, (definition) => {\n // The definition's schemas drive the mapping rows; the head keeps focus.\n commit(withMapping({ definition }, inputOf(), outputOf()), \"io\");\n });\n headEl.append(editor.element);\n }\n\n function renderInput(): void {\n inputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n // Input mapping: one row per declared field, each a data path or a constant.\n const properties = isPlainObject(definition.input.properties) ? Object.keys(definition.input.properties) : [];\n // No element scope supplied (the widget-level `load`): the root data paths ARE the scope.\n const scopePaths = ctx.scopePaths ?? allPaths(ctx.getDataSchema?.());\n const pathOptions = [...new Set([...scopePaths, ...helperPaths()])];\n const mapping = inputOf();\n const rows = properties.map((field) => {\n const value = mapping[field];\n const isConst = isPlainObject(value) && \"const\" in value;\n const kindSelect = select([{ value: \"path\" }, { value: \"const\" }], isConst ? \"const\" : \"path\", \"wgd-select wgd-attr-mode\", (next) => {\n commit(withMapping(binding, { ...inputOf(), [field]: next === \"const\" ? { const: \"\" } : field }, outputOf()), \"input\");\n });\n const onValue = (next: string): void => {\n const nextMapping = inputOf();\n if (isConst) {\n let literal: unknown;\n try { literal = JSON.parse(next); } catch { literal = next; }\n nextMapping[field] = { const: literal };\n } else if (next === \"\") {\n delete nextMapping[field];\n } else {\n nextMapping[field] = next;\n }\n commit(withMapping(binding, nextMapping, outputOf()), \"none\");\n };\n const valueInput = isConst\n ? textInput(JSON.stringify(value.const), \"wgd-input wgd-rec-value\", onValue, \"JSON literal\")\n : pathSelect(typeof value === \"string\" ? value : \"\", pathOptions, onValue, \"data path\");\n return h(\"div\", { class: \"wgd-rec-row\" }, [h(\"span\", { class: \"wgd-rec-key wgd-binding-field\" }, [field]), kindSelect, valueInput]);\n });\n inputEl.append(\n label(\"Input mapping (field \u2190 data path or constant)\"),\n properties.length > 0 ? h(\"div\", { class: \"wgd-record\" }, rows) : h(\"div\", { class: \"wgd-diagnostic\" }, [\"The input schema declares no properties.\"])\n );\n }\n\n function renderOutput(): void {\n outputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n const output = outputOf();\n const mode = output.mode ?? \"merge\";\n const modeSel = select(OUTPUT_MODES.map((m) => ({ value: m })), mode, \"wgd-select\", (next) => {\n const nextOutput: OutputBinding = { ...outputOf(), mode: next as OutputMode };\n if (next !== \"patch\") delete nextOutput.path;\n commit(withMapping(binding, inputOf(), nextOutput), \"output\");\n });\n const outputRow: (Node | string)[] = [label(\"Output\"), modeSel];\n if (mode === \"patch\") {\n outputRow.push(textInput(output.path ?? \"\", \"wgd-input\", (next) => {\n commit(withMapping(binding, inputOf(), { ...outputOf(), path: next }), \"output\");\n }, \"data path to write at\"));\n }\n outputEl.append(h(\"div\", { class: \"wgd-row\" }, outputRow));\n outputEl.append(outputMapEditor(definition, output, (map) => {\n const nextOutput = outputOf();\n if (map === undefined) delete nextOutput.map; else nextOutput.map = map;\n commit(withMapping(binding, inputOf(), nextOutput), \"none\");\n }));\n }\n\n /**\n * Output projection rows: target (a widget data path, relative to the\n * patch path when that mode is on) \u2190 source (a response path). Both\n * inputs complete from the respective schemas, and a type mismatch is\n * flagged here \u2014 at execution it would only surface as INVALID_TYPE.\n * Unnamed rows are editor-local until they get a target.\n */\n function outputMapEditor(\n definition: HttpActionDefinition,\n output: OutputBinding,\n onMap: (map: Record<string, string> | undefined) => void\n ): HTMLElement {\n const container = h(\"div\", { class: \"wgd-record wgd-output-map\" });\n let map: Record<string, string> = clone(output.map ?? {});\n const pending: { source: string }[] = [];\n const widgetSchema = ctx.getDataSchema?.();\n const base = (output.mode ?? \"merge\") === \"patch\" && output.path ? output.path : \"\";\n const targetRoot = base === \"\" ? widgetSchema : schemaAt(widgetSchema, base);\n const targetOptions = allPaths(targetRoot);\n const sourceOptions = [\".\", ...allPaths(definition.output)];\n const mismatch = diagnosticLine(undefined);\n mismatch.classList.add(\"wgd-type-mismatch\");\n\n function commitMap(next: Record<string, string>): void {\n map = next;\n onMap(Object.keys(map).length > 0 ? map : undefined);\n render();\n }\n function flag(text: string): void {\n mismatch.hidden = false;\n mismatch.textContent = text;\n }\n function targetControl(target: string, onTarget: (next: string) => void): HTMLElement {\n const control = pathSelect(target, targetOptions, onTarget, \"target data path\", \"wgd-input wgd-rec-key\");\n control.classList.add(\"wgd-map-target\");\n return control;\n }\n function render(): void {\n container.replaceChildren();\n const problems: string[] = [];\n for (const [target, source] of Object.entries(map)) {\n const targetType = schemaType(schemaAt(targetRoot, target));\n const sourceType = schemaType(schemaAt(definition.output, source));\n if (typesConflict(sourceType, targetType)) {\n problems.push(`'${source}' is ${sourceType} in the response but '${base ? `${base}.` : \"\"}${target}' is ${targetType} in the widget schema`);\n }\n const targetInput = targetControl(target, (next) => {\n if (next === target) return;\n if (next === \"\" || Object.hasOwn(map, next)) { flag(`'${next || \"(empty)\"}' is already a projection target.`); return; }\n const entries = Object.entries(map).map(([k, v]) => (k === target ? [next, v] : [k, v]));\n commitMap(Object.fromEntries(entries));\n });\n const sourceInput = pathSelect(source, sourceOptions, (next) => commitMap({ ...map, [target]: next }), \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => {\n const { [target]: _gone, ...rest } = map;\n commitMap(rest);\n });\n container.append(h(\"div\", { class: \"wgd-rec-row\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n }\n pending.forEach((row, index) => {\n const targetInput = targetControl(\"\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(map, next)) { flag(`'${next}' is already a projection target.`); return; }\n pending.splice(index, 1);\n commitMap({ ...map, [next]: row.source });\n });\n const sourceInput = pathSelect(row.source, sourceOptions, (next) => { row.source = next; render(); }, \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n container.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ projection\"]);\n add.addEventListener(\"click\", () => { pending.push({ source: \"\" }); render(); });\n mismatch.hidden = problems.length === 0;\n mismatch.textContent = problems.length === 0 ? \"\" : `Type mismatch: ${problems.join(\"; \")}.`;\n container.append(h(\"div\", { class: \"wgd-row\" }, [add]), mismatch);\n }\n render();\n return container;\n }\n\n function render(): void {\n renderHead();\n renderInput();\n renderOutput();\n }\n render();\n return {\n element,\n setValue(binding) {\n current = binding === undefined ? undefined : clone(binding);\n render();\n }\n };\n}\n", "/**\n * The designer's derive step: run widgentic's pure validators over the\n * draft and shape their structured errors into per-panel diagnostics.\n * Everything here goes through public package entries \u2014 the designer owns\n * no validation logic of its own.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport {\n createCatalog,\n validateDataAgainstSchema,\n widgetStylesToCss\n} from \"@widgentic/core\";\nimport type { WidgetStyles } from \"@widgentic/core\";\nimport type { WidgetContractError } from \"@widgentic/core\";\nimport { collectActionRefs, parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeError } from \"@widgentic/core\";\nimport type { WidgetDraft } from \"./store.js\";\n\nexport interface TemplateIssue {\n code: string;\n message: string;\n /** Node path when the validator reports one. */\n path?: string;\n}\n\nexport interface StyleIssue {\n selector: string;\n property?: string;\n message: string;\n}\n\nexport interface DesignerDiagnostics {\n /** Problem with the kind id itself (empty, or colliding with a base kind). */\n kind?: string;\n template?: TemplateIssue;\n /** `descriptor.dataExample` vs `descriptor.dataSchema`. */\n example?: WidgetContractError;\n /** `sampleData` vs `descriptor.dataSchema`. */\n sample?: WidgetContractError;\n /** Entries the renderer's safety filters would skip. */\n styles: StyleIssue[];\n theme?: ThemeError;\n /** Shared-schema reference problems (unknown ref, or ref + inline). */\n schemaRef?: string;\n /** The widget-level `load` binding failed validation. */\n load?: string;\n /** Shared actions referenced by the template or `load` that are not among the supplied ones. */\n actionRefs?: string;\n /** True when the draft can be registered and previewed. */\n previewable: boolean;\n}\n\n/** Host-supplied shared schemas the draft may reference by name. */\nexport interface DeriveOptions {\n schemas?: { name: string; schema: Record<string, unknown> }[];\n /** Host-supplied shared actions the draft may bind by name. */\n actions?: { name: string }[];\n}\n\n/**\n * The schema validation actually runs against: the inline one, or the\n * referenced shared one resolved from the supplied list \u2014 the same join\n * the server's composition performs.\n */\nexport function effectiveDataSchema(\n draft: WidgetDraft,\n schemas: { name: string; schema: Record<string, unknown> }[] = []\n): Record<string, unknown> | undefined {\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n return schemas.find((entry) => entry.name === ref)?.schema;\n }\n const inline = draft.descriptor?.dataSchema;\n return isPlainObject(inline) ? inline : undefined;\n}\n\nconst BASE_KINDS = new Set(createCatalog().kinds());\n\n/**\n * Detect style entries the renderer would skip, using only the public\n * generator: a probe that produces no CSS was filtered by the safety\n * guards. Selector and per-declaration issues are reported separately.\n */\nfunction auditStyles(styles: WidgetStyles | undefined): StyleIssue[] {\n if (!isPlainObject(styles)) return [];\n const issues: StyleIssue[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (widgetStylesToCss({ [selector]: { color: \"red\" } }) === \"\") {\n issues.push({\n selector,\n message:\n \"Selector would be skipped \u2014 every comma-separated part must target a .wg- class and avoid ;{}<>@\\\\.\"\n });\n continue;\n }\n if (!isPlainObject(declarations)) {\n issues.push({ selector, message: \"Declarations must be a property \u2192 value map.\" });\n continue;\n }\n for (const [property, value] of Object.entries(declarations)) {\n if (\n typeof value !== \"string\" ||\n widgetStylesToCss({ \".wg-probe\": { [property]: value } }) === \"\"\n ) {\n issues.push({\n selector,\n property,\n message:\n \"Declaration would be skipped \u2014 unsafe property name or value (no url(), expression(), or ;{}<>@\\\\).\"\n });\n }\n }\n }\n return issues;\n}\n\n/** Run every validator; total \u2014 never throws on any draft shape. */\nexport function deriveDiagnostics(\n draft: WidgetDraft,\n options: DeriveOptions = {}\n): DesignerDiagnostics {\n const diagnostics: DesignerDiagnostics = { styles: [], previewable: false };\n\n if (typeof draft.kind !== \"string\" || draft.kind.trim().length === 0) {\n diagnostics.kind = \"Kind must be a non-empty id.\";\n } else if (BASE_KINDS.has(draft.kind)) {\n diagnostics.kind = `'${draft.kind}' is a built-in kind \u2014 pick a distinct id.`;\n }\n\n const template = validateTemplate(draft.template);\n if (!template.ok) {\n const issue: TemplateIssue = {\n code: template.error.code,\n message: template.error.message\n };\n const path = (template.error as { path?: unknown }).path;\n if (typeof path === \"string\") issue.path = path;\n diagnostics.template = issue;\n }\n\n // Shared-schema refs resolve here exactly as the server's composition\n // resolves them, so diagnostics match what the store will enforce.\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n if (draft.descriptor?.dataSchema !== undefined) {\n diagnostics.schemaRef =\n \"A descriptor carries 'dataSchema' OR 'dataSchemaRef', never both.\";\n } else if (\n (options.schemas ?? []).every((entry) => entry.name !== ref)\n ) {\n diagnostics.schemaRef = `References unknown schema '${ref}' \u2014 it is not among the supplied shared schemas.`;\n }\n }\n const schema = effectiveDataSchema(draft, options.schemas ?? []);\n if (isPlainObject(schema)) {\n if (draft.descriptor.dataExample !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.descriptor.dataExample);\n if (error) diagnostics.example = error;\n }\n if (draft.sampleData !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.sampleData);\n if (error) diagnostics.sample = error;\n }\n }\n\n diagnostics.styles = auditStyles(draft.descriptor?.styles);\n\n if (draft.load !== undefined) {\n const problem = validateLoadBinding(draft.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) diagnostics.load = `${problem.message} (at ${problem.path})`;\n }\n if (options.actions !== undefined) {\n const known = new Set(options.actions.map((action) => action.name));\n const unknown = collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref));\n if (unknown.length > 0) {\n diagnostics.actionRefs = `References unknown shared action${unknown.length === 1 ? \"\" : \"s\"} ${unknown\n .map((ref) => `'${ref}'`)\n .join(\", \")} \u2014 bound elements will render disabled.`;\n }\n }\n\n if (draft.theme !== undefined) {\n const theme = validateTheme(draft.theme);\n if (!theme.ok) diagnostics.theme = theme.error;\n }\n\n diagnostics.previewable =\n diagnostics.kind === undefined && diagnostics.template === undefined;\n return diagnostics;\n}\n", "/**\n * Template editing: a structured node tree and a JSON source pane \u2014 two\n * projections of one canonical model (the draft's template). The JSON\n * pane is parse-gated (invalid JSON never reaches the store; last valid\n * wins); structural edits from either side may still fail\n * `validateTemplate`, which surfaces as diagnostics pinned to the node\n * path without ever losing the draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { collectActionRefs } from \"@widgentic/core\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { ActionBinding, StoredAction } from \"@widgentic/core\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { collectPaths, schemaType } from \"./schema-paths.js\";\nimport { effectiveDataSchema } from \"./validate.js\";\nimport { diagnosticLine, fitSelect, h, menuButton } from \"./dom.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\ntype Path = (string | number)[];\n\n/** What a data path is being used for \u2014 decides which paths are offered. */\ntype PathUse = \"bind\" | \"each\" | \"when\";\n\n/** Paths worth offering for a given use. */\nfunction pathOptions(scope: unknown, use: PathUse): string[] {\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(scope, \"\", entries);\n const scalars = new Set([\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\",\n undefined\n ]);\n const filtered = entries.filter(({ schema }) => {\n const type = schemaType(schema);\n if (use === \"each\") return type === \"array\";\n if (use === \"bind\") return scalars.has(type);\n return true; // `when` tests truthiness of anything\n });\n const paths = filtered.map((entry) => entry.path);\n // \".\" is the scope itself \u2014 the item inside an each over scalars.\n if (use !== \"each\" && scalars.has(schemaType(scope))) paths.unshift(\".\");\n return paths;\n}\n\n/** Schema in effect inside `each: <path>` \u2014 the array's item schema. */\nfunction itemScope(scope: unknown, eachPath: string): unknown {\n if (!isPlainObject(scope) || eachPath === \".\") return undefined;\n let current: unknown = scope;\n for (const segment of eachPath.split(\".\")) {\n if (!isPlainObject(current) || !isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n return isPlainObject(current) && schemaType(current) === \"array\"\n ? current.items\n : undefined;\n}\n\nconst REMOVE = Symbol(\"remove\");\n\nfunction pathString(path: Path): string {\n let out = \"\";\n for (const step of path) {\n const segment = typeof step === \"number\" ? `children.${step}` : step;\n out = out === \"\" ? segment : `${out}.${segment}`;\n }\n return out;\n}\n\n/** Immutable set/remove at a node path (numbers index `children`). */\nfunction setNode(node: unknown, path: Path, next: unknown): unknown {\n if (path.length === 0) return next === REMOVE ? undefined : next;\n const [step, ...rest] = path as [string | number, ...Path];\n if (typeof step === \"number\") {\n if (!isPlainObject(node) || !Array.isArray(node.children)) return node;\n const children = [...(node.children as unknown[])];\n if (rest.length === 0 && next === REMOVE) {\n children.splice(step, 1);\n } else {\n children[step] = setNode(children[step], rest, next);\n }\n return { ...node, children };\n }\n if (!isPlainObject(node)) return node;\n if (rest.length === 0 && next === REMOVE) {\n const { [step]: _removed, ...remaining } = node;\n return remaining;\n }\n return { ...node, [step]: setNode(node[step], rest, next) };\n}\n\nfunction swapChildren(root: unknown, parent: Path, a: number, b: number): unknown {\n const holder = parent.length === 0 ? root : getNode(root, parent);\n if (!isPlainObject(holder) || !Array.isArray(holder.children)) return root;\n const children = [...(holder.children as unknown[])];\n if (a < 0 || b < 0 || a >= children.length || b >= children.length) return root;\n const [x, y] = [children[a], children[b]];\n children[a] = y;\n children[b] = x;\n const swapped = { ...holder, children };\n return parent.length === 0 ? swapped : setNode(root, parent, swapped);\n}\n\nfunction getNode(node: unknown, path: Path): unknown {\n let current = node;\n for (const step of path) {\n if (!isPlainObject(current)) return undefined;\n current =\n typeof step === \"number\"\n ? Array.isArray(current.children)\n ? (current.children as unknown[])[step]\n : undefined\n : current[step];\n }\n return current;\n}\n\nconst NODE_PRESETS: Record<string, () => unknown> = {\n text: () => \"text\",\n bind: () => ({ bind: \".\" }),\n element: () => ({ tag: \"div\", children: [] }),\n each: () => ({ each: \".\", template: \"item\" }),\n when: () => ({ when: \".\", template: \"shown\" })\n};\n\n/** What element bindings can reach: shared actions, secrets, schemas. */\nexport interface TemplateActionContext {\n actions: StoredAction[];\n secretNames: string[];\n schemas: SchemaEntry[];\n}\n\nexport interface TemplatePanelOptions {\n actionContext?: TemplateActionContext;\n}\n\n/** A bound attribute value, narrowed once per attribute row (a type literal: comparable with the raw record). */\ntype AttrBind = {\n bind: string;\n prefix?: string;\n map?: Record<string, string>;\n default?: string;\n};\n\nexport function mountTemplatePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n options: TemplatePanelOptions = {}\n): {\n element: HTMLElement;\n refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void;\n dispose(): void;\n} {\n const actionContext: TemplateActionContext = options.actionContext ?? { actions: [], secretNames: [], schemas: [] };\n // Shared refs the draft binds that no supplied action answers to.\n let unknownRefs = new Set<string>();\n const treeHost = h(\"div\", { class: \"wgd-tree\" });\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-template-json\",\n rows: \"14\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n attachJsonHighlight(jsonArea);\n jsonWrap.hidden = true;\n\n const treeTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Tree\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"JSON\"]);\n treeTab.addEventListener(\"click\", () => {\n treeHost.hidden = false;\n jsonWrap.hidden = true;\n });\n jsonTab.addEventListener(\"click\", () => {\n treeHost.hidden = true;\n jsonWrap.hidden = false;\n });\n\n const templateDiag = diagnosticLine(undefined);\n const element = h(\"details\", { class: \"wgd-section\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-section-title\" }, [\"Template\"]),\n h(\"div\", { class: \"wgd-section-body\" }, [\n h(\"div\", { class: \"wgd-row\" }, [treeTab, jsonTab]),\n templateDiag,\n treeHost,\n jsonWrap\n ])\n ]);\n\n function commit(next: unknown): void {\n store.update((draft) => ({ ...draft, template: next as WidgetTemplate }));\n }\n\n function commitAt(path: Path, next: unknown): void {\n commit(setNode(store.get().template, path, next));\n }\n\n // --- JSON pane: parse-gated projection --------------------------------\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n commit(parsed);\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (template keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n // --- Tree editor -------------------------------------------------------\n function changeInput(\n value: string,\n onCommit: (value: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLInputElement {\n const input = h(\"input\", { type: \"text\", class: className });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n /**\n * Collapse state, keyed by node path so it survives the full re-render\n * every draft edit triggers. Paths shift when siblings move or vanish \u2014\n * an accepted approximation, exactly like text-editor fold markers.\n */\n const collapsedPaths = new Set<string>();\n\n /**\n * One node = one header row: chevron, badge, the node's own value\n * control(s), then add/move/remove icons (revealed on hover). Sub-\n * structure (attrs, children, slots) nests below and folds away when\n * the node is collapsed; a muted summary keeps the hidden shape legible.\n */\n function nodeShell(\n /** Omitted for elements \u2014 their tag select already names the node. */\n badge: string | undefined,\n path: Path,\n inline: (Node | string)[],\n body: (Node | string)[],\n errorText: string | undefined,\n removable: boolean,\n moves?: { parent: Path; index: number; count: number },\n extras?: { icons?: (Node | string)[]; summary?: string }\n ): HTMLElement {\n const key = pathString(path);\n const collapsible = body.length > 0;\n const isCollapsed = collapsible && collapsedPaths.has(key);\n let chevron: HTMLElement;\n if (collapsible) {\n chevron = h(\n \"button\",\n {\n class: \"wgd-chevron\",\n type: \"button\",\n title: isCollapsed ? \"Expand\" : \"Collapse\"\n },\n [isCollapsed ? \"\u25B8\" : \"\u25BE\"]\n );\n chevron.addEventListener(\"click\", () => {\n if (isCollapsed) collapsedPaths.delete(key);\n else collapsedPaths.add(key);\n renderTree();\n });\n } else {\n // Every row reserves the chevron column so values align.\n chevron = h(\"span\", { class: \"wgd-chevron wgd-chevron-none\" });\n }\n const header: (Node | string)[] =\n badge === undefined\n ? [chevron, ...inline]\n : [chevron, h(\"span\", { class: \"wgd-node-badge\" }, [badge]), ...inline];\n if (isCollapsed && extras?.summary !== undefined) {\n header.push(h(\"span\", { class: \"wgd-node-summary\" }, [extras.summary]));\n }\n const icons: (Node | string)[] = [...(extras?.icons ?? [])];\n if (moves && moves.count > 1) {\n if (moves.index > 0) {\n const up = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move up\" }, [\"\u2191\"]);\n up.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index - 1))\n );\n icons.push(up);\n }\n if (moves.index < moves.count - 1) {\n const down = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move down\" }, [\"\u2193\"]);\n down.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index + 1))\n );\n icons.push(down);\n }\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () =>\n path.length === 0 ? commit(\"\") : commitAt(path, REMOVE)\n );\n icons.push(remove);\n }\n if (icons.length > 0) {\n header.push(h(\"span\", { class: \"wgd-node-icons\" }, icons));\n }\n const children: (Node | string)[] = [h(\"div\", { class: \"wgd-node-row\" }, header)];\n // Diagnostics stay visible even on a collapsed node \u2014 folding must\n // never hide an error.\n if (errorText !== undefined) children.push(diagnosticLine(errorText));\n if (!isCollapsed) children.push(...body);\n return h(\"div\", { class: \"wgd-node\", \"data-path\": key }, children);\n }\n\n /** Tags the built-in styles and typical widget markup actually use. */\n const TAG_OPTIONS = [\n \"div\", \"span\", \"p\", \"section\", \"article\", \"header\", \"footer\",\n \"h1\", \"h2\", \"h3\", \"h4\", \"strong\", \"em\", \"small\", \"code\", \"pre\",\n \"ul\", \"ol\", \"li\", \"dl\", \"dt\", \"dd\",\n \"table\", \"thead\", \"tbody\", \"tr\", \"th\", \"td\",\n \"img\", \"a\", \"figure\", \"figcaption\", \"hr\", \"br\", \"label\"\n ];\n\n /**\n * Data-path control. With a schema in scope it is a select of the paths\n * that scope actually offers (plus the current value if it is off-schema,\n * and a custom escape); without one it stays a free-text input.\n */\n function pathControl(\n value: string,\n scope: unknown,\n use: PathUse,\n onCommit: (path: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLElement {\n const options = isPlainObject(scope) ? pathOptions(scope, use) : [];\n if (options.length === 0) {\n return changeInput(value, onCommit, className);\n }\n const select = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n for (const option of known ? options : [value, ...options]) {\n select.append(\n h(\"option\", { value: option }, [\n option === value && !known ? `${option} (off-schema)` : option\n ])\n );\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = value;\n fitSelect(select);\n const custom = changeInput(value, onCommit, className);\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n // The wrap carries the row-shape marker (e.g. wgd-attr-value) so rows\n // read the same whether the value is a select or free text.\n const marker = className.includes(\"wgd-attr-value\") ? \" wgd-attr-value\" : \"\";\n return h(\"span\", { class: `wgd-pathwrap${marker}` }, [select, custom]);\n }\n\n function tagControl(tag: string, onCommit: (tag: string) => void): HTMLElement {\n const select = h(\"select\", { class: \"wgd-select wgd-tag\" });\n const options = TAG_OPTIONS.includes(tag) ? TAG_OPTIONS : [tag, ...TAG_OPTIONS];\n for (const option of options) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = tag;\n fitSelect(select);\n const custom = changeInput(tag, onCommit, \"wgd-input wgd-tag-custom\");\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n return h(\"span\", { class: \"wgd-tagwrap\" }, [select, custom]);\n }\n\n function slotEditor(\n label: string,\n parentPath: Path,\n slot: \"template\" | \"empty\" | \"else\",\n node: unknown,\n required: boolean,\n errorPath: string | undefined,\n scope: unknown\n ): HTMLElement {\n const slotPath = [...parentPath, slot];\n if (node === undefined) {\n const menu = menuButton(\n `+ ${label}`,\n `Set '${label}' to a node`,\n Object.keys(NODE_PRESETS),\n (name) => {\n const preset = NODE_PRESETS[name];\n if (preset) commitAt(slotPath, preset());\n }\n );\n return required\n ? h(\"div\", { class: \"wgd-slot\" }, [\n diagnosticLine(`Missing required '${label}'.`),\n menu\n ])\n : h(\"div\", { class: \"wgd-slot wgd-slot-unset\" }, [menu]);\n }\n return h(\"div\", { class: \"wgd-slot\" }, [\n h(\"span\", { class: \"wgd-slot-label\" }, [label]),\n renderNode(node, slotPath, errorPath, !required, undefined, scope)\n ]);\n }\n\n function renderNode(\n node: unknown,\n path: Path,\n errorPath: string | undefined,\n removable = true,\n moves?: { parent: Path; index: number; count: number },\n scope?: unknown\n ): HTMLElement {\n const here = pathString(path);\n const errorHere =\n errorPath !== undefined &&\n (errorPath === here ||\n ((errorPath.startsWith(here === \"\" ? \"attrs.\" : `${here}.attrs.`) ||\n errorPath.startsWith(here === \"\" ? \"action\" : `${here}.action`)) &&\n isPlainObject(node) &&\n typeof node.tag === \"string\"))\n ? currentError\n : undefined;\n\n if (typeof node === \"string\") {\n return nodeShell(\n \"text\",\n path,\n [changeInput(node, (value) => commitAt(path, value))],\n [],\n errorHere,\n removable,\n moves\n );\n }\n if (!isPlainObject(node)) {\n return nodeShell(\n \"invalid\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Not a template node.\",\n removable,\n moves\n );\n }\n if (typeof node.bind === \"string\") {\n return nodeShell(\n \"bind\",\n path,\n [\n pathControl(node.bind, scope, \"bind\", (value) =>\n commitAt(path, { bind: value })\n )\n ],\n [],\n errorHere,\n removable,\n moves\n );\n }\n if (typeof node.each === \"string\") {\n return nodeShell(\n \"each\",\n path,\n [\n pathControl(node.each, scope, \"each\", (value) =>\n commitAt(path, { ...node, each: value })\n )\n ],\n [\n // Inside an each, the scope becomes the array's item schema.\n slotEditor(\n \"template\",\n path,\n \"template\",\n node.template,\n true,\n errorPath,\n itemScope(scope, node.each)\n ),\n slotEditor(\n \"empty\",\n path,\n \"empty\",\n node.empty,\n false,\n errorPath,\n scope\n )\n ],\n errorHere,\n removable,\n moves,\n { summary: node.empty !== undefined ? \"template \u00B7 empty\" : \"template\" }\n );\n }\n if (typeof node.when === \"string\") {\n return nodeShell(\n \"when\",\n path,\n [\n pathControl(node.when, scope, \"when\", (value) =>\n commitAt(path, { ...node, when: value })\n )\n ],\n [\n slotEditor(\"template\", path, \"template\", node.template, true, errorPath, scope),\n slotEditor(\"else\", path, \"else\", node.else, false, errorPath, scope)\n ],\n errorHere,\n removable,\n moves,\n { summary: node.else !== undefined ? \"template \u00B7 else\" : \"template\" }\n );\n }\n if (typeof node.tag === \"string\") {\n const attrs = isPlainObject(node.attrs) ? node.attrs : {};\n const binding = isPlainObject(node.action) ? (node.action as ActionBinding) : undefined;\n const attrRows = Object.entries(attrs).map(([name, value]) => {\n // The bind's transform fields, when present. Every write goes\n // through rebuild() so editing one field never drops the others.\n // `bound` is meaningful only while `isBind`; narrowed once here.\n const bound: AttrBind =\n isPlainObject(value) && typeof value.bind === \"string\" ? (value as AttrBind) : { bind: \"\" };\n const isBind = isPlainObject(value) && typeof value.bind === \"string\";\n const bindValue = isBind ? bound : undefined;\n const rebuild = (fields: {\n bind: string;\n prefix?: string | undefined;\n map?: Record<string, string> | undefined;\n default?: string | undefined;\n }): Record<string, unknown> => {\n const out: Record<string, unknown> = { bind: fields.bind };\n if (fields.map !== undefined) {\n out.map = fields.map;\n if (fields.default !== undefined && fields.default !== \"\") {\n out.default = fields.default;\n }\n } else if (fields.prefix !== undefined && fields.prefix !== \"\") {\n out.prefix = fields.prefix;\n }\n return out;\n };\n const setAttr = (nextValue: unknown): void => {\n commitAt(path, { ...node, attrs: { ...attrs, [name]: nextValue } });\n };\n const nameInput = changeInput(\n name,\n (nextName) => {\n const entries = Object.entries(attrs).map(([k, v]) =>\n k === name ? ([nextName, v] as const) : ([k, v] as const)\n );\n commitAt(path, { ...node, attrs: Object.fromEntries(entries) });\n },\n \"wgd-input wgd-attr-name\"\n );\n const mode = h(\"select\", { class: \"wgd-select wgd-attr-mode\" });\n mode.append(h(\"option\", { value: \"literal\" }, [\"literal\"]));\n mode.append(h(\"option\", { value: \"bind\" }, [\"bind\"]));\n mode.value = isBind ? \"bind\" : \"literal\";\n fitSelect(mode);\n // Literal: free text. Bind: the same path dropdown the bind/each/when nodes use.\n const literalInput = changeInput(String(isBind ? \"\" : value), (next) => setAttr(next), \"wgd-input wgd-attr-value\");\n const valueInput: HTMLElement = isBind\n ? pathControl(\n bound.bind,\n scope,\n \"bind\",\n (next) => setAttr(rebuild({ ...bound, bind: next })),\n \"wgd-input wgd-attr-value\"\n )\n : literalInput;\n mode.addEventListener(\"change\", () => {\n // Switching modes carries the current text across as a starting point.\n const current = isBind ? bound.bind : literalInput.value;\n setAttr(mode.value === \"bind\" ? { bind: current || \".\" } : current);\n });\n const removeAttr = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove attribute\" }, [\"\u2715\"]);\n removeAttr.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = attrs;\n commitAt(path, { ...node, attrs: rest });\n });\n\n const row: (Node | string)[] = [nameInput, mode, valueInput];\n const hasMap = bindValue?.map !== undefined;\n const hasPrefix =\n bindValue?.prefix !== undefined && bindValue.prefix !== \"\";\n if (isBind && !hasMap) {\n // Literal prefix (mailto:/tel: links). Hidden while a map is\n // active \u2014 one transform per value, mirroring the validator.\n const prefixInput = changeInput(\n bindValue?.prefix ?? \"\",\n (next) => setAttr(rebuild({ ...bound, map: undefined, prefix: next })),\n \"wgd-input wgd-attr-prefix\"\n );\n prefixInput.placeholder = \"prefix\";\n prefixInput.title = \"Literal prefix, e.g. mailto: \u2014 emitted only when the bound value is non-empty\";\n row.push(prefixInput);\n }\n if (isBind && !hasMap && !hasPrefix) {\n const addMap = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Map values to authored literals (e.g. status \u2192 class)\" },\n [\"map\"]\n );\n addMap.addEventListener(\"click\", () =>\n setAttr(rebuild({ ...bound, prefix: undefined, map: {} }))\n );\n row.push(h(\"span\", { class: \"wgd-node-icons\" }, [addMap, removeAttr]));\n } else {\n row.push(removeAttr);\n }\n\n const attrRow = h(\"div\", { class: \"wgd-attr-row\" }, row);\n const parts: (Node | string)[] = [attrRow];\n if (isBind && hasMap) {\n // The map block: data value \u2192 authored literal rows, plus the\n // miss default. Emptying the record drops the transform.\n const mapEditor = createRecordEditor(\n bound.map,\n { key: \"data value\", value: \"authored literal\", add: \"+ mapping\" },\n (nextMap) => {\n setAttr(\n nextMap === undefined\n ? { bind: bound.bind }\n : rebuild({ ...bound, map: nextMap })\n );\n }\n );\n const defaultInput = changeInput(\n bound.default ?? \"\",\n (next) => setAttr(rebuild({ ...bound, default: next })),\n \"wgd-input wgd-attr-map-default\"\n );\n defaultInput.placeholder = \"default (on miss)\";\n parts.push(\n h(\"div\", { class: \"wgd-attr-map\" }, [\n mapEditor.element,\n h(\"div\", { class: \"wgd-rec-row\" }, [\n h(\"span\", { class: \"wgd-st-colon\" }, [\"\u21B3\"]),\n defaultInput\n ])\n ])\n );\n }\n return parts.length === 1\n ? attrRow\n : h(\"div\", { class: \"wgd-attr\" }, parts);\n });\n const childNodes = Array.isArray(node.children) ? (node.children as unknown[]) : [];\n // One add menu per element covers attributes and every child form \u2014\n // the tree carries no persistent per-form button rows.\n const addMenu = menuButton(\n \"+\",\n \"Add attribute or child node\",\n // Actions belong on activatable elements: buttons and links.\n [\n \"attribute\",\n ...(binding === undefined && (node.tag === \"button\" || node.tag === \"a\") ? [\"action\"] : []),\n ...Object.keys(NODE_PRESETS)\n ],\n (choice) => {\n collapsedPaths.delete(pathString(path)); // never add into a fold\n const preset = NODE_PRESETS[choice];\n if (choice === \"attribute\") {\n commitAt(path, { ...node, attrs: { ...attrs, \"\": \"\" } });\n } else if (choice === \"action\") {\n const first = actionContext.actions[0];\n commitAt(path, {\n ...node,\n action: first !== undefined ? { ref: first.name } : { definition: { kind: \"prompt\", text: [\"Tell me more\"] } }\n });\n } else if (preset) {\n commitAt([...path, childNodes.length], preset());\n }\n }\n );\n const body: (Node | string)[] = [];\n if (attrRows.length > 0) body.push(h(\"div\", { class: \"wgd-attrs\" }, attrRows));\n // Action binding: the element becomes activatable in Apps hosts. The\n // editor commits the whole binding; `undefined` drops the key.\n if (binding !== undefined) {\n const scopePaths = isPlainObject(scope) ? pathOptions(scope, \"when\") : [];\n const bindingEditor = createBindingEditor(\n binding,\n {\n ...actionContext,\n scopePaths,\n // The widget's effective data schema drives output-map targets.\n getDataSchema: () => effectiveDataSchema(store.get(), actionContext.schemas)\n },\n (next) => {\n if (next === undefined) {\n const { action: _gone, ...rest } = node;\n commitAt(path, rest);\n } else {\n commitAt(path, { ...node, action: next });\n }\n }\n );\n const actionParts: (Node | string)[] = [h(\"span\", { class: \"wgd-slot-label\" }, [\"action\"]), bindingEditor.element];\n // An unknown shared ref is flagged at the element carrying it.\n const ref = \"ref\" in binding && typeof binding.ref === \"string\" ? binding.ref : undefined;\n if (ref !== undefined && unknownRefs.has(ref)) {\n actionParts.push(diagnosticLine(`Unknown shared action '${ref}' \u2014 this element renders disabled.`));\n }\n body.push(h(\"div\", { class: \"wgd-attrs wgd-node-action\" }, actionParts));\n }\n if (childNodes.length > 0) {\n body.push(\n h(\n \"div\",\n { class: \"wgd-children\" },\n childNodes.map((child, index) =>\n renderNode(\n child,\n [...path, index],\n errorPath,\n true,\n { parent: path, index, count: childNodes.length },\n scope\n )\n )\n )\n );\n }\n const summaryParts: string[] = [];\n if (attrRows.length > 0) {\n summaryParts.push(`${attrRows.length} attr${attrRows.length === 1 ? \"\" : \"s\"}`);\n }\n if (binding !== undefined) summaryParts.push(\"action\");\n if (childNodes.length > 0) {\n summaryParts.push(\n `${childNodes.length} ${childNodes.length === 1 ? \"child\" : \"children\"}`\n );\n }\n return nodeShell(\n undefined, // the tag select is the node's label\n path,\n [tagControl(node.tag, (value) => commitAt(path, { ...node, tag: value }))],\n body,\n errorHere,\n removable,\n moves,\n { icons: [addMenu], summary: summaryParts.join(\" \u00B7 \") }\n );\n }\n return nodeShell(\n \"unknown\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Unknown template node form.\",\n removable,\n moves\n );\n }\n\n let currentError: string | undefined;\n let lastDraft: WidgetDraft | undefined;\n let lastErrorPath: string | undefined;\n\n /** Rebuild the tree from the last refresh inputs (collapse toggles). */\n function renderTree(): void {\n if (lastDraft === undefined) return;\n // Shared refs resolve like inline schemas \u2014 a ref-based widget gets the same path completions.\n treeHost.replaceChildren(\n renderNode(\n lastDraft.template,\n [],\n lastErrorPath,\n true,\n undefined,\n effectiveDataSchema(lastDraft, actionContext.schemas)\n )\n );\n }\n\n function refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void {\n currentError = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}`\n : undefined;\n lastDraft = draft;\n lastErrorPath = diagnostics.template?.path;\n const known = new Set(actionContext.actions.map((action) => action.name));\n unknownRefs = new Set(collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref)));\n const templateMessage = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path !== undefined && diagnostics.template.path !== \"\"\n ? ` (at ${diagnostics.template.path})`\n : \"\")\n : diagnostics.actionRefs;\n templateDiag.hidden = templateMessage === undefined;\n templateDiag.textContent = templateMessage ?? \"\";\n if (!treeHost.hidden || treeHost.childNodes.length === 0) {\n renderTree();\n }\n if (document.activeElement !== jsonArea) {\n jsonArea.value = JSON.stringify(draft.template, null, 2);\n repaintHighlight(jsonArea);\n }\n }\n\n refreshers.push(() => undefined); // template refresh runs via refresh() below\n\n return { element, refresh, dispose: () => element.remove() };\n}\n", "/**\n * Preview controls in the widget designer: which of the host-supplied\n * named themes the DRAFT renders under \u2014 plus a read-only reference of\n * the effective tokens, so style authoring can reach for\n * `var(--wg-\u2026)` by sight instead of memory.\n *\n * Theme *authoring* lives in the standalone theme designer \u2014 this panel\n * only selects and displays. There is deliberately no preview-kind\n * selector: the widget designer previews the draft, and previewing\n * arbitrary kinds under a theme is the theme designer's job.\n */\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { TOKEN_SPECS } from \"@widgentic/core\";\nimport { diagnosticLine, h, section } from \"./dom.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport function mountThemePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n themes: ThemeEntry[] = []\n): {\n element: HTMLElement;\n /** Show the theme validator's error \u2014 this panel owns the value. */\n setDiagnostic(message: string | undefined): void;\n dispose(): void;\n} {\n // Theme validation errors were computed and dropped before this: the\n // panel that owns the offending value showed nothing at all.\n const themeDiag = diagnosticLine(undefined);\n // Theme selector: \"none\" plus whatever the host supplied.\n const themeSelect = h(\"select\", {\n class: \"wgd-select wgd-theme-select\"\n });\n themeSelect.append(h(\"option\", { value: \"\" }, [\"(none \u2014 defaults)\"]));\n for (const entry of themes) {\n themeSelect.append(\n h(\"option\", { value: entry.name }, [entry.label ?? entry.name])\n );\n }\n themeSelect.addEventListener(\"change\", () => {\n const entry = themes.find((candidate) => candidate.name === themeSelect.value);\n store.update((draft) => {\n if (entry === undefined) {\n const { theme: _gone, ...rest } = draft;\n return rest;\n }\n return { ...draft, theme: entry.tokens };\n });\n });\n\n // Token reference: the EFFECTIVE preview tokens \u2014 the selected entry\n // merged over the registry defaults \u2014 plus the entry's x-* customs.\n // Types come from TOKEN_SPECS metadata (color \u2192 swatch), never inferred.\n const tokenList = h(\"div\", { class: \"wgd-token-ref\" });\n\n function renderTokenReference(theme: Record<string, string> | undefined): void {\n tokenList.replaceChildren();\n for (const [name, spec] of Object.entries(TOKEN_SPECS)) {\n const value = theme?.[name] ?? spec.default;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: spec.use }, [\n spec.type === \"color\"\n ? h(\"span\", {\n class: \"wgd-token-ref-swatch\",\n style: `background: ${value}`\n })\n : h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n for (const [name, value] of Object.entries(theme ?? {})) {\n if (!name.startsWith(\"x-\")) continue;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: \"Custom variable\" }, [\n h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n }\n renderTokenReference(store.get().theme);\n\n refreshers.push((draft) => {\n // Reflect programmatic theme loads; an unrecognized map shows as none.\n if (draft.theme === undefined) {\n themeSelect.value = \"\";\n } else {\n const match = themes.find(\n (entry) => JSON.stringify(entry.tokens) === JSON.stringify(draft.theme)\n );\n themeSelect.value = match?.name ?? \"\";\n }\n renderTokenReference(draft.theme);\n });\n\n const rows: (Node | string)[] = [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview theme\"]),\n themeSelect\n ]),\n h(\"span\", { class: \"wgd-field-label\" }, [\n themes.length === 0\n ? \"No themes supplied by the host \u2014 design themes in the theme designer.\"\n : \"Themes come from the host; edit them in the theme designer.\"\n ]),\n themeDiag,\n h(\"details\", { class: \"wgd-token-ref-details\" }, [\n h(\"summary\", { class: \"wgd-field-label\" }, [\n \"Theme tokens (reference for styles)\"\n ]),\n tokenList\n ])\n ];\n\n const element = section(\"Preview\", rows);\n return {\n element,\n setDiagnostic(message) {\n themeDiag.hidden = message === undefined;\n themeDiag.textContent = message ?? \"\";\n },\n dispose: () => element.remove()\n };\n}\n", "/**\n * Editor panels: plain modules over the draft store. Refresh discipline:\n * every store change re-derives diagnostics and refreshes bound controls,\n * but never overwrites the control the user is typing in\n * (`document.activeElement` wins) \u2014 the store is the single model, the\n * DOM is a projection.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { diagnosticLine, h, section, textArea, textField, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { mountIoPanel } from \"./io.js\";\nimport { createJsonTreeEditor } from \"./json-tree-editor.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport { createStylesEditor } from \"./styles-editor.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { mountTemplatePanel } from \"./template-panel.js\";\nimport type { TemplateActionContext } from \"./template-panel.js\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { mountThemePanel } from \"./theme-panel.js\";\nimport { deriveDiagnostics, effectiveDataSchema } from \"./validate.js\";\n\n/** Tabbed container: first tab visible, buttons switch panes. */\nfunction tabs(entries: { label: string; element: HTMLElement }[]): HTMLElement {\n const buttons = entries.map((entry, index) => {\n const button = h(\n \"button\",\n { class: `wgd-button wgd-tab${index === 0 ? \" wgd-tab-active\" : \"\"}`, type: \"button\" },\n [entry.label]\n );\n button.addEventListener(\"click\", () => {\n entries.forEach((other, i) => {\n other.element.hidden = i !== index;\n buttons[i]?.classList.toggle(\"wgd-tab-active\", i === index);\n });\n });\n entry.element.hidden = index !== 0;\n return button;\n });\n return h(\"div\", { class: \"wgd-tabs\" }, [\n h(\"div\", { class: \"wgd-row\" }, buttons),\n ...entries.map((entry) => entry.element)\n ]);\n}\n\n/** Column layout: definition (exported) on the left, presentation on the right. */\nexport interface PanelColumns {\n left: HTMLElement;\n right: HTMLElement;\n}\n\ntype Refresher = (draft: WidgetDraft) => void;\n\n/**\n * JSON-valued textarea with parse gating: invalid JSON never reaches the\n * store (last-valid-wins) \u2014 the parse error shows beside the field.\n */\nfunction jsonField(\n label: string,\n read: (draft: WidgetDraft) => unknown,\n write: (draft: WidgetDraft, value: unknown) => WidgetDraft,\n clear: ((draft: WidgetDraft) => WidgetDraft) | undefined,\n store: DraftStore,\n refreshers: Refresher[],\n rows = 6\n): HTMLElement {\n const parseError = diagnosticLine(undefined);\n const initial = read(store.get());\n const field = textArea(\n label,\n initial === undefined ? \"\" : JSON.stringify(initial, null, 2),\n (text) => {\n if (text.trim() === \"\") {\n parseError.hidden = true;\n if (clear) store.update((draft) => clear(draft));\n return;\n }\n try {\n const value: unknown = JSON.parse(text);\n parseError.hidden = true;\n parseError.textContent = \"\";\n store.update((draft) => write(draft, value));\n } catch (error) {\n parseError.hidden = false;\n parseError.textContent = `Invalid JSON (draft keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n },\n rows\n );\n const area = requireChild(field, \"textarea\");\n attachJsonHighlight(area);\n refreshers.push((draft) => {\n if (document.activeElement === area) return;\n const value = read(draft);\n area.value = value === undefined ? \"\" : JSON.stringify(value, null, 2);\n repaintHighlight(area); // programmatic writes fire no input event\n });\n return h(\"div\", undefined, [field, parseError]);\n}\n\nexport function mountPanels(\n store: DraftStore,\n columns: PanelColumns,\n themes: ThemeEntry[] = [],\n schemas: SchemaEntry[] = [],\n actionContext: TemplateActionContext = { actions: [], secretNames: [], schemas: [] }\n): { dispose(): void } {\n const refreshers: Refresher[] = [];\n const disposers: (() => void)[] = [];\n\n function bindText(\n label: string,\n read: (draft: WidgetDraft) => string,\n write: (draft: WidgetDraft, value: string) => WidgetDraft\n ): HTMLElement {\n const field = textField(label, read(store.get()), (value) =>\n store.update((draft) => write(draft, value))\n );\n const input = requireChild(field, \"input\");\n refreshers.push((draft) => {\n if (document.activeElement !== input) input.value = read(draft);\n });\n return field;\n }\n\n // --- General: kind + prose descriptor fields (left) -------------------\n const kindDiag = diagnosticLine(undefined);\n // Hints: name\u2192doc rows beside the parse-gated JSON pane \u2014 the same\n // Tree/JSON pair as styles, scaled down to a flat record.\n const hintsEditor = createRecordEditor(\n store.get().descriptor.hints,\n { key: \"hint name\", value: \"what the hint does\", add: \"+ hint\" },\n (hints) =>\n store.update((d) => {\n if (hints === undefined) {\n const { hints: _h, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, hints } };\n })\n );\n refreshers.push((draft) => hintsEditor.setValue(draft.descriptor.hints));\n const generalPanel = section(\"General\", [\n bindText(\"Kind (id)\", (d) => d.kind, (d, v) => ({ ...d, kind: v })),\n kindDiag,\n bindText(\n \"Description\",\n (d) => d.descriptor.description ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, description: v } })\n ),\n bindText(\n \"Data shape (prose)\",\n (d) => d.descriptor.dataShape ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataShape: v } })\n ),\n h(\"div\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Hints\"]),\n tabs([\n { label: \"Tree\", element: hintsEditor.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"\",\n (d) => d.descriptor.hints,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n const hints = Object.fromEntries(\n Object.entries(v).map(([k, doc]) => [k, String(doc)])\n ) as Record<string, string>;\n return { ...d, descriptor: { ...d.descriptor, hints } };\n },\n (d) => {\n const { hints: _hints, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers,\n 3\n )\n }\n ])\n ])\n ]);\n\n // --- Data schema (left, definition): inline editing OR a shared ref ----\n // Two modes, mirroring the store's contract: an inline dataSchema, or a\n // dataSchemaRef into the host-supplied shared schemas \u2014 never both.\n const schemaBuilder = createSchemaBuilder(store.get().descriptor.dataSchema, (schema) =>\n store.update((d) => {\n if (schema === undefined) {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, dataSchema: schema } };\n })\n );\n refreshers.push((draft) => schemaBuilder.setValue(draft.descriptor.dataSchema));\n const inlineEditors = tabs([\n { label: \"Builder\", element: schemaBuilder.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataSchema (JSON-Schema subset: type/properties/required/items/enum/pattern)\",\n (d) => d.descriptor.dataSchema,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n return { ...d, descriptor: { ...d.descriptor, dataSchema: v } };\n },\n (d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]);\n\n const modeSelect = h(\"select\", { class: \"wgd-select wgd-schema-mode\" });\n modeSelect.append(h(\"option\", { value: \"inline\" }, [\"define inline\"]));\n const sharedOption = h(\"option\", { value: \"shared\" }, [\"use shared\"]);\n if (schemas.length === 0) sharedOption.disabled = true;\n modeSelect.append(sharedOption);\n\n const refSelect = h(\"select\", { class: \"wgd-select wgd-schema-ref\" });\n for (const entry of schemas) {\n refSelect.append(h(\"option\", { value: entry.name }, [entry.label ?? entry.name]));\n }\n refSelect.addEventListener(\"change\", () => {\n store.update((d) => ({\n ...d,\n descriptor: { ...d.descriptor, dataSchemaRef: refSelect.value }\n }));\n });\n\n // The shared schema shows read-only: editing it from inside a widget\n // draft would be edit-at-a-distance \u2014 that belongs to the schema section.\n const sharedView = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-shared\",\n rows: \"10\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const schemaRefDiag = diagnosticLine(undefined);\n const sharedWrap = h(\"div\", undefined, [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Shared schema\"]),\n refSelect\n ]),\n sharedView,\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Read-only here \u2014 edit shared schemas in the Data schemas section.\"\n ])\n ]);\n\n modeSelect.addEventListener(\"change\", () => {\n if (modeSelect.value === \"shared\") {\n const name =\n store.get().descriptor.dataSchemaRef ?? schemas[0]?.name ?? \"\";\n store.update((d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: { ...rest, dataSchemaRef: name } };\n });\n } else {\n // Back to inline: seed with the resolved shared schema (a copy), so\n // \"customize from here\" is one switch away.\n const resolved = effectiveDataSchema(store.get(), schemas);\n store.update((d) => {\n const { dataSchemaRef: _r, ...rest } = d.descriptor;\n return {\n ...d,\n descriptor: {\n ...rest,\n dataSchema: (resolved ?? { type: \"object\" }) as Record<string, unknown>\n }\n };\n });\n }\n });\n\n function refreshSchemaMode(draft: WidgetDraft): void {\n const ref = draft.descriptor.dataSchemaRef;\n const shared = typeof ref === \"string\";\n modeSelect.value = shared ? \"shared\" : \"inline\";\n inlineEditors.hidden = shared;\n sharedWrap.hidden = !shared;\n if (shared) {\n if (refSelect.value !== ref) refSelect.value = ref;\n const resolved = schemas.find((entry) => entry.name === ref)?.schema;\n sharedView.value =\n resolved === undefined ? \"\" : JSON.stringify(resolved, null, 2);\n repaintHighlight(sharedView); // programmatic writes fire no input event\n }\n }\n refreshers.push(refreshSchemaMode);\n refreshSchemaMode(store.get());\n\n const schemaPanel = section(\n \"Data schema\",\n [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Source\"]),\n modeSelect\n ]),\n schemaRefDiag,\n inlineEditors,\n sharedWrap\n ],\n false\n );\n // The highlight layer wraps the textarea in place, so attach after the\n // section assembly gives it a parent.\n attachJsonHighlight(sharedView);\n\n /**\n * Adaptive data editor: schema-driven form when a dataSchema exists,\n * generic JSON tree otherwise \u2014 rebuilt when the schema changes; the raw\n * JSON textarea remains as a sibling tab either way.\n */\n function adaptiveDataEditor(\n read: (d: WidgetDraft) => unknown,\n write: (d: WidgetDraft, v: unknown) => WidgetDraft\n ): HTMLElement {\n const hostEl = h(\"div\");\n let schemaKey = \"\";\n let editor:\n | { element: HTMLElement; setValue(v: unknown): void }\n | undefined;\n\n function rebuild(draft: WidgetDraft): void {\n const schema = effectiveDataSchema(draft, schemas);\n const key = schema === undefined ? \"\" : JSON.stringify(schema);\n if (editor !== undefined && key === schemaKey) {\n editor.setValue(read(draft));\n return;\n }\n schemaKey = key;\n const onChange = (value: unknown): void =>\n store.update((d) => write(d, value));\n editor =\n schema !== undefined && isPlainObject(schema)\n ? createSchemaForm(schema as DataSchema, read(draft), onChange)\n : createJsonTreeEditor(read(draft), onChange);\n hostEl.replaceChildren(editor.element);\n }\n\n rebuild(store.get());\n refreshers.push(rebuild);\n return hostEl;\n }\n\n // --- Sample data = the descriptor's dataExample (left, exported) -------\n const exampleDiag = diagnosticLine(undefined);\n const samplePanel = section(\n \"Sample data\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"dataExample \u2014 ships with the widget as the example agents imitate\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataExample (JSON)\",\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } }),\n (d) => {\n const { dataExample: _e, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]),\n exampleDiag\n ],\n false\n );\n\n // --- Data for preview (right, session-only) ----------------------------\n const sampleDiag = diagnosticLine(undefined);\n const previewDataPanel = section(\n \"Data for preview\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Overrides dataExample in the preview only (not exported)\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"Preview data (JSON)\",\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v }),\n (d) => {\n const { sampleData: _s, ...rest } = d;\n return rest;\n },\n store,\n refreshers,\n 4\n )\n }\n ]),\n sampleDiag\n ],\n false\n );\n\n // --- Styles panel (right, presentation): Tree + JSON tabs --------------\n // Two projections of the one draft value, exactly like the template's\n // tree/JSON pair: the tree enforces the string-only two-level shape,\n // the JSON pane stays parse-gated.\n const stylesDiag = h(\"div\");\n const stylesEditor = createStylesEditor(store.get().descriptor.styles, (styles) =>\n store.update((d) => {\n if (styles === undefined) {\n const { styles: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, styles } };\n })\n );\n refreshers.push((draft) => stylesEditor.setValue(draft.descriptor.styles));\n const stylesPanel = section(\"Styles (.wg- selectors, guarded like the server)\", [\n tabs([\n { label: \"Tree\", element: stylesEditor.element },\n {\n label: \"JSON\",\n // No legend \u2014 the section title already names the shape.\n element: jsonField(\n \"\",\n (d) => d.descriptor.styles,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n return {\n ...d,\n descriptor: {\n ...d.descriptor,\n styles: v as Record<string, Record<string, string>>\n }\n };\n },\n (d) => {\n const { styles: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]),\n stylesDiag\n ]);\n\n const templatePanel = mountTemplatePanel(store, refreshers, { actionContext });\n const themePanel = mountThemePanel(store, refreshers, themes);\n\n // --- Load: the widget-level http GET action run once per instance -------\n const loadDiag = diagnosticLine(undefined);\n const loadEditor = createBindingEditor(\n store.get().load,\n {\n ...actionContext,\n loadOnly: true,\n getDataSchema: () => effectiveDataSchema(store.get(), schemas)\n },\n (binding: ActionBinding | undefined) =>\n store.update((d) => {\n if (binding === undefined) {\n const { load: _l, ...rest } = d;\n return rest;\n }\n return { ...d, load: binding };\n })\n );\n refreshers.push((draft) => {\n if (!loadEditor.element.contains(document.activeElement)) loadEditor.setValue(draft.load);\n });\n // Same compact chrome as an element's binding editor in the tree.\n const loadPanel = section(\n \"Load action (http GET, runs once when the widget first renders in an Apps host)\",\n [h(\"div\", { class: \"wgd-compact wgd-load\" }, [loadEditor.element]), loadDiag],\n false\n );\n const ioPanel = mountIoPanel(store);\n\n // Read-only marks the right column's EDITING sections; the theme panel\n // (preview selector + token reference) stays live in that mode.\n previewDataPanel.classList.add(\"wgd-edit-only\");\n stylesPanel.classList.add(\"wgd-edit-only\");\n\n // Left: the widget definition (what export produces). Right: presentation.\n columns.left.append(\n generalPanel,\n schemaPanel,\n samplePanel,\n templatePanel.element,\n loadPanel,\n ioPanel.element\n );\n columns.right.append(previewDataPanel, stylesPanel, themePanel.element);\n disposers.push(templatePanel.dispose, themePanel.dispose, ioPanel.dispose);\n\n // Diagnostics refresh: derive once per change here (cheap, pure) \u2014 and\n // once immediately, so the tree/JSON projections render before any edit.\n function applyDiagnostics(draft: WidgetDraft): void {\n const diagnostics = deriveDiagnostics(draft, { schemas, actions: actionContext.actions });\n kindDiag.hidden = diagnostics.kind === undefined;\n // Unknown refs are flagged in the template panel, at the element; the\n // Load section only ever speaks about the load binding.\n loadDiag.hidden = diagnostics.load === undefined;\n loadDiag.textContent = diagnostics.load ?? \"\";\n kindDiag.textContent = diagnostics.kind ?? \"\";\n exampleDiag.hidden = diagnostics.example === undefined;\n exampleDiag.textContent = diagnostics.example\n ? `dataExample vs dataSchema: ${diagnostics.example.code} at ${diagnostics.example.path} \u2014 ${diagnostics.example.message}`\n : \"\";\n sampleDiag.hidden = diagnostics.sample === undefined;\n sampleDiag.textContent = diagnostics.sample\n ? `sample vs dataSchema: ${diagnostics.sample.code} at ${diagnostics.sample.path} \u2014 ${diagnostics.sample.message}`\n : \"\";\n schemaRefDiag.hidden = diagnostics.schemaRef === undefined;\n schemaRefDiag.textContent = diagnostics.schemaRef ?? \"\";\n themePanel.setDiagnostic(\n diagnostics.theme\n ? `${diagnostics.theme.code}: ${diagnostics.theme.message}`\n : undefined\n );\n stylesDiag.replaceChildren(\n ...diagnostics.styles.map((issue) =>\n diagnosticLine(\n `${issue.selector}${issue.property ? ` \u2192 ${issue.property}` : \"\"}: ${issue.message}`\n )\n )\n );\n for (const refresh of refreshers) refresh(draft);\n templatePanel.refresh(draft, diagnostics);\n }\n\n const off = store.subscribe(applyDiagnostics);\n disposers.push(off);\n applyDiagnostics(store.get());\n\n return {\n dispose() {\n for (const dispose of disposers) dispose();\n columns.left.replaceChildren();\n columns.right.replaceChildren();\n }\n };\n}\n", "/**\n * Live preview through the real pipeline: the draft template compiles into\n * a delegating renderer registered ONCE under a stable internal kind, so a\n * single `mountWidget` handle survives every template revision and updates\n * patch the DOM in place (`reactive-rendering` dogfooded). Built-in kinds\n * share the same scratch catalog for theme-designer previews.\n *\n * Invalid drafts freeze the last good render behind an error banner \u2014\n * never a blank pane (the app-template error-state lesson).\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { createCatalog, widgetStylesToCss } from \"@widgentic/core\";\nimport type { WidgetRenderer } from \"@widgentic/core\";\nimport type { WidgetPayload } from \"@widgentic/core\";\nimport { mountWidget } from \"@widgentic/core\";\nimport type { WidgetMount } from \"@widgentic/core\";\nimport { compileTemplate, validateTemplate } from \"@widgentic/core\";\nimport { applyTheme, injectBaseStyles } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\nimport type { StoredAction } from \"@widgentic/core\";\n\n/** Internal kind the draft renders under (stable across recompiles). */\nexport const PREVIEW_KIND = \"designer-preview\";\n\n/**\n * A host-supplied definition the preview can render by kind. `descriptor`\n * stays `unknown` on purpose: hosts hand these straight off the wire, so\n * the preview narrows what it needs and ignores the rest.\n */\nexport interface PreviewWidget {\n kind: string;\n template: unknown;\n descriptor?: unknown;\n}\n\nexport interface PreviewOptions {\n /**\n * Custom widget definitions to make previewable by kind \u2014 a theme is\n * judged against the widgets it will actually dress, not only the\n * built-ins. Definitions that fail template validation are skipped.\n */\n widgets?: PreviewWidget[];\n /** Shared actions, so `{ ref }` bindings preview with their real kind. */\n actions?: StoredAction[];\n}\n\nexport interface PreviewController {\n readonly pane: HTMLElement;\n /** Selectable kinds: built-ins plus the registered customs. */\n readonly kinds: string[];\n /**\n * Re-render for a draft revision. The WIDGET designer always renders\n * the draft (no `previewKind`); the optional kind parameter exists for\n * the THEME designer, whose job is previewing catalog kinds under a\n * theme.\n */\n update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void;\n dispose(): void;\n}\n\nexport function createPreview(options: PreviewOptions = {}): PreviewController {\n injectBaseStyles(document);\n\n const banner = h(\"div\", { class: \"wgd-banner\" });\n banner.hidden = true;\n const kindStyles = h(\"style\");\n const mountRoot = h(\"div\", { class: \"wgd-preview\" });\n const pane = h(\"div\", { class: \"wgd-preview-pane\" }, [banner, kindStyles, mountRoot]);\n\n const catalog = createCatalog();\n let renderer: WidgetRenderer = () => ({ tag: \"div\", children: [\"\u2026\"] });\n catalog.register(\n PREVIEW_KIND,\n (payload: WidgetPayload) => renderer(payload),\n {\n description: \"Designer preview delegate.\",\n dataShape: \"Defined by the draft being designed.\"\n }\n );\n\n // Host-supplied customs join the scratch catalog so the theme designer\n // can preview them. Each carries its own styles, emitted when selected.\n const customStyles = new Map<string, string>();\n for (const widget of options.widgets ?? []) {\n const validated = validateTemplate(widget.template);\n // Untrusted-ish input: a bad definition is skipped, never fatal.\n if (!validated.ok || typeof widget.kind !== \"string\" || widget.kind === \"\") continue;\n const compiled = compileTemplate(validated.template);\n const descriptor = isPlainObject(widget.descriptor) ? widget.descriptor : {};\n try {\n catalog.register(widget.kind, (payload: WidgetPayload) => compiled(payload), {\n description: `Custom widget '${widget.kind}' supplied for preview.`,\n dataShape: \"Defined by the supplied definition.\",\n ...(descriptor.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {})\n });\n } catch {\n continue; // a reserved/duplicate kind never breaks the designer\n }\n if (isPlainObject(descriptor.styles)) {\n customStyles.set(\n widget.kind,\n widgetStylesToCss(descriptor.styles as Record<string, Record<string, string>>)\n );\n }\n }\n const kinds = catalog.kinds().filter((kind) => kind !== PREVIEW_KIND);\n\n let mount: WidgetMount | undefined;\n\n function update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void {\n const renderingDraft = previewKind === undefined || previewKind === PREVIEW_KIND;\n if (renderingDraft && !diagnostics.previewable) {\n const issue =\n diagnostics.kind ??\n (diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path ? ` (at ${diagnostics.template.path})` : \"\")\n : \"Draft is not previewable.\");\n banner.hidden = false;\n // Freezing needs something to freeze ON. On the first update there\n // is no mount yet \u2014 reachable whenever a host supplies an invalid\n // or reserved-kind `initialWidget` \u2014 and returning here left the\n // pane blank, the one state the contract forbids.\n if (mount === undefined) {\n banner.textContent = `Nothing to preview yet \u2014 ${issue}`;\n mountRoot.replaceChildren(\n h(\"div\", { class: \"wgd-preview-empty\" }, [\n \"No preview: the draft has never been valid.\"\n ])\n );\n return;\n }\n banner.textContent = `Preview frozen on the last valid draft \u2014 ${issue}`;\n return; // keep the last good render mounted\n }\n // A first valid render replaces the empty state.\n mountRoot.querySelector(\".wgd-preview-empty\")?.remove();\n banner.hidden = true;\n banner.textContent = \"\";\n\n if (renderingDraft) {\n const validated = validateTemplate(draft.template);\n if (!validated.ok) return; // defensive: previewable implies ok\n const shared = options.actions ?? [];\n renderer = compileTemplate(validated.template, {\n actions: (ref) => shared.find((action) => action.name === ref)?.definition\n });\n }\n // Styles follow whatever is on screen: the draft's own, or the\n // selected custom kind's (a built-in needs none).\n kindStyles.textContent = renderingDraft\n ? draft.descriptor.styles\n ? widgetStylesToCss(draft.descriptor.styles)\n : \"\"\n : customStyles.get(previewKind as string) ?? \"\";\n // Unsafe values are also skipped inside applyTheme (lenient layer).\n applyTheme(mountRoot, draft.theme ?? {});\n\n const payload = {\n kind: renderingDraft ? PREVIEW_KIND : (previewKind as string),\n data: renderingDraft\n ? draft.sampleData ?? draft.descriptor.dataExample ?? null\n : sampleFor(previewKind as string)\n };\n if (mount === undefined) {\n // No onAction: the preview never executes anything; bound elements\n // only wear the inert badge below.\n mount = mountWidget(payload, mountRoot, { catalog });\n } else {\n mount.update(payload);\n }\n for (const bound of mountRoot.querySelectorAll(\"[data-wg-action]\")) {\n bound.classList.add(\"wg-designer-action\");\n }\n }\n\n /** Built-in preview data for the THEME designer's kind previews. */\n function sampleFor(kind: string): unknown {\n return catalog.describe(kind)?.dataExample ?? { value: \"preview\" };\n }\n\n return {\n pane,\n kinds,\n update,\n dispose() {\n mount?.dispose();\n mount = undefined;\n pane.replaceChildren();\n }\n };\n}\n", "/**\n * Designer draft store: one micro-store per designer instance \u2014 get,\n * immutable update, subscribe, and a bounded undo stack. Deliberately\n * framework-free (the \"Arrow JS direction\": fine-grained subscriptions,\n * no VDOM) so the designer stays a zero-dependency embeddable.\n */\nimport type { WidgetDescriptorInput } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { WidgetTheme } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\n\n/** The draft being designed \u2014 the server's `CustomWidget` shape plus session extras. */\nexport interface WidgetDraft {\n kind: string;\n template: WidgetTemplate;\n /**\n * Mirrors the store's shape: `dataSchemaRef` names a shared schema in\n * place of an inline `dataSchema` (never both). Export carries the ref\n * as authored \u2014 resolution belongs to the server's composition.\n */\n descriptor: WidgetDescriptorInput & { dataSchemaRef?: string };\n /** Optional http GET action run once when the widget first renders. */\n load?: ActionBinding;\n /** Optional preview data overriding `descriptor.dataExample`. */\n sampleData?: unknown;\n /** Preview theme (also the theme-designer working copy). */\n theme?: WidgetTheme;\n}\n\nexport type DraftListener = (draft: WidgetDraft) => void;\n\nconst UNDO_LIMIT = 50;\n\nexport interface DraftStore {\n get(): WidgetDraft;\n /** Replace the draft via an updater; records undo history. */\n update(updater: (draft: WidgetDraft) => WidgetDraft): void;\n /** Replace wholesale (imports/loads); clears history. */\n replace(draft: WidgetDraft): void;\n undo(): boolean;\n subscribe(listener: DraftListener): () => void;\n}\n\n/** Structured-clone with JSON semantics \u2014 drafts are serializable by contract. */\nexport function cloneDraft(draft: WidgetDraft): WidgetDraft {\n return JSON.parse(JSON.stringify(draft)) as WidgetDraft;\n}\n\nexport function starterDraft(): WidgetDraft {\n // Everything the starter binds is DECLARED in its dataSchema \u2014 the\n // preferred pattern: schema-declared properties validate, `$meta.*`\n // paths do not, so new drafts start on the validated side.\n return {\n kind: \"my-widget\",\n template: {\n tag: \"div\",\n attrs: { class: \"wg-template\" },\n children: [{ tag: \"h2\", children: [{ bind: \"title\" }] }, { bind: \"message\" }]\n },\n descriptor: {\n description: \"Describe what this widget is for.\",\n dataShape: \"{ title?, message }\",\n dataExample: {\n title: \"My widget\",\n message: \"Hello from the widgentic designer\"\n },\n dataSchema: {\n type: \"object\",\n required: [\"message\"],\n properties: {\n title: { type: \"string\" },\n message: { type: \"string\" }\n }\n }\n }\n };\n}\n\nexport function createDraftStore(initial?: WidgetDraft): DraftStore {\n let current = cloneDraft(initial ?? starterDraft());\n const history: WidgetDraft[] = [];\n const listeners = new Set<DraftListener>();\n\n function notify(): void {\n for (const listener of [...listeners]) listener(current);\n }\n\n return {\n get: () => current,\n update(updater) {\n history.push(current);\n if (history.length > UNDO_LIMIT) history.shift();\n current = cloneDraft(updater(cloneDraft(current)));\n notify();\n },\n replace(draft) {\n history.length = 0;\n current = cloneDraft(draft);\n notify();\n },\n undo() {\n const previous = history.pop();\n if (previous === undefined) return false;\n current = previous;\n notify();\n return true;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n };\n}\n", "/**\n * The designer shell: layout, store wiring, and the embedding handle.\n * Panels and the preview are plain modules receiving the store \u2014 every\n * designer instance is fully closure-scoped so multiple instances coexist\n * in one document.\n */\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetTheme } from \"@widgentic/core\";\nimport { applyChrome, h, injectDesignerStyles } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { applyDefinition, checkDefinition } from \"./io.js\";\nimport type { WidgetDefinition } from \"./io.js\";\nimport { mountPanels } from \"./panels.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport type { StoredAction } from \"@widgentic/core\";\nimport { createPreview } from \"./preview.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport { cloneDraft, createDraftStore, starterDraft } from \"./store.js\";\nimport { deriveDiagnostics } from \"./validate.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\nexport type { WidgetDefinition } from \"./io.js\";\n\nexport interface DesignerOptions {\n initialWidget?: WidgetDefinition;\n initialTheme?: WidgetTheme;\n /**\n * Named themes offered as preview options. Theme authoring belongs to\n * the standalone theme designer; the widget designer only selects.\n */\n themes?: ThemeEntry[];\n /**\n * Shared data schemas the draft may reference by name (the Data schema\n * section's \"use shared\" mode). Schema authoring belongs to the\n * standalone schema designer; the widget designer only selects.\n */\n schemas?: SchemaEntry[];\n /**\n * Shared actions the draft may bind by name (element `action` bindings\n * and the widget-level `load`). Action authoring belongs to the\n * standalone action designer; the widget designer only binds.\n */\n actions?: StoredAction[];\n /** Secret names offered when an inline http action needs a header or query secret. */\n secretNames?: string[];\n /**\n * Designer chrome appearance. \"auto\" (default) follows the host's\n * `prefers-color-scheme`; the explicit values pin it. This is the\n * designer's own UI \u2014 the widget preview uses the draft's theme.\n */\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its theme selector operate. Toggle later via\n * `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type LoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface DesignerHandle {\n getDraft(): WidgetDraft;\n loadWidget(definition: unknown): LoadResult;\n loadTheme(theme: unknown): LoadResult;\n /** Disable/enable editing; the preview and theme selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(\n listener: (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n ): () => void;\n dispose(): void;\n}\n\nexport function createDesigner(\n container: Element,\n options: DesignerOptions = {}\n): DesignerHandle {\n injectDesignerStyles(document);\n\n const base: WidgetDraft = options.initialWidget\n ? cloneDraft({ ...options.initialWidget })\n : starterDraft();\n const initial: WidgetDraft =\n options.initialTheme !== undefined ? { ...base, theme: options.initialTheme } : base;\n const store = createDraftStore(initial);\n\n const listeners = new Set<\n (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n >();\n\n const preview = createPreview({ actions: options.actions ?? [] });\n const leftColumn = h(\"div\", { class: \"wgd-panels\" });\n const rightSections = h(\"div\", { class: \"wgd-preview-pane\" });\n const rightColumn = h(\"div\", { class: \"wgd-side\" }, [preview.pane, rightSections]);\n const root = h(\"div\", { class: \"wgd-root\" }, [leftColumn, rightColumn]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const actionContext = {\n actions: options.actions ?? [],\n secretNames: options.secretNames ?? [],\n schemas: options.schemas ?? []\n };\n const panels = mountPanels(\n store,\n { left: leftColumn, right: rightSections },\n options.themes ?? [],\n options.schemas ?? [],\n actionContext\n );\n\n function refresh(draft: WidgetDraft): void {\n const diagnostics = deriveDiagnostics(draft, {\n schemas: options.schemas ?? [],\n actions: options.actions ?? []\n });\n preview.update(draft, diagnostics);\n for (const listener of [...listeners]) listener(draft, diagnostics);\n }\n\n const unsubscribe = store.subscribe(refresh);\n refresh(store.get());\n\n /**\n * Read-only: every editing surface goes inert (visible, inoperable \u2014\n * section summaries stay clickable so content can still be inspected),\n * while the preview and the theme panel's selector keep working. inert\n * is applied to section BODIES, which are stable elements: panel\n * re-renders replace children inside them, never the bodies themselves.\n */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n // Complex selectors inside :not() are not universally supported, so\n // the view-only exclusion is filtered here rather than in the query.\n const bodies = [\n ...root.querySelectorAll(\n \".wgd-panels .wgd-section-body, .wgd-edit-only > .wgd-section-body\"\n )\n ].filter((body) => !body.parentElement?.classList.contains(\"wgd-view-only\"));\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getDraft: () => cloneDraft(store.get()),\n setReadOnly,\n loadWidget(definition) {\n const errors = checkDefinition(definition);\n if (errors.length > 0) return { ok: false, errors };\n applyDefinition(store, definition as unknown as WidgetDefinition);\n return { ok: true };\n },\n loadTheme(theme) {\n const validated = validateTheme(theme);\n if (!validated.ok) {\n return { ok: false, errors: [validated.error.message] };\n }\n store.update((draft) => ({ ...draft, theme: validated.theme }));\n return { ok: true };\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n unsubscribe();\n panels.dispose();\n preview.dispose();\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone schema designer: edits a stored-schema entry\n * (`{ name, label?, description?, schema }` \u2014 the widget-store's shape)\n * so one definition (`person`) can serve many widgets. Split out like the\n * theme designer: an app routes to \"design a schema\" as its own\n * destination, and a host embedding one designer should not ship the\n * others. Shares the chrome, the schema builder, and the parse-gated\n * JSON discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\n\n/** The store's identifier charset \u2014 kept local: `@widgentic/mcp/store` is a\n * Node-only entry and the designer runs in browsers. */\nconst SAFE_NAME = /^[a-zA-Z0-9._-]+$/;\n\nexport interface SchemaEntry {\n name: string;\n label?: string;\n description?: string;\n schema: Record<string, unknown>;\n}\n\nexport interface SchemaDesignerOptions {\n initialSchema?: SchemaEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert. Toggle\n * later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type SchemaLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface SchemaDesignerHandle {\n getSchema(): SchemaEntry;\n loadSchema(entry: unknown): SchemaLoadResult;\n /** Disable/enable editing. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: SchemaEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): SchemaEntry {\n return {\n name: \"my-schema\",\n label: \"My schema\",\n schema: { type: \"object\", properties: {} }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkSchemaEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Schema entry must be an object.\"];\n if (typeof entry.name !== \"string\" || entry.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n } else if (!SAFE_NAME.test(entry.name)) {\n errors.push(\n `'${entry.name}' is not a valid schema name \u2014 use letters, digits, '.', '_' or '-'.`\n );\n }\n if (!isPlainObject(entry.schema)) {\n errors.push(\"'schema' must be a plain object.\");\n }\n return errors;\n}\n\nexport function createSchemaDesigner(\n container: Element,\n options: SchemaDesignerOptions = {}\n): SchemaDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: SchemaEntry = options.initialSchema\n ? (JSON.parse(JSON.stringify(options.initialSchema)) as SchemaEntry)\n : starterEntry();\n const listeners = new Set<(entry: SchemaEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-schema-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n function getEntry(): SchemaEntry {\n return JSON.parse(JSON.stringify(entry)) as SchemaEntry;\n }\n\n function notify(): void {\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity panel ----------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n const identity = section(\"Schema\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n const bad = value.trim() === \"\" || !SAFE_NAME.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad\n ? \"Name must be non-empty using letters, digits, '.', '_' or '-'.\"\n : \"\";\n notify();\n }\n ),\n nameDiag,\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n notify();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n notify();\n }\n )\n ]);\n\n // --- Definition panel: builder + parse-gated JSON, one view at a time --\n const builder = createSchemaBuilder(entry.schema as DataSchema, (schema) => {\n entry = { ...entry, schema: (schema ?? {}) as Record<string, unknown> };\n syncJson();\n notify();\n });\n\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"12\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n if (!isPlainObject(parsed)) throw new Error(\"schema must be an object\");\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, schema: parsed };\n builder.setValue(parsed as DataSchema);\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (schema keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n repaintHighlight(jsonArea);\n }\n\n const builderTab = h(\n \"button\",\n { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" },\n [\"Builder\"]\n );\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\n \"JSON\"\n ]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n builder.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n builder.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n builder.element,\n jsonWrap\n ]);\n\n // --- Import / Export: the agent hand-off -------------------------------\n // Live testing surfaced this within a day of list_schemas shipping: an\n // agent drafts the complete entry JSON from the guide, and Import is\n // where the user pastes it. Same two-section shape as the siblings.\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-import\",\n rows: \"6\",\n spellcheck: \"false\"\n });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadSchema(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Import schema entry JSON ({ name, label?, description?, schema })\"\n ]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export schema entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n // Export copies out what is on screen \u2014 read-only leaves it operable.\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, importSection, exportSection);\n // The JSON layer wraps the textareas in place, so attach after assembly.\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadSchema(input: unknown): SchemaLoadResult {\n const errors = checkSchemaEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = JSON.parse(JSON.stringify(input)) as SchemaEntry;\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n builder.setValue(entry.schema as DataSchema);\n syncJson();\n notify();\n return { ok: true };\n }\n\n /** Same mechanism as the other designers: inert the section bodies \u2014\n * except the view-only Export, which restricts nothing. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getSchema: getEntry,\n loadSchema,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone theme designer: edits a NAMED theme entry\n * (`{ name, label?, description?, tokens }` \u2014 the theme registry's shape,\n * which is also what a host persists) with live preview against any\n * catalog kind.\n *\n * Split from the widget designer on purpose: an app routes to \"design a\n * theme\" and \"design a widget\" as separate destinations, and a host\n * embedding one should not ship the other. Both share the preview\n * controller, chrome, and store discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { createCatalog } from \"@widgentic/core\";\nimport {\n THEME_TOKENS,\n TOKEN_DEFAULTS,\n TOKEN_SPECS,\n isSafeTokenValue,\n validateTheme\n} from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetThemeInput } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { createPreview } from \"./preview.js\";\nimport type { PreviewWidget } from \"./preview.js\";\nimport { starterDraft } from \"./store.js\";\nimport type { WidgetDraft } from \"./store.js\";\n\nconst BASE_KINDS = createCatalog().kinds();\n\n/** Hex form the native color input accepts. */\nconst HEX = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i;\nconst CUSTOM_NAME = /^x-[a-z0-9][a-z0-9-]*$/;\n\nfunction toHexInput(value: string): string | undefined {\n if (!HEX.test(value)) return undefined;\n if (value.length === 7) return value.toLowerCase();\n const [, r, g, b] = value.toLowerCase();\n return `#${r}${r}${g}${g}${b}${b}`;\n}\n\nexport interface ThemeDesignerOptions {\n initialTheme?: ThemeEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Custom widget definitions to offer in the preview-kind selector\n * beside the built-ins \u2014 a theme is judged against the widgets it will\n * actually dress. Invalid definitions are skipped.\n */\n widgets?: PreviewWidget[];\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its kind selector operate. Toggle later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type ThemeLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ThemeDesignerHandle {\n getTheme(): ThemeEntry;\n loadTheme(entry: unknown): ThemeLoadResult;\n /** Disable/enable editing; the preview and kind selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ThemeEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ThemeEntry {\n return { name: \"my-theme\", label: \"My theme\", tokens: {} };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkThemeEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n return [\"Theme entry must be an object.\"];\n }\n const candidate = entry as Record<string, unknown>;\n if (typeof candidate.name !== \"string\" || candidate.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n }\n const validated = validateTheme(candidate.tokens ?? {});\n if (!validated.ok) {\n errors.push(`tokens: ${validated.error.code} \u2014 ${validated.error.message}`);\n }\n return errors;\n}\n\nexport function createThemeDesigner(\n container: Element,\n options: ThemeDesignerOptions = {}\n): ThemeDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ThemeEntry = options.initialTheme\n ? (JSON.parse(JSON.stringify(options.initialTheme)) as ThemeEntry)\n : starterEntry();\n const listeners = new Set<(entry: ThemeEntry) => void>();\n\n const preview = createPreview(\n options.widgets ? { widgets: options.widgets } : {}\n );\n // Built-ins plus whatever custom definitions the host supplied.\n const previewKinds = preview.kinds.length > 0 ? preview.kinds : BASE_KINDS;\n let previewKind = previewKinds[0] ?? \"card\";\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const side = h(\"div\", { class: \"wgd-side\" }, [preview.pane]);\n const root = h(\"div\", { class: \"wgd-root wgd-theme-designer\" }, [panels, side]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n /** A draft carrying only what the preview needs: kind + this theme. */\n function previewDraft(): WidgetDraft {\n return { ...starterDraft(), theme: entry.tokens };\n }\n\n function refresh(): void {\n preview.update(previewDraft(), { styles: [], previewable: true }, previewKind);\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n function getEntry(): ThemeEntry {\n return JSON.parse(JSON.stringify(entry)) as ThemeEntry;\n }\n\n function setToken(key: string, value: string): void {\n const tokens = { ...entry.tokens } as Record<string, string>;\n if (value === \"\") delete tokens[key];\n else tokens[key] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n refresh();\n }\n\n // --- Identity panel ----------------------------------------------------\n /** Bind a text field and register its refresher (import must update it). */\n const identityRefreshers: (() => void)[] = [];\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n const identity = section(\"Theme\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n refresh();\n }\n ),\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n refresh();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n refresh();\n }\n )\n ]);\n\n // The kind selector is a PREVIEW control, so it lives beside the\n // preview, outside the editing panels \u2014 read-only mode keeps it live.\n const kindSelect = h(\"select\", {\n class: \"wgd-select wgd-preview-kind\"\n });\n for (const kind of previewKinds) {\n kindSelect.append(h(\"option\", { value: kind }, [kind]));\n }\n kindSelect.value = previewKind;\n kindSelect.addEventListener(\"change\", () => {\n previewKind = kindSelect.value;\n refresh();\n });\n side.prepend(\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview kind\"]),\n kindSelect\n ])\n );\n\n // --- Token panel -------------------------------------------------------\n const tokenRefreshers: (() => void)[] = [];\n const tokenRows: (Node | string)[] = [];\n for (const token of THEME_TOKENS) {\n const input = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\",\n placeholder: TOKEN_DEFAULTS[token]\n });\n input.value = entry.tokens[token] ?? \"\";\n const issue = diagnosticLine(undefined);\n // Control choice comes from the token's declared type \u2014 no guessing.\n const swatch = TOKEN_SPECS[token].type === \"color\"\n ? (h(\"input\", {\n type: \"color\",\n class: \"wgd-swatch\",\n title: `Pick --wg-${token}`\n }))\n : undefined;\n\n const paint = (value: string): void => {\n const effective = value === \"\" ? TOKEN_DEFAULTS[token] : value;\n if (swatch !== undefined) {\n const hex = toHexInput(effective);\n if (hex !== undefined) swatch.value = hex;\n swatch.style.background = isSafeTokenValue(effective) ? effective : \"transparent\";\n }\n };\n paint(input.value);\n swatch?.addEventListener(\"input\", () => {\n input.value = swatch.value;\n input.dispatchEvent(new Event(\"input\", { bubbles: true }));\n });\n input.addEventListener(\"input\", () => {\n const unsafe = input.value !== \"\" && !isSafeTokenValue(input.value);\n issue.hidden = !unsafe;\n issue.textContent = unsafe\n ? \"INVALID_TOKEN_VALUE: unsafe value withheld from the preview (no ;{}<> url() expression()).\"\n : \"\";\n paint(input.value);\n setToken(token, input.value);\n });\n tokenRefreshers.push(() => {\n if (document.activeElement !== input) {\n input.value = entry.tokens[token] ?? \"\";\n paint(input.value);\n }\n });\n tokenRows.push(\n h(\"div\", undefined, [\n h(\"label\", { class: \"wgd-field\", title: TOKEN_SPECS[token].use }, [\n h(\"span\", { class: \"wgd-field-label\" }, [`--wg-${token}`]),\n h(\n \"div\",\n { class: \"wgd-token-row\" },\n swatch === undefined ? [input] : [input, swatch]\n )\n ]),\n issue\n ])\n );\n }\n const tokenPanel = section(\"Tokens\", tokenRows);\n\n // --- Custom variables --------------------------------------------------\n const customHost = h(\"div\", { class: \"wgd-jt-children\" });\n const customError = diagnosticLine(undefined);\n\n function customEntries(): [string, string][] {\n return Object.entries(entry.tokens).filter(([key]) =>\n CUSTOM_NAME.test(key)\n ) as [string, string][];\n }\n\n function renderCustom(): void {\n const rows = customEntries().map(([key, value]) => {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n nameInput.value = key;\n nameInput.addEventListener(\"change\", () => {\n const next = nameInput.value;\n if (!CUSTOM_NAME.test(next)) {\n customError.hidden = false;\n customError.textContent = `'${next}' is not a valid custom name \u2014 use x-<lowercase-kebab>.`;\n nameInput.value = key;\n return;\n }\n customError.hidden = true;\n const tokens = { ...entry.tokens } as Record<string, string>;\n delete tokens[key];\n tokens[next] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n renderCustom();\n refresh();\n });\n const valueInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\"\n });\n valueInput.value = value;\n valueInput.addEventListener(\"input\", () => setToken(key, valueInput.value));\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n setToken(key, \"\");\n renderCustom();\n });\n return h(\"div\", { class: \"wgd-attr-row\" }, [nameInput, valueInput, remove]);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ variable\"\n ]);\n add.addEventListener(\"click\", () => {\n let name = \"x-custom\";\n for (let i = 1; name in entry.tokens; i++) name = `x-custom${i}`;\n setToken(name, \"0\");\n renderCustom();\n });\n customHost.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n renderCustom();\n const customPanel = section(\"Custom variables (--wg-x-*)\", [\n customHost,\n customError\n ]);\n\n // --- Import / export ---------------------------------------------------\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export theme entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n });\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"5\",\n spellcheck: \"false\"\n });\n const importError = diagnosticLine(undefined);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadTheme(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n // Two independent sections, import first \u2014 the same shape the widget\n // designer uses, so both designers read alike.\n const importPanel = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import theme entry JSON\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const exportPanel = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n exportPanel.classList.add(\"wgd-view-only\");\n\n panels.append(identity, tokenPanel, customPanel, importPanel, exportPanel);\n\n function loadTheme(input: unknown): ThemeLoadResult {\n const errors = checkThemeEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = JSON.parse(JSON.stringify(input)) as ThemeEntry;\n for (const refreshIdentity of identityRefreshers) refreshIdentity();\n for (const refreshToken of tokenRefreshers) refreshToken();\n renderCustom();\n refresh();\n return { ok: true };\n }\n\n refresh();\n\n /** Same mechanism as the widget designer: inert the section bodies. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getTheme: getEntry,\n loadTheme,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n preview.dispose();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone action designer: edits a stored-action entry\n * (`{ name, label?, description?, definition }` \u2014 the widget-store's\n * shape). Split out like the theme and schema designers. The Test control\n * appears only when the host supplies `options.testCall`: the library\n * performs no network I/O, and a test call must run through the host's\n * production execution path (secrets, SSRF guard, redaction).\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { ActionDefinition, HttpActionDefinition, StoredAction } from \"@widgentic/core\";\nimport { ACTION_NAME, validateActionDefinition } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { createDefinitionEditor } from \"./action-editor.js\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\n\nexport type ActionEntry = StoredAction;\n\nexport interface ActionDesignerOptions {\n initialAction?: ActionEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n readOnly?: boolean;\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n /**\n * Host-supplied test call (the production execute path). Without it no\n * Test control renders. Resolves to whatever the host wants shown \u2014\n * typically the redacted response or a structured error.\n */\n testCall?: (definition: HttpActionDefinition, args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type ActionLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ActionDesignerHandle {\n getAction(): ActionEntry;\n loadAction(entry: unknown): ActionLoadResult;\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ActionEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ActionEntry {\n return {\n name: \"my-action\",\n label: \"My action\",\n definition: { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkActionEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Action entry must be an object.\"];\n if (typeof entry.name !== \"string\" || !ACTION_NAME.test(entry.name)) {\n errors.push(\"'name' must be lowercase letters, digits and dashes, starting with a letter (max 64).\");\n }\n for (const field of [\"label\", \"description\"] as const) {\n if (entry[field] !== undefined && typeof entry[field] !== \"string\") {\n errors.push(`'${field}' must be a string when present.`);\n }\n }\n const problem = validateActionDefinition(entry.definition, \"definition\");\n if (problem) errors.push(`${problem.message} (at ${problem.path})`);\n return errors;\n}\n\n/** A checked entry with only the fields the shape declares; empty texts are dropped. */\nfunction normalizeEntry(input: Record<string, unknown>): ActionEntry {\n const entry: ActionEntry = { name: input.name as string, definition: clone(input.definition as ActionDefinition) };\n if (typeof input.label === \"string\" && input.label !== \"\") entry.label = input.label;\n if (typeof input.description === \"string\" && input.description !== \"\") entry.description = input.description;\n return entry;\n}\n\n/** Set or drop an optional text field: an emptied field leaves the entry. */\nfunction withText(current: ActionEntry, field: \"label\" | \"description\", value: string): ActionEntry {\n const { [field]: _gone, ...rest } = current;\n return value === \"\" ? rest : { ...rest, [field]: value };\n}\n\nexport function createActionDesigner(\n container: Element,\n options: ActionDesignerOptions = {}\n): ActionDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ActionEntry = options.initialAction ? clone(options.initialAction) : starterEntry();\n const testCall = options.testCall;\n const listeners = new Set<(entry: ActionEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-action-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const getEntry = (): ActionEntry => clone(entry);\n function notify(): void {\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity --------------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n function identityField(label: string, read: () => string, write: (value: string) => void): HTMLElement {\n const field = textField(label, read(), write);\n const inputEl = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== inputEl) inputEl.value = read();\n });\n return field;\n }\n const identity = section(\"Action\", [\n identityField(\"Name (id)\", () => entry.name, (value) => {\n entry = { ...entry, name: value };\n const bad = !ACTION_NAME.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad ? \"Name must be lowercase letters, digits and dashes, starting with a letter.\" : \"\";\n notify();\n }),\n nameDiag,\n identityField(\"Label\", () => entry.label ?? \"\", (value) => {\n entry = withText(entry, \"label\", value);\n notify();\n }),\n identityField(\"Description\", () => entry.description ?? \"\", (value) => {\n entry = withText(entry, \"description\", value);\n notify();\n })\n ]);\n\n // --- Definition: editor + parse-gated JSON -----------------------------\n const definitionDiag = diagnosticLine(undefined);\n const editor = createDefinitionEditor(\n entry.definition,\n { ...(options.schemas ? { schemas: options.schemas } : {}), ...(options.secretNames ? { secretNames: options.secretNames } : {}) },\n (definition) => {\n entry = { ...entry, definition };\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n }\n );\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", { class: \"wgd-textarea\", rows: \"12\", spellcheck: \"false\" });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n const problem = validateActionDefinition(parsed, \"definition\");\n if (problem) throw new Error(`${problem.message} (at ${problem.path})`);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, definition: parsed as ActionDefinition };\n editor.setValue(entry.definition);\n refreshDefinitionDiag();\n refreshTest();\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid (definition keeps the last valid value): ${errorMessage(error)}`;\n }\n });\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n repaintHighlight(jsonArea);\n }\n function refreshDefinitionDiag(): void {\n const problem = validateActionDefinition(entry.definition, \"definition\");\n definitionDiag.hidden = problem === undefined;\n definitionDiag.textContent = problem ? `${problem.message} (at ${problem.path})` : \"\";\n }\n refreshDefinitionDiag();\n\n const builderTab = h(\"button\", { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" }, [\"Editor\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\"JSON\"]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n editor.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n editor.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n definitionDiag,\n editor.element,\n jsonWrap\n ]);\n\n // --- Test (host-supplied) ------------------------------------------------\n const testHost = h(\"div\", { class: \"wgd-action-test\" });\n const testSection = section(\"Test\", [testHost]);\n let testArgs: Record<string, unknown> = {};\n // Arguments belong to one input schema: a different schema starts them over.\n let testInputJson: string | undefined;\n function refreshTest(): void {\n if (testCall === undefined) return;\n testHost.replaceChildren();\n if (entry.definition.kind !== \"http\") {\n testInputJson = undefined;\n testArgs = {};\n testHost.append(h(\"p\", { class: \"wgd-diagnostic\" }, [\"Prompt actions run in the host's composer; nothing to test.\"]));\n return;\n }\n const definitionNow = entry.definition;\n const inputJson = JSON.stringify(definitionNow.input);\n if (inputJson !== testInputJson) testArgs = {};\n testInputJson = inputJson;\n const form = createSchemaForm(definitionNow.input as DataSchema, testArgs, (value) => {\n testArgs = isPlainObject(value) ? value : {};\n });\n testArgs = isPlainObject(form.getValue()) ? (form.getValue() as Record<string, unknown>) : {};\n const output = h(\"pre\", { class: \"wgd-test-output\" });\n const run = h(\"button\", { class: \"wgd-button wgd-add wgd-test-run\", type: \"button\" }, [\"Test call\"]);\n run.addEventListener(\"click\", () => {\n run.disabled = true;\n run.classList.add(\"wgd-busy\");\n run.setAttribute(\"aria-busy\", \"true\");\n output.textContent = \"\u2026\";\n void testCall(definitionNow, testArgs)\n .then((result) => {\n output.textContent = typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n })\n .catch((error: Error) => {\n output.textContent = `Test failed: ${error.message}`;\n })\n .finally(() => {\n run.disabled = false;\n run.classList.remove(\"wgd-busy\");\n run.removeAttribute(\"aria-busy\");\n });\n });\n testHost.append(h(\"span\", { class: \"wgd-field-label\" }, [\"Arguments\"]), form.element, h(\"div\", { class: \"wgd-row\" }, [run]), output);\n }\n refreshTest();\n\n // --- Import / Export ------------------------------------------------------\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", { class: \"wgd-textarea wgd-action-import\", rows: \"6\", spellcheck: \"false\" });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadAction(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import action entry JSON ({ name, label?, description?, definition })\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const output = h(\"textarea\", { class: \"wgd-textarea\", rows: \"8\", readonly: \"\", spellcheck: \"false\" });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"Export action entry\"]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]), output]);\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, ...(testCall === undefined ? [] : [testSection]), importSection, exportSection);\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadAction(input: unknown): ActionLoadResult {\n const errors = checkActionEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = normalizeEntry(input as Record<string, unknown>);\n testArgs = {};\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n editor.setValue(entry.definition);\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n return { ok: true };\n }\n\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getAction: getEntry,\n loadAction,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Opt-in custom element wrapping the factory. Registration only ever\n * happens through the explicit call \u2014 importing this module has no\n * custom-element registry side effects, so hosts stay in control.\n */\nimport { createDesigner } from \"./shell.js\";\nimport type { DesignerHandle } from \"./shell.js\";\nimport { createSchemaDesigner } from \"./schema-designer.js\";\nimport type { SchemaDesignerHandle } from \"./schema-designer.js\";\nimport { createThemeDesigner } from \"./theme-designer.js\";\nimport type { ThemeDesignerHandle } from \"./theme-designer.js\";\nimport { createActionDesigner } from \"./action-designer.js\";\nimport type { ActionDesignerHandle } from \"./action-designer.js\";\nimport { parseChromeAttribute } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\n\n/**\n * The attributes every designer element shares, read once at connect:\n * `appearance` pins the chrome scheme, `chrome` (JSON) hands over the\n * host's chrome tokens. Anything invalid is ignored, never thrown.\n */\nfunction elementOptions(\n element: Element\n): { appearance?: \"light\" | \"dark\"; chrome?: ChromeOptions } {\n const appearance = element.getAttribute(\"appearance\");\n const chrome = parseChromeAttribute(element.getAttribute(\"chrome\"));\n return {\n ...(appearance === \"light\" || appearance === \"dark\" ? { appearance } : {}),\n ...(chrome === undefined ? {} : { chrome })\n };\n}\n\nexport const DEFAULT_TAG = \"widgentic-designer\";\nexport const DEFAULT_THEME_TAG = \"widgentic-theme-designer\";\nexport const DEFAULT_SCHEMA_TAG = \"widgentic-schema-designer\";\nexport const DEFAULT_ACTION_TAG = \"widgentic-action-designer\";\n\nexport function defineDesignerElement(tagName: string = DEFAULT_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticDesignerElement extends HTMLElement {\n #handle: DesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((draft, diagnostics) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", {\n detail: { draft, diagnostics },\n bubbles: true\n })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n /** The embedding host's programmatic access to the wrapped handle. */\n get designer(): DesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticDesignerElement);\n}\n\n/** Sibling registrar for the standalone theme designer. */\nexport function defineThemeDesignerElement(tagName: string = DEFAULT_THEME_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticThemeDesignerElement extends HTMLElement {\n #handle: ThemeDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createThemeDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { theme: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ThemeDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticThemeDesignerElement);\n}\n\n/** Sibling registrar for the standalone schema designer. */\nexport function defineSchemaDesignerElement(tagName: string = DEFAULT_SCHEMA_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticSchemaDesignerElement extends HTMLElement {\n #handle: SchemaDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createSchemaDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { schema: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): SchemaDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticSchemaDesignerElement);\n}\n\n/** Sibling registrar for the standalone action designer. */\nexport function defineActionDesignerElement(tagName: string = DEFAULT_ACTION_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticActionDesignerElement extends HTMLElement {\n #handle: ActionDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createActionDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { action: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ActionDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticActionDesignerElement);\n}\n", "/**\n * Browser bundle entry (`@widgentic/designer/browser`): loading this module\n * from a <script type=\"module\"> registers the designer custom elements, so a\n * page without a bundler can host the designers. Bundler users import the\n * package root instead.\n */\nimport { defineActionDesignerElement, defineDesignerElement, defineSchemaDesignerElement, defineThemeDesignerElement } from \"./index.js\";\n\ndefineActionDesignerElement();\ndefineDesignerElement();\ndefineSchemaDesignerElement();\ndefineThemeDesignerElement();\n\nexport {};\n"],
5
- "mappings": "AAgBA,SAASA,GAAcC,EAAkD,CACvE,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC5E,CASO,SAASC,GACdC,EACAC,EAA2B,CAAC,EACZ,CAChB,GAAI,CAACJ,GAAcG,CAAK,EACtB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,GACN,QAAS,iCACX,CACF,EAGF,GAAI,EAAE,SAAUA,GACd,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,2CACX,CACF,EAGF,IAAME,EAAOF,EAAM,KACnB,GAAI,OAAOE,GAAS,SAClB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,OACN,QAAS,gCACX,CACF,EAEF,GAAIA,EAAK,SAAW,EAClB,MAAO,CACL,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O,IAAM,OAAW,OAE/C,MAAMY,UAAuC,WAAY,CACvDV,GACAC,GAEA,mBAA0B,CACpB,KAAKD,KAAY,SACrB,KAAKA,GAAUW,GAAqB,KAAMvB,GAAe,IAAI,CAAC,EAC9D,KAAKa,GAAe,KAAKD,GAAQ,UAAWQ,GAAU,CACpD,KAAK,cACH,IAAI,YAAY,mBAAoB,CAAE,OAAQ,CAAE,OAAQA,CAAM,EAAG,QAAS,EAAK,CAAC,CAClF,CACF,CAAC,EACH,CAEA,sBAA6B,CAC3B,KAAKP,KAAe,EACpB,KAAKD,IAAS,QAAQ,EACtB,KAAKA,GAAU,OACf,KAAKC,GAAe,MACtB,CAEA,IAAI,UAA6C,CAC/C,OAAO,KAAKD,EACd,CACF,CAEA,eAAe,OAAOF,EAASY,CAA8B,CAC/D,CAGO,SAASE,GAA4Bd,EAAkBF,GAA0B,CACtF,GAAI,eAAe,IAAIE,CAAO,IAAM,OAAW,OAE/C,MAAMe,UAAuC,WAAY,CACvDb,GACAC,GAEA,mBAA0B,CACpB,KAAKD,KAAY,SACrB,KAAKA,GAAUc,GAAqB,KAAM1B,GAAe,IAAI,CAAC,EAC9D,KAAKa,GAAe,KAAKD,GAAQ,UAAWQ,GAAU,CACpD,KAAK,cACH,IAAI,YAAY,mBAAoB,CAAE,OAAQ,CAAE,OAAQA,CAAM,EAAG,QAAS,EAAK,CAAC,CAClF,CACF,CAAC,EACH,CAEA,sBAA6B,CAC3B,KAAKP,KAAe,EACpB,KAAKD,IAAS,QAAQ,EACtB,KAAKA,GAAU,OACf,KAAKC,GAAe,MACtB,CAEA,IAAI,UAA6C,CAC/C,OAAO,KAAKD,EACd,CACF,CAEA,eAAe,OAAOF,EAASe,CAA8B,CAC/D,CClKAE,GAA4B,EAC5BC,GAAsB,EACtBC,GAA4B,EAC5BC,GAA2B",
4
+ "sourcesContent": ["import type { WidgetPayload } from \"./types.js\";\nimport type { WidgetContractError } from \"./errors.js\";\n\nexport interface ValidateOptions {\n /**\n * If provided and non-empty, payloads whose `kind` is not in the set fail\n * with `UNKNOWN_KIND`. When omitted or empty, kind membership is not\n * checked (kind format is still validated).\n */\n knownKinds?: ReadonlySet<string>;\n}\n\nexport type ValidateResult =\n | { ok: true; payload: WidgetPayload }\n | { ok: false; error: WidgetContractError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Validate an unknown input against the widget contract.\n *\n * Returns a discriminated result. The `payload` returned on success is the\n * original input (unknown top-level fields are preserved for forward\n * compatibility).\n */\nexport function validateWidgetPayload(\n input: unknown,\n options: ValidateOptions = {}\n): ValidateResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"\",\n message: \"Payload must be a plain object.\"\n }\n };\n }\n\n if (!(\"kind\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Payload is missing required field 'kind'.\"\n }\n };\n }\n\n const kind = input.kind;\n if (typeof kind !== \"string\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"kind\",\n message: \"Field 'kind' must be a string.\"\n }\n };\n }\n if (kind.length === 0) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Field 'kind' must be a non-empty string.\"\n }\n };\n }\n\n if (!(\"data\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data\",\n message: \"Payload is missing required field 'data'.\"\n }\n };\n }\n\n if (\"hints\" in input && input.hints !== undefined && !isPlainObject(input.hints)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"hints\",\n message: \"Field 'hints' must be an object when present.\"\n }\n };\n }\n\n if (\"meta\" in input && input.meta !== undefined && !isPlainObject(input.meta)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"meta\",\n message: \"Field 'meta' must be an object when present.\"\n }\n };\n }\n\n const { knownKinds } = options;\n if (knownKinds && knownKinds.size > 0 && !knownKinds.has(kind)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${kind}'.`\n }\n };\n }\n\n // Preserve unknown top-level fields by returning the original input.\n return { ok: true, payload: input as WidgetPayload };\n}\n", "/**\n * URL safety primitives shared by the template DSL and the catalog's image\n * rendering. They live in the contract layer \u2014 the zero-dependency base\n * both consumers sit on \u2014 so the strict and lenient layers can never drift\n * (`templates` imports from `catalog`, so `catalog` cannot import back).\n */\n\n/** Schemes allowed in URL-bearing attributes (plus relative references). */\nexport const ALLOWED_SCHEMES = new Set([\"http\", \"https\", \"mailto\", \"tel\"]);\n\n/**\n * Strip control characters and whitespace before scheme inspection,\n * mirroring how browsers parse URLs (defeats `java\\nscript:` obfuscation).\n */\nfunction cleanUrl(value: string): string {\n return value.replace(/[\\u0000-\\u0020]+/g, \"\");\n}\n\n/**\n * True when a URL value is safe for a URL-bearing attribute: an allowed\n * scheme or a relative reference.\n */\nexport function isSafeUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return true;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/**\n * True only for an EXPLICITLY-schemed allowed URL \u2014 unlike {@link isSafeUrl},\n * relative references do not qualify: as anchor targets they are dead\n * clicks inside the app frame and junk navigation on served pages.\n */\nexport function isLinkableUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return false;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/** `data:image/<subtype>;base64,<payload>` \u2014 the only `data:` form images accept. */\nconst DATA_IMAGE = /^data:image\\/[a-z0-9.+-]+;base64,[a-z0-9+/=]*$/i;\n\n/** Absolute http(s) \u2014 image sources are fetched, so relative refs are useless. */\nconst HTTP_URL = /^https?:\\/\\//i;\n\n/**\n * True when a value is acceptable as an image source: an absolute http(s)\n * URL or a base64 `data:image/*` URI. Broader `data:` stays banned here and\n * everywhere else \u2014 data-URI navigation is an XSS vector; data-URI images\n * are not.\n */\nexport function isSafeImageSrc(value: string): boolean {\n const cleaned = cleanUrl(value);\n return DATA_IMAGE.test(cleaned) || HTTP_URL.test(cleaned);\n}\n\nconst IMAGE_EXTENSION = /\\.(png|jpe?g|gif|webp|avif|svg)$/i;\n\n/**\n * Auto-detection predicate for the built-in renderers: a safe image source\n * that self-identifies as an image \u2014 `data:image/*`, or an http(s) URL\n * whose pathname ends in an image extension (query strings tolerated).\n * Extensionless image URLs need a `hints.images` entry instead.\n */\nexport function looksLikeImageUrl(value: string): boolean {\n const cleaned = cleanUrl(value);\n if (!isSafeImageSrc(cleaned)) return false;\n if (cleaned.toLowerCase().startsWith(\"data:image/\")) return true;\n try {\n return IMAGE_EXTENSION.test(new URL(cleaned).pathname);\n } catch {\n return false;\n }\n}\n", "/**\n * Pure render tree produced by widget renderers.\n *\n * Plain, JSON-serializable data \u2014 no DOM or framework types \u2014 so renderers\n * are testable anywhere and the output layers (`renderToHtml`, `mountNode`)\n * stay thin and swappable. There is deliberately no raw-HTML node type: all\n * text is escaped at the output boundary.\n */\nimport type { WidgetPayload } from \"../contract/types.js\";\n\n/** Attribute map. Values are plain strings (escaped by output layers). */\nexport type WidgetNodeAttrs = Record<string, string>;\n\n/** A tagged element in the render tree. */\nexport interface WidgetElementNode {\n tag: string;\n attrs?: WidgetNodeAttrs;\n children?: WidgetNode[];\n}\n\n/** An element in the render tree: a text node or a tagged element. */\nexport type WidgetNode = string | WidgetElementNode;\n\n/** A widget renderer: pure function from payload to render tree. */\nexport type WidgetRenderer = (payload: WidgetPayload) => WidgetNode;\n\n/** Convenience node constructor (omits empty attrs/children). */\nexport function el(\n tag: string,\n attrs?: WidgetNodeAttrs,\n children?: WidgetNode[]\n): WidgetElementNode {\n const node: WidgetElementNode = { tag };\n if (attrs && Object.keys(attrs).length > 0) node.attrs = attrs;\n if (children && children.length > 0) node.children = children;\n return node;\n}\n", "import type { WidgetKind } from \"../contract/types.js\";\nimport type { DataSchema } from \"./schema.js\";\nimport type { WidgetStyles } from \"./styles.js\";\n\n/**\n * Agent-facing documentation for a widget kind. Descriptors make the\n * catalog reflectable: tooling (e.g. the widgentic MCP server's\n * `list_widgets`) lists them so agents can pick a widget and shape their\n * `data` without reading source.\n */\nexport interface WidgetDescriptor {\n kind: WidgetKind;\n /** What the widget is for. */\n description: string;\n /** Human-readable description of the expected `data` input. */\n dataShape: string;\n /** Small example `data` value an agent can imitate. */\n dataExample?: unknown;\n /** Supported hint keys and what they do. */\n hints?: Record<string, string>;\n /**\n * Optional JSON-Schema subset for `data` (see schema.ts). When present,\n * `catalog.render` validates data against it before rendering; kinds\n * without one keep their lenient fallback behavior.\n */\n dataSchema?: DataSchema;\n /**\n * Optional CSS-as-data for the kind's `.wg-` classes (see styles.ts).\n * Included in `page` output and exposable by hosts; guarded like themes.\n */\n styles?: WidgetStyles;\n}\n\n/** Descriptor as supplied at registration; `kind` is filled by the catalog. */\nexport type WidgetDescriptorInput = Omit<WidgetDescriptor, \"kind\">;\n\n/**\n * Honest documentation of the built-ins' actual (lenient) behavior. Every\n * `dataExample` is asserted by tests to render successfully.\n */\nexport const BUILTIN_DESCRIPTORS: Record<\n \"card\" | \"table\" | \"tree\" | \"custom\" | \"group\",\n WidgetDescriptorInput\n> = {\n card: {\n description:\n \"Key/value details for a single entity, with optional title and subtitle.\",\n dataShape:\n \"A plain object. `title`, `subtitle`, and `fields` are used when present; \" +\n \"other entries become field key/value pairs. Primitives render as a single \" +\n \"value line. `meta.title`/`meta.subtitle` fill in missing chrome. Send \" +\n \"field values typed (e.g. price: 9.99, not '$9.99') and use \" +\n \"hints.fieldFormat for display formatting \u2014 the payload keeps the \" +\n \"typed value while the render gets its unit. Field values that are \" +\n \"image URLs render as images (see hints.images).\",\n dataExample: {\n title: \"Essence Mascara\",\n subtitle: \"beauty\",\n fields: { price: 9.99, rating: 2.56, stock: 99 }\n },\n hints: {\n fieldFormat:\n \"Record<fieldKey, pattern> \u2014 formats matching field values by \" +\n \"substituting {value} in the pattern (e.g. { price: '${value}', \" +\n \"rating: '{value} / 5' }); a pattern without {value} is prefixed \" +\n \"to the value. Output is escaped like any text.\",\n images:\n \"Record<fieldKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"field values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: thumb); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text; image treatment wins over \" +\n \"fieldFormat for the same key.\",\n links:\n \"Record<fieldKey, boolean | prefix> \u2014 true links a field whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same key. Links are never \" +\n \"automatic \u2014 opt in per field.\"\n }\n },\n table: {\n description: \"Rows and columns for arrays of records.\",\n dataShape:\n \"An array of records (plain objects). Columns are the union of record keys \" +\n \"in first-seen order; missing cells render empty; non-array data becomes a \" +\n \"single row. Cell values that are image URLs render as avatars (see \" +\n \"hints.images). meta.title/meta.subtitle render as the table's caption. \" +\n \"Send cell values typed (e.g. total: 11471334.78, not '11,471,334.78') \" +\n \"and use hints.fieldFormat for display formatting \u2014 the payload keeps \" +\n \"the typed value while the render gets its unit.\",\n dataExample: [\n { name: \"Ada\", role: \"eng\", avatar: \"https://picsum.photos/id/64/64/64.jpg\" },\n { name: \"Lin\", role: \"ops\", avatar: \"https://picsum.photos/id/65/64/64.jpg\" }\n ],\n hints: {\n columns: \"string[] \u2014 overrides column selection and order\",\n fieldFormat:\n \"Record<columnKey, pattern> \u2014 formats matching cell values by \" +\n \"substituting {value} in the pattern (e.g. { total: '${value}' }); \" +\n \"a pattern without {value} is prefixed to the value. Output is \" +\n \"escaped like any text; image treatment wins for the same column.\",\n links:\n \"Record<columnKey, boolean | prefix> \u2014 true links cells whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same column. Links are never \" +\n \"automatic \u2014 opt in per column.\",\n images:\n \"Record<columnKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"cell values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: avatar); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text.\"\n }\n },\n tree: {\n description: \"Collapsible hierarchy of labeled nodes.\",\n dataShape:\n \"Nested `{ label, children[] }` nodes \u2014 a single root object or an array of \" +\n \"them. Nodes without a usable `label` get a JSON fallback label. \" +\n \"meta.title renders as a title line above the tree.\",\n dataExample: {\n label: \"root\",\n children: [{ label: \"leaf\", children: [] }]\n },\n hints: {\n expandDepth:\n \"number \u2014 branches at depth < value start expanded (default: \" +\n \"unlimited). Presentational only: the full subtree is always in the \" +\n \"markup; `data-expanded` appears only on nodes with children, and \" +\n \"the widgentic base stylesheet hides collapsed children via CSS.\"\n }\n },\n custom: {\n description:\n \"Generic escape hatch: renders any data as pretty-printed JSON. Best \" +\n \"for raw inspection and debugging \u2014 for human-legible output, reshape \" +\n \"the data and use card, table, or tree instead (e.g. join values with \" +\n \"their units: '24.4 \u00B0C').\",\n dataShape: \"Any JSON value, rendered verbatim (value-exact, not byte-exact).\",\n dataExample: { anything: [\"goes\", 42] }\n },\n group: {\n description:\n \"Several widgets in one response \u2014 mixed kinds in a single layout \" +\n \"container. Use ONE group render instead of repeated render calls \" +\n \"when showing multiple widgets together.\",\n dataShape:\n \"{ items: [{ kind, data, hints?, meta? }, ...] } \u2014 each item is a \" +\n \"full sub-widget rendered exactly as a top-level call would be \" +\n \"(any listed kind except 'group'; groups do not nest). At most 20 \" +\n \"items per group.\",\n dataExample: {\n items: [\n { kind: \"card\", data: { title: \"Ada\", fields: { role: \"eng\" } } },\n { kind: \"card\", data: { title: \"Lin\", fields: { role: \"ops\" } } }\n ]\n },\n hints: {\n layout:\n \"'stack' | 'row' | 'grid' \u2014 how items sit together (default: \" +\n \"stack). 'row' wraps; 'grid' uses equal columns.\",\n gap: \"'none' | 'sm' | 'md' | 'lg' \u2014 spacing between items (default: md).\",\n columns: \"number 1-4 \u2014 column count for layout: 'grid' (default: 2).\"\n }\n }\n};\n", "import type { WidgetContractError } from \"../contract/errors.js\";\n\n/**\n * A JSON-Schema *subset* for widget `data`: `type`, `properties`,\n * `required`, `items`, `enum`, `pattern`. Unknown keywords are ignored\n * (forward compatible), never misinterpreted \u2014 and that policy extends to\n * `pattern` values this module refuses to run (see the ReDoS bounds\n * below). Violations map to the existing contract vocabulary with dotted\n * paths into the data.\n */\nexport type DataSchema = Record<string, unknown>;\n\n// `pattern` bounds: schemas arrive from descriptor authors, but the strings\n// they test arrive from agents \u2014 an exponential-backtracking pattern over\n// attacker-lengthened input is a denial of service. Overlong patterns,\n// nested-quantifier shapes, and RegExp-invalid sources are IGNORED (never\n// misinterpreted as passing or failing); tested strings are capped.\n/** Longest `pattern` the validator will compile. */\nexport const PATTERN_MAX_LENGTH = 256;\nconst TESTED_STRING_MAX = 10_000;\nconst NESTED_QUANTIFIER = /(\\([^)]*[+*][^)]*\\)|\\[[^\\]]*\\][+*])[+*{]/;\n\nfunction compileSafePattern(pattern: unknown): RegExp | undefined {\n if (typeof pattern !== \"string\" || pattern.length > PATTERN_MAX_LENGTH) {\n return undefined;\n }\n if (NESTED_QUANTIFIER.test(pattern)) return undefined;\n try {\n return new RegExp(pattern);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction matchesSingleType(type: string, data: unknown): boolean {\n switch (type) {\n case \"object\":\n return isPlainObject(data);\n case \"array\":\n return Array.isArray(data);\n case \"string\":\n return typeof data === \"string\";\n case \"number\":\n return typeof data === \"number\";\n case \"integer\":\n return typeof data === \"number\" && Number.isInteger(data);\n case \"boolean\":\n return typeof data === \"boolean\";\n case \"null\":\n return data === null;\n default:\n // Unknown type keyword: ignore rather than reject.\n return true;\n }\n}\n\nfunction matchesType(type: unknown, data: unknown): boolean {\n if (typeof type === \"string\") return matchesSingleType(type, data);\n if (Array.isArray(type)) {\n return type.some(\n (candidate) =>\n typeof candidate === \"string\" && matchesSingleType(candidate, data)\n );\n }\n return true;\n}\n\nfunction enumMatches(allowed: unknown[], data: unknown): boolean {\n return allowed.some((value) => {\n if (value === data) return true;\n try {\n return JSON.stringify(value) === JSON.stringify(data);\n } catch {\n return false;\n }\n });\n}\n\nfunction formatType(type: unknown): string {\n return Array.isArray(type) ? type.join(\" | \") : String(type);\n}\n\n/**\n * Validate `data` against a subset schema. Returns the first violation as a\n * contract-vocabulary error (`MISSING_FIELD` for required, `INVALID_TYPE`\n * for type/enum) with a dotted path, or `undefined` when valid. Never\n * throws.\n */\nexport function validateDataAgainstSchema(\n schema: DataSchema,\n data: unknown,\n path = \"data\"\n): WidgetContractError | undefined {\n if (Array.isArray(schema.enum) && !enumMatches(schema.enum, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must be one of the enumerated options.`\n };\n }\n\n if (schema.type !== undefined && !matchesType(schema.type, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must have type ${formatType(schema.type)}.`\n };\n }\n\n // Pattern applies to string data only \u2014 type mismatches are `type`'s job.\n if (typeof data === \"string\" && schema.pattern !== undefined) {\n const regex = compileSafePattern(schema.pattern);\n if (regex !== undefined && !regex.test(data.slice(0, TESTED_STRING_MAX))) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must match pattern ${String(schema.pattern)}.`\n };\n }\n }\n\n if (isPlainObject(data)) {\n if (Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && !(key in data)) {\n return {\n code: \"MISSING_FIELD\",\n path: `${path}.${key}`,\n message: `Missing required property '${key}'.`\n };\n }\n }\n }\n if (isPlainObject(schema.properties)) {\n for (const [key, subschema] of Object.entries(schema.properties)) {\n if (key in data && isPlainObject(subschema)) {\n const error = validateDataAgainstSchema(\n subschema,\n data[key],\n `${path}.${key}`\n );\n if (error) return error;\n }\n }\n }\n }\n\n if (Array.isArray(data) && isPlainObject(schema.items)) {\n for (let i = 0; i < data.length; i++) {\n const error = validateDataAgainstSchema(\n schema.items as DataSchema,\n data[i],\n `${path}.${i}`\n );\n if (error) return error;\n }\n }\n\n return undefined;\n}\n", "/** Shared helpers for the built-in renderers. */\nimport { isLinkableUrl } from \"../../contract/urls.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\n\n/** Same plain-object definition as the contract validator. */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Render any value as display text. Strings pass through; primitives\n * stringify; structured values fall back to compact JSON. Never throws.\n */\nexport function formatValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"\";\n if (\n value === null ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\"\n ) {\n return String(value);\n }\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\n/** Apply a `fieldFormat` pattern: substitute `{value}`, or append when absent. */\nexport function applyPattern(pattern: string, value: string): string {\n return pattern.includes(\"{value}\")\n ? pattern.split(\"{value}\").join(value)\n : pattern + value;\n}\n\n/**\n * Wrap display text in an anchor when the caller opted this key into\n * `hints.links` AND the raw value is an explicitly-schemed safe URL.\n * Built-ins construct nodes directly (they never pass the template\n * compiler's URL guard), so the scheme check lives here \u2014 mirroring\n * `isSafeImageSrc` in the image path. Everything else stays plain text.\n */\nexport function linkOrText(\n key: string,\n raw: unknown,\n hints: unknown,\n display: string\n): WidgetNode {\n const links =\n isPlainObject(hints) && isPlainObject(hints.links) ? hints.links : undefined;\n const hint = links?.[key];\n if (typeof raw !== \"string\" || raw === \"\") return display;\n // true: the value IS the URL. String: an author-supplied prefix composed\n // with the value (e.g. \"mailto:\") \u2014 the display stays the clean value,\n // and the COMPOSED href faces the guard, so a hostile value can never\n // smuggle a scheme past an author prefix.\n const href =\n hint === true ? raw : typeof hint === \"string\" ? hint + raw : undefined;\n if (href === undefined || !isLinkableUrl(href)) return display;\n return el(\n \"a\",\n { class: \"wg-link\", href, rel: \"noopener noreferrer\" },\n [display]\n );\n}\n", "import { isSafeImageSrc, looksLikeImageUrl } from \"../../contract/urls.js\";\nimport type { WidgetElementNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Image presentation variants; each maps to a `wg-img-<shape>` class. */\nexport type ImageShape = \"avatar\" | \"thumb\" | \"hero\";\n\nconst SHAPES = new Set<string>([\"avatar\", \"thumb\", \"hero\"]);\n\n/**\n * Decide whether a card-field / table-cell value renders as an image.\n * `hints.images` (keyed by field/column name) overrides auto-detection:\n * a shape string forces that shape, `true` forces the context default,\n * `false` suppresses. Hints never bypass safety \u2014 an unsafe source always\n * renders as text (`null` here). Auto-detection requires the value to\n * self-identify as an image (`looksLikeImageUrl`).\n */\nexport function resolveImage(\n key: string,\n value: unknown,\n hints: Record<string, unknown> | undefined,\n defaultShape: ImageShape\n): { src: string; shape: ImageShape } | null {\n if (typeof value !== \"string\") return null;\n const images = isPlainObject(hints?.images) ? hints.images : undefined;\n const hint = images?.[key];\n if (hint === false) return null;\n if (typeof hint === \"string\" && SHAPES.has(hint)) {\n return isSafeImageSrc(value)\n ? { src: value, shape: hint as ImageShape }\n : null;\n }\n if (hint === true) {\n return isSafeImageSrc(value) ? { src: value, shape: defaultShape } : null;\n }\n return looksLikeImageUrl(value) ? { src: value, shape: defaultShape } : null;\n}\n\n/** The standard image element: stable classes, key as alt, lazy loading. */\nexport function imageNode(\n key: string,\n src: string,\n shape: ImageShape\n): WidgetElementNode {\n return el(\"img\", {\n class: `wg-img wg-img-${shape}`,\n src,\n alt: key,\n loading: \"lazy\",\n decoding: \"async\"\n });\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\n\n/**\n * `card` renderer.\n *\n * Uses `data.title`/`data.subtitle`/`data.fields` when present; other\n * plain-object entries become field key/value pairs; primitives and `null`\n * render as a single value line. `meta.title`/`meta.subtitle` fill in when\n * `data` does not provide them. Total: never throws.\n */\nexport function renderCard(payload: WidgetPayload): WidgetNode {\n const { data, meta } = payload;\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n\n let title: unknown;\n let subtitle: unknown;\n let fieldEntries: [string, unknown][] = [];\n let value: string | undefined;\n\n if (isPlainObject(data)) {\n title = data.title;\n subtitle = data.subtitle;\n if (isPlainObject(data.fields)) {\n fieldEntries = Object.entries(data.fields);\n } else {\n fieldEntries = Object.entries(data).filter(\n ([key]) => key !== \"title\" && key !== \"subtitle\"\n );\n }\n } else {\n value = formatValue(data);\n }\n\n if (title === undefined) title = meta?.title;\n if (subtitle === undefined) subtitle = meta?.subtitle;\n\n const children: WidgetNode[] = [];\n if (title !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n children.push(\n el(\"div\", { class: \"wg-card-subtitle\" }, [formatValue(subtitle)])\n );\n }\n if (value !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-value\" }, [value]));\n }\n if (fieldEntries.length > 0) {\n children.push(\n el(\n \"dl\",\n { class: \"wg-card-fields\" },\n fieldEntries.map(([key, fieldValue]) => {\n // Image treatment wins over fieldFormat for the same key.\n const image = resolveImage(key, fieldValue, payload.hints, \"thumb\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(key, image.src, image.shape);\n } else {\n const raw = formatValue(fieldValue);\n const pattern = fieldFormat?.[key];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(key, fieldValue, payload.hints, text);\n }\n return el(\"div\", { class: \"wg-card-field\" }, [\n el(\"dt\", { class: \"wg-card-field-key\" }, [key]),\n el(\"dd\", { class: \"wg-card-field-value\" }, [display])\n ]);\n })\n )\n );\n }\n return el(\"div\", { class: \"wg-card\" }, children);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\n\n/**\n * `table` renderer.\n *\n * One row per record; columns are the union of record keys in first-seen\n * order, overridable via `hints.columns`. Non-array data becomes a\n * single-record array; non-object rows are wrapped as `{ value }`. Missing\n * cells render empty. Total: never throws.\n */\nexport function renderTable(payload: WidgetPayload): WidgetNode {\n const rows = Array.isArray(payload.data) ? payload.data : [payload.data];\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n const records: Record<string, unknown>[] = rows.map((row) =>\n isPlainObject(row) ? row : { value: row }\n );\n\n const hintColumns = payload.hints?.columns;\n let columns: string[];\n if (\n Array.isArray(hintColumns) &&\n hintColumns.every((column): column is string => typeof column === \"string\")\n ) {\n columns = hintColumns;\n } else {\n columns = [];\n const seen = new Set<string>();\n for (const record of records) {\n for (const key of Object.keys(record)) {\n if (!seen.has(key)) {\n seen.add(key);\n columns.push(key);\n }\n }\n }\n }\n\n // Caption chrome from meta \u2014 a table's data has no title slot, so meta\n // is the only source; absence means no caption. <caption> must be the\n // table's first child per the HTML content model.\n const chrome: WidgetNode[] = [];\n const title = payload.meta?.title;\n const subtitle = payload.meta?.subtitle;\n if (title !== undefined || subtitle !== undefined) {\n const parts: WidgetNode[] = [];\n if (title !== undefined) {\n parts.push(el(\"span\", { class: \"wg-table-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n parts.push(\n el(\"span\", { class: \"wg-table-subtitle\" }, [formatValue(subtitle)])\n );\n }\n chrome.push(el(\"caption\", { class: \"wg-table-caption\" }, parts));\n }\n\n return el(\"table\", { class: \"wg-table\" }, [\n ...chrome,\n el(\"thead\", { class: \"wg-table-head\" }, [\n el(\n \"tr\",\n undefined,\n columns.map((column) =>\n el(\"th\", { class: \"wg-table-header\" }, [column])\n )\n )\n ]),\n el(\n \"tbody\",\n { class: \"wg-table-body\" },\n records.map((record) =>\n el(\n \"tr\",\n { class: \"wg-table-row\" },\n columns.map((column) => {\n if (!(column in record)) {\n return el(\"td\", { class: \"wg-table-cell\" }, [\"\"]);\n }\n const value = record[column];\n // Precedence per column: image > link > formatted text.\n const image = resolveImage(column, value, payload.hints, \"avatar\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(column, image.src, image.shape);\n } else {\n const raw = formatValue(value);\n const pattern = fieldFormat?.[column];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(column, value, payload.hints, text);\n }\n return el(\"td\", { class: \"wg-table-cell\" }, [display]);\n })\n )\n )\n )\n ]);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode, WidgetNodeAttrs } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { formatValue, isPlainObject } from \"./format.js\";\n\n/**\n * `tree` renderer.\n *\n * Renders nested `{ label, children[] }` nodes; nodes without a usable\n * `label` get a JSON-snippet fallback (excluding `children`). Recurses only\n * into array-valued `children`. `hints.expandDepth` (default unlimited)\n * marks nodes at depth < value as expanded via `data-expanded` \u2014 state only,\n * no behavior. Total: never throws.\n */\nexport function renderTree(payload: WidgetPayload): WidgetNode {\n const depthHint = payload.hints?.expandDepth;\n const expandDepth =\n typeof depthHint === \"number\" && depthHint >= 0 ? depthHint : Infinity;\n const roots = Array.isArray(payload.data) ? payload.data : [payload.data];\n const list = el(\n \"ul\",\n { class: \"wg-tree\" },\n roots.map((node) => renderNode(node, 0, expandDepth))\n );\n // Title chrome from meta \u2014 tree data has no title slot, so meta is the\n // only source; absence means no title line.\n const title = payload.meta?.title;\n if (title === undefined) return list;\n return el(\"div\", { class: \"wg-tree-titled\" }, [\n el(\"div\", { class: \"wg-tree-title\" }, [formatValue(title)]),\n list\n ]);\n}\n\nfunction nodeLabel(node: unknown): string {\n if (isPlainObject(node)) {\n if (node.label !== undefined) return formatValue(node.label);\n const { children: _children, ...rest } = node;\n if (Object.keys(rest).length > 0) return formatValue(rest);\n }\n return formatValue(node);\n}\n\nfunction renderNode(\n node: unknown,\n depth: number,\n expandDepth: number\n): WidgetNode {\n const hasChildren =\n isPlainObject(node) &&\n Array.isArray(node.children) &&\n node.children.length > 0;\n\n // The expansion attribute marks expandable branches only \u2014 its presence\n // identifies a branch, its value the initial state. Leaves carry none.\n const attrs: WidgetNodeAttrs = hasChildren\n ? {\n class: \"wg-tree-node\",\n \"data-expanded\": depth < expandDepth ? \"true\" : \"false\"\n }\n : { class: \"wg-tree-node\" };\n\n const children: WidgetNode[] = [\n el(\"span\", { class: \"wg-tree-label\" }, [nodeLabel(node)])\n ];\n if (hasChildren) {\n children.push(\n el(\n \"ul\",\n { class: \"wg-tree-children\" },\n (node.children as unknown[]).map((child) =>\n renderNode(child, depth + 1, expandDepth)\n )\n )\n );\n }\n return el(\"li\", attrs, children);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\n\n/**\n * Built-in `custom` renderer \u2014 the generic escape hatch.\n *\n * Renders `data` as pretty-printed JSON in a preformatted block, falling\n * back to `String(data)` when serialization fails (circular data, bigint).\n * Hosts register richer kinds via the catalog's registration API.\n */\nexport function renderCustom(payload: WidgetPayload): WidgetNode {\n let text: string;\n try {\n text = JSON.stringify(payload.data, null, 2) ?? String(payload.data);\n } catch {\n text = String(payload.data);\n }\n return el(\"pre\", { class: \"wg-custom\" }, [text]);\n}\n", "/**\n * `group` built-in \u2014 several widgets in one render.\n *\n * The renderer here only builds the layout container; item rendering is\n * the catalog dispatch's job (items re-enter `catalog.render`, so\n * registered and composed kinds participate and per-item errors keep\n * their structured codes with `data.items[<i>]`-prefixed paths).\n */\nimport type { WidgetContractError } from \"../../contract/errors.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Hard cap on `data.items` \u2014 bounds total render work per call. */\nexport const GROUP_MAX_ITEMS = 20;\n\nexport const GROUP_LAYOUTS = [\"stack\", \"row\", \"grid\"] as const;\nexport const GROUP_GAPS = [\"none\", \"sm\", \"md\", \"lg\"] as const;\n/** `columns` is clamped into this range (grid only). */\nexport const GROUP_MAX_COLUMNS = 4;\n\nexport interface GroupItem {\n kind: string;\n data: unknown;\n hints?: unknown;\n meta?: unknown;\n}\n\nexport type GroupEnvelopeResult =\n | { ok: true; items: GroupItem[] }\n | { ok: false; error: WidgetContractError };\n\n/**\n * Validate the group envelope: `data.items` is an array of sub-widget\n * objects with string kinds, no nested groups, within the item cap.\n * Item *content* is not judged here \u2014 each item faces the full contract\n * and schema validation when it re-enters the catalog.\n */\nexport function checkGroupEnvelope(data: unknown): GroupEnvelopeResult {\n if (!isPlainObject(data) || data.items === undefined) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data.items\",\n message: \"'group' data must be an object with an 'items' array.\"\n }\n };\n }\n const items = data.items;\n if (!Array.isArray(items)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: \"'items' must be an array of sub-widgets.\"\n }\n };\n }\n if (items.length > GROUP_MAX_ITEMS) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: `'items' holds ${items.length} sub-widgets; a group renders at most ${GROUP_MAX_ITEMS}.`\n }\n };\n }\n const checked: GroupItem[] = [];\n for (let i = 0; i < items.length; i++) {\n const item: unknown = items[i];\n if (!isPlainObject(item)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}]`,\n message: \"each item must be an object: { kind, data, hints?, meta? }.\"\n }\n };\n }\n if (typeof item.kind !== \"string\" || item.kind === \"\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"each item needs a widget kind (non-empty string).\"\n }\n };\n }\n if (item.kind === \"group\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"a 'group' cannot contain another 'group'.\"\n }\n };\n }\n const entry: GroupItem = { kind: item.kind, data: item.data };\n if (item.hints !== undefined) entry.hints = item.hints;\n if (item.meta !== undefined) entry.meta = item.meta;\n checked.push(entry);\n }\n return { ok: true, items: checked };\n}\n\n/**\n * Build the layout container. Hints only ever SELECT from the fixed\n * class names below \u2014 no hint or data value contributes characters to\n * the class list. Unknown values fall back to the defaults (hint\n * diagnostics, not renderers, tell the caller).\n */\nexport function renderGroupContainer(\n hints: unknown,\n children: WidgetNode[]\n): WidgetNode {\n const h = isPlainObject(hints) ? hints : {};\n const layout = GROUP_LAYOUTS.some((known) => known === h.layout)\n ? (h.layout as string)\n : \"stack\";\n const gap = GROUP_GAPS.some((known) => known === h.gap)\n ? (h.gap as string)\n : \"md\";\n const classes = [`wg-group`, `wg-group-${layout}`, `wg-gap-${gap}`];\n if (layout === \"grid\") {\n const raw = typeof h.columns === \"number\" && Number.isFinite(h.columns) ? h.columns : 2;\n const columns = Math.min(GROUP_MAX_COLUMNS, Math.max(1, Math.trunc(raw)));\n classes.push(`wg-cols-${columns}`);\n }\n return el(\"div\", { class: classes.join(\" \") }, children);\n}\n", "import { validateWidgetPayload } from \"../contract/validate.js\";\nimport type { WidgetContractError } from \"../contract/errors.js\";\nimport type { WidgetKind } from \"../contract/types.js\";\nimport type { WidgetNode, WidgetRenderer } from \"./node.js\";\nimport type { WidgetDescriptor, WidgetDescriptorInput } from \"./descriptors.js\";\nimport { BUILTIN_DESCRIPTORS } from \"./descriptors.js\";\nimport { validateDataAgainstSchema } from \"./schema.js\";\nimport { renderCard } from \"./widgets/card.js\";\nimport { renderTable } from \"./widgets/table.js\";\nimport { renderTree } from \"./widgets/tree.js\";\nimport { renderCustom } from \"./widgets/custom.js\";\nimport { checkGroupEnvelope, renderGroupContainer } from \"./widgets/group.js\";\n\n/**\n * Group composition: an item's action descriptors were compiled against\n * the ITEM's template, so they name the item's kind (`widget`) but not\n * where the item sits in the group payload. Stamping `at` lets the server\n * fold an action's result back into the right item and re-render the whole\n * group. Returns a NEW tree \u2014 renderers may hand back cached nodes, and\n * composition must not mutate what a pure renderer returned. Groups do not\n * nest, so the location is always one level: `data.items.<i>`.\n */\nfunction stampActionLocation(node: WidgetNode, location: string): WidgetNode {\n if (typeof node === \"string\") return node;\n const raw = node.attrs?.[\"data-wg-action\"];\n let attrs = node.attrs;\n if (typeof raw === \"string\") {\n try {\n const descriptor = JSON.parse(raw) as Record<string, unknown>;\n if (typeof descriptor === \"object\" && descriptor !== null) {\n attrs = { ...node.attrs, \"data-wg-action\": JSON.stringify({ ...descriptor, at: location }) };\n }\n } catch {\n /* not a descriptor */\n }\n }\n const children = node.children?.map((child) => stampActionLocation(child, location));\n return {\n tag: node.tag,\n ...(attrs !== undefined ? { attrs } : {}),\n ...(children !== undefined ? { children } : {})\n };\n}\n\n/**\n * Thrown when a widget kind is registered twice on the same catalog.\n * Double registration is a host programming error, surfaced loudly at\n * setup time \u2014 unlike render-time errors, which are structured results.\n */\nexport class DuplicateKindError extends Error {\n readonly code: \"DUPLICATE_KIND\" = \"DUPLICATE_KIND\";\n readonly kind: string;\n\n constructor(kind: string) {\n super(`Widget kind '${kind}' is already registered.`);\n this.name = \"DuplicateKindError\";\n this.kind = kind;\n }\n}\n\n/** Discriminated result of `catalog.render` (mirrors the contract pattern). */\nexport type RenderResult =\n | { ok: true; node: WidgetNode }\n | { ok: false; error: WidgetContractError };\n\nexport interface WidgetCatalog {\n /**\n * Register a renderer for a new kind, optionally with agent-facing\n * documentation. Throws {@link DuplicateKindError} on duplicates\n * (built-ins included). Without a descriptor, a minimal one is generated\n * so every renderable kind stays listable.\n */\n register(\n kind: WidgetKind,\n renderer: WidgetRenderer,\n descriptor?: WidgetDescriptorInput\n ): void;\n has(kind: WidgetKind): boolean;\n resolve(kind: WidgetKind): WidgetRenderer | undefined;\n /** Currently registered kinds, as a fresh array. */\n kinds(): WidgetKind[];\n /** Descriptor for a kind, or undefined when the kind is unknown. */\n describe(kind: WidgetKind): WidgetDescriptor | undefined;\n /** All descriptors, as a fresh array. */\n list(): WidgetDescriptor[];\n /** Validate a payload against the contract (with this catalog's kinds) and render it. Never throws. */\n render(payload: unknown): RenderResult;\n}\n\n/**\n * Create an independent catalog instance with the built-ins (`card`,\n * `table`, `tree`, `custom`) pre-registered.\n */\nexport function createCatalog(): WidgetCatalog {\n const renderers = new Map<WidgetKind, WidgetRenderer>();\n const descriptors = new Map<WidgetKind, WidgetDescriptor>();\n\n const catalog: WidgetCatalog = {\n register(kind, renderer, descriptor) {\n if (renderers.has(kind)) throw new DuplicateKindError(kind);\n renderers.set(kind, renderer);\n descriptors.set(kind, {\n kind,\n description: descriptor?.description ?? `Custom widget kind '${kind}'.`,\n dataShape: descriptor?.dataShape ?? \"Defined by the registered renderer.\",\n ...(descriptor?.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {}),\n ...(descriptor?.hints ? { hints: descriptor.hints } : {}),\n ...(descriptor?.dataSchema ? { dataSchema: descriptor.dataSchema } : {}),\n ...(descriptor?.styles ? { styles: descriptor.styles } : {})\n });\n },\n has: (kind) => renderers.has(kind),\n resolve: (kind) => renderers.get(kind),\n kinds: () => [...renderers.keys()],\n describe: (kind) => descriptors.get(kind),\n list: () => [...descriptors.values()],\n render(payload) {\n const validated = validateWidgetPayload(payload, {\n knownKinds: new Set(renderers.keys())\n });\n if (!validated.ok) return validated;\n // Opt-in structural validation: kinds with a dataSchema fail fast\n // with a dotted data path instead of rendering a lenient fallback.\n const schema = descriptors.get(validated.payload.kind)?.dataSchema;\n if (schema) {\n const schemaError = validateDataAgainstSchema(\n schema,\n validated.payload.data\n );\n if (schemaError) return { ok: false, error: schemaError };\n }\n // `group` recurses through this same entry so registered and\n // composed kinds participate and per-item failures keep their\n // structured codes, re-pathed under `data.items[<i>]`. Renderers\n // stay pure `(payload) => WidgetNode`; composition is dispatch work.\n if (validated.payload.kind === \"group\") {\n const envelope = checkGroupEnvelope(validated.payload.data);\n if (!envelope.ok) return envelope;\n const children: WidgetNode[] = [];\n for (let i = 0; i < envelope.items.length; i++) {\n const item = envelope.items[i]!;\n const sub = catalog.render({\n kind: item.kind,\n data: item.data,\n ...(item.hints !== undefined ? { hints: item.hints } : {}),\n ...(item.meta !== undefined ? { meta: item.meta } : {})\n });\n if (!sub.ok) {\n const subPath = sub.error.path;\n return {\n ok: false,\n error: {\n ...sub.error,\n path: `data.items[${i}]${subPath ? `.${subPath}` : \"\"}`\n }\n };\n }\n children.push(stampActionLocation(sub.node, `data.items.${i}`));\n }\n return {\n ok: true,\n node: renderGroupContainer(validated.payload.hints, children)\n };\n }\n const renderer = renderers.get(validated.payload.kind);\n if (renderer === undefined) {\n // Unreachable while knownKinds is non-empty; kept for totality.\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${validated.payload.kind}'.`\n }\n };\n }\n // Built-ins are total by construction; this guards the extension\n // point \u2014 a registered renderer that throws must surface as a\n // structured error, never a propagated exception.\n try {\n return { ok: true, node: renderer(validated.payload) };\n } catch (thrown) {\n return {\n ok: false,\n error: {\n code: \"RENDER_FAILED\",\n path: \"widget\",\n message: `Renderer for kind '${validated.payload.kind}' threw: ${\n thrown instanceof Error ? thrown.message : String(thrown)\n }`\n }\n };\n }\n }\n };\n\n // Built-ins go through register() so they get the same duplicate\n // protection and hosts cannot silently override them.\n catalog.register(\"card\", renderCard, BUILTIN_DESCRIPTORS.card);\n catalog.register(\"table\", renderTable, BUILTIN_DESCRIPTORS.table);\n catalog.register(\"tree\", renderTree, BUILTIN_DESCRIPTORS.tree);\n catalog.register(\"custom\", renderCustom, BUILTIN_DESCRIPTORS.custom);\n // `render()` intercepts 'group' before renderer lookup, so this renderer\n // only serves direct `resolve()` callers (e.g. designer previews); it\n // delegates back through the dispatch so items render for them too.\n catalog.register(\n \"group\",\n (payload) => {\n const result = catalog.render(payload);\n if (result.ok) return result.node;\n throw new Error(result.error.message);\n },\n BUILTIN_DESCRIPTORS.group\n );\n\n return catalog;\n}\n", "/**\n * Registered widget styles: custom kinds ship their look as data alongside\n * their template/renderer. Same trust model as themes \u2014 designer-authored,\n * so selectors, properties, and values are all guarded, and unsafe entries\n * are skipped rather than emitted.\n */\nexport type WidgetStyles = Record<string, Record<string, string>>;\n\n/** Substrings that disqualify a selector, property or value. Exported\n * so the authoring guide derives the rule instead of restating it. */\nexport const UNSAFE = /[;{}<>@\\\\]/;\n/** The property-name allowlist: not merely \"no banned characters\". */\nexport const PROPERTY_NAME = /^-?[a-zA-Z][a-zA-Z-]*$/;\n\n/** Every comma-separated selector part must target a .wg- class. */\nfunction isSafeSelector(selector: string): boolean {\n if (UNSAFE.test(selector)) return false;\n const parts = selector.split(\",\").map((part) => part.trim());\n return parts.length > 0 && parts.every((part) => part.includes(\".wg-\"));\n}\n\nfunction isSafeValue(value: string): boolean {\n return (\n !UNSAFE.test(value) &&\n !/url\\s*\\(/i.test(value) &&\n !/expression\\s*\\(/i.test(value)\n );\n}\n\n/**\n * Generate CSS from a styles map, emitting only guarded entries. Values may\n * reference theme tokens via `var(--wg-*)`. Never throws.\n */\nexport function widgetStylesToCss(styles: WidgetStyles): string {\n const rules: string[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (!isSafeSelector(selector)) continue;\n if (typeof declarations !== \"object\" || declarations === null) continue;\n const lines: string[] = [];\n for (const [property, value] of Object.entries(declarations)) {\n if (!PROPERTY_NAME.test(property)) continue;\n if (typeof value !== \"string\" || !isSafeValue(value)) continue;\n lines.push(` ${property}: ${value};`);\n }\n if (lines.length > 0) {\n rules.push(`${selector} {\\n${lines.join(\"\\n\")}\\n}`);\n }\n }\n return rules.join(\"\\n\");\n}\n", "/**\n * Theme token registry. Tokens are the only theming surface: the base\n * stylesheet reads them via `var(--wg-<token>, <default>)` and themes are\n * plain maps of bare token names to values. The defaults table is the\n * single source of truth for the light look.\n */\n/**\n * The token table: every token's default, its VALUE TYPE, and what it is\n * for. Type metadata is not decoration \u2014 tooling reads it (the theme\n * designer picks a color picker vs a text field from `type`, never by\n * guessing at the default's shape) and `list_theme_tokens` tells agents\n * what kind of value each token expects. `use` doubles as the\n * documentation that earns a token its place when the base stylesheet\n * cannot consume it.\n */\nexport type TokenType =\n | \"color\"\n | \"dimension\"\n | \"number\"\n | \"font-family\"\n | \"font-weight\"\n | \"shadow\";\n\nexport interface TokenSpec {\n default: string;\n type: TokenType;\n use: string;\n /**\n * Token this one inherits from when a theme leaves it unset. Declared\n * here rather than special-cased in the stylesheet because a literal\n * default at `:root` would sever that inheritance: a `var()` fallback\n * applies only when the property is UNSET, so defining\n * `--wg-surface: #ffffff` makes `var(--wg-surface, var(--wg-bg, \u2026))`\n * unreachable. The defaults block emits a chain for these instead.\n */\n fallback?: string;\n}\n\nexport const TOKEN_SPECS = {\n bg: { default: \"#ffffff\", type: \"color\", use: \"Page background behind widgets.\" },\n surface: {\n default: \"#ffffff\",\n type: \"color\",\n fallback: \"bg\",\n use: \"Widget panel background (cards, tables); falls back to bg when unset.\"\n },\n fg: { default: \"#1f2430\", type: \"color\", use: \"Primary text.\" },\n muted: { default: \"#6b7280\", type: \"color\", use: \"Secondary text: labels, captions, keys.\" },\n accent: { default: \"#2563eb\", type: \"color\", use: \"Emphasis: titles, links, filled badges.\" },\n \"accent-fg\": {\n default: \"#ffffff\",\n type: \"color\",\n use: \"Text drawn on an accent fill (filled badges and buttons).\"\n },\n border: { default: \"#e2e8f0\", type: \"color\", use: \"Hairlines: panel edges, row rules.\" },\n \"border-width\": { default: \"1px\", type: \"dimension\", use: \"Width of those hairlines.\" },\n radius: { default: \"6px\", type: \"dimension\", use: \"Default corner rounding.\" },\n \"radius-sm\": { default: \"3px\", type: \"dimension\", use: \"Tight rounding: pills, chips, inline marks.\" },\n \"radius-lg\": { default: \"12px\", type: \"dimension\", use: \"Generous rounding: hero media, large panels.\" },\n spacing: { default: \"8px\", type: \"dimension\", use: \"Base spacing step.\" },\n \"spacing-sm\": { default: \"4px\", type: \"dimension\", use: \"Half step: inline gaps inside a row.\" },\n \"spacing-lg\": { default: \"16px\", type: \"dimension\", use: \"Double step: section separation.\" },\n \"font-family\": {\n default: \"system-ui, -apple-system, 'Segoe UI', sans-serif\",\n type: \"font-family\",\n use: \"Body text family.\"\n },\n \"font-mono\": {\n default: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n type: \"font-family\",\n use: \"Monospace family for code and raw JSON (the custom kind).\"\n },\n \"font-size\": { default: \"14px\", type: \"dimension\", use: \"Body text size.\" },\n \"font-size-sm\": { default: \"12px\", type: \"dimension\", use: \"Small text: captions, stats, pills.\" },\n \"font-size-lg\": { default: \"18px\", type: \"dimension\", use: \"Large text: widget titles.\" },\n \"font-weight-bold\": {\n default: \"600\",\n type: \"font-weight\",\n use: \"Weight for titles and emphasized labels.\"\n },\n \"line-height\": { default: \"1.45\", type: \"number\", use: \"Text density.\" },\n shadow: {\n default: \"0 1px 3px rgba(0, 0, 0, 0.12)\",\n type: \"shadow\",\n use: \"Panel elevation.\"\n },\n danger: { default: \"#b91c1c\", type: \"color\", use: \"Error status: fills and text (see .wg-status-danger).\" },\n \"danger-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a danger fill.\" },\n success: { default: \"#15803d\", type: \"color\", use: \"Success status (see .wg-status-success).\" },\n \"success-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a success fill.\" },\n warning: { default: \"#b45309\", type: \"color\", use: \"Warning status (see .wg-status-warning).\" },\n \"warning-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a warning fill.\" },\n info: { default: \"#0369a1\", type: \"color\", use: \"Informational status (see .wg-status-info).\" },\n \"info-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on an info fill.\" },\n \"avatar-size\": { default: \"32px\", type: \"dimension\", use: \"Box of .wg-img-avatar images.\" },\n \"thumb-size\": { default: \"48px\", type: \"dimension\", use: \"Box of .wg-img-thumb images.\" }\n} as const satisfies Record<string, TokenSpec>;\n\n/** Default value per token \u2014 derived, so the table stays the one source. */\nexport const TOKEN_DEFAULTS = Object.fromEntries(\n Object.entries(TOKEN_SPECS).map(([name, spec]) => [name, spec.default])\n) as { [K in keyof typeof TOKEN_SPECS]: (typeof TOKEN_SPECS)[K][\"default\"] };\n\nexport type ThemeToken = keyof typeof TOKEN_SPECS;\n\n/** All theme token names, in defaults-table order. */\nexport const THEME_TOKENS: readonly ThemeToken[] = Object.keys(\n TOKEN_SPECS\n) as ThemeToken[];\n\n/**\n * A theme: bare token names to CSS values. Bare keys make unknown-token\n * validation trivial and structurally prevent setting arbitrary custom\n * properties \u2014 the `--wg-` prefix is always applied by this module.\n */\nexport type WidgetTheme = Partial<Record<ThemeToken, string>>;\n\n/**\n * A theme plus author-defined `x-*` variables (emitted as `--wg-x-<name>`).\n * Kept as a separate type on purpose: `WidgetTheme` has only optional\n * properties, which is what makes TypeScript reject `{ sneaky: \"red\" }` via\n * weak-type detection \u2014 an index signature here would silently disable that\n * protection for every consumer. Functions accept this wider input; the\n * runtime validator is the authority on which keys are legal.\n */\nexport type WidgetThemeInput = WidgetTheme &\n Partial<Record<`x-${string}`, string>>;\n\nexport type ThemeErrorCode =\n | \"INVALID_THEME\"\n | \"UNKNOWN_TOKEN\"\n | \"INVALID_TOKEN_VALUE\";\n\nexport interface ThemeError {\n code: ThemeErrorCode;\n message: string;\n /** Offending token name, when applicable. */\n token?: string;\n}\n\n/**\n * Value guard shared by validation (strict) and application (lenient\n * defense in depth). Rejects exfiltration and execution vectors \u2014 not\n * invalid CSS: declaration/HTML escapes, `url()` (resource fetching), and\n * `expression()` (legacy script execution in old embedded webviews).\n */\nexport function isSafeTokenValue(value: string): boolean {\n return (\n !/[;{}<>]/.test(value) &&\n !/url\\s*\\(/i.test(value) &&\n !/expression\\s*\\(/i.test(value)\n );\n}\n", "import type { ThemeToken } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_DEFAULTS } from \"./tokens.js\";\n\n/** `var(--wg-<token>, <light default>)` \u2014 every themeable knob goes through this. */\nfunction v(token: ThemeToken): string {\n return `var(--wg-${token}, ${TOKEN_DEFAULTS[token]})`;\n}\n\n/**\n * Every registry token DEFINED at :root with its default, so custom\n * widget styles may reference bare `var(--wg-<token>)` and always\n * resolve. The built-in rules below carry their own fallbacks and never\n * needed this; custom authors write plain references (per the authoring\n * guide), and before this block an applied theme was the only thing that\n * defined tokens \u2014 every token it didn't set silently collapsed the\n * author's declaration (observed live: a valid widget rendered jammed\n * because `--wg-spacing-lg` was \"not defined\"). Themes override these\n * (later style elements and element-level applyTheme both win).\n *\n * Literals only \u2014 a chain here would NOT work: `--wg-surface:\n * var(--wg-bg, \u2026)` substitutes against `:root`'s own `--wg-bg` at\n * computed-value time and inherits that resolved value, so a descendant\n * overriding `--wg-bg` never reaches it. Tokens declaring a `fallback`\n * are resolved where the theme is applied instead (see `withFallbacks`\n * in apply.ts); this block only guarantees a bare `var(--wg-<token>)`\n * always resolves to something.\n */\nconst tokenDefaultsBlock = `:root {\n${THEME_TOKENS.map((token) => ` --wg-${token}: ${TOKEN_DEFAULTS[token]};`).join(\"\\n\")}\n}`;\n\n/**\n * Predefined styles for the built-in `wg-*` classes. Generated from the\n * token defaults table, so the light theme lives in exactly one place and\n * every visual knob is overridable by a theme.\n */\nexport const baseStylesheet = `\n${tokenDefaultsBlock}\n.wg-card, .wg-table, .wg-tree, .wg-custom, .wg-template {\n font-family: ${v(\"font-family\")};\n font-size: ${v(\"font-size\")};\n line-height: ${v(\"line-height\")};\n color: ${v(\"fg\")};\n}\n.wg-card {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius-lg\")};\n box-shadow: ${v(\"shadow\")};\n padding: ${v(\"spacing-lg\")};\n}\n.wg-card-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-subtitle {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-fields {\n margin: 0;\n}\n.wg-card-field {\n display: flex;\n gap: ${v(\"spacing\")};\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-card-field-key {\n color: ${v(\"muted\")};\n}\n.wg-card-field-value {\n margin: 0;\n}\n.wg-table {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n border-collapse: collapse;\n}\n.wg-table-header {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n text-align: left;\n border-bottom: calc(${v(\"border-width\")} * 2) solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-table-cell {\n border-bottom: ${v(\"border-width\")} solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-tree {\n list-style: none;\n margin: 0;\n padding-left: 0;\n}\n.wg-tree-children {\n list-style: none;\n padding-left: ${v(\"spacing-lg\")};\n border-left: ${v(\"border-width\")} solid ${v(\"border\")};\n}\n.wg-tree-node {\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-tree-node[data-expanded=\"false\"] > .wg-tree-children {\n display: none;\n}\n.wg-custom {\n font-family: ${v(\"font-mono\")};\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n padding: ${v(\"spacing\")};\n overflow: auto;\n}\n.wg-status {\n display: inline-block;\n padding: 0 ${v(\"spacing-sm\")};\n border-radius: ${v(\"radius-sm\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n}\n.wg-status-danger { background: ${v(\"danger\")}; color: ${v(\"danger-fg\")}; }\n.wg-status-success { background: ${v(\"success\")}; color: ${v(\"success-fg\")}; }\n.wg-status-warning { background: ${v(\"warning\")}; color: ${v(\"warning-fg\")}; }\n.wg-status-info { background: ${v(\"info\")}; color: ${v(\"info-fg\")}; }\n.wg-status-accent { background: ${v(\"accent\")}; color: ${v(\"accent-fg\")}; }\n.wg-img {\n object-fit: cover;\n vertical-align: middle;\n background: ${v(\"border\")};\n}\n.wg-img-avatar {\n width: ${v(\"avatar-size\")};\n height: ${v(\"avatar-size\")};\n border-radius: 50%;\n}\n.wg-img-thumb {\n width: ${v(\"thumb-size\")};\n height: ${v(\"thumb-size\")};\n border-radius: ${v(\"radius\")};\n}\n.wg-img-hero {\n display: block;\n width: 100%;\n max-width: 100%;\n height: auto;\n border-radius: ${v(\"radius\")};\n}\n.wg-table-caption {\n caption-side: top;\n text-align: left;\n padding-bottom: ${v(\"spacing\")};\n}\n.wg-table-title {\n display: block;\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing-sm\")};\n}\n.wg-table-subtitle {\n display: block;\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n}\n.wg-tree-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-link {\n color: ${v(\"accent\")};\n text-decoration: underline;\n}\n.wg-group {\n display: flex;\n flex-direction: column;\n}\n.wg-group-row {\n flex-direction: row;\n flex-wrap: wrap;\n}\n.wg-group-row > * {\n flex: 1 1 240px;\n min-width: 0;\n}\n.wg-group-grid {\n display: grid;\n}\n.wg-group-grid > * {\n min-width: 0;\n}\n.wg-cols-1 { grid-template-columns: 1fr; }\n.wg-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }\n.wg-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }\n.wg-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }\n.wg-gap-none { gap: 0; }\n.wg-gap-sm { gap: ${v(\"spacing-sm\")}; }\n.wg-gap-md { gap: ${v(\"spacing\")}; }\n.wg-gap-lg { gap: ${v(\"spacing-lg\")}; }\n`.trim();\n\nconst STYLE_MARKER = \"data-widgentic\";\n\n/**\n * Append the base stylesheet to the document head as a marked `<style>`\n * element. Idempotent: repeated calls leave exactly one element.\n */\nexport function injectBaseStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"base\");\n style.textContent = baseStylesheet;\n doc.head.appendChild(style);\n}\n", "import type { ThemeError, TokenSpec, WidgetTheme, WidgetThemeInput } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_SPECS, isSafeTokenValue } from \"./tokens.js\";\n\nexport type ValidateThemeResult =\n | { ok: true; theme: WidgetThemeInput }\n | { ok: false; error: ThemeError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst KNOWN_TOKENS: ReadonlySet<string> = new Set(THEME_TOKENS);\n\n/**\n * Author-defined variables: `x-<name>` keys are accepted alongside registry\n * tokens and emitted as `--wg-x-<name>`. This is the sanctioned escape\n * hatch for custom widgets that need their own knobs, so the registry does\n * not have to grow for every one-off. Names are lowercase/kebab so the\n * generated custom property is always a valid CSS identifier. Exported so\n * tooling states this rule by reading it, never by restating it.\n */\nexport const CUSTOM_VARIABLE = /^x-[a-z0-9][a-z0-9-]*$/;\n\n/** Custom-variable keys carried by a theme, in declaration order. */\nfunction customKeys(theme: WidgetThemeInput): string[] {\n return Object.keys(theme).filter((key) => CUSTOM_VARIABLE.test(key));\n}\n\n/** The `--wg-*` property name a theme key maps to. */\nfunction propertyName(key: string): string {\n return `--wg-${key}`;\n}\n\n/** Validate an unknown value as a theme. Never throws. */\nexport function validateTheme(input: unknown): ValidateThemeResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: { code: \"INVALID_THEME\", message: \"Theme must be a plain object.\" }\n };\n }\n for (const [token, value] of Object.entries(input)) {\n if (!KNOWN_TOKENS.has(token) && !CUSTOM_VARIABLE.test(token)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_TOKEN\",\n message:\n `Unknown theme token '${token}'. Use a registry token, or a ` +\n `custom variable named 'x-<lowercase-kebab>'.`,\n token\n }\n };\n }\n if (typeof value !== \"string\" || !isSafeTokenValue(value)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TOKEN_VALUE\",\n message: `Token '${token}' has an invalid or unsafe value.`,\n token\n }\n };\n }\n }\n return { ok: true, theme: input as WidgetThemeInput };\n}\n\n/**\n * Fill in tokens a theme left unset that declare a `fallback`, using the\n * fallback token's value FROM THIS THEME.\n *\n * This cannot live in the base stylesheet: a `:root` chain\n * (`--wg-surface: var(--wg-bg, \u2026)`) substitutes against `:root`'s own\n * `--wg-bg` at computed-value time and then inherits that resolved\n * value, so a descendant overriding `--wg-bg` never reaches it. Resolving\n * where the theme is applied puts both declarations on the same element,\n * which is the only place the relationship holds (observed live at v24: a\n * bg-only dark theme painted white cards).\n */\nfunction withFallbacks(theme: WidgetThemeInput): WidgetThemeInput {\n const source = theme as Record<string, unknown>;\n let filled: Record<string, unknown> | undefined;\n for (const token of THEME_TOKENS) {\n const { fallback } = TOKEN_SPECS[token] as TokenSpec;\n if (fallback === undefined) continue;\n if (typeof source[token] === \"string\") continue; // theme set it explicitly\n const inherited = source[fallback];\n if (typeof inherited !== \"string\") continue; // nothing to inherit from\n filled ??= { ...source };\n filled[token] = inherited;\n }\n return (filled ?? theme) as WidgetThemeInput;\n}\n\n/**\n * Apply a theme to a container as inline `--wg-*` custom properties\n * (scoped: descendants inherit them; siblings are unaffected). Replace\n * semantics \u2014 previously applied tokens are removed first, so\n * `applyTheme(el, {})` resets to the stylesheet defaults. Invalid entries\n * are skipped; the CSSOM path (`setProperty`) parses no stylesheet text,\n * so declaration escape is structurally impossible here.\n */\nexport function applyTheme(container: Element, input: WidgetThemeInput): void {\n const theme = withFallbacks(input);\n const style = (container as Partial<ElementCSSInlineStyle>).style;\n if (!style) return;\n // Replace semantics: clear every property this module could have set,\n // custom variables included (they are removed by name from the inline\n // style, which is the only place applyTheme writes).\n for (const token of THEME_TOKENS) {\n style.removeProperty(propertyName(token));\n }\n for (let i = style.length - 1; i >= 0; i--) {\n const property = style.item(i);\n if (property.startsWith(\"--wg-x-\")) style.removeProperty(property);\n }\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n style.setProperty(propertyName(key), value);\n }\n }\n}\n\n/**\n * Generate a CSS rule assigning the theme's tokens under `selector`\n * (default `:root`). Only entries passing the safety guard are emitted.\n */\nexport function themeToCss(input: WidgetThemeInput, selector = \":root\"): string {\n const theme = withFallbacks(input);\n const declarations: string[] = [];\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n declarations.push(` ${propertyName(key)}: ${value};`);\n }\n }\n return `${selector} {\\n${declarations.join(\"\\n\")}\\n}`;\n}\n\n/** Dark preset \u2014 ordinary theme data, a starting point for custom themes. */\nexport const darkTheme: WidgetTheme = {\n bg: \"#0f131c\",\n surface: \"#161b26\",\n fg: \"#e5e9f0\",\n muted: \"#8b93a7\",\n accent: \"#7aa2f7\",\n \"accent-fg\": \"#0f131c\",\n border: \"#2a3140\",\n shadow: \"0 1px 3px rgba(0, 0, 0, 0.6)\",\n danger: \"#f0a3a3\",\n success: \"#8fd19e\",\n warning: \"#e8b878\",\n info: \"#7cc4e8\"\n};\n", "/**\n * The one `isPlainObject`. Every entry imports it relatively, so the\n * zero-dependency entries stay zero-dependency and the source-scan tests\n * keep passing.\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "/**\n * Safety constants shared by validation (strict) and interpretation\n * (lenient defense in depth). Both layers MUST consult these \u2014 keeping them\n * in one module is what prevents the two from drifting. URL safety itself\n * lives in the contract layer (`contract/urls.ts`) so the catalog's image\n * rendering shares the exact same rules; re-exported here to keep this\n * module the single import point for template safety.\n */\nexport {\n ALLOWED_SCHEMES,\n isSafeUrl,\n isSafeImageSrc\n} from \"../contract/urls.js\";\n\n/**\n * Attributes that are code or embedded documents: event handlers (`on*`)\n * and `srcdoc`, which smuggles a whole document past the tag policy.\n */\nexport const FORBIDDEN_ATTR = /^(?:on.*|srcdoc)$/i;\n\n/**\n * Tags that introduce active or foreign content into the frame. A template\n * is data, never a program: these fail validation and render as nothing\n * when validation was bypassed \u2014 the same two-layer stance as `on*`.\n */\nexport const FORBIDDEN_TAGS: ReadonlySet<string> = new Set([\n \"script\", \"iframe\", \"frame\", \"frameset\", \"object\", \"embed\", \"style\",\n \"link\", \"meta\", \"base\", \"template\", \"noscript\"\n]);\n\n/**\n * Renderer-owned attributes (`data-wg-*`): action descriptors and render\n * markers. Authors cannot write them \u2014 only a validated `action` binding\n * produces one \u2014 so a hand-written descriptor never reaches a tree.\n */\nexport const RESERVED_ATTR = /^data-wg-/i;\n\n/** Attributes whose values are URLs and can smuggle script schemes. */\nexport const URL_ATTRS = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"data\",\n \"poster\",\n \"ping\"\n]);\n\n/** Maximum template nesting depth accepted by validation. */\nexport const MAX_TEMPLATE_DEPTH = 64;\n", "/**\n * The template path grammar, shared by validation (strict) and\n * interpretation (lenient) so the two never drift:\n *\n * \".\" the current scope itself\n * \"$index\" zero-based position in the innermost `each`\n * \"$meta.<segments>\" reads payload.meta\n * \"$root[.<segments>]\" reads payload.data regardless of `each` nesting\n * \"$parent\"+ [.<rest>] steps out of one enclosing `each` per token;\n * <rest> is segments, \"$index\", or nothing\n * \"<segments>\" dot path against the current scope\n *\n * Reserved tokens (`$meta`, `$root`, `$parent`, `$index`) are only valid in\n * the positions above; anywhere else the path is invalid.\n */\nexport interface ParsedPath {\n base: \"scope\" | \"meta\" | \"root\";\n /** Enclosing-scope hops (`$parent` count). */\n up: number;\n /** The path names the current index rather than a value. */\n index: boolean;\n segments: string[];\n}\n\nconst RESERVED = new Set([\"$meta\", \"$root\", \"$parent\", \"$index\"]);\n\n/** Parse a path; `undefined` when the syntax is invalid. Never throws. */\nexport function parsePath(value: string): ParsedPath | undefined {\n if (value === \".\") return { base: \"scope\", up: 0, index: false, segments: [] };\n const tokens = value.split(\".\");\n let i = 0;\n let base: ParsedPath[\"base\"] = \"scope\";\n let up = 0;\n if (tokens[0] === \"$meta\") {\n base = \"meta\";\n i = 1;\n } else if (tokens[0] === \"$root\") {\n base = \"root\";\n i = 1;\n } else {\n while (tokens[i] === \"$parent\") {\n up++;\n i++;\n }\n }\n const rest = tokens.slice(i);\n if (rest.length === 1 && rest[0] === \"$index\") {\n if (base !== \"scope\") return undefined;\n return { base, up, index: true, segments: [] };\n }\n if (rest.length === 0) {\n if (base === \"meta\") return undefined;\n return { base, up, index: false, segments: [] };\n }\n if (rest.some((segment) => segment === \"\" || RESERVED.has(segment))) return undefined;\n return { base, up, index: false, segments: rest };\n}\n", "/**\n * The action model: what a widget can ask for when a person activates a\n * bound element. Two kinds \u2014 `prompt` proposes a user message through the\n * host, `http` performs a server-side request against an author-declared\n * URL \u2014 both plain JSON data, storable and validatable, never code.\n *\n * Zero-dependency by design: this module is shared by the template\n * compiler (which resolves bindings into descriptors at render time), the\n * store (which validates stored actions), the server (which executes) and\n * the designers (which edit).\n */\nimport type { DataSchema } from \"../catalog/index.js\";\n\n/** A prompt's text: literals and `{ bind }` segments resolved at render time. */\nexport type PromptSegment = string | { bind: string };\n\nexport interface PromptActionDefinition {\n kind: \"prompt\";\n text: PromptSegment[];\n}\n\n/** A by-name reference to one of the principal's secrets. */\nexport interface SecretRef {\n secret: string;\n}\n\n/** Header and query values: author literals or secret references. */\nexport type HeaderValue = string | SecretRef;\n\nexport type HttpMethod = \"GET\" | \"POST\";\n\nexport interface HttpActionDefinition {\n kind: \"http\";\n method: HttpMethod;\n /** Absolute https URL, fixed by the author \u2014 bindings never reach it. */\n url: string;\n /** JSON Schema (`type: \"object\"`) of the arguments. */\n input: DataSchema;\n /** JSON Schema the response body must satisfy. */\n output: DataSchema;\n headers?: Record<string, HeaderValue>;\n query?: Record<string, HeaderValue>;\n}\n\nexport type ActionDefinition = PromptActionDefinition | HttpActionDefinition;\n\n/** A shared, named action a principal owns. */\nexport interface StoredAction {\n name: string;\n label?: string;\n description?: string;\n definition: ActionDefinition;\n}\n\n/** Input mapping: input-schema field \u2192 template path or literal. */\nexport type InputMapping = Record<string, string | { const: unknown }>;\n\nexport type OutputMode = \"replace\" | \"merge\" | \"patch\";\n\nexport interface OutputBinding {\n /** Default `merge`. */\n mode?: OutputMode;\n /** Required for `patch`: the dotted data path the response is written at. */\n path?: string;\n /** Projection applied first: target data path \u2192 source response path. */\n map?: Record<string, string>;\n}\n\n/**\n * A binding names an action \u2014 a shared one by `ref`, or an inline one\n * under `definition` (nested so the definition's `input`/`output` schemas\n * never collide with the binding's `input` mapping and `output` mode) \u2014\n * plus how data flows.\n */\nexport type ActionBinding = ({ ref: string } | { definition: ActionDefinition }) & {\n input?: InputMapping;\n output?: OutputBinding;\n};\n\n/** Why an action renders unavailable. */\nexport type ActionDisabledReason = \"scope\" | \"unresolved\";\n\n/**\n * What a rendered element carries in `data-wg-action`: everything the\n * bridge needs, nothing it must evaluate.\n */\nexport interface ActionDescriptor {\n /** Binding identifier: the element's dotted template path, or \"load\". */\n id: string;\n kind?: ActionDefinition[\"kind\"];\n /** Resolved http arguments. */\n args?: Record<string, unknown>;\n /** Resolved prompt text. */\n text?: string;\n disabled?: ActionDisabledReason;\n /** The kind whose template declared the binding (set when registered). */\n widget?: string;\n /**\n * Inside a `group` render: the dotted path of the item payload within the\n * root payload (e.g. `data.items.2`), stamped by the group composition.\n */\n at?: string;\n}\n\n/** Structured validation error; `path` is dotted, relative to the caller's root. */\nexport interface ActionError {\n code: \"INVALID_ACTION\";\n message: string;\n path: string;\n}\n\n/** Upper bound on a resolved prompt message. */\nexport const PROMPT_TEXT_MAX = 2_000;\n\n/** Secret names: short, lowercase, URL- and header-safe. */\nexport const SECRET_NAME = /^[a-z][a-z0-9-]{0,63}$/;\n\n/** Action names share the secret-name discipline. */\nexport const ACTION_NAME = SECRET_NAME;\n\nexport const OUTPUT_MODES: readonly OutputMode[] = [\"replace\", \"merge\", \"patch\"];\n\nexport const HTTP_METHODS: readonly HttpMethod[] = [\"GET\", \"POST\"];\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type {\n ActionDefinition,\n ActionError\n} from \"./types.js\";\nimport {\n HTTP_METHODS,\n OUTPUT_MODES,\n PROMPT_TEXT_MAX,\n SECRET_NAME\n} from \"./types.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction fail(message: string, path: string): ActionError {\n return { code: \"INVALID_ACTION\", message, path };\n}\n\n/** RFC 7230 token: what a header or query parameter NAME may be. */\nconst HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\n/** Header names the transport owns; an author must not set them. */\nconst RESERVED_HEADERS: ReadonlySet<string> = new Set([\n \"host\", \"content-length\", \"transfer-encoding\", \"connection\"\n]);\n\n/** Segments that would reach the prototype chain or the template grammar's reserved tokens. */\nconst FORBIDDEN_SEGMENTS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * The dotted-path grammar for output `path` and `map` entries: non-empty\n * segments, no `$`-tokens, nothing that addresses a prototype.\n */\nexport function isDataPath(value: string): boolean {\n if (value === \"\") return false;\n return value.split(\".\").every(\n (segment) => segment !== \"\" && !segment.startsWith(\"$\") && !FORBIDDEN_SEGMENTS.has(segment)\n );\n}\n\n/** A header/query value: literal string or `{ secret: name }`. */\nfunction checkHeaderValue(value: unknown, path: string): ActionError | undefined {\n if (typeof value === \"string\") return undefined;\n if (isPlainObject(value) && typeof value.secret === \"string\") {\n if (!SECRET_NAME.test(value.secret)) {\n return fail(`Secret reference '${value.secret}' is not a valid secret name.`, path);\n }\n if (Object.keys(value).length !== 1) {\n return fail(\"A secret reference carries only 'secret'.\", path);\n }\n return undefined;\n }\n return fail(\"Value must be a string or a { secret } reference.\", path);\n}\n\n/** Does any nested value look like a secret reference? */\nfunction containsSecretRef(value: unknown): boolean {\n if (!isPlainObject(value) && !Array.isArray(value)) return false;\n if (isPlainObject(value) && typeof value.secret === \"string\") return true;\n const entries = Array.isArray(value) ? value : Object.values(value);\n return entries.some(containsSecretRef);\n}\n\nfunction checkUrl(url: unknown, path: string): ActionError | undefined {\n if (typeof url !== \"string\" || url.length === 0) {\n return fail(\"'url' must be a non-empty string.\", path);\n }\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return fail(`'url' must be an absolute URL (got '${url}').`, path);\n }\n if (parsed.protocol !== \"https:\") return fail(\"'url' must use https.\", path);\n if (parsed.username !== \"\" || parsed.password !== \"\") {\n return fail(\"'url' must not carry userinfo.\", path);\n }\n if (parsed.hash !== \"\") return fail(\"'url' must not carry a fragment.\", path);\n return undefined;\n}\n\n/**\n * Validate an action definition. `path` locates it for the caller (an\n * element's `action`, a stored action's `definition`). Never throws.\n */\nexport interface DefinitionCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n}\n\nexport function validateActionDefinition(\n input: unknown,\n path = \"\",\n options: DefinitionCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action definition must be an object.\", path);\n if (input.kind === \"prompt\") {\n if (!Array.isArray(input.text)) {\n return fail(\"'text' must be an array of literals and { bind } segments.\", join(path, \"text\"));\n }\n let literal = 0;\n for (let i = 0; i < input.text.length; i++) {\n const segment = input.text[i];\n if (typeof segment === \"string\") {\n literal += segment.length;\n continue;\n }\n if (isPlainObject(segment) && typeof segment.bind === \"string\" && Object.keys(segment).length === 1) {\n if (options.isPath && !options.isPath(segment.bind)) {\n return fail(`Invalid data path '${segment.bind}'.`, join(path, `text.${i}`));\n }\n continue;\n }\n return fail(\"Prompt segments are strings or { bind } objects.\", join(path, `text.${i}`));\n }\n if (literal > PROMPT_TEXT_MAX) {\n return fail(`Prompt text exceeds ${PROMPT_TEXT_MAX} characters.`, join(path, \"text\"));\n }\n return undefined;\n }\n if (input.kind === \"http\") {\n if (!HTTP_METHODS.some((m) => m === input.method)) {\n return fail(\"'method' must be GET or POST.\", join(path, \"method\"));\n }\n const urlError = checkUrl(input.url, join(path, \"url\"));\n if (urlError) return urlError;\n if (!isPlainObject(input.input) || input.input.type !== \"object\") {\n return fail(\"'input' must be a JSON Schema with type \\\"object\\\".\", join(path, \"input\"));\n }\n if (containsSecretRef(input.input)) {\n return fail(\"Secret references are allowed only in headers and query.\", join(path, \"input\"));\n }\n if (!isPlainObject(input.output)) {\n return fail(\"'output' must be a JSON Schema object.\", join(path, \"output\"));\n }\n for (const field of [\"headers\", \"query\"] as const) {\n const map = input[field];\n if (map === undefined) continue;\n if (!isPlainObject(map)) return fail(`'${field}' must be an object.`, join(path, field));\n for (const [name, value] of Object.entries(map)) {\n const namePath = join(path, `${field}.${name}`);\n if (!HEADER_TOKEN.test(name)) {\n return fail(`'${name}' is not a valid ${field === \"headers\" ? \"header\" : \"parameter\"} name.`, namePath);\n }\n if (field === \"headers\" && RESERVED_HEADERS.has(name.toLowerCase())) {\n return fail(`Header '${name}' is set by the transport and cannot be declared.`, namePath);\n }\n const error = checkHeaderValue(value, namePath);\n if (error) return error;\n }\n }\n return undefined;\n }\n return fail(\"'kind' must be \\\"prompt\\\" or \\\"http\\\".\", join(path, \"kind\"));\n}\n\nexport interface BindingCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n /** Resolve a `ref` to its definition when the caller knows the catalog. */\n resolve?: (ref: string) => ActionDefinition | undefined;\n /** `load` bindings: http GET only. */\n loadOnly?: boolean;\n}\n\nfunction definitionOf(\n binding: Record<string, unknown>,\n options: BindingCheckOptions\n): ActionDefinition | undefined {\n if (typeof binding.ref === \"string\") return options.resolve?.(binding.ref);\n return binding.definition as ActionDefinition | undefined;\n}\n\n/**\n * Validate a binding: `{ ref }` or an inline definition, plus `input` and\n * `output`. When the definition is known (inline, or resolved through\n * `options.resolve`), input keys are checked against its input schema and\n * `load` bindings are held to http GET. Never throws.\n */\nexport function validateActionBinding(\n input: unknown,\n path = \"\",\n options: BindingCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action binding must be an object.\", path);\n const hasRef = \"ref\" in input;\n if (hasRef) {\n if (typeof input.ref !== \"string\" || input.ref.length === 0) {\n return fail(\"'ref' must name a shared action.\", join(path, \"ref\"));\n }\n if (\"definition\" in input) return fail(\"A binding is either a { ref } or a { definition }, not both.\", path);\n if (options.resolve && options.resolve(input.ref) === undefined) {\n return fail(`Unknown action '${input.ref}'.`, join(path, \"ref\"));\n }\n } else if (\"definition\" in input) {\n const definitionError = validateActionDefinition(input.definition, join(path, \"definition\"), {\n ...(options.isPath ? { isPath: options.isPath } : {})\n });\n if (definitionError) return definitionError;\n } else {\n return fail(\"A binding names a shared action ({ ref }) or carries an inline { definition }.\", path);\n }\n const definition = definitionOf(input, options);\n\n if (options.loadOnly && definition !== undefined) {\n if (definition.kind !== \"http\" || definition.method !== \"GET\") {\n return fail(\"'load' accepts only http GET actions.\", path);\n }\n }\n\n if (input.input !== undefined) {\n if (!isPlainObject(input.input)) return fail(\"'input' must be an object.\", join(path, \"input\"));\n if (definition?.kind === \"prompt\") {\n return fail(\"Prompt actions take no input mapping.\", join(path, \"input\"));\n }\n const declared = definition?.kind === \"http\" && isPlainObject(definition.input.properties)\n ? definition.input.properties\n : undefined;\n for (const [field, value] of Object.entries(input.input)) {\n const fieldPath = join(path, `input.${field}`);\n if (declared !== undefined && !(field in declared)) {\n return fail(`Input field '${field}' is not declared by the action's input schema.`, fieldPath);\n }\n if (typeof value === \"string\") {\n if (options.isPath && !options.isPath(value)) {\n return fail(`Invalid data path '${value}'.`, fieldPath);\n }\n continue;\n }\n if (isPlainObject(value) && \"const\" in value && Object.keys(value).length === 1) {\n if (containsSecretRef(value.const)) {\n return fail(\"Secret references are allowed only in headers and query.\", fieldPath);\n }\n continue;\n }\n return fail(\"Input values are data paths or { const } literals.\", fieldPath);\n }\n }\n\n if (input.output !== undefined) {\n const outPath = join(path, \"output\");\n if (!isPlainObject(input.output)) return fail(\"'output' must be an object.\", outPath);\n if (definition?.kind === \"prompt\") return fail(\"Prompt actions have no output.\", outPath);\n const { mode, path: target, map } = input.output;\n if (mode !== undefined && !OUTPUT_MODES.some((m) => m === mode)) {\n return fail(\"'mode' must be replace, merge or patch.\", join(outPath, \"mode\"));\n }\n if (mode === \"patch\") {\n if (typeof target !== \"string\" || !isDataPath(target)) {\n return fail(\"'patch' requires a valid data 'path'.\", join(outPath, \"path\"));\n }\n } else if (target !== undefined) {\n return fail(\"'path' is only meaningful with mode \\\"patch\\\".\", join(outPath, \"path\"));\n }\n if (map !== undefined) {\n if (!isPlainObject(map)) return fail(\"'map' must be an object of data paths.\", join(outPath, \"map\"));\n const entries = Object.entries(map);\n if (entries.length === 0) return fail(\"'map' must not be empty (omit it to take the whole response).\", join(outPath, \"map\"));\n for (const [key, value] of entries) {\n const entryPath = join(outPath, `map.${key}`);\n if (key === \".\") {\n if (entries.length > 1) return fail(\"A '.' target takes the whole projection and must be the only entry.\", entryPath);\n } else if (!isDataPath(key)) {\n return fail(`'${key}' is not a valid data path.`, entryPath);\n }\n if (typeof value !== \"string\" || (value !== \".\" && !isDataPath(value))) {\n return fail(\"Map values are data paths into the response ('.' for the whole response).\", entryPath);\n }\n }\n }\n }\n return undefined;\n}\n\n/** A widget's `load` binding: http GET only (see `BindingCheckOptions.loadOnly`). */\nexport function validateLoadBinding(\n input: unknown,\n path = \"load\",\n options: Omit<BindingCheckOptions, \"loadOnly\"> = {}\n): ActionError | undefined {\n return validateActionBinding(input, path, { ...options, loadOnly: true });\n}\n\n/** Secret names an http definition references in its headers and query. */\nexport function collectSecretRefs(definition: unknown): string[] {\n if (!isPlainObject(definition) || definition.kind !== \"http\") return [];\n const names = new Set<string>();\n for (const field of [\"headers\", \"query\"] as const) {\n const map = definition[field];\n if (!isPlainObject(map)) continue;\n for (const value of Object.values(map)) {\n if (isPlainObject(value) && typeof value.secret === \"string\") names.add(value.secret);\n }\n }\n return [...names];\n}\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type { TemplateError, WidgetTemplate } from \"./types.js\";\nimport { FORBIDDEN_ATTR, FORBIDDEN_TAGS, MAX_TEMPLATE_DEPTH, RESERVED_ATTR } from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { validateActionBinding } from \"../actions/validate.js\";\n\nexport type ValidateTemplateResult =\n | { ok: true; template: WidgetTemplate }\n | { ok: false; error: TemplateError };\n\n/**\n * Thrown by `registerTemplate` when the template fails validation \u2014\n * registration is host setup, where failing loudly is the convention.\n * Carries the structured error for programmatic handling.\n */\nexport class InvalidTemplateError extends Error {\n readonly templateError: TemplateError;\n\n constructor(kind: string, error: TemplateError) {\n super(\n `Invalid widget template for kind '${kind}' at '${error.path}': ${error.message} (${error.code})`\n );\n this.name = \"InvalidTemplateError\";\n this.templateError = error;\n }\n}\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction nodeError(message: string, path: string): TemplateError {\n return { code: \"INVALID_TEMPLATE_NODE\", message, path };\n}\n\n/** Path syntax per paths.ts: \".\", \"$index\", \"$meta.\"/\"$root.\"/\"$parent.\"-prefixed, or dot segments. */\nfunction checkPathSyntax(value: string, path: string): TemplateError | undefined {\n if (parsePath(value) !== undefined) return undefined;\n return {\n code: \"INVALID_PATH\",\n message: `Invalid data path '${value}'.`,\n path\n };\n}\n\nfunction check(node: unknown, path: string, depth: number): TemplateError | undefined {\n if (depth > MAX_TEMPLATE_DEPTH) {\n return {\n code: \"TEMPLATE_TOO_DEEP\",\n message: `Template exceeds the maximum nesting depth of ${MAX_TEMPLATE_DEPTH}.`,\n path\n };\n }\n if (typeof node === \"string\") return undefined;\n if (!isPlainObject(node)) {\n return nodeError(\"Template node must be a string or a plain object.\", path);\n }\n\n if (\"bind\" in node) {\n if (typeof node.bind !== \"string\") {\n return nodeError(\"'bind' must be a string path.\", path);\n }\n return checkPathSyntax(node.bind, path);\n }\n\n if (\"each\" in node) {\n if (typeof node.each !== \"string\") {\n return nodeError(\"'each' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.each, path);\n if (pathError) return pathError;\n if (!(\"template\" in node)) {\n return nodeError(\"'each' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"empty\" in node && node.empty !== undefined) {\n return check(node.empty, join(path, \"empty\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"when\" in node) {\n if (typeof node.when !== \"string\") {\n return nodeError(\"'when' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.when, path);\n if (pathError) return pathError;\n if (!(\"template\" in node)) {\n return nodeError(\"'when' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"else\" in node && node.else !== undefined) {\n return check(node.else, join(path, \"else\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"tag\" in node) {\n if (typeof node.tag !== \"string\" || node.tag.length === 0) {\n return nodeError(\"'tag' must be a non-empty string.\", path);\n }\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) {\n return {\n code: \"FORBIDDEN_TAG\",\n message: `Element '${node.tag}' is not allowed in templates (active or foreign content).`,\n path\n };\n }\n if (\"attrs\" in node && node.attrs !== undefined) {\n if (!isPlainObject(node.attrs)) {\n return nodeError(\"'attrs' must be an object.\", path);\n }\n for (const [name, value] of Object.entries(node.attrs)) {\n const attrPath = join(path, `attrs.${name}`);\n if (FORBIDDEN_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is not allowed in templates (event handlers and srcdoc).`,\n path: attrPath\n };\n }\n if (RESERVED_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is reserved for the renderer (data-wg-*); use an 'action' binding.`,\n path: attrPath\n };\n }\n if (typeof value === \"string\") continue;\n if (isPlainObject(value) && typeof value.bind === \"string\") {\n const pathError = checkPathSyntax(value.bind, attrPath);\n if (pathError) return pathError;\n // One transform per value: map selects an authored literal,\n // prefix glues one in front \u2014 combining them has no use case\n // and every combination would need teaching forever.\n const hasMap = value.map !== undefined;\n const hasPrefix = value.prefix !== undefined;\n if (hasMap && hasPrefix) {\n return nodeError(\n `Attribute '${name}' carries both 'map' and 'prefix' \u2014 one transform per value.`,\n attrPath\n );\n }\n if (hasMap) {\n if (\n !isPlainObject(value.map) ||\n Object.values(value.map).some((entry) => typeof entry !== \"string\")\n ) {\n return nodeError(\n `Attribute '${name}': 'map' must be an object of string values.`,\n attrPath\n );\n }\n if (value.default !== undefined && typeof value.default !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'default' must be a string.`,\n attrPath\n );\n }\n } else if (value.default !== undefined) {\n return nodeError(\n `Attribute '${name}': 'default' requires 'map'.`,\n attrPath\n );\n }\n if (hasPrefix && typeof value.prefix !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'prefix' must be a string.`,\n attrPath\n );\n }\n continue;\n }\n return nodeError(\n `Attribute '${name}' must be a string, { bind }, { bind, map, default? } or { bind, prefix } value.`,\n attrPath\n );\n }\n }\n if (\"action\" in node && node.action !== undefined) {\n // An element is a link OR an action \u2014 both would leave the bridge\n // guessing which the author meant.\n const hasHref =\n isPlainObject(node.attrs) &&\n Object.keys(node.attrs).some((name) => name.toLowerCase() === \"href\");\n if (hasHref) {\n return {\n code: \"CONFLICTING_ATTRIBUTES\",\n message: \"An element carries 'href' or an 'action' binding, never both.\",\n path\n };\n }\n const actionError = validateActionBinding(node.action, join(path, \"action\"), {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (actionError) {\n return { code: \"INVALID_ACTION\", message: actionError.message, path: actionError.path };\n }\n }\n if (\"children\" in node && node.children !== undefined) {\n if (!Array.isArray(node.children)) {\n return nodeError(\"'children' must be an array.\", path);\n }\n for (let i = 0; i < node.children.length; i++) {\n const childError = check(\n node.children[i],\n join(path, `children.${i}`),\n depth + 1\n );\n if (childError) return childError;\n }\n }\n return undefined;\n }\n\n return nodeError(\n \"Unknown template node form (expected text, bind, tag, each, or when).\",\n path\n );\n}\n\n/** Validate an unknown value as a widget template. Never throws. */\nexport function validateTemplate(input: unknown): ValidateTemplateResult {\n const error = check(input, \"\", 0);\n if (error) return { ok: false, error };\n return { ok: true, template: input as WidgetTemplate };\n}\n", "/**\n * Addressing nodes inside a template by the validator's dotted path\n * convention (`children.2.template`, `else`, \u2026) \u2014 the identifier an action\n * binding is known by \u2014 and enumerating the shared actions a template\n * references, so stores can enforce referential integrity without a\n * second grammar.\n */\nimport { isPlainObject } from \"../shared/plain-object.js\";\nimport type { ActionBinding } from \"../actions/types.js\";\n\n/** The template node at a dotted path (\"\" is the root); `undefined` when absent. */\nexport function findTemplateNode(template: unknown, path: string): unknown {\n if (path === \"\") return template;\n let current: unknown = template;\n for (const segment of path.split(\".\")) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/** The element's `action` binding at a dotted path, when that node is a bound element. */\nexport function findActionBinding(template: unknown, path: string): ActionBinding | undefined {\n const node = findTemplateNode(template, path);\n if (isPlainObject(node) && typeof node.tag === \"string\" && isPlainObject(node.action)) {\n return node.action as ActionBinding;\n }\n return undefined;\n}\n\n/** Visit every binding object a template (and an optional `load`) carries. */\nfunction eachBinding(template: unknown, load: unknown, onBinding: (binding: Record<string, unknown>) => void): void {\n const visit = (node: unknown): void => {\n if (!isPlainObject(node)) return;\n if (isPlainObject(node.action)) onBinding(node.action);\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (node[key] !== undefined) visit(node[key]);\n }\n if (Array.isArray(node.children)) for (const child of node.children) visit(child);\n };\n visit(template);\n if (isPlainObject(load)) onBinding(load);\n}\n\n/** Every shared-action name a template (and an optional `load`) references by `ref`. */\nexport function collectActionRefs(template: unknown, load?: unknown): string[] {\n const refs = new Set<string>();\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref === \"string\") refs.add(binding.ref);\n });\n return [...refs];\n}\n\n/** Every inline action definition in a template (and `load`), for secret-reference scans. */\nexport function collectInlineActions(template: unknown, load?: unknown): unknown[] {\n const out: unknown[] = [];\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref !== \"string\" && binding.definition !== undefined) out.push(binding.definition);\n });\n return out;\n}\n\n/** Does the template (or `load`) carry any action binding at all? */\nexport function hasActionBindings(template: unknown, load?: unknown): boolean {\n if (load !== undefined) return true;\n return collectActionRefs(template).length > 0 || collectInlineActions(template).length > 0;\n}\n", "import type { WidgetPayload } from \"../contract/types.js\";\nimport type {\n WidgetCatalog,\n WidgetDescriptorInput,\n WidgetElementNode,\n WidgetNode,\n WidgetNodeAttrs,\n WidgetRenderer\n} from \"../catalog/index.js\";\nimport type {\n ActionBinding,\n ActionDefinition,\n ActionDescriptor,\n ActionDisabledReason\n} from \"../actions/types.js\";\nimport { PROMPT_TEXT_MAX } from \"../actions/types.js\";\nimport type { WidgetTemplate } from \"./types.js\";\nimport {\n FORBIDDEN_ATTR,\n FORBIDDEN_TAGS,\n RESERVED_ATTR,\n URL_ATTRS,\n isSafeImageSrc,\n isSafeUrl\n} from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { InvalidTemplateError, validateTemplate } from \"./validate.js\";\nimport { formatValue } from \"../catalog/widgets/format.js\";\nimport { isPlainObject } from \"../shared/plain-object.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\n/**\n * One scope frame: the root frame holds `payload.data`; every `each`\n * pushes the current item with its position. `$parent` walks the stack,\n * `$root` reads the bottom, `$index` reads the top's position.\n */\ninterface Frame {\n scope: unknown;\n index?: number;\n}\n\n/**\n * Resolve a path against the scope chain (see paths.ts for the grammar).\n * Missing, non-traversable or malformed paths resolve to `undefined` \u2014\n * never throws.\n */\nfunction resolvePath(path: string, frames: Frame[], meta: unknown): unknown {\n const parsed = parsePath(path);\n if (parsed === undefined) return undefined;\n let current: unknown;\n if (parsed.base === \"meta\") {\n current = meta;\n } else if (parsed.base === \"root\") {\n current = frames[0]?.scope;\n } else {\n const depth = frames.length - 1 - parsed.up;\n if (depth < 0) return undefined;\n const frame = frames[depth];\n if (frame === undefined) return undefined;\n if (parsed.index) return frame.index;\n current = frame.scope;\n }\n for (const segment of parsed.segments) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/**\n * Interpretation budget. `each` multiplies template nodes by the length of\n * AGENT-supplied data, so template size bounds nothing on its own \u2014 a\n * stored template driven by a large payload could otherwise spend the\n * process. Counting work (nodes emitted, plus one unit per `each`\n * iteration so empty iterations are not free) rather than watching a\n * clock keeps the bound reproducible: the same template and data always\n * truncate at the same place.\n */\nexport const DEFAULT_MAX_NODES = 50_000;\n\ninterface Budget {\n remaining: number;\n truncated: boolean;\n}\n\n/** Render-time knowledge about actions the caller supplies. */\n/** The compile options the action layer reads; the options object itself serves. */\ntype ActionContext = Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\">;\n\n/**\n * Resolve a binding into the descriptor an element carries. Everything the\n * bridge needs is decided here, in scope, at render time: the prompt's\n * text, the http arguments, and whether the action is available at all.\n */\nfunction buildDescriptor(\n binding: ActionBinding,\n id: string,\n frames: Frame[],\n meta: unknown,\n ctx: ActionContext\n): ActionDescriptor {\n const definition: ActionDefinition | undefined =\n \"ref\" in binding && typeof binding.ref === \"string\"\n ? ctx.actions?.(binding.ref)\n : \"definition\" in binding && isPlainObject(binding.definition)\n ? (binding.definition as ActionDefinition)\n : undefined;\n if (definition === undefined || (definition.kind !== \"prompt\" && definition.kind !== \"http\")) {\n const unresolved: ActionDescriptor = { id, disabled: \"unresolved\" };\n if (ctx.kind !== undefined) unresolved.widget = ctx.kind;\n return unresolved;\n }\n if (definition.kind === \"prompt\") {\n let text = \"\";\n const segments = Array.isArray(definition.text) ? definition.text : [];\n for (const segment of segments) {\n if (typeof segment === \"string\") text += segment;\n else if (isPlainObject(segment) && typeof segment.bind === \"string\") {\n text += formatValue(resolvePath(segment.bind, frames, meta));\n }\n if (text.length >= PROMPT_TEXT_MAX) break;\n }\n // Cap by code point so a surrogate pair is never split.\n const prompt: ActionDescriptor = { id, kind: \"prompt\", text: Array.from(text).slice(0, PROMPT_TEXT_MAX).join(\"\") };\n if (ctx.kind !== undefined) prompt.widget = ctx.kind;\n return prompt;\n }\n const args: Record<string, unknown> = {};\n if (isPlainObject(binding.input)) {\n for (const [field, value] of Object.entries(binding.input)) {\n let resolved: unknown;\n if (typeof value === \"string\") resolved = resolvePath(value, frames, meta);\n else if (isPlainObject(value) && \"const\" in value) resolved = value.const;\n if (resolved !== undefined) args[field] = resolved;\n }\n }\n const descriptor: ActionDescriptor = { id, kind: \"http\", args };\n if (ctx.httpDisabled !== undefined) descriptor.disabled = ctx.httpDisabled;\n if (ctx.kind !== undefined) descriptor.widget = ctx.kind;\n return descriptor;\n}\n\n/**\n * Interpret a template node into zero or more render-tree nodes.\n * Lenient by design: validation is the strict layer, so unknown or\n * malformed forms render as nothing rather than throwing (defense in\n * depth for templates that bypassed validation). `tpath` is the node's\n * dotted position in the TEMPLATE (the validator's path convention) \u2014 the\n * identifier an action binding is known by.\n */\nfunction interpretNode(\n node: unknown,\n frames: Frame[],\n meta: unknown,\n budget: Budget,\n tpath: string,\n ctx: ActionContext\n): WidgetNode[] {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n return [];\n }\n if (typeof node === \"string\") {\n budget.remaining--;\n return [node];\n }\n if (!isPlainObject(node)) return [];\n\n if (typeof node.bind === \"string\") {\n budget.remaining--;\n return [formatValue(resolvePath(node.bind, frames, meta))];\n }\n\n if (typeof node.each === \"string\") {\n const value = resolvePath(node.each, frames, meta);\n const items = Array.isArray(value) ? value : [];\n if (items.length === 0) {\n return node.empty === undefined\n ? []\n : interpretNode(node.empty, frames, meta, budget, join(tpath, \"empty\"), ctx);\n }\n const out: WidgetNode[] = [];\n const itemPath = join(tpath, \"template\");\n for (let i = 0; i < items.length; i++) {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n break;\n }\n budget.remaining--; // the iteration itself costs, even when it renders nothing\n frames.push({ scope: items[i], index: i });\n out.push(...interpretNode(node.template, frames, meta, budget, itemPath, ctx));\n frames.pop();\n }\n return out;\n }\n\n if (typeof node.when === \"string\") {\n const truthy = Boolean(resolvePath(node.when, frames, meta));\n const branch = truthy ? node.template : node.else;\n return branch === undefined\n ? []\n : interpretNode(branch, frames, meta, budget, join(tpath, truthy ? \"template\" : \"else\"), ctx);\n }\n\n if (typeof node.tag === \"string\" && node.tag.length > 0) {\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) return []; // active content never reaches a tree\n budget.remaining--;\n const attrs: WidgetNodeAttrs = {};\n if (isPlainObject(node.attrs)) {\n for (const [name, raw] of Object.entries(node.attrs)) {\n // Handlers are code; data-wg-* is the renderer's own vocabulary.\n if (FORBIDDEN_ATTR.test(name) || RESERVED_ATTR.test(name)) continue;\n let value: string | undefined;\n if (typeof raw === \"string\") {\n value = raw;\n } else if (isPlainObject(raw) && typeof raw.bind === \"string\") {\n const resolved = resolvePath(raw.bind, frames, meta);\n if (isPlainObject(raw.map)) {\n // The resolved value SELECTS a key; every emitted character\n // is an author-written literal. A miss falls to `default`,\n // or empty \u2014 an unanticipated status degrades, never breaks.\n const key = formatValue(resolved);\n const hit = Object.prototype.hasOwnProperty.call(raw.map, key)\n ? raw.map[key]\n : undefined;\n value =\n typeof hit === \"string\"\n ? hit\n : typeof raw.default === \"string\"\n ? raw.default\n : \"\";\n } else if (typeof raw.prefix === \"string\") {\n // The prefix is never emitted alone: no dead mailto: hrefs.\n // The composed value still faces the URL guard below.\n const text = formatValue(resolved);\n value = text === \"\" ? \"\" : raw.prefix + text;\n } else {\n value = formatValue(resolved);\n }\n }\n if (value === undefined) continue;\n const lower = name.toLowerCase();\n if (URL_ATTRS.has(lower)) {\n // Image sources additionally accept data:image/*; every other\n // URL attribute keeps the strict scheme set (data-URI\n // navigation is an XSS vector; data-URI images are not).\n const imageContext = lower === \"src\" && node.tag.toLowerCase() === \"img\";\n const allowed =\n isSafeUrl(value) || (imageContext && isSafeImageSrc(value));\n if (!allowed) continue;\n }\n attrs[name] = value;\n }\n }\n if (isPlainObject(node.action)) {\n attrs[\"data-wg-action\"] = JSON.stringify(\n buildDescriptor(node.action as ActionBinding, tpath, frames, meta, ctx)\n );\n }\n const children = Array.isArray(node.children)\n ? node.children.flatMap((child, i) =>\n interpretNode(child, frames, meta, budget, join(tpath, `children.${i}`), ctx)\n )\n : [];\n const element: WidgetElementNode = { tag: node.tag };\n if (Object.keys(attrs).length > 0) element.attrs = attrs;\n if (children.length > 0) element.children = children;\n return [element];\n }\n\n return [];\n}\n\n/** Count the nodes a template's STRUCTURE contains (not its output). */\nexport function countTemplateNodes(template: unknown): number {\n if (typeof template === \"string\") return 1;\n if (!isPlainObject(template)) return 0;\n if (typeof template.bind === \"string\") return 1;\n let total = 1;\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (template[key] !== undefined) total += countTemplateNodes(template[key]);\n }\n if (Array.isArray(template.children)) {\n for (const child of template.children) total += countTemplateNodes(child);\n }\n return total;\n}\n\nexport interface CompileOptions {\n /** Node budget for one render (default {@link DEFAULT_MAX_NODES}). */\n maxNodes?: number;\n /**\n * Resolve `{ ref }` action bindings to their definitions (the\n * principal's shared actions). Unresolvable refs render disabled.\n */\n actions?: (ref: string) => ActionDefinition | undefined;\n /**\n * Render every http action disabled with this reason \u2014 the server sets\n * `\"scope\"` when the caller's key cannot execute.\n */\n httpDisabled?: ActionDisabledReason;\n /** The kind this template is registered as \u2014 stamped into descriptors. */\n kind?: string;\n}\n\n/**\n * Compile a template into an ordinary widget renderer. The renderer is pure\n * and total; when the root interprets to anything other than exactly one\n * node, the output is wrapped in a `div.wg-template`. Renders are bounded\n * by a node budget \u2014 an exhausted budget stops interpretation and marks\n * the output with `data-truncated`, so the outcome is visible rather than\n * silently short.\n */\nexport function compileTemplate(\n template: WidgetTemplate,\n options: CompileOptions = {}\n): WidgetRenderer {\n const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;\n const ctx: ActionContext = options;\n return (payload: WidgetPayload): WidgetNode => {\n const budget: Budget = { remaining: maxNodes, truncated: false };\n const frames: Frame[] = [{ scope: payload.data }];\n const nodes = interpretNode(template, frames, payload.meta, budget, \"\", ctx);\n if (!budget.truncated && nodes.length === 1) {\n const only = nodes[0];\n if (only !== undefined) return only;\n }\n const attrs: WidgetNodeAttrs = { class: \"wg-template\" };\n if (budget.truncated) attrs[\"data-truncated\"] = \"true\";\n return { tag: \"div\", attrs, children: nodes };\n };\n}\n\n/**\n * Resolve a binding outside the tree \u2014 the widget-level `load` binding,\n * whose descriptor rides `structuredContent.load` rather than an element.\n * Resolved against the payload's root scope.\n */\nexport function resolveActionDescriptor(\n binding: ActionBinding,\n id: string,\n payload: WidgetPayload,\n options: Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\"> = {}\n): ActionDescriptor {\n const ctx: ActionContext = options;\n return buildDescriptor(binding, id, [{ scope: payload.data }], payload.meta, ctx);\n}\n\n/**\n * Validate, compile, and register a template as a widget kind. Throws\n * {@link InvalidTemplateError} on invalid templates and the catalog's\n * `DuplicateKindError` on duplicate kinds \u2014 registration is host setup.\n */\nexport function registerTemplate(\n catalog: WidgetCatalog,\n kind: string,\n template: unknown,\n descriptor?: WidgetDescriptorInput,\n options?: CompileOptions\n): void {\n const validated = validateTemplate(template);\n if (!validated.ok) {\n throw new InvalidTemplateError(kind, validated.error);\n }\n catalog.register(kind, compileTemplate(validated.template, { ...options, kind }), descriptor);\n}\n", "import type { WidgetNode } from \"../catalog/index.js\";\n\n/**\n * Materialize a render tree as fresh DOM. Text becomes text nodes (no HTML\n * parsing), matching the catalog DOM layer's safety discipline. Private to\n * the reactive module \u2014 the catalog's builder stays private to its own.\n */\nexport function buildDom(node: WidgetNode, doc: Document): Node {\n if (typeof node === \"string\") return doc.createTextNode(node);\n const element = doc.createElement(node.tag);\n if (node.attrs) {\n for (const [name, value] of Object.entries(node.attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (node.children) {\n for (const child of node.children) {\n element.appendChild(buildDom(child, doc));\n }\n }\n return element;\n}\n", "import type { WidgetElementNode, WidgetNode } from \"../catalog/index.js\";\nimport { buildDom } from \"./build.js\";\n\n/**\n * Patch `dom` in place so it reflects `next`, given that it currently\n * reflects `prev`. Returns the node now representing `next` \u2014 the same node\n * when patched in place, a freshly built replacement when the shape (tag or\n * node type) changed. Identity is preserved wherever shape matches.\n */\nexport function patchNode(prev: WidgetNode, next: WidgetNode, dom: Node): Node {\n if (typeof prev === \"string\" && typeof next === \"string\") {\n if (prev !== next) dom.nodeValue = next;\n return dom;\n }\n if (\n typeof prev !== \"string\" &&\n typeof next !== \"string\" &&\n prev.tag === next.tag &&\n dom.nodeType === 1\n ) {\n patchElement(prev, next, dom as Element);\n return dom;\n }\n // Shape changed: replace only this subtree.\n const doc = dom.ownerDocument;\n if (!doc || !dom.parentNode) return dom;\n const replacement = buildDom(next, doc);\n dom.parentNode.replaceChild(replacement, dom);\n return replacement;\n}\n\nfunction patchElement(\n prev: WidgetElementNode,\n next: WidgetElementNode,\n element: Element\n): void {\n const prevAttrs = prev.attrs ?? {};\n const nextAttrs = next.attrs ?? {};\n for (const [name, value] of Object.entries(nextAttrs)) {\n if (prevAttrs[name] !== value) element.setAttribute(name, value);\n }\n for (const name of Object.keys(prevAttrs)) {\n if (!(name in nextAttrs)) element.removeAttribute(name);\n }\n patchChildren(prev.children ?? [], next.children ?? [], element);\n}\n\nfunction patchChildren(\n prev: readonly WidgetNode[],\n next: readonly WidgetNode[],\n element: Element\n): void {\n const doc = element.ownerDocument;\n // Snapshot: childNodes is live and patchNode may replace entries.\n const domChildren: Node[] = [];\n for (let i = 0; i < element.childNodes.length; i++) {\n const child = element.childNodes[i];\n if (child) domChildren.push(child);\n }\n\n const shared = Math.min(prev.length, next.length);\n for (let i = 0; i < shared; i++) {\n const prevChild = prev[i];\n const nextChild = next[i];\n const childDom = domChildren[i];\n if (prevChild === undefined || nextChild === undefined) continue;\n if (childDom) {\n patchNode(prevChild, nextChild, childDom);\n } else {\n element.appendChild(buildDom(nextChild, doc));\n }\n }\n for (let i = shared; i < next.length; i++) {\n const extra = next[i];\n if (extra !== undefined) element.appendChild(buildDom(extra, doc));\n }\n for (let i = prev.length - 1; i >= shared; i--) {\n const surplus = domChildren[i];\n if (surplus) element.removeChild(surplus);\n }\n}\n", "import type { WidgetCatalog, WidgetNode } from \"../catalog/index.js\";\nimport { createCatalog } from \"../catalog/index.js\";\nimport type { WidgetContractError } from \"../contract/index.js\";\nimport type { ActionDescriptor } from \"../actions/index.js\";\nimport { buildDom } from \"./build.js\";\nimport { patchNode } from \"./diff.js\";\n\n/** Outcome of a mount or update. Failures leave the DOM untouched. */\nexport type UpdateResult =\n | { ok: true }\n | { ok: false; error: WidgetContractError };\n\n/** An activated element's descriptor, handed to the host untouched. */\nexport type ActionActivation = ActionDescriptor;\n\nexport interface MountOptions {\n /**\n * Catalog used for validation and rendering. Defaults to a fresh\n * `createCatalog()` per mount; pass a shared instance to render custom\n * registered kinds.\n */\n catalog?: WidgetCatalog;\n /**\n * Receives activations of mounted `[data-wg-action]` elements (click, or\n * Enter/Space on non-button hosts) with the parsed descriptor and the\n * currently mounted payload; the default action is prevented. Without\n * it, action elements are inert \u2014 the mount never executes anything.\n */\n onAction?: (activation: ActionActivation, payload: unknown) => void;\n}\n\nexport interface WidgetMount {\n /** Outcome of the initial render performed by `mountWidget`. */\n readonly initial: UpdateResult;\n /**\n * Re-render with a new payload, patching the DOM in place. Returns a\n * structured error (DOM untouched) for invalid payloads. Throws if the\n * mount was disposed \u2014 that is a host programming error.\n */\n update(payload: unknown): UpdateResult;\n /** Currently rendered tree (`undefined` before the first successful render). */\n node(): WidgetNode | undefined;\n /** Empty the container and end this mount. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Mount a widget payload into `container` and keep updating it in place.\n * The first render is just an internal `update`; its outcome is exposed as\n * `initial`, so a failed first payload does not cost the caller the handle.\n */\nexport function mountWidget(\n payload: unknown,\n container: Element,\n options: MountOptions = {}\n): WidgetMount {\n const catalog = options.catalog ?? createCatalog();\n let current: WidgetNode | undefined;\n let root: Node | undefined;\n let disposed = false;\n let mountedPayload: unknown;\n\n // Delegated on the container: descriptors are data the host decides\n // about \u2014 this layer only parses and forwards them.\n const onAction = options.onAction;\n function parseDescriptor(el: Element): ActionDescriptor | undefined {\n try {\n const parsed = JSON.parse(el.getAttribute(\"data-wg-action\") ?? \"\") as unknown;\n if (typeof parsed === \"object\" && parsed !== null && typeof (parsed as { id?: unknown }).id === \"string\") {\n return parsed as ActionDescriptor;\n }\n } catch {\n /* malformed descriptor: inert */\n }\n return undefined;\n }\n function activation(event: Event): void {\n const target = event.target as Element | null;\n const el = target?.closest?.(\"[data-wg-action]\");\n if (!el || !container.contains(el)) return;\n if (event.type === \"keydown\") {\n const key = (event as KeyboardEvent).key;\n if (key !== \"Enter\" && key !== \" \") return;\n if (el.tagName === \"BUTTON\" || el.tagName === \"A\") return; // native keyboard \u2192 click\n }\n event.preventDefault();\n if (onAction === undefined) return;\n const descriptor = parseDescriptor(el);\n if (descriptor !== undefined) onAction(descriptor, mountedPayload);\n }\n container.addEventListener(\"click\", activation);\n container.addEventListener(\"keydown\", activation);\n\n function update(nextPayload: unknown): UpdateResult {\n if (disposed) {\n throw new Error(\n \"Widget mount is disposed; create a new mount instead of updating.\"\n );\n }\n const rendered = catalog.render(nextPayload);\n if (!rendered.ok) return rendered;\n\n if (current === undefined || root === undefined) {\n const built = buildDom(rendered.node, container.ownerDocument);\n container.replaceChildren(built);\n root = built;\n } else {\n root = patchNode(current, rendered.node, root);\n }\n current = rendered.node;\n mountedPayload = nextPayload;\n return { ok: true };\n }\n\n function dispose(): void {\n if (disposed) return;\n disposed = true;\n container.removeEventListener(\"click\", activation);\n container.removeEventListener(\"keydown\", activation);\n container.replaceChildren();\n current = undefined;\n root = undefined;\n mountedPayload = undefined;\n }\n\n return {\n initial: update(payload),\n update,\n node: () => current,\n dispose\n };\n}\n", "/**\n * The chrome tokens and the palettes painted through them.\n *\n * `CHROME_DEFAULTS` is not a description of the defaults \u2014 it IS them: the\n * injected stylesheet's token blocks are generated from this object, so a host\n * that paints its own surfaces from the export cannot drift from the\n * designers. There is deliberately no second palette to fall back to: a host\n * that wants a different look passes its own values through `chrome`, and\n * `chromeCss` renders whatever palette it hands back.\n *\n * Colours and shape carry the product's identity. Typography does not: a\n * library must never default to a webfont it cannot serve, so `font`,\n * `font-mono` and the three sizes stay system values in both palettes and a\n * host with its own typeface passes it through `chrome`.\n */\n\n/**\n * The chrome tokens \u2014 every `--wgd-<token>` the stylesheet paints with.\n * Colours (18) differ between the schemes; typography, shape and shadow are\n * declared per scheme too so each palette stands alone. Public API: a rename\n * is a spec change.\n */\nexport const CHROME_TOKENS = [\n \"bg\", \"panel\", \"border\", \"line\", \"text\", \"muted\",\n \"accent\", \"accent-bg\", \"accent-line\",\n \"danger\", \"danger-bg\", \"danger-line\", \"hover\",\n \"hl-key\", \"hl-str\", \"hl-num\", \"hl-bool\", \"hl-punct\",\n \"font\", \"font-mono\", \"font-size\", \"font-size-sm\", \"font-size-xs\",\n \"radius-sm\", \"radius\", \"radius-lg\", \"gap\", \"shadow\"\n] as const;\n\nexport type ChromeToken = (typeof CHROME_TOKENS)[number];\n\n/** A host's partial chrome: token \u2192 CSS value (`var()` references welcome). */\nexport type ChromeOptions = Partial<Record<ChromeToken, string>>;\n\n/** Every token valued \u2014 what a palette is. */\nexport type ChromeScheme = Record<ChromeToken, string>;\n\n/** A complete palette: both schemes, every token. */\nexport interface ChromePalette {\n light: ChromeScheme;\n dark: ChromeScheme;\n}\n\n/** Shared by both palettes: see the module header on why typography is not branded. */\nconst TYPOGRAPHY = {\n font: \"system-ui, sans-serif\",\n \"font-mono\": \"ui-monospace, monospace\",\n \"font-size\": \"13px\",\n \"font-size-sm\": \"12px\",\n \"font-size-xs\": \"11px\"\n} as const;\n\n/**\n * The widgentic palette \u2014 what the designers render with when a host passes\n * no `chrome`, and what a host paints its own page with to match them.\n *\n * Every colour sits on the logo mark's own hue (197.6deg, from `#40a0c8`).\n * Surfaces, text and accents come from the product's existing palette;\n * `border`, `accent-line` and `danger-line` are DERIVED, not chosen: each is\n * the lightest value on that hue which still clears 3:1 against the surface\n * it sits on, because those edges are what identifies a control, a focused tag\n * and a banner. Minimum weight that complies, so nothing is heavier than\n * accessibility requires. See chrome-contrast.test.ts for the gate.\n */\nexport const CHROME_DEFAULTS: ChromePalette = {\n light: {\n bg: \"#f6fafc\", panel: \"#ffffff\", border: \"#6e95a6\",\n line: \"#e4ecf2\", text: \"#0b1b26\", muted: \"#56707f\",\n accent: \"#1e6f92\", \"accent-bg\": \"#e3f1f7\", \"accent-line\": \"#4b91ae\",\n danger: \"#b42318\", \"danger-bg\": \"#fdf2f2\", \"danger-line\": \"#c97572\",\n hover: \"#eef5f9\",\n \"hl-key\": \"#1e6f92\", \"hl-str\": \"#2e7d5b\", \"hl-num\": \"#96620f\",\n \"hl-bool\": \"#7a4fbf\", \"hl-punct\": \"#56707f\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(11, 27, 38, 0.35)\"\n },\n dark: {\n bg: \"#0b141b\", panel: \"#10202a\", border: \"#437082\",\n line: \"#1b2f3d\", text: \"#e6f0f5\", muted: \"#93a9b6\",\n accent: \"#8acbe6\", \"accent-bg\": \"#14303d\", \"accent-line\": \"#3e7e98\",\n danger: \"#f0a3a3\", \"danger-bg\": \"#2a1a1c\", \"danger-line\": \"#a3524f\",\n hover: \"#152a36\",\n \"hl-key\": \"#8acbe6\", \"hl-str\": \"#6cc79a\", \"hl-num\": \"#e0b25a\",\n \"hl-bool\": \"#bb9af7\", \"hl-punct\": \"#93a9b6\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(0, 0, 0, 0.7)\"\n }\n};\n\nexport interface ChromeCssOptions {\n /** Custom-property prefix, dashes included. Default `--wgd`. */\n prefix?: string;\n /** Selector the light block is written under. Default `:root`. */\n selector?: string;\n /** Selector for the dark block inside `prefers-color-scheme: dark`; defaults to `selector`. */\n darkMediaSelector?: string;\n /** Optional selector for an unconditional dark block \u2014 an explicit host toggle. */\n darkSelector?: string;\n}\n\nfunction declarations(scheme: ChromeScheme, prefix: string, indent: string): string {\n return CHROME_TOKENS.map((token) => `${indent}${prefix}-${token}: ${scheme[token]};`).join(\"\\n\");\n}\n\n/**\n * Render a palette as CSS declaration blocks \u2014 the light values under\n * `selector`, the dark values under `prefers-color-scheme: dark`, and\n * optionally under an explicit selector a host toggles. Every token is\n * declared in every block, so nothing falls back to a browser value.\n *\n * A string builder, deliberately: no injection, no runtime, no dependency.\n * The designers' own stylesheet is built with it, and so is a host page that\n * wants its surfaces to match them.\n */\nexport function chromeCss(palette: ChromePalette, options: ChromeCssOptions = {}): string {\n const prefix = options.prefix ?? \"--wgd\";\n const selector = options.selector ?? \":root\";\n const darkMediaSelector = options.darkMediaSelector ?? selector;\n const blocks = [\n `${selector} {\\n${declarations(palette.light, prefix, \" \")}\\n}`,\n `@media (prefers-color-scheme: dark) {\\n ${darkMediaSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n }\\n}`\n ];\n if (options.darkSelector !== undefined) {\n blocks.push(`${options.darkSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n}`);\n }\n return blocks.join(\"\\n\");\n}\n", "/**\n * Tiny DOM helpers for the designer chrome \u2014 the same hand-rolled\n * discipline as the rest of the project, sized for form-heavy panels.\n * Designer chrome classes are prefixed `wgd-` (widget content inside the\n * preview keeps the normal `wg-` classes).\n */\nimport { CHROME_DEFAULTS, CHROME_TOKENS, chromeCss } from \"./chrome-defaults.js\";\nimport type { ChromeOptions } from \"./chrome-defaults.js\";\n\nexport type Child = Node | string;\n\n/** The first `<selector>` under `parent`, which the caller's own markup guarantees exists. */\nexport function requireChild<K extends keyof HTMLElementTagNameMap>(\n parent: ParentNode,\n selector: K\n): HTMLElementTagNameMap[K] {\n const found = parent.querySelector(selector);\n if (found === null) throw new Error(`Designer chrome is missing a <${selector}> element.`);\n return found;\n}\n\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs?: Record<string, string>,\n children?: Child[]\n): HTMLElementTagNameMap[K];\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement;\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement {\n const element = document.createElement(tag);\n if (attrs) {\n for (const [name, value] of Object.entries(attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (children) {\n for (const child of children) {\n element.append(child);\n }\n }\n return element;\n}\n\n/** Labeled single-line input bound through a callback. */\nexport function textField(\n label: string,\n value: string,\n onInput: (value: string) => void\n): HTMLElement {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = value;\n input.addEventListener(\"input\", () => onInput(input.value));\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n input\n ]);\n}\n\n/** Labeled multi-line textarea bound through a callback. */\nexport function textArea(\n label: string,\n value: string,\n onInput: (value: string) => void,\n rows = 6\n): HTMLElement {\n const area = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: String(rows),\n spellcheck: \"false\"\n });\n area.value = value;\n area.addEventListener(\"input\", () => onInput(area.value));\n // An empty label means the surrounding chrome already names the field \u2014\n // no legend row.\n return h(\"label\", { class: \"wgd-field\" }, [\n ...(label === \"\" ? [] : [h(\"span\", { class: \"wgd-field-label\" }, [label])]),\n area\n ]);\n}\n\n/** Collapsible titled section (open by default). */\nexport function section(title: string, children: Child[], open = true): HTMLElement {\n const attrs: Record<string, string> = { class: \"wgd-section\" };\n if (open) attrs.open = \"\";\n return h(\"details\", attrs, [\n h(\"summary\", { class: \"wgd-section-title\" }, [title]),\n h(\"div\", { class: \"wgd-section-body\" }, children)\n ]);\n}\n\n/**\n * Size a select to its SELECTED label (a bare <select> sizes to its\n * widest option, or to whatever flex hands it), so the caret sits beside\n * the text instead of drifting with leftover row width. ch tracks\n * monospace text exactly; the em term scales with padding, and the px\n * term covers the UA's caret region, which does NOT scale with font size\n * (11px selects clip under a pure em term). Re-fits on change.\n */\nexport function fitSelect(select: HTMLSelectElement): void {\n const fit = (): void => {\n const label = select.options[select.selectedIndex]?.text ?? select.value;\n select.style.width = `calc(${Math.max(label.length, 1)}ch + 1.2em + 18px)`;\n };\n fit();\n select.addEventListener(\"change\", fit);\n}\n\n/**\n * Compact add-menu: one toggle button revealing the options on demand \u2014\n * the tree stays calm instead of carrying a button per option at every\n * level. Closes on pick, outside pointer-down, or Escape.\n */\nexport function menuButton(\n label: string,\n title: string,\n options: string[],\n onPick: (option: string) => void\n): HTMLElement {\n const wrap = h(\"span\", { class: \"wgd-menuwrap\" });\n const toggle = h(\n \"button\",\n { class: \"wgd-icon wgd-menu-toggle\", type: \"button\", title },\n [label]\n );\n const menu = h(\"div\", { class: \"wgd-menu\" });\n menu.hidden = true;\n\n const close = (): void => {\n menu.hidden = true;\n document.removeEventListener(\"pointerdown\", onOutside, true);\n document.removeEventListener(\"keydown\", onKey, true);\n };\n const onOutside = (event: Event): void => {\n if (!wrap.contains(event.target as Node)) close();\n };\n const onKey = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\") close();\n };\n\n toggle.addEventListener(\"click\", () => {\n if (!menu.hidden) {\n close();\n return;\n }\n menu.hidden = false;\n document.addEventListener(\"pointerdown\", onOutside, true);\n document.addEventListener(\"keydown\", onKey, true);\n });\n for (const option of options) {\n const item = h(\n \"button\",\n { class: \"wgd-menu-item\", type: \"button\" },\n [option]\n );\n item.addEventListener(\"click\", () => {\n close();\n onPick(option);\n });\n menu.append(item);\n }\n wrap.append(toggle, menu);\n return wrap;\n}\n\n/** Inline diagnostic line (empty text removes it from the flow). */\nexport function diagnosticLine(text: string | undefined): HTMLElement {\n const el = h(\"div\", { class: \"wgd-diagnostic\" }, text === undefined ? [] : [text]);\n if (text === undefined) el.setAttribute(\"hidden\", \"\");\n return el;\n}\n\n// The token list and the palettes live in chrome-defaults.ts, which the\n// stylesheet below is generated from; re-exported here so the modules that\n// already import chrome types from this one keep working.\nexport { CHROME_TOKENS } from \"./chrome-defaults.js\";\nexport type { ChromeOptions, ChromeToken } from \"./chrome-defaults.js\";\n\nconst CHROME_TOKEN_SET: ReadonlySet<string> = new Set<string>(CHROME_TOKENS);\n\n// On a custom property a CSS-wide keyword acts on the property itself (it\n// inherits/resets the TOKEN, not the consumer), so it never expresses what\n// a host means by it; hosts pass `var(--their-token, fallback)` instead.\nconst CSS_WIDE_KEYWORD = /^(inherit|initial|unset|revert|revert-layer)$/i;\n\n/**\n * Apply a host's chrome on a designer root as inline custom properties \u2014\n * the style attribute outranks every rule in the injected stylesheet, so\n * the host's values win over the light/dark defaults. Unknown tokens,\n * non-string values and CSS-wide keywords are ignored at the door.\n */\nexport function applyChrome(root: HTMLElement, chrome: ChromeOptions | undefined): void {\n if (chrome === undefined) return;\n for (const [token, value] of Object.entries(chrome)) {\n if (!CHROME_TOKEN_SET.has(token)) continue;\n if (typeof value !== \"string\" || CSS_WIDE_KEYWORD.test(value.trim())) continue;\n root.style.setProperty(`--wgd-${token}`, value);\n }\n}\n\n/** The element form of the option: a `chrome` attribute holding JSON; anything else \u2192 nothing. */\nexport function parseChromeAttribute(value: string | null): ChromeOptions | undefined {\n if (value === null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return parsed as ChromeOptions;\n } catch {\n return undefined;\n }\n}\n\nconst STYLE_MARKER = \"data-widgentic-designer\";\n\n/** Designer chrome stylesheet \u2014 injected once per document. */\nexport function injectDesignerStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"chrome\");\n style.textContent = `\n/* Chrome tokens (CHROME_TOKENS), generated from CHROME_DEFAULTS so the\n exported palette IS the applied one. A host overrides any of them through\n options.chrome (inline on the root, which outranks these rules). Widget\n content inside the preview keeps its own --wg-* theme tokens. */\n${chromeCss(CHROME_DEFAULTS, {\n selector: \".wgd-root\",\n darkMediaSelector: '.wgd-root:not([data-wgd-theme=\"light\"])',\n darkSelector: '.wgd-root[data-wgd-theme=\"dark\"]'\n})}\n.wgd-root { display: flex; gap: var(--wgd-gap); font-family: var(--wgd-font); font-size: var(--wgd-font-size); align-items: flex-start; color: var(--wgd-text); background: var(--wgd-bg); }\n/* Any chrome class that sets display would silently defeat the hidden\n attribute (learned live twice: the add menu, then the styles tree as a\n tab pane). hidden always wins \u2014 scoped to the designer's own tree. */\n.wgd-root [hidden] { display: none !important; }\n/* Read-only: editing surfaces are inert (visible, inoperable) and read\n de-emphasized; the preview and its selectors stay full-strength. The\n controls flatten into plain values \u2014 a form that cannot be typed in\n should not look like a form (opacity alone was invisible on dark). */\n.wgd-readonly .wgd-section-body[inert] { opacity: 0.75; }\n/* Empty preview state \u2014 shown only when there has never been a valid\n render to freeze on; a blank pane is the one state the contract bans. */\n.wgd-preview-empty { color: var(--wgd-muted); font-style: italic; font-size: var(--wgd-font-size-sm); }\n.wgd-readonly [inert] .wgd-input,\n.wgd-readonly [inert] .wgd-select,\n.wgd-readonly [inert] .wgd-textarea,\n.wgd-readonly [inert] textarea.wgd-hl-input {\n border-color: transparent; background: transparent; box-shadow: none;\n}\n.wgd-readonly [inert] .wgd-hl { background: transparent; }\n/* Controls that only exist to mutate carry no meaning here. */\n.wgd-readonly [inert] .wgd-button,\n.wgd-readonly [inert] .wgd-icon,\n.wgd-readonly [inert] .wgd-add,\n.wgd-readonly [inert] input[type=\"checkbox\"] { opacity: 0.4; }\n.wgd-panels { flex: 1 1 460px; min-width: 340px; display: flex; flex-direction: column; gap: 8px; }\n.wgd-side { flex: 1 1 420px; min-width: 320px; display: flex; flex-direction: column; gap: 8px; position: sticky; top: 8px; }\n.wgd-preview-pane { display: flex; flex-direction: column; gap: 8px; }\n.wgd-section { border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 6px 10px; background: var(--wgd-panel); }\n.wgd-section-title { cursor: pointer; font-weight: 600; }\n.wgd-section-body { display: flex; flex-direction: column; gap: 8px; padding-top: 8px; }\n.wgd-field { display: flex; flex-direction: column; gap: 2px; }\n.wgd-field-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-input, .wgd-textarea, .wgd-select { font: inherit; padding: 4px 6px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); }\n/* Textareas fill their panel regardless of the intrinsic cols width. */\n.wgd-textarea { font-family: var(--wgd-font-mono); white-space: pre; width: 100%; box-sizing: border-box; min-width: 0; resize: vertical; }\n.wgd-preview .wg-designer-action { position: relative; outline: 1px dashed var(--wgd-muted); outline-offset: 2px; }\n.wgd-preview .wg-designer-action::after { content: \"\u26A1 action\"; position: absolute; top: -0.9em; right: 0; font: calc(var(--wgd-font-size-xs) - 1px) var(--wgd-font); color: var(--wgd-muted); background: var(--wgd-panel); padding: 0 4px; border-radius: var(--wgd-radius-sm); pointer-events: none; }\n.wgd-binding { display: flex; flex-direction: column; gap: 6px; padding: 6px 8px; border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius); margin: 4px 0; }\n.wgd-binding-field { min-width: 8ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-action-definition { display: flex; flex-direction: column; gap: 6px; }\n.wgd-action-schema { display: flex; flex-direction: column; gap: 4px; padding: 4px 0; }\n.wgd-test-output { font: var(--wgd-font-size-sm) var(--wgd-font-mono); white-space: pre-wrap; word-break: break-all; max-height: 240px; overflow: auto; margin: 6px 0 0; }\n.wgd-diagnostic { color: var(--wgd-danger); font-size: var(--wgd-font-size-sm); white-space: pre-wrap; }\n.wgd-banner { border: 1px solid var(--wgd-danger-line); background: var(--wgd-danger-bg); color: var(--wgd-danger); border-radius: var(--wgd-radius-lg); padding: 8px 10px; margin-bottom: 8px; }\n/* The preview is the WIDGET's surface, not chrome: it establishes the\n --wg-* context (like composePage does for page output) so widget content\n \u2014 including custom kinds the base stylesheet doesn't color \u2014 never\n inherits the designer's own text/background. */\n.wgd-preview { border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 16px; background: var(--wg-bg); color: var(--wg-fg); }\n.wgd-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }\n.wgd-button { font: inherit; padding: 4px 10px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); cursor: pointer; }\n.wgd-button:hover { background: var(--wgd-hover); }\n.wgd-tab-active { background: var(--wgd-accent-bg); border-color: var(--wgd-accent); }\n/* Shared tree/editor chrome (JSON tree, schema builder/form, template tree) */\n.wgd-jt-children, .wgd-children { margin-left: 10px; padding-left: 10px; border-left: 2px solid var(--wgd-line); display: flex; flex-direction: column; gap: 4px; }\n.wgd-jt-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }\n.wgd-jt-entry { padding: 2px 0; }\n.wgd-jt-key { font-family: var(--wgd-font-mono); color: var(--wgd-muted); min-width: 2ch; }\n.wgd-jt-keyinput, .wgd-jt-type { max-width: 12ch; }\n.wgd-jt-summary { cursor: pointer; color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-sf-object { border: 1px solid var(--wgd-line); border-radius: var(--wgd-radius-lg); padding: 6px 10px; margin: 4px 0; }\n/* Schema builder: property name + type + required on one row. */\n.wgd-sb-node { margin-left: 8px; padding: 1px 0 1px 8px; border-left: 2px solid var(--wgd-line); }\n.wgd-sb-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; }\n.wgd-sb-constraints { padding-left: 12px; }\n.wgd-sb-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-prop { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); }\n.wgd-sb-type { flex: 0 0 auto; max-width: 11ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-req { display: flex; gap: 2px; align-items: center; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-constraint { flex: 1 1 auto; min-width: 6ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-root { padding: 2px 0 2px 8px; border-left: 2px solid transparent; }\n/* Schema builder: the template tree's flat discipline \u2014 chrome on\n hover/focus only, removal revealed by the row, fitted type selects. */\n.wgd-schemabuilder .wgd-input, .wgd-schemabuilder .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-schemabuilder .wgd-input:hover, .wgd-schemabuilder .wgd-select:hover,\n.wgd-schemabuilder .wgd-input:focus, .wgd-schemabuilder .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-schemabuilder .wgd-sb-type { flex: 0 0 auto; box-sizing: border-box; max-width: none; color: var(--wgd-accent); }\n.wgd-schemabuilder .wgd-sb-prop { font-size: var(--wgd-font-size-sm); color: var(--wgd-hl-key); }\n.wgd-sb-row { border-radius: var(--wgd-radius-sm); }\n.wgd-sb-row:hover { background: var(--wgd-hover); }\n.wgd-sb-row > .wgd-icon { visibility: hidden; }\n.wgd-sb-row:hover > .wgd-icon, .wgd-sb-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-schemabuilder .wgd-button { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-schemabuilder .wgd-button:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n.wgd-remove { color: var(--wgd-danger); }\n/* Breathing room between a tab strip and its active pane. */\n.wgd-tabs > .wgd-row { margin-bottom: 6px; }\n/* Template tree: one node = one slim row; sub-structure indents below.\n Controls stay flat (chrome appears on hover/focus) so a deep template\n reads like the JSON it projects, not like a form. */\n.wgd-node { padding: 0 0 0 4px; }\n.wgd-node-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; border-radius: var(--wgd-radius-sm); }\n.wgd-node-row:hover { background: var(--wgd-hover); }\n.wgd-node-badge { font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border-radius: var(--wgd-radius-sm); padding: 0 5px; flex: 0 0 auto; }\n.wgd-node-icons { display: flex; gap: 2px; margin-left: auto; flex: 0 0 auto; visibility: hidden; }\n.wgd-node-row:hover > .wgd-node-icons, .wgd-node-row:focus-within > .wgd-node-icons { visibility: visible; }\n.wgd-node-value { flex: 1 1 auto; min-width: 4ch; }\n.wgd-icon { font: inherit; font-size: var(--wgd-font-size-xs); line-height: 1.4; padding: 0 5px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); background: var(--wgd-bg); cursor: pointer; color: var(--wgd-muted); }\n.wgd-icon:hover { background: var(--wgd-hover); }\n/* Compact controls: inside tree nodes, and wherever a section opts in with\n .wgd-compact (the Load action editor mirrors an element's binding editor). */\n.wgd-node .wgd-input, .wgd-node .wgd-select,\n.wgd-compact .wgd-input, .wgd-compact .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-node .wgd-input:hover, .wgd-node .wgd-select:hover, .wgd-compact .wgd-input:hover, .wgd-compact .wgd-select:hover,\n.wgd-node .wgd-input:focus, .wgd-node .wgd-select:focus, .wgd-compact .wgd-input:focus, .wgd-compact .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-compact .wgd-binding { border: none; padding: 0; }\n/* Busy controls (the host-supplied Test call): disabled, with a spinner. */\n.wgd-button.wgd-busy { opacity: 0.7; cursor: progress; }\n.wgd-button.wgd-busy::after { content: \"\"; display: inline-block; width: 10px; height: 10px; margin-left: 6px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; vertical-align: -1px; animation: wgd-spin 0.8s linear infinite; }\n@keyframes wgd-spin { to { transform: rotate(360deg); } }\n.wgd-tagwrap, .wgd-pathwrap { display: contents; }\n/* Collapse chevron: every tree row reserves the column so values align. */\n.wgd-chevron { flex: 0 0 auto; width: 16px; padding: 0; border: none; background: none; color: var(--wgd-muted); font-size: calc(var(--wgd-font-size-xs) - 1px); cursor: pointer; }\n.wgd-chevron-none { visibility: hidden; }\n.wgd-node-summary { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n/* Attrs vs children: attributes group under a dotted muted rail with\n key-colored names; children keep the solid accent rail. */\n.wgd-attrs { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 0; }\n.wgd-attr-row > .wgd-icon { visibility: hidden; }\n.wgd-attr-row:hover > .wgd-icon, .wgd-attr-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-attr-name { font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); flex: 0 1 auto; min-width: 5ch; }\n.wgd-attr-prefix { flex: 0 1 auto; min-width: 6ch; max-width: 10ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-str); }\n.wgd-attr { display: flex; flex-direction: column; gap: 1px; }\n/* Transform block under a bind attr: one more dotted level in. */\n.wgd-attr-map { margin-left: 24px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-map-default { flex: 1 1 auto; min-width: 8ch; }\n.wgd-attr-mode { flex: 0 0 auto; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); }\n.wgd-children { margin-left: 14px; padding-left: 8px; border-left: 2px solid var(--wgd-accent-line); gap: 1px; }\n.wgd-slot { display: flex; flex-direction: column; gap: 1px; }\n.wgd-slot-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); font-style: italic; padding-left: 4px; }\n/* Add menu: one toggle, options in a popover. */\n.wgd-menuwrap { position: relative; display: inline-flex; }\n.wgd-menu-toggle { color: var(--wgd-accent); }\n.wgd-menu { position: absolute; top: 100%; left: 0; z-index: 10; min-width: 9ch; display: flex; flex-direction: column; background: var(--wgd-panel); border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); box-shadow: var(--wgd-shadow); padding: 2px; }\n/* An OPEN menu must not inherit the icons' hover-gated visibility:\n visibility (unlike display) lets a child re-assert visible. */\n.wgd-menu:not([hidden]) { visibility: visible; }\n.wgd-menuwrap:has(> .wgd-menu:not([hidden])) { visibility: visible; }\n/* Menus in the right-aligned icons area hang leftward, not off-panel. */\n.wgd-node-icons .wgd-menu { left: auto; right: 0; }\n.wgd-menu-item { font: inherit; font-size: var(--wgd-font-size-sm); text-align: left; padding: 3px 8px; border: none; border-radius: var(--wgd-radius-sm); background: none; color: var(--wgd-text); cursor: pointer; white-space: nowrap; }\n.wgd-menu-item:hover { background: var(--wgd-accent-bg); color: var(--wgd-accent); }\n/* Styles tree: selector rows with declaration rows \u2014 the same flat\n template-tree discipline (flat inputs, hover-revealed icons). */\n.wgd-styles { display: flex; flex-direction: column; gap: 2px; }\n.wgd-st-row { display: flex; gap: 4px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-row:hover { background: var(--wgd-hover); }\n.wgd-st-row:hover > .wgd-node-icons, .wgd-st-row:focus-within > .wgd-node-icons { visibility: visible; }\n.wgd-styles .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); font-family: var(--wgd-font-mono); border-color: transparent; background: transparent; }\n.wgd-styles .wgd-input:hover, .wgd-styles .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-st-selector { flex: 1 1 auto; min-width: 8ch; color: var(--wgd-accent); }\n.wgd-st-decls { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-st-decl { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-decl:hover { background: var(--wgd-hover); }\n.wgd-st-decl > .wgd-icon { visibility: hidden; }\n.wgd-st-decl:hover > .wgd-icon, .wgd-st-decl:focus-within > .wgd-icon { visibility: visible; }\n.wgd-st-prop { flex: 0 1 auto; min-width: 8ch; color: var(--wgd-hl-key); }\n.wgd-st-value { flex: 1 1 auto; min-width: 8ch; }\n.wgd-st-colon { color: var(--wgd-muted); flex: 0 0 auto; }\n.wgd-st-add { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-st-add:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n/* Import and export stack as sibling sections with the column's rhythm. */\n.wgd-io { display: flex; flex-direction: column; gap: 8px; }\n/* Flat string\u2192string record rows (hints): mono keys, prose values. */\n.wgd-record { display: flex; flex-direction: column; gap: 1px; }\n.wgd-rec-row { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-rec-row:hover { background: var(--wgd-hover); }\n.wgd-rec-row > .wgd-icon { visibility: hidden; }\n.wgd-rec-row:hover > .wgd-icon, .wgd-rec-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-record .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-record .wgd-input:hover, .wgd-record .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-rec-key { flex: 0 1 auto; min-width: 8ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); }\n.wgd-rec-value { flex: 1 1 auto; min-width: 8ch; }\n/* The tag select IS the element node's label: flat, accent, monospace.\n Tag and path selects are width-fitted to their SELECTED value by the\n panel (fitSelect), so carets hug the text \u2014 no flex stretching here. */\n.wgd-node .wgd-tag { flex: 0 0 auto; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border: 1px solid transparent; border-radius: var(--wgd-radius-sm); padding: 0 4px; }\n.wgd-node .wgd-tag:hover, .wgd-node .wgd-tag:focus { border-color: var(--wgd-accent-line); }\n.wgd-node .wgd-path { flex: 0 1 auto; min-width: 6ch; max-width: 100%; font-family: var(--wgd-font-mono); }\n.wgd-node .wgd-select { box-sizing: border-box; }\n/* Theme panel: swatch beside each color token. */\n/* Syntax coloring: <pre> layer behind a transparent-text textarea. Every\n metric here must mirror .wgd-textarea or the glyphs drift apart. */\n.wgd-hlwrap { position: relative; }\n.wgd-hl, .wgd-hl-input {\n font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size); line-height: 1.45;\n padding: 4px 6px; border: 1px solid transparent; border-radius: var(--wgd-radius);\n box-sizing: border-box; white-space: pre; tab-size: 2; letter-spacing: normal;\n}\n.wgd-hl {\n position: absolute; inset: 0; margin: 0; overflow: hidden;\n pointer-events: none; z-index: 0; background: var(--wgd-bg);\n color: var(--wgd-text);\n}\ntextarea.wgd-hl-input {\n position: relative; z-index: 1; background: transparent; color: transparent;\n caret-color: var(--wgd-text); border-color: var(--wgd-border);\n}\n.wgd-hl-k { color: var(--wgd-hl-key); }\n.wgd-hl-s { color: var(--wgd-hl-str); }\n.wgd-hl-n { color: var(--wgd-hl-num); }\n.wgd-hl-b { color: var(--wgd-hl-bool); }\n.wgd-hl-p { color: var(--wgd-hl-punct); }\n.wgd-swatch { flex: 0 0 auto; width: 26px; height: 22px; padding: 0; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: none; cursor: pointer; }\n.wgd-token-row { display: flex; gap: 6px; align-items: center; }\n.wgd-token-row .wgd-input { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-token-ref { display: flex; flex-direction: column; gap: 2px; max-height: 220px; overflow-y: auto; margin-top: 4px; }\n.wgd-token-ref-row { display: flex; gap: 6px; align-items: center; font-size: var(--wgd-font-size-xs); }\n.wgd-token-ref-swatch { flex: 0 0 auto; width: 14px; height: 14px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); }\n.wgd-token-ref-noswatch { border-style: dashed; opacity: 0.35; }\n.wgd-token-ref-name { font-family: var(--wgd-font-mono); color: var(--wgd-accent); }\n.wgd-token-ref-value { color: var(--wgd-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.wgd-token-ref-details summary { cursor: pointer; }\n`;\n doc.head.appendChild(style);\n}\n", "/** Package-local helpers (kept here rather than exported from core \u2014 see design D4). */\n\n/** Structural copy of JSON-shaped data; the designers hand out copies, never their state. */\nexport function clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** A caught value's message without asserting it is an Error. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n", "/**\n * Cheap syntax coloring for the JSON textareas: a highlighted <pre> layer\n * sits exactly behind a transparent-text <textarea>, so the browser keeps\n * doing all the real work (typing, selection, undo, IME) and we only paint\n * colors. No editor library, no parsing beyond a tokenizer \u2014 invalid JSON\n * still colors sensibly because the tokenizer is regex-based, never a\n * parser.\n *\n * The two layers must agree on every metric that affects glyph position\n * (font, size, line-height, padding, border width, white-space); the\n * stylesheet keeps them in lockstep.\n */\n\ninterface Token {\n /** Token class suffix: k(ey) s(tring) n(umber) b(oolean/null) p(unctuation). */\n cls: string;\n text: string;\n}\n\nconst JSON_TOKENS =\n /(\"(?:[^\"\\\\]|\\\\.)*\")(\\s*:)?|(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)|\\b(true|false|null)\\b|([{}[\\],:])/g;\n\nexport function tokenizeJson(text: string): Token[] {\n const out: Token[] = [];\n let last = 0;\n let match: RegExpExecArray | null;\n JSON_TOKENS.lastIndex = 0;\n while ((match = JSON_TOKENS.exec(text)) !== null) {\n if (match.index > last) out.push({ cls: \"\", text: text.slice(last, match.index) });\n if (match[1] !== undefined) {\n // A string followed by ':' is an object key.\n if (match[2] !== undefined) {\n out.push({ cls: \"k\", text: match[1] });\n out.push({ cls: \"p\", text: match[2] });\n } else {\n out.push({ cls: \"s\", text: match[1] });\n }\n } else if (match[3] !== undefined) {\n out.push({ cls: \"n\", text: match[3] });\n } else if (match[4] !== undefined) {\n out.push({ cls: \"b\", text: match[4] });\n } else if (match[5] !== undefined) {\n out.push({ cls: \"p\", text: match[5] });\n }\n last = JSON_TOKENS.lastIndex;\n }\n if (last < text.length) out.push({ cls: \"\", text: text.slice(last) });\n return out;\n}\n\n/** Paint tokens into the layer as DOM nodes (never innerHTML). */\nfunction paint(layer: HTMLElement, text: string): void {\n const nodes: Node[] = [];\n for (const token of tokenizeJson(text)) {\n if (token.cls === \"\") {\n nodes.push(document.createTextNode(token.text));\n continue;\n }\n const span = document.createElement(\"span\");\n span.className = `wgd-hl-${token.cls}`;\n span.textContent = token.text;\n nodes.push(span);\n }\n // A trailing newline needs a following glyph box to render as a line.\n nodes.push(document.createTextNode(\"\\n\"));\n layer.replaceChildren(...nodes);\n}\n\n/**\n * Wrap a textarea in the highlight layer. Returns a disposer that restores\n * the original DOM shape.\n */\nexport function attachJsonHighlight(textarea: HTMLTextAreaElement): () => void {\n const parent = textarea.parentNode;\n if (parent === null) return () => undefined;\n\n const wrap = document.createElement(\"div\");\n wrap.className = \"wgd-hlwrap\";\n const layer = document.createElement(\"pre\");\n layer.className = \"wgd-hl\";\n layer.setAttribute(\"aria-hidden\", \"true\");\n\n parent.insertBefore(wrap, textarea);\n wrap.append(layer, textarea);\n textarea.classList.add(\"wgd-hl-input\");\n\n const sync = (): void => {\n paint(layer, textarea.value);\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n const syncScroll = (): void => {\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n // Tab indents instead of moving focus \u2014 these panes hold indented JSON.\n // Shift+Tab keeps its focus-moving default as the keyboard escape.\n const onTab = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\" || event.shiftKey || textarea.readOnly) return;\n event.preventDefault();\n const { selectionStart, selectionEnd, value } = textarea;\n textarea.value = `${value.slice(0, selectionStart)} ${value.slice(selectionEnd)}`;\n textarea.selectionStart = textarea.selectionEnd = selectionStart + 2;\n // The commit path listens for input; a synthetic one keeps the store\n // and the paint layer in step with the inserted spaces.\n textarea.dispatchEvent(new Event(\"input\", { bubbles: true }));\n };\n\n textarea.addEventListener(\"input\", sync);\n textarea.addEventListener(\"scroll\", syncScroll);\n textarea.addEventListener(\"keydown\", onTab);\n sync();\n\n return () => {\n textarea.removeEventListener(\"input\", sync);\n textarea.removeEventListener(\"scroll\", syncScroll);\n textarea.removeEventListener(\"keydown\", onTab);\n textarea.classList.remove(\"wgd-hl-input\");\n wrap.replaceWith(textarea);\n };\n}\n\n/**\n * Repaint after a programmatic value change (store refresh), which fires\n * no input event.\n */\nexport function repaintHighlight(textarea: HTMLTextAreaElement): void {\n const layer = textarea.parentElement?.querySelector(\".wgd-hl\");\n if (layer instanceof HTMLElement) paint(layer, textarea.value);\n}\n", "/**\n * Import/export in the server's shapes: widget JSON is exactly the\n * `CustomWidget` definition (`{ kind, template, descriptor }`) that\n * `examples/mcp-server/widgets/` registers; themes are bare token maps.\n * Imports are untrusted \u2014 everything re-validates, and a failed import\n * never touches the current draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport { parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { } from \"@widgentic/core\";\nimport { diagnosticLine, h, section, textArea, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport interface WidgetDefinition {\n kind: WidgetDraft[\"kind\"];\n template: WidgetDraft[\"template\"];\n descriptor: WidgetDraft[\"descriptor\"];\n load?: ActionBinding;\n}\n\n/** Validate an untrusted definition; errors instead of throws. */\nexport function checkDefinition(definition: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(definition)) return [\"Definition must be an object.\"];\n if (typeof definition.kind !== \"string\" || definition.kind.trim() === \"\") {\n errors.push(\"'kind' must be a non-empty string.\");\n }\n const template = validateTemplate(definition.template);\n if (!template.ok) {\n errors.push(`template: ${template.error.code} \u2014 ${template.error.message}`);\n }\n if (!isPlainObject(definition.descriptor)) {\n errors.push(\"'descriptor' must be an object.\");\n } else if (typeof definition.descriptor.description !== \"string\") {\n errors.push(\"'descriptor.description' must be a string.\");\n }\n if (definition.load !== undefined) {\n const problem = validateLoadBinding(definition.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) errors.push(`load: ${problem.message} (at ${problem.path})`);\n }\n return errors;\n}\n\nexport function exportWidgetJson(draft: WidgetDraft): string {\n const definition: WidgetDefinition = {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n };\n return JSON.stringify(definition, null, 2);\n}\n\nexport function exportThemeJson(draft: WidgetDraft): string {\n return JSON.stringify(draft.theme ?? {}, null, 2);\n}\n\nexport type ImportResult =\n | { ok: true; definition: WidgetDefinition }\n | { ok: false; errors: string[] };\n\nexport function importWidgetJson(text: string): ImportResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n return { ok: false, errors: [`Invalid JSON: ${errorMessage(error)}`] };\n }\n const errors = checkDefinition(parsed);\n if (errors.length > 0) return { ok: false, errors };\n return { ok: true, definition: parsed as unknown as WidgetDefinition };\n}\n\n/** Apply a validated definition to the store, preserving the session theme. */\nexport function applyDefinition(store: DraftStore, definition: WidgetDefinition): void {\n const theme = store.get().theme;\n store.replace({\n kind: definition.kind,\n template: definition.template,\n descriptor: definition.descriptor,\n ...(definition.load !== undefined ? { load: definition.load } : {}),\n ...(theme !== undefined ? { theme } : {})\n });\n}\n\nfunction camelCase(kind: string): string {\n return kind\n .split(/[^a-zA-Z0-9]+/)\n .filter((part) => part.length > 0)\n .map((part, i) => (i === 0 ? part : part[0]?.toUpperCase() + part.slice(1)))\n .join(\"\");\n}\n\n/**\n * Emit a module body compatible with `examples/mcp-server/widgets/` \u2014\n * the manual-registration bridge until wire registration exists.\n */\nexport function toTypeScriptModule(draft: WidgetDraft): string {\n const name = camelCase(draft.kind) || \"custom\";\n return (\n `import type { CustomWidget } from \"./index.js\";\\n\\n` +\n `export const ${name}Widget: CustomWidget = ${JSON.stringify(\n {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n },\n null,\n 2\n )};\\n`\n );\n}\n\nexport function mountIoPanel(store: DraftStore): {\n element: HTMLElement;\n dispose(): void;\n} {\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n\n function button(label: string, produce: () => string): HTMLElement {\n const el = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [label]);\n el.addEventListener(\"click\", () => {\n output.value = produce();\n repaintHighlight(output);\n });\n return el;\n }\n\n const importError = diagnosticLine(undefined);\n const importField = textArea(\"Import widget JSON\", \"\", () => undefined, 5);\n const importArea = requireChild(importField, \"textarea\");\n attachJsonHighlight(importArea);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n const result = importWidgetJson(importArea.value);\n if (!result.ok) {\n importError.hidden = false;\n importError.textContent = result.errors.join(\"\\n\");\n return; // current draft untouched\n }\n importError.hidden = true;\n importError.textContent = \"\";\n applyDefinition(store, result.definition);\n });\n\n // Import and export are independent flows \u2014 two sections, import first\n // (bringing a drafted definition in is the more common entry point).\n const importSection = section(\"Import\", [\n importField,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n // Export copies out what is already on screen, so read-only leaves it\n // operable: the mode restricts editing, not looking.\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-row\" }, [\n button(\"Export widget JSON\", () => exportWidgetJson(store.get())),\n button(\"Export theme JSON\", () => exportThemeJson(store.get())),\n button(\"Copy as TypeScript\", () => toTypeScriptModule(store.get()))\n ]),\n output\n ]);\n exportSection.classList.add(\"wgd-view-only\");\n const element = h(\"div\", { class: \"wgd-io\" }, [importSection, exportSection]);\n // After assembly: the layer wraps the textarea in place, so the element\n // must already have its parent.\n attachJsonHighlight(output);\n\n return { element, dispose: () => element.remove() };\n}\n", "/**\n * Generic JSON value editor: collapsible tree with in-place key/value\n * editing, type switching, and add/remove \u2014 the NanoJSON/JSONTree\n * interaction pattern, built in-house because the general libraries carry\n * far more (and weigh far more) than the designer needs.\n *\n * Structural operations re-render the tree; text edits commit on change\n * (blur/Enter) so typing is never interrupted.\n */\nimport { h } from \"./dom.js\";\n\ntype Path = (string | number)[];\n\nconst TYPE_OPTIONS = [\"string\", \"number\", \"boolean\", \"null\", \"object\", \"array\"] as const;\ntype TypeName = (typeof TYPE_OPTIONS)[number];\n\nfunction typeOf(value: unknown): TypeName {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return (typeof value) as TypeName;\n}\n\nfunction defaultFor(type: TypeName, previous: unknown): unknown {\n switch (type) {\n case \"string\":\n return typeof previous === \"number\" || typeof previous === \"boolean\"\n ? String(previous)\n : \"\";\n case \"number\": {\n const parsed = Number(previous);\n return Number.isFinite(parsed) ? parsed : 0;\n }\n case \"boolean\":\n return previous === \"true\" ? true : Boolean(previous) && previous !== \"false\";\n case \"null\":\n return null;\n case \"object\":\n return {};\n case \"array\":\n return [];\n }\n}\n\nfunction setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n if (typeof root === \"object\" && root !== null) {\n const copy = { ...(root as Record<string, unknown>) };\n if (rest.length === 0 && remove) delete copy[step as string];\n else copy[step as string] = setAt(copy[step as string], rest, value, remove);\n return copy;\n }\n return root;\n}\n\nfunction renameKey(root: unknown, path: Path, from: string, to: string): unknown {\n const holder = path.reduce<unknown>(\n (node, step) =>\n typeof node === \"object\" && node !== null\n ? (node as Record<string, unknown>)[step as string]\n : undefined,\n root\n );\n if (typeof holder !== \"object\" || holder === null || Array.isArray(holder)) return root;\n const entries = Object.entries(holder).map(([k, v]) =>\n k === from ? ([to, v] as const) : ([k, v] as const)\n );\n return setAt(root, path, Object.fromEntries(entries));\n}\n\nexport interface JsonTreeEditor {\n element: HTMLElement;\n getValue(): unknown;\n /** External update (skipped while the user is editing inside the tree). */\n setValue(value: unknown): void;\n}\n\nexport function createJsonTreeEditor(\n initial: unknown,\n onChange: (value: unknown) => void\n): JsonTreeEditor {\n let current: unknown = initial;\n const element = h(\"div\", { class: \"wgd-jsontree\" });\n\n function commit(next: unknown): void {\n current = next;\n render();\n onChange(current);\n }\n\n function commitText(path: Path, type: TypeName, text: string): void {\n const value =\n type === \"number\"\n ? Number.isFinite(Number(text))\n ? Number(text)\n : 0\n : text;\n current = setAt(current, path, value);\n onChange(current); // no re-render: in-place text edit\n }\n\n function typeSelect(value: unknown, path: Path): HTMLSelectElement {\n const select = h(\"select\", { class: \"wgd-select wgd-jt-type\" });\n for (const option of TYPE_OPTIONS) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.value = typeOf(value);\n select.addEventListener(\"change\", () =>\n commit(setAt(current, path, defaultFor(select.value as TypeName, value)))\n );\n return select;\n }\n\n function valueControl(value: unknown, path: Path): Node {\n const type = typeOf(value);\n if (type === \"boolean\") {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value as boolean;\n box.addEventListener(\"change\", () => commit(setAt(current, path, box.checked)));\n return box;\n }\n if (type === \"null\") return h(\"code\", undefined, [\"null\"]);\n if (type === \"string\" || type === \"number\") {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = String(value);\n input.addEventListener(\"change\", () => commitText(path, type, input.value));\n return input;\n }\n return h(\"span\");\n }\n\n function entryRow(\n keyLabel: Node,\n value: unknown,\n path: Path,\n removable: boolean\n ): HTMLElement {\n const row = h(\"div\", { class: \"wgd-jt-row\" }, [keyLabel, typeSelect(value, path)]);\n const type = typeOf(value);\n if (type !== \"object\" && type !== \"array\") {\n row.append(valueControl(value, path));\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => commit(setAt(current, path, undefined, true)));\n row.append(remove);\n }\n const wrap = h(\"div\", { class: \"wgd-jt-entry\" }, [row]);\n if (type === \"object\" || type === \"array\") {\n wrap.append(renderContainer(value, path));\n }\n return wrap;\n }\n\n function renderContainer(value: unknown, path: Path): HTMLElement {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n body.append(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [String(index)]), item, [...path, index], true)\n );\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit(setAt(current, [...path, value.length], \"\"))\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n } else if (typeof value === \"object\" && value !== null) {\n for (const [key, item] of Object.entries(value)) {\n const keyInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n keyInput.value = key;\n keyInput.addEventListener(\"change\", () =>\n commit(renameKey(current, path, key, keyInput.value))\n );\n body.append(entryRow(keyInput, item, [...path, key], true));\n }\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ property\"]);\n add.addEventListener(\"click\", () => {\n const holder = value as Record<string, unknown>;\n let name = \"key\";\n for (let i = 1; name in holder; i++) name = `key${i}`;\n commit(setAt(current, [...path, name], \"\"));\n });\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n const details = h(\"details\", { class: \"wgd-jt-branch\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-jt-summary\" }, [\n Array.isArray(value)\n ? `[ ${value.length} item${value.length === 1 ? \"\" : \"s\"} ]`\n : `{ ${Object.keys(value as object).length} propert${Object.keys(value as object).length === 1 ? \"y\" : \"ies\"} }`\n ]),\n body\n ]);\n return details;\n }\n\n function render(): void {\n element.replaceChildren(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [\"value\"]), current, [], false)\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value;\n render();\n }\n };\n}\n", "/**\n * Structured editor for the dataSchema subset \u2014 the property-card pattern\n * from the React schema-builder ecosystem, sized to widgentic's six\n * keywords (type/properties/required/items/enum/pattern) so it stays a\n * dependency-free couple hundred lines.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h } from \"./dom.js\";\n\nconst TYPES = [\"object\", \"array\", \"string\", \"number\", \"integer\", \"boolean\", \"null\", \"any\"] as const;\n\n/**\n * Types the builder offers `enum` for. The validator accepts `enum` on any\n * type (deep JSON comparison, per JSON Schema), but enumerating whole\n * objects/arrays belongs in the JSON tab, not a form.\n */\nconst ENUM_TYPES = new Set([\"string\", \"number\", \"integer\", \"any\"]);\n\nexport interface SchemaBuilder {\n element: HTMLElement;\n getValue(): DataSchema | undefined;\n setValue(schema: DataSchema | undefined): void;\n}\n\nexport function createSchemaBuilder(\n initial: DataSchema | undefined,\n onChange: (schema: DataSchema | undefined) => void\n): SchemaBuilder {\n let current: DataSchema | undefined = initial;\n const element = h(\"div\", { class: \"wgd-schemabuilder\" });\n\n function commit(next: DataSchema | undefined, rerender = true): void {\n current = next;\n onChange(current);\n if (rerender) render();\n }\n\n /** Rebuild a node with one key changed/removed (undefined removes). */\n function withKey(node: DataSchema, key: string, value: unknown): DataSchema {\n const copy: DataSchema = { ...node };\n if (value === undefined) delete copy[key];\n else copy[key] = value;\n return copy;\n }\n\n /**\n * One schema node. `lead`/`trail` let a parent put the property name and\n * its required/remove controls on the SAME row as the type select.\n */\n function renderNode(\n node: DataSchema,\n apply: (next: DataSchema) => void,\n depth: number,\n lead: (Node | string)[] = [],\n trail: (Node | string)[] = []\n ): HTMLElement {\n const rows: (Node | string)[] = [];\n\n const typeSelect = h(\"select\", { class: \"wgd-select wgd-sb-type\" });\n for (const t of TYPES) typeSelect.append(h(\"option\", { value: t }, [t]));\n // Nullable type arrays ([<type>, \"null\"], either order) present as the\n // PRIMARY type + a nullable toggle \u2014 never collapsing to \"any\", which\n // silently hid pattern/enum for agent-authored nullable fields.\n const rawType = node.type;\n const typeList = Array.isArray(rawType)\n ? rawType.filter((t): t is string => typeof t === \"string\")\n : undefined;\n const nullable = typeList?.includes(\"null\") ?? false;\n const currentType =\n typeof rawType === \"string\"\n ? rawType\n : (typeList?.find((t) => t !== \"null\") ?? (nullable ? \"null\" : \"any\"));\n typeSelect.value = TYPES.some((type) => type === currentType)\n ? currentType\n : \"any\";\n fitSelect(typeSelect);\n const nullBox = h(\"input\", {\n type: \"checkbox\",\n title: \"Also allows null\"\n });\n nullBox.checked = nullable;\n nullBox.disabled = typeSelect.value === \"any\" || typeSelect.value === \"null\";\n /** The `type` value the current controls describe. */\n function typeValue(selected: string, allowNull: boolean): unknown {\n if (selected === \"any\") return undefined;\n return allowNull && selected !== \"null\" ? [selected, \"null\"] : selected;\n }\n nullBox.addEventListener(\"change\", () => {\n apply(withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked)));\n });\n typeSelect.addEventListener(\"change\", () => {\n let next = withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked));\n if (typeSelect.value !== \"object\") {\n next = withKey(withKey(next, \"properties\", undefined), \"required\", undefined);\n }\n if (typeSelect.value !== \"array\") next = withKey(next, \"items\", undefined);\n if (typeSelect.value !== \"string\") next = withKey(next, \"pattern\", undefined);\n if (!ENUM_TYPES.has(typeSelect.value)) next = withKey(next, \"enum\", undefined);\n apply(next);\n });\n // Header row: [name?] [type] [nullable] [required?] [remove?]\n rows.push(\n h(\"div\", { class: \"wgd-sb-row\" }, [\n ...lead,\n typeSelect,\n h(\"label\", { class: \"wgd-sb-req wgd-sb-null\", title: \"Also allows null\" }, [\n nullBox,\n \"null\"\n ]),\n ...trail\n ])\n );\n\n // Constraints row \u2014 only the ones this type can actually use.\n const constraints: (Node | string)[] = [];\n if (typeSelect.value === \"string\") {\n const pattern = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: \"pattern (regex, optional)\"\n });\n pattern.value = typeof node.pattern === \"string\" ? node.pattern : \"\";\n pattern.addEventListener(\"change\", () =>\n apply(withKey(node, \"pattern\", pattern.value === \"\" ? undefined : pattern.value))\n );\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"pattern\"]), pattern);\n }\n const enumError = diagnosticLine(undefined);\n // `enum` is type-agnostic in the validator, but enumerating whole\n // objects/arrays is a JSON-tab affair \u2014 the builder offers it where\n // it is actually useful.\n if (ENUM_TYPES.has(typeSelect.value)) {\n const enumInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: 'enum [\"a\",\"b\"] (optional)'\n });\n enumInput.value = Array.isArray(node.enum) ? JSON.stringify(node.enum) : \"\";\n enumInput.addEventListener(\"change\", () => {\n if (enumInput.value.trim() === \"\") {\n enumError.hidden = true;\n apply(withKey(node, \"enum\", undefined));\n return;\n }\n try {\n const parsed: unknown = JSON.parse(enumInput.value);\n if (!Array.isArray(parsed)) throw new Error(\"must be a JSON array\");\n enumError.hidden = true;\n apply(withKey(node, \"enum\", parsed));\n } catch (error) {\n enumError.hidden = false;\n enumError.textContent = `enum ignored: ${errorMessage(error)}`;\n }\n });\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"enum\"]), enumInput);\n }\n if (constraints.length > 0) {\n rows.push(h(\"div\", { class: \"wgd-sb-row wgd-sb-constraints\" }, constraints), enumError);\n }\n\n // Object: property cards + required toggles\n if (typeSelect.value === \"object\") {\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required)\n ? node.required.filter((k): k is string => typeof k === \"string\")\n : [];\n const cards = h(\"div\", { class: \"wgd-jt-children\" });\n for (const [name, sub] of Object.entries(properties)) {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-prop\",\n placeholder: \"property name\"\n });\n nameInput.value = name;\n nameInput.addEventListener(\"change\", () => {\n const entries = Object.entries(properties).map(([k, v]) =>\n k === name ? ([nameInput.value, v] as const) : ([k, v] as const)\n );\n const nextRequired = required.map((k) => (k === name ? nameInput.value : k));\n apply(\n withKey(\n withKey(node, \"properties\", Object.fromEntries(entries)),\n \"required\",\n nextRequired.length > 0 ? nextRequired : undefined\n )\n );\n });\n const requiredBox = h(\"input\", { type: \"checkbox\", title: \"required\" });\n requiredBox.checked = required.includes(name);\n requiredBox.addEventListener(\"change\", () => {\n const nextRequired = requiredBox.checked\n ? [...required, name]\n : required.filter((k) => k !== name);\n apply(withKey(node, \"required\", nextRequired.length > 0 ? nextRequired : undefined));\n });\n const removeProp = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove property\" }, [\"\u2715\"]);\n removeProp.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = properties;\n apply(\n withKey(\n withKey(node, \"properties\", Object.keys(rest).length > 0 ? rest : undefined),\n \"required\",\n required.filter((k) => k !== name).length > 0\n ? required.filter((k) => k !== name)\n : undefined\n )\n );\n });\n // Name, type, required and remove all share the property's first row.\n cards.append(\n renderNode(\n isPlainObject(sub) ? (sub as DataSchema) : {},\n (nextSub) =>\n apply(withKey(node, \"properties\", { ...properties, [name]: nextSub })),\n depth + 1,\n [nameInput],\n [\n h(\"label\", { class: \"wgd-sb-req\", title: \"required\" }, [requiredBox, \"req\"]),\n removeProp\n ]\n )\n );\n }\n const addProp = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ property\"\n ]);\n addProp.addEventListener(\"click\", () => {\n let name = \"field\";\n for (let i = 1; name in properties; i++) name = `field${i}`;\n apply(withKey(node, \"properties\", { ...properties, [name]: { type: \"string\" } }));\n });\n cards.append(h(\"div\", { class: \"wgd-toolbar\" }, [addProp]));\n rows.push(cards);\n }\n\n // Array: items node\n if (typeSelect.value === \"array\") {\n rows.push(\n h(\"div\", { class: \"wgd-slot\" }, [\n renderNode(\n isPlainObject(node.items) ? (node.items as DataSchema) : {},\n (nextItems) => apply(withKey(node, \"items\", nextItems)),\n depth + 1,\n [h(\"span\", { class: \"wgd-sb-label\" }, [\"items\"])]\n )\n ])\n );\n }\n\n return h(\"div\", { class: depth === 0 ? \"wgd-sb-root\" : \"wgd-sb-node\" }, rows);\n }\n\n function render(): void {\n if (current === undefined) {\n const start = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ add a data schema\"\n ]);\n start.addEventListener(\"click\", () => commit({ type: \"object\" }));\n element.replaceChildren(\n h(\"div\", undefined, [\n h(\"span\", { class: \"wgd-sb-label\" }, [\n \"No schema \u2014 data is accepted leniently.\"\n ]),\n h(\"div\", { class: \"wgd-toolbar\" }, [start])\n ])\n );\n return;\n }\n const clear = h(\"button\", { class: \"wgd-button wgd-add wgd-remove\", type: \"button\" }, [\n \"remove schema\"\n ]);\n clear.addEventListener(\"click\", () => commit(undefined));\n element.replaceChildren(\n renderNode(current, (next) => commit(next), 0),\n h(\"div\", { class: \"wgd-toolbar\" }, [clear])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(schema) {\n if (element.contains(document.activeElement)) return;\n current = schema;\n render();\n }\n };\n}\n", "/**\n * Flat editor for a string\u2192string record (hints: name \u2192 doc), under the\n * same flat discipline as the styles tree \u2014 one slim row per entry,\n * removal revealed by the row. Values are strings by construction, so\n * the tree enforces the exact shape; anything looser is a JSON-tab\n * affair.\n */\nimport { h } from \"./dom.js\";\n\nexport interface RecordEditor {\n element: HTMLElement;\n getValue(): Record<string, string> | undefined;\n setValue(record: Record<string, string> | undefined): void;\n}\n\nexport function createRecordEditor(\n initial: Record<string, string> | undefined,\n placeholders: { key: string; value: string; add: string },\n onChange: (record: Record<string, string> | undefined) => void\n): RecordEditor {\n let current: Record<string, string> | undefined = initial;\n const element = h(\"div\", { class: \"wgd-record\" });\n\n function commit(next: Record<string, string>): void {\n // An emptied record means \"none\" \u2014 the owning key drops entirely.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function render(): void {\n const record = current ?? {};\n const rows = Object.entries(record).map(([key, value]) => {\n const keyInput = changeInput(\n key,\n placeholders.key,\n \"wgd-input wgd-rec-key\",\n (next) => {\n const entries = Object.entries(record).map(([k, v]) =>\n k === key ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const valueInput = changeInput(\n value,\n placeholders.value,\n \"wgd-input wgd-rec-value\",\n (next) => commit({ ...record, [key]: next })\n );\n const remove = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove entry\" },\n [\"\u2715\"]\n );\n remove.addEventListener(\"click\", () => {\n const { [key]: _gone, ...rest } = record;\n commit(rest);\n });\n return h(\"div\", { class: \"wgd-rec-row\" }, [\n keyInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n remove\n ]);\n });\n const add = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [placeholders.add]\n );\n add.addEventListener(\"click\", () => {\n let key = \"\";\n for (let i = 1; key in record; i++) key = `key${i}`;\n commit({ ...record, [key]: \"\" });\n });\n element.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(record) {\n if (element.contains(document.activeElement)) return;\n current = record;\n render();\n }\n };\n}\n", "/**\n * Schema-driven data form: generates controls from widgentic's dataSchema\n * subset (type/properties/required/items/enum/pattern). This is the\n * @json-editor/json-editor interaction model, sized to the six keywords\n * the subset actually has \u2014 which is what makes an in-house generator a\n * few hundred lines instead of a 150 KB dependency.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nfunction firstType(schema: DataSchema): string | undefined {\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n // Nullable arrays pick the PRIMARY type regardless of order.\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n if (type.includes(\"null\")) return \"null\";\n }\n return undefined;\n}\n\nfunction seedFor(schema: DataSchema): unknown {\n if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];\n switch (firstType(schema)) {\n case \"object\": {\n const seed: Record<string, unknown> = {};\n if (isPlainObject(schema.properties) && Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && isPlainObject(schema.properties[key])) {\n seed[key] = seedFor(schema.properties[key] as DataSchema);\n }\n }\n }\n return seed;\n }\n case \"array\":\n return [];\n case \"number\":\n case \"integer\":\n return 0;\n case \"boolean\":\n return false;\n case \"null\":\n return null;\n default:\n return \"\";\n }\n}\n\nexport interface SchemaForm {\n element: HTMLElement;\n getValue(): unknown;\n setValue(value: unknown): void;\n}\n\nexport function createSchemaForm(\n schema: DataSchema,\n initial: unknown,\n onChange: (value: unknown) => void\n): SchemaForm {\n let current: unknown = initial ?? seedFor(schema);\n const element = h(\"div\", { class: \"wgd-schemaform\" });\n\n type Path = (string | number)[];\n\n function setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n const holder = isPlainObject(root) ? { ...root } : {};\n if (rest.length === 0 && remove) delete holder[step as string];\n else holder[step as string] = setAt(holder[step as string], rest, value, remove);\n return holder;\n }\n\n function commit(path: Path, value: unknown, rerender = false): void {\n current = setAt(current, path, value);\n onChange(current);\n if (rerender) render();\n }\n\n function control(node: DataSchema, value: unknown, path: Path, label: string): HTMLElement {\n if (Array.isArray(node.enum)) {\n const select = h(\"select\", { class: \"wgd-select\" });\n for (const option of node.enum) {\n select.append(h(\"option\", { value: JSON.stringify(option) }, [JSON.stringify(option)]));\n }\n select.value = JSON.stringify(value ?? node.enum[0]);\n select.addEventListener(\"change\", () =>\n commit(path, JSON.parse(select.value) as unknown)\n );\n return field(label, select);\n }\n switch (firstType(node)) {\n case \"boolean\": {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value === true;\n box.addEventListener(\"change\", () => commit(path, box.checked));\n return field(label, box);\n }\n case \"number\":\n case \"integer\": {\n const input = h(\"input\", { type: \"number\", class: \"wgd-input\" });\n input.value = typeof value === \"number\" ? String(value) : \"0\";\n input.addEventListener(\"change\", () => {\n const parsed = Number(input.value);\n commit(path, Number.isFinite(parsed) ? parsed : 0);\n });\n return field(label, input);\n }\n case \"object\": {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required) ? node.required : [];\n const holder = isPlainObject(value) ? value : {};\n for (const [name, sub] of Object.entries(properties)) {\n if (!isPlainObject(sub)) continue;\n const isRequired = required.includes(name);\n body.append(\n control(\n sub as DataSchema,\n holder[name] ?? (isRequired ? seedFor(sub as DataSchema) : undefined),\n [...path, name],\n isRequired ? `${name} *` : name\n )\n );\n }\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n case \"array\": {\n const itemsSchema = isPlainObject(node.items) ? (node.items as DataSchema) : {};\n const items = Array.isArray(value) ? value : [];\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n items.forEach((item, index) => {\n const row = h(\"div\", { class: \"wgd-jt-entry\" }, [\n control(itemsSchema, item, [...path, index], `#${index}`)\n ]);\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove item\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n current = setAt(current, [...path, index], undefined, true);\n onChange(current);\n render();\n });\n row.append(remove);\n body.append(row);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit([...path, items.length], seedFor(itemsSchema), true)\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n default: {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n if (typeof node.pattern === \"string\") {\n input.setAttribute(\"placeholder\", `pattern: ${node.pattern}`);\n input.setAttribute(\"title\", `Must match ${node.pattern}`);\n }\n input.value = typeof value === \"string\" ? value : value === undefined ? \"\" : String(value);\n input.addEventListener(\"change\", () => commit(path, input.value));\n return field(label, input);\n }\n }\n }\n\n function field(label: string, controlEl: Node): HTMLElement {\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n controlEl\n ]);\n }\n\n function render(): void {\n element.replaceChildren(control(schema, current, [], \"data\"));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value ?? seedFor(schema);\n render();\n }\n };\n}\n", "/**\n * Structured editor for the descriptor's styles \u2014 selector rows with\n * their declaration rows, under the template tree's flat discipline.\n * The value is `Record<selector, Record<property, value>>` (strings\n * only), so the tree enforces the exact shape the server's style guards\n * expect; anything looser belongs in the JSON tab.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nexport type WidgetStylesValue = Record<string, Record<string, string>>;\n\nexport interface StylesEditor {\n element: HTMLElement;\n getValue(): WidgetStylesValue | undefined;\n setValue(styles: WidgetStylesValue | undefined): void;\n}\n\nexport function createStylesEditor(\n initial: WidgetStylesValue | undefined,\n onChange: (styles: WidgetStylesValue | undefined) => void\n): StylesEditor {\n let current: WidgetStylesValue | undefined = initial;\n const element = h(\"div\", { class: \"wgd-styles\" });\n\n function commit(next: WidgetStylesValue): void {\n // An emptied record means \"no styles\" \u2014 the descriptor drops the key.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function renderSelector(\n selector: string,\n declarations: Record<string, string>,\n styles: WidgetStylesValue\n ): HTMLElement {\n const rename = changeInput(\n selector,\n \".wg-selector\",\n \"wgd-input wgd-st-selector\",\n (next) => {\n const entries = Object.entries(styles).map(([k, v]) =>\n k === selector ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const addDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Add declaration\" },\n [\"+\"]\n );\n addDecl.addEventListener(\"click\", () => {\n commit({ ...styles, [selector]: { ...declarations, \"\": \"\" } });\n });\n const removeSelector = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove selector\" },\n [\"\u2715\"]\n );\n removeSelector.addEventListener(\"click\", () => {\n const { [selector]: _gone, ...rest } = styles;\n commit(rest);\n });\n const declRows = Object.entries(declarations).map(([property, value]) => {\n const propInput = changeInput(\n property,\n \"property\",\n \"wgd-input wgd-st-prop\",\n (next) => {\n const entries = Object.entries(declarations).map(([k, v]) =>\n k === property ? ([next, v] as const) : ([k, v] as const)\n );\n commit({ ...styles, [selector]: Object.fromEntries(entries) });\n }\n );\n const valueInput = changeInput(\n value,\n \"value (no url(...), no ;)\",\n \"wgd-input wgd-st-value\",\n (next) => {\n commit({\n ...styles,\n [selector]: { ...declarations, [property]: next }\n });\n }\n );\n const removeDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove declaration\" },\n [\"\u2715\"]\n );\n removeDecl.addEventListener(\"click\", () => {\n const { [property]: _gone, ...rest } = declarations;\n commit({ ...styles, [selector]: rest });\n });\n return h(\"div\", { class: \"wgd-st-decl\" }, [\n propInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n removeDecl\n ]);\n });\n return h(\"div\", { class: \"wgd-st-rule\" }, [\n h(\"div\", { class: \"wgd-st-row\" }, [\n rename,\n h(\"span\", { class: \"wgd-node-icons\" }, [addDecl, removeSelector])\n ]),\n h(\"div\", { class: \"wgd-st-decls\" }, declRows)\n ]);\n }\n\n function render(): void {\n const styles = current ?? {};\n const addSelector = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [\"+ selector\"]\n );\n addSelector.addEventListener(\"click\", () => {\n let name = \".wg-\";\n for (let i = 1; name in styles; i++) name = `.wg-${i}`;\n commit({ ...styles, [name]: {} });\n });\n element.replaceChildren(\n ...Object.entries(styles).map(([selector, declarations]) =>\n renderSelector(\n selector,\n isPlainObject(declarations)\n ? (declarations as Record<string, string>)\n : {},\n styles\n )\n ),\n h(\"div\", { class: \"wgd-toolbar\" }, [addSelector])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(styles) {\n if (element.contains(document.activeElement)) return;\n current = styles;\n render();\n }\n };\n}\n", "/**\n * Path helpers over widgentic's dataSchema subset, shared by the template\n * panel (bind/each/when completions) and the binding editor (input and\n * output mapping completions, type checks). Nullable type arrays pick the\n * PRIMARY type; `any` (no type) is treated as unknown, never mismatched.\n */\nimport { isPlainObject } from \"@widgentic/core\";\n/** The primary type a schema declares, if any. */\nexport function schemaType(schema: unknown): string | undefined {\n if (!isPlainObject(schema)) return undefined;\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n }\n return undefined;\n}\n\n/**\n * Dotted paths reachable from a schema, with the schema at each path.\n * Arrays are offered as themselves; descending into their items needs an\n * `each` first, so collection stops there.\n */\nexport function collectPaths(\n schema: unknown,\n prefix: string,\n out: { path: string; schema: unknown }[],\n depth = 0\n): void {\n if (!isPlainObject(schema) || depth > 3) return;\n if (schemaType(schema) !== \"object\" || !isPlainObject(schema.properties)) return;\n for (const [name, sub] of Object.entries(schema.properties)) {\n const path = prefix === \"\" ? name : `${prefix}.${name}`;\n out.push({ path, schema: sub });\n collectPaths(sub, path, out, depth + 1);\n }\n}\n\n/** The sub-schema at a dotted path (\"\" or \".\" is the schema itself). */\nexport function schemaAt(schema: unknown, path: string): unknown {\n if (path === \"\" || path === \".\") return schema;\n let current: unknown = schema;\n for (const segment of path.split(\".\")) {\n if (!isPlainObject(current)) return undefined;\n if (schemaType(current) === \"array\") {\n current = isPlainObject(current.items) ? current.items : undefined;\n if (!/^\\d+$/.test(segment)) {\n // A named segment under an array steps into the item schema.\n if (!isPlainObject(current) || !isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n continue;\n }\n if (!isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n return current;\n}\n\n/** Numeric types agree with each other; unknown never mismatches. */\nexport function typesConflict(a: string | undefined, b: string | undefined): boolean {\n if (a === undefined || b === undefined) return false;\n const norm = (t: string) => (t === \"integer\" ? \"number\" : t);\n return norm(a) !== norm(b);\n}\n\n/** All dotted paths under a schema (leaves and branches), for completions. */\nexport function allPaths(schema: unknown): string[] {\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(schema, \"\", entries);\n return entries.map((entry) => entry.path);\n}\n", "/**\n * Shared editors for the action model: an action DEFINITION (prompt or\n * http) and a BINDING (shared ref or inline definition, plus the input\n * mapping and output mode). The standalone action designer edits\n * definitions; the widget designer binds them to elements and to the\n * widget's `load`. Everything is plain DOM over immutable values, and no\n * network I/O happens here \u2014 testing an action is the host's job.\n *\n * Handlers read the editor's live state at event time and a commit\n * re-renders only its own section, so two edits in a row never lose each\n * other and focus survives a commit. Rows without a name (a new header,\n * query parameter or projection) live in editor-local state until they are\n * named; only named rows reach `onChange`.\n */\nimport type { DataSchema } from \"@widgentic/core\";\nimport type {\n ActionBinding,\n ActionDefinition,\n HttpActionDefinition,\n InputMapping,\n OutputBinding,\n OutputMode,\n PromptSegment,\n StoredAction\n} from \"@widgentic/core\";\nimport { HTTP_METHODS, OUTPUT_MODES } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h } from \"./dom.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { allPaths, schemaAt, schemaType, typesConflict } from \"./schema-paths.js\";\n\n/** The path select's escape hatch to free text. */\nconst CUSTOM_PATH = \"__custom__\";\n\ntype HeaderValue = string | { secret: string };\ntype HeaderMap = Record<string, HeaderValue>;\ntype RefBinding = { ref: string } & Pick<ActionBinding, \"input\" | \"output\">;\n\nexport interface ActionEditorContext {\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n}\n\nexport function starterPromptDefinition(): ActionDefinition {\n return { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] };\n}\n\nexport function starterHttpDefinition(): HttpActionDefinition {\n return {\n kind: \"http\",\n method: \"GET\",\n url: \"https://api.example.com/resource\",\n input: { type: \"object\", properties: {} },\n output: { type: \"object\" }\n };\n}\n\nfunction isRefBinding(binding: ActionBinding): binding is RefBinding {\n return \"ref\" in binding && typeof binding.ref === \"string\";\n}\n\nfunction textInput(value: string, className: string, onCommit: (value: string) => void, placeholder = \"\"): HTMLInputElement {\n const el = h(\"input\", { type: \"text\", class: className, placeholder });\n el.value = value;\n el.addEventListener(\"change\", () => onCommit(el.value));\n return el;\n}\n\nfunction select(options: { value: string; label?: string }[], value: string, className: string, onChange: (value: string) => void): HTMLSelectElement {\n const el = h(\"select\", { class: className });\n for (const option of options) el.append(h(\"option\", { value: option.value }, [option.label ?? option.value]));\n el.value = value;\n fitSelect(el);\n el.addEventListener(\"change\", () => onChange(el.value));\n return el;\n}\n\nfunction label(text: string): HTMLElement {\n return h(\"span\", { class: \"wgd-field-label\" }, [text]);\n}\n\nfunction removeButton(onClick: () => void): HTMLElement {\n const button = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n button.addEventListener(\"click\", onClick);\n return button;\n}\n\n/**\n * Path picker: a select over the known paths (plus the current value when\n * it is off-schema) with a \"custom\u2026\" escape to free text \u2014 the template\n * panel's pathControl, for mappings. The placeholder option clears the\n * value. With no known paths it is a text input.\n */\nfunction pathSelect(\n value: string,\n options: string[],\n onCommit: (path: string) => void,\n placeholder: string,\n className = \"wgd-input wgd-rec-value\"\n): HTMLElement {\n if (options.length === 0) return textInput(value, className, onCommit, placeholder);\n const sel = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n const listed = known || value === \"\" ? options : [value, ...options];\n sel.append(h(\"option\", { value: \"\" }, [placeholder]));\n for (const option of listed) {\n sel.append(h(\"option\", { value: option }, [option === value && !known ? `${option} (off-schema)` : option]));\n }\n sel.append(h(\"option\", { value: CUSTOM_PATH }, [\"custom\u2026\"]));\n sel.value = value;\n fitSelect(sel);\n const custom = textInput(value, className, onCommit, placeholder);\n custom.hidden = true;\n sel.addEventListener(\"change\", () => {\n if (sel.value === CUSTOM_PATH) {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(sel.value);\n });\n return h(\"span\", { class: \"wgd-pathwrap\" }, [sel, custom]);\n}\n\n/**\n * Header/query map rows: name, literal-or-secret mode, value. Unnamed rows\n * are editor-local; a rename onto an existing name is flagged, not applied.\n */\nfunction headerMapEditor(\n initial: HeaderMap | undefined,\n secretNames: string[],\n labels: { add: string; name: string },\n onChange: (next: HeaderMap | undefined) => void\n): HTMLElement {\n let current: HeaderMap = clone(initial ?? {});\n const pending: { value: HeaderValue }[] = [];\n const element = h(\"div\", { class: \"wgd-record wgd-headers\" });\n const duplicate = diagnosticLine(undefined);\n\n function commit(next: HeaderMap): void {\n current = next;\n onChange(Object.keys(current).length > 0 ? current : undefined);\n render();\n }\n function flagDuplicate(name: string): void {\n duplicate.hidden = false;\n duplicate.textContent = `'${name}' is already used; pick another ${labels.name} name.`;\n }\n function valueControl(value: HeaderValue, onValue: (next: HeaderValue) => void): HTMLElement[] {\n const isSecret = isPlainObject(value);\n const mode = select(\n [{ value: \"literal\" }, { value: \"secret\" }],\n isSecret ? \"secret\" : \"literal\",\n \"wgd-select wgd-attr-mode\",\n (next) => onValue(next === \"secret\" ? { secret: secretNames[0] ?? \"\" } : \"\")\n );\n if (isSecret) {\n const names = secretNames.includes(value.secret) ? secretNames : [value.secret, ...secretNames];\n const picker = select(\n names.map((n) => ({ value: n, label: n === \"\" ? \"(pick a secret)\" : n })),\n value.secret,\n \"wgd-select wgd-secret\",\n (next) => onValue({ secret: next })\n );\n return [mode, picker];\n }\n return [mode, textInput(value, \"wgd-input wgd-rec-value\", onValue, \"value\")];\n }\n function render(): void {\n element.replaceChildren();\n duplicate.hidden = true;\n for (const [name, value] of Object.entries(current)) {\n const nameInput = textInput(name, \"wgd-input wgd-rec-key\", (next) => {\n if (next === name) return;\n if (next === \"\" || Object.hasOwn(current, next)) { flagDuplicate(next || \"(empty)\"); return; }\n const entries = Object.entries(current).map(([k, v]) => (k === name ? [next, v] : [k, v]));\n commit(Object.fromEntries(entries));\n }, labels.name);\n const controls = valueControl(value, (next) => commit({ ...current, [name]: next }));\n const remove = removeButton(() => {\n const { [name]: _gone, ...rest } = current;\n commit(rest);\n });\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [nameInput, ...controls, remove]));\n }\n pending.forEach((row, index) => {\n const nameInput = textInput(\"\", \"wgd-input wgd-rec-key\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(current, next)) { flagDuplicate(next); return; }\n pending.splice(index, 1);\n commit({ ...current, [next]: row.value });\n }, labels.name);\n const controls = valueControl(row.value, (next) => { row.value = next; render(); });\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n element.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [nameInput, ...controls, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [labels.add]);\n add.addEventListener(\"click\", () => { pending.push({ value: \"\" }); render(); });\n element.append(h(\"div\", { class: \"wgd-row\" }, [add]), duplicate);\n }\n render();\n return element;\n}\n\n/** Prompt text: ordered literal/bind segments. */\nfunction segmentsEditor(initial: PromptSegment[], onChange: (next: PromptSegment[]) => void): HTMLElement {\n let current = clone(initial);\n const element = h(\"div\", { class: \"wgd-record wgd-segments\" });\n function commit(next: PromptSegment[]): void {\n current = next;\n onChange(current);\n render();\n }\n function render(): void {\n element.replaceChildren();\n current.forEach((segment, index) => {\n const isBind = typeof segment !== \"string\";\n const mode = select([{ value: \"text\" }, { value: \"bind\" }], isBind ? \"bind\" : \"text\", \"wgd-select wgd-attr-mode\", (next) => {\n const copy = [...current];\n copy[index] = next === \"bind\" ? { bind: \".\" } : \"\";\n commit(copy);\n });\n const value = textInput(\n isBind ? segment.bind : segment,\n \"wgd-input wgd-rec-value\",\n (next) => {\n const copy = [...current];\n copy[index] = isBind ? { bind: next } : next;\n commit(copy);\n },\n isBind ? \"data path\" : \"text\"\n );\n const remove = removeButton(() => commit(current.filter((_, i) => i !== index)));\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [mode, value, remove]));\n });\n const addText = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ text\"]);\n addText.addEventListener(\"click\", () => commit([...current, \"\"]));\n const addBind = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ bind\"]);\n addBind.addEventListener(\"click\", () => commit([...current, { bind: \".\" }]));\n element.append(h(\"div\", { class: \"wgd-row\" }, [addText, addBind]));\n }\n render();\n return element;\n}\n\nexport interface DefinitionEditor {\n element: HTMLElement;\n getValue(): ActionDefinition;\n setValue(definition: ActionDefinition): void;\n}\n\n/** Editor for one action definition, either kind. */\nexport function createDefinitionEditor(\n initial: ActionDefinition | undefined,\n ctx: ActionEditorContext,\n onChange: (definition: ActionDefinition) => void\n): DefinitionEditor {\n let current: ActionDefinition = clone(initial ?? starterPromptDefinition());\n const headEl = h(\"div\", { class: \"wgd-action-head\" });\n const schemasEl = h(\"div\", { class: \"wgd-action-schemas\" });\n const mapsEl = h(\"div\", { class: \"wgd-action-maps\" });\n const element = h(\"div\", { class: \"wgd-action-definition\" }, [headEl, schemasEl, mapsEl]);\n\n /** The live http definition; handlers call this at event time, never a render-time copy. */\n function http(): HttpActionDefinition {\n return current as HttpActionDefinition;\n }\n\n function commit(next: ActionDefinition, rerender: \"all\" | \"schemas\" | \"none\"): void {\n current = next;\n onChange(clone(current));\n if (rerender === \"all\") render();\n else if (rerender === \"schemas\") renderSchemas();\n }\n\n function schemaSection(title: string, which: \"input\" | \"output\"): HTMLElement {\n const builder = createSchemaBuilder(http()[which] as DataSchema, (schema) => {\n commit({ ...http(), [which]: schema ?? { type: \"object\" } }, \"none\");\n });\n const parts: (Node | string)[] = [label(title), builder.element];\n const shared = ctx.schemas ?? [];\n if (shared.length > 0) {\n // Actions store their schemas INLINE (a contract must not drift when a\n // shared schema is edited), so this is a copy \u2014 and says so.\n const copyFrom = select(\n [{ value: \"\", label: \"copy a shared schema into this action\u2026\" }, ...shared.map((s) => ({ value: s.name }))],\n \"\",\n \"wgd-select\",\n (name) => {\n const entry = shared.find((s) => s.name === name);\n if (entry) commit({ ...http(), [which]: clone(entry.schema) }, \"schemas\");\n }\n );\n parts.push(h(\"div\", { class: \"wgd-row\" }, [copyFrom, label(\"(a copy \u2014 later edits to the shared schema do not follow)\")]));\n }\n return h(\"div\", { class: \"wgd-action-schema\" }, parts);\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const kind = select(\n [{ value: \"prompt\", label: \"prompt \u2014 propose a message\" }, { value: \"http\", label: \"http \u2014 call an API\" }],\n current.kind,\n \"wgd-select wgd-action-kind\",\n (next) => commit(next === \"http\" ? starterHttpDefinition() : starterPromptDefinition(), \"all\")\n );\n if (current.kind === \"prompt\") {\n headEl.append(\n h(\"div\", { class: \"wgd-row\" }, [label(\"Kind\"), kind]),\n label(\"Message (literals and bound values; the user reviews and sends it)\"),\n segmentsEditor(current.text, (text) => commit({ kind: \"prompt\", text }, \"none\"))\n );\n return;\n }\n const method = select(HTTP_METHODS.map((m) => ({ value: m })), current.method, \"wgd-select\", (next) =>\n commit({ ...http(), method: next as HttpActionDefinition[\"method\"] }, \"none\")\n );\n // Kind and method describe one thing \u2014 what call this is \u2014 so they share a row.\n const url = textInput(current.url, \"wgd-input wgd-action-url\", (next) => commit({ ...http(), url: next }, \"none\"), \"https://\u2026\");\n headEl.append(\n h(\"div\", { class: \"wgd-row\" }, [label(\"Kind\"), kind, label(\"Method\"), method]),\n h(\"label\", { class: \"wgd-field\" }, [label(\"URL (https, fixed)\"), url])\n );\n }\n\n function renderSchemas(): void {\n schemasEl.replaceChildren();\n if (current.kind !== \"http\") return;\n schemasEl.append(\n schemaSection(\"Input schema (arguments; GET \u2192 query, POST \u2192 JSON body)\", \"input\"),\n schemaSection(\"Output schema (the response must satisfy it)\", \"output\")\n );\n }\n\n function renderMaps(): void {\n mapsEl.replaceChildren();\n if (current.kind !== \"http\") return;\n const secretNames = ctx.secretNames ?? [];\n mapsEl.append(\n label(\"Headers\"),\n headerMapEditor(current.headers, secretNames, { add: \"+ header\", name: \"header\" }, (headers) => {\n const { headers: _h, ...rest } = http();\n commit(headers === undefined ? rest : { ...rest, headers }, \"none\");\n }),\n label(\"Fixed query parameters\"),\n headerMapEditor(current.query, secretNames, { add: \"+ parameter\", name: \"parameter\" }, (query) => {\n const { query: _q, ...rest } = http();\n commit(query === undefined ? rest : { ...rest, query }, \"none\");\n })\n );\n }\n\n function render(): void {\n renderHead();\n renderSchemas();\n renderMaps();\n }\n render();\n return {\n element,\n getValue: () => clone(current),\n setValue(definition) {\n current = clone(definition);\n render();\n }\n };\n}\n\nexport interface BindingEditorContext extends ActionEditorContext {\n /** Shared actions offered by name. */\n actions?: StoredAction[];\n /** Data paths in scope at the bound element, offered as completions. */\n scopePaths?: string[];\n /** The widget's effective data schema (inline or resolved ref) \u2014 drives output-map targets and type checks. */\n getDataSchema?: () => DataSchema | undefined;\n /** `load` bindings: http GET only, no prompt. */\n loadOnly?: boolean;\n}\n\nexport interface BindingEditor {\n element: HTMLElement;\n setValue(binding: ActionBinding | undefined): void;\n}\n\n/** Editor for a binding: none / shared / inline, input mapping, output mode. */\nexport function createBindingEditor(\n initial: ActionBinding | undefined,\n ctx: BindingEditorContext,\n onChange: (binding: ActionBinding | undefined) => void\n): BindingEditor {\n let current: ActionBinding | undefined = initial === undefined ? undefined : clone(initial);\n const headEl = h(\"div\", { class: \"wgd-binding-head\" });\n const inputEl = h(\"div\", { class: \"wgd-binding-input\" });\n const outputEl = h(\"div\", { class: \"wgd-binding-output\" });\n const element = h(\"div\", { class: \"wgd-binding\" }, [headEl, inputEl, outputEl]);\n\n function definitionOf(binding: ActionBinding | undefined): ActionDefinition | undefined {\n if (binding === undefined) return undefined;\n if (isRefBinding(binding)) return (ctx.actions ?? []).find((a) => a.name === binding.ref)?.definition;\n return binding.definition;\n }\n const inputOf = (): InputMapping => clone(current?.input ?? {});\n const outputOf = (): OutputBinding => clone(current?.output ?? {});\n\n function commit(next: ActionBinding | undefined, rerender: \"all\" | \"io\" | \"input\" | \"output\" | \"none\"): void {\n current = next;\n onChange(next === undefined ? undefined : clone(next));\n if (rerender === \"all\") render();\n else if (rerender === \"io\") { renderInput(); renderOutput(); }\n else if (rerender === \"input\") renderInput();\n else if (rerender === \"output\") renderOutput();\n }\n\n function withMapping(binding: ActionBinding, input: InputMapping | undefined, output: OutputBinding | undefined): ActionBinding {\n const head: { ref: string } | { definition: ActionDefinition } = isRefBinding(binding)\n ? { ref: binding.ref }\n : { definition: binding.definition };\n return {\n ...head,\n ...(input !== undefined && Object.keys(input).length > 0 ? { input } : {}),\n ...(output !== undefined && Object.keys(output).length > 0 ? { output } : {})\n };\n }\n\n /** Helper completions are complete paths: the scope markers alone, plus every root path. */\n function helperPaths(): string[] {\n const root = allPaths(ctx.getDataSchema?.()).map((p) => `$root.${p}`);\n return [\"$index\", \"$parent\", \"$root\", ...root];\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const shared = (ctx.actions ?? []).filter((a) => !ctx.loadOnly || (a.definition.kind === \"http\" && a.definition.method === \"GET\"));\n const mode = current === undefined ? \"none\" : isRefBinding(current) ? \"shared\" : \"inline\";\n const modeSelect = select(\n [{ value: \"none\", label: ctx.loadOnly ? \"no load action\" : \"no action\" }, { value: \"shared\", label: \"shared action\" }, { value: \"inline\", label: \"inline definition\" }],\n mode,\n \"wgd-select wgd-binding-mode\",\n (next) => {\n if (next === \"none\") commit(undefined, \"all\");\n else if (next === \"shared\") commit({ ref: shared[0]?.name ?? \"\" }, \"all\");\n else commit({ definition: starterHttpDefinition() }, \"all\");\n }\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [modeSelect]));\n if (current === undefined) return;\n if (isRefBinding(current)) {\n const ref = current.ref;\n const names = shared.map((a) => a.name);\n const options = (names.includes(ref) ? names : [ref, ...names]).map((n) => ({ value: n, label: n === \"\" ? \"(pick an action)\" : names.includes(n) ? n : `${n} (unknown)` }));\n const refSelect = select(options, ref, \"wgd-select wgd-binding-ref\", (next) =>\n commit(withMapping({ ref: next }, inputOf(), outputOf()), \"io\")\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [label(\"Action\"), refSelect]));\n return;\n }\n const editor = createDefinitionEditor(current.definition, ctx, (definition) => {\n // The definition's schemas drive the mapping rows; the head keeps focus.\n commit(withMapping({ definition }, inputOf(), outputOf()), \"io\");\n });\n headEl.append(editor.element);\n }\n\n function renderInput(): void {\n inputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n // Input mapping: one row per declared field, each a data path or a constant.\n const properties = isPlainObject(definition.input.properties) ? Object.keys(definition.input.properties) : [];\n // No element scope supplied (the widget-level `load`): the root data paths ARE the scope.\n const scopePaths = ctx.scopePaths ?? allPaths(ctx.getDataSchema?.());\n const pathOptions = [...new Set([...scopePaths, ...helperPaths()])];\n const mapping = inputOf();\n const rows = properties.map((field) => {\n const value = mapping[field];\n const isConst = isPlainObject(value) && \"const\" in value;\n const kindSelect = select([{ value: \"path\" }, { value: \"const\" }], isConst ? \"const\" : \"path\", \"wgd-select wgd-attr-mode\", (next) => {\n commit(withMapping(binding, { ...inputOf(), [field]: next === \"const\" ? { const: \"\" } : field }, outputOf()), \"input\");\n });\n const onValue = (next: string): void => {\n const nextMapping = inputOf();\n if (isConst) {\n let literal: unknown;\n try { literal = JSON.parse(next); } catch { literal = next; }\n nextMapping[field] = { const: literal };\n } else if (next === \"\") {\n delete nextMapping[field];\n } else {\n nextMapping[field] = next;\n }\n commit(withMapping(binding, nextMapping, outputOf()), \"none\");\n };\n const valueInput = isConst\n ? textInput(JSON.stringify(value.const), \"wgd-input wgd-rec-value\", onValue, \"JSON literal\")\n : pathSelect(typeof value === \"string\" ? value : \"\", pathOptions, onValue, \"data path\");\n return h(\"div\", { class: \"wgd-rec-row\" }, [h(\"span\", { class: \"wgd-rec-key wgd-binding-field\" }, [field]), kindSelect, valueInput]);\n });\n inputEl.append(\n label(\"Input mapping (field \u2190 data path or constant)\"),\n properties.length > 0 ? h(\"div\", { class: \"wgd-record\" }, rows) : h(\"div\", { class: \"wgd-diagnostic\" }, [\"The input schema declares no properties.\"])\n );\n }\n\n function renderOutput(): void {\n outputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n const output = outputOf();\n const mode = output.mode ?? \"merge\";\n const modeSel = select(OUTPUT_MODES.map((m) => ({ value: m })), mode, \"wgd-select\", (next) => {\n const nextOutput: OutputBinding = { ...outputOf(), mode: next as OutputMode };\n if (next !== \"patch\") delete nextOutput.path;\n commit(withMapping(binding, inputOf(), nextOutput), \"output\");\n });\n const outputRow: (Node | string)[] = [label(\"Output\"), modeSel];\n if (mode === \"patch\") {\n outputRow.push(textInput(output.path ?? \"\", \"wgd-input\", (next) => {\n commit(withMapping(binding, inputOf(), { ...outputOf(), path: next }), \"output\");\n }, \"data path to write at\"));\n }\n outputEl.append(h(\"div\", { class: \"wgd-row\" }, outputRow));\n outputEl.append(outputMapEditor(definition, output, (map) => {\n const nextOutput = outputOf();\n if (map === undefined) delete nextOutput.map; else nextOutput.map = map;\n commit(withMapping(binding, inputOf(), nextOutput), \"none\");\n }));\n }\n\n /**\n * Output projection rows: target (a widget data path, relative to the\n * patch path when that mode is on) \u2190 source (a response path). Both\n * inputs complete from the respective schemas, and a type mismatch is\n * flagged here \u2014 at execution it would only surface as INVALID_TYPE.\n * Unnamed rows are editor-local until they get a target.\n */\n function outputMapEditor(\n definition: HttpActionDefinition,\n output: OutputBinding,\n onMap: (map: Record<string, string> | undefined) => void\n ): HTMLElement {\n const container = h(\"div\", { class: \"wgd-record wgd-output-map\" });\n let map: Record<string, string> = clone(output.map ?? {});\n const pending: { source: string }[] = [];\n const widgetSchema = ctx.getDataSchema?.();\n const base = (output.mode ?? \"merge\") === \"patch\" && output.path ? output.path : \"\";\n const targetRoot = base === \"\" ? widgetSchema : schemaAt(widgetSchema, base);\n const targetOptions = allPaths(targetRoot);\n const sourceOptions = [\".\", ...allPaths(definition.output)];\n const mismatch = diagnosticLine(undefined);\n mismatch.classList.add(\"wgd-type-mismatch\");\n\n function commitMap(next: Record<string, string>): void {\n map = next;\n onMap(Object.keys(map).length > 0 ? map : undefined);\n render();\n }\n function flag(text: string): void {\n mismatch.hidden = false;\n mismatch.textContent = text;\n }\n function targetControl(target: string, onTarget: (next: string) => void): HTMLElement {\n const control = pathSelect(target, targetOptions, onTarget, \"target data path\", \"wgd-input wgd-rec-key\");\n control.classList.add(\"wgd-map-target\");\n return control;\n }\n function render(): void {\n container.replaceChildren();\n const problems: string[] = [];\n for (const [target, source] of Object.entries(map)) {\n const targetType = schemaType(schemaAt(targetRoot, target));\n const sourceType = schemaType(schemaAt(definition.output, source));\n if (typesConflict(sourceType, targetType)) {\n problems.push(`'${source}' is ${sourceType} in the response but '${base ? `${base}.` : \"\"}${target}' is ${targetType} in the widget schema`);\n }\n const targetInput = targetControl(target, (next) => {\n if (next === target) return;\n if (next === \"\" || Object.hasOwn(map, next)) { flag(`'${next || \"(empty)\"}' is already a projection target.`); return; }\n const entries = Object.entries(map).map(([k, v]) => (k === target ? [next, v] : [k, v]));\n commitMap(Object.fromEntries(entries));\n });\n const sourceInput = pathSelect(source, sourceOptions, (next) => commitMap({ ...map, [target]: next }), \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => {\n const { [target]: _gone, ...rest } = map;\n commitMap(rest);\n });\n container.append(h(\"div\", { class: \"wgd-rec-row\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n }\n pending.forEach((row, index) => {\n const targetInput = targetControl(\"\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(map, next)) { flag(`'${next}' is already a projection target.`); return; }\n pending.splice(index, 1);\n commitMap({ ...map, [next]: row.source });\n });\n const sourceInput = pathSelect(row.source, sourceOptions, (next) => { row.source = next; render(); }, \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n container.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ projection\"]);\n add.addEventListener(\"click\", () => { pending.push({ source: \"\" }); render(); });\n mismatch.hidden = problems.length === 0;\n mismatch.textContent = problems.length === 0 ? \"\" : `Type mismatch: ${problems.join(\"; \")}.`;\n container.append(h(\"div\", { class: \"wgd-row\" }, [add]), mismatch);\n }\n render();\n return container;\n }\n\n function render(): void {\n renderHead();\n renderInput();\n renderOutput();\n }\n render();\n return {\n element,\n setValue(binding) {\n current = binding === undefined ? undefined : clone(binding);\n render();\n }\n };\n}\n", "/**\n * The designer's derive step: run widgentic's pure validators over the\n * draft and shape their structured errors into per-panel diagnostics.\n * Everything here goes through public package entries \u2014 the designer owns\n * no validation logic of its own.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport {\n createCatalog,\n validateDataAgainstSchema,\n widgetStylesToCss\n} from \"@widgentic/core\";\nimport type { WidgetStyles } from \"@widgentic/core\";\nimport type { WidgetContractError } from \"@widgentic/core\";\nimport { collectActionRefs, parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeError } from \"@widgentic/core\";\nimport type { WidgetDraft } from \"./store.js\";\n\nexport interface TemplateIssue {\n code: string;\n message: string;\n /** Node path when the validator reports one. */\n path?: string;\n}\n\nexport interface StyleIssue {\n selector: string;\n property?: string;\n message: string;\n}\n\nexport interface DesignerDiagnostics {\n /** Problem with the kind id itself (empty, or colliding with a base kind). */\n kind?: string;\n template?: TemplateIssue;\n /** `descriptor.dataExample` vs `descriptor.dataSchema`. */\n example?: WidgetContractError;\n /** `sampleData` vs `descriptor.dataSchema`. */\n sample?: WidgetContractError;\n /** Entries the renderer's safety filters would skip. */\n styles: StyleIssue[];\n theme?: ThemeError;\n /** Shared-schema reference problems (unknown ref, or ref + inline). */\n schemaRef?: string;\n /** The widget-level `load` binding failed validation. */\n load?: string;\n /** Shared actions referenced by the template or `load` that are not among the supplied ones. */\n actionRefs?: string;\n /** True when the draft can be registered and previewed. */\n previewable: boolean;\n}\n\n/** Host-supplied shared schemas the draft may reference by name. */\nexport interface DeriveOptions {\n schemas?: { name: string; schema: Record<string, unknown> }[];\n /** Host-supplied shared actions the draft may bind by name. */\n actions?: { name: string }[];\n}\n\n/**\n * The schema validation actually runs against: the inline one, or the\n * referenced shared one resolved from the supplied list \u2014 the same join\n * the server's composition performs.\n */\nexport function effectiveDataSchema(\n draft: WidgetDraft,\n schemas: { name: string; schema: Record<string, unknown> }[] = []\n): Record<string, unknown> | undefined {\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n return schemas.find((entry) => entry.name === ref)?.schema;\n }\n const inline = draft.descriptor?.dataSchema;\n return isPlainObject(inline) ? inline : undefined;\n}\n\nconst BASE_KINDS = new Set(createCatalog().kinds());\n\n/**\n * Detect style entries the renderer would skip, using only the public\n * generator: a probe that produces no CSS was filtered by the safety\n * guards. Selector and per-declaration issues are reported separately.\n */\nfunction auditStyles(styles: WidgetStyles | undefined): StyleIssue[] {\n if (!isPlainObject(styles)) return [];\n const issues: StyleIssue[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (widgetStylesToCss({ [selector]: { color: \"red\" } }) === \"\") {\n issues.push({\n selector,\n message:\n \"Selector would be skipped \u2014 every comma-separated part must target a .wg- class and avoid ;{}<>@\\\\.\"\n });\n continue;\n }\n if (!isPlainObject(declarations)) {\n issues.push({ selector, message: \"Declarations must be a property \u2192 value map.\" });\n continue;\n }\n for (const [property, value] of Object.entries(declarations)) {\n if (\n typeof value !== \"string\" ||\n widgetStylesToCss({ \".wg-probe\": { [property]: value } }) === \"\"\n ) {\n issues.push({\n selector,\n property,\n message:\n \"Declaration would be skipped \u2014 unsafe property name or value (no url(), expression(), or ;{}<>@\\\\).\"\n });\n }\n }\n }\n return issues;\n}\n\n/** Run every validator; total \u2014 never throws on any draft shape. */\nexport function deriveDiagnostics(\n draft: WidgetDraft,\n options: DeriveOptions = {}\n): DesignerDiagnostics {\n const diagnostics: DesignerDiagnostics = { styles: [], previewable: false };\n\n if (typeof draft.kind !== \"string\" || draft.kind.trim().length === 0) {\n diagnostics.kind = \"Kind must be a non-empty id.\";\n } else if (BASE_KINDS.has(draft.kind)) {\n diagnostics.kind = `'${draft.kind}' is a built-in kind \u2014 pick a distinct id.`;\n }\n\n const template = validateTemplate(draft.template);\n if (!template.ok) {\n const issue: TemplateIssue = {\n code: template.error.code,\n message: template.error.message\n };\n const path = (template.error as { path?: unknown }).path;\n if (typeof path === \"string\") issue.path = path;\n diagnostics.template = issue;\n }\n\n // Shared-schema refs resolve here exactly as the server's composition\n // resolves them, so diagnostics match what the store will enforce.\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n if (draft.descriptor?.dataSchema !== undefined) {\n diagnostics.schemaRef =\n \"A descriptor carries 'dataSchema' OR 'dataSchemaRef', never both.\";\n } else if (\n (options.schemas ?? []).every((entry) => entry.name !== ref)\n ) {\n diagnostics.schemaRef = `References unknown schema '${ref}' \u2014 it is not among the supplied shared schemas.`;\n }\n }\n const schema = effectiveDataSchema(draft, options.schemas ?? []);\n if (isPlainObject(schema)) {\n if (draft.descriptor.dataExample !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.descriptor.dataExample);\n if (error) diagnostics.example = error;\n }\n if (draft.sampleData !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.sampleData);\n if (error) diagnostics.sample = error;\n }\n }\n\n diagnostics.styles = auditStyles(draft.descriptor?.styles);\n\n if (draft.load !== undefined) {\n const problem = validateLoadBinding(draft.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) diagnostics.load = `${problem.message} (at ${problem.path})`;\n }\n if (options.actions !== undefined) {\n const known = new Set(options.actions.map((action) => action.name));\n const unknown = collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref));\n if (unknown.length > 0) {\n diagnostics.actionRefs = `References unknown shared action${unknown.length === 1 ? \"\" : \"s\"} ${unknown\n .map((ref) => `'${ref}'`)\n .join(\", \")} \u2014 bound elements will render disabled.`;\n }\n }\n\n if (draft.theme !== undefined) {\n const theme = validateTheme(draft.theme);\n if (!theme.ok) diagnostics.theme = theme.error;\n }\n\n diagnostics.previewable =\n diagnostics.kind === undefined && diagnostics.template === undefined;\n return diagnostics;\n}\n", "/**\n * Template editing: a structured node tree and a JSON source pane \u2014 two\n * projections of one canonical model (the draft's template). The JSON\n * pane is parse-gated (invalid JSON never reaches the store; last valid\n * wins); structural edits from either side may still fail\n * `validateTemplate`, which surfaces as diagnostics pinned to the node\n * path without ever losing the draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { collectActionRefs } from \"@widgentic/core\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { ActionBinding, StoredAction } from \"@widgentic/core\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { collectPaths, schemaType } from \"./schema-paths.js\";\nimport { effectiveDataSchema } from \"./validate.js\";\nimport { diagnosticLine, fitSelect, h, menuButton } from \"./dom.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\ntype Path = (string | number)[];\n\n/** What a data path is being used for \u2014 decides which paths are offered. */\ntype PathUse = \"bind\" | \"each\" | \"when\";\n\n/** Paths worth offering for a given use. */\nfunction pathOptions(scope: unknown, use: PathUse): string[] {\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(scope, \"\", entries);\n const scalars = new Set([\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\",\n undefined\n ]);\n const filtered = entries.filter(({ schema }) => {\n const type = schemaType(schema);\n if (use === \"each\") return type === \"array\";\n if (use === \"bind\") return scalars.has(type);\n return true; // `when` tests truthiness of anything\n });\n const paths = filtered.map((entry) => entry.path);\n // \".\" is the scope itself \u2014 the item inside an each over scalars.\n if (use !== \"each\" && scalars.has(schemaType(scope))) paths.unshift(\".\");\n return paths;\n}\n\n/** Schema in effect inside `each: <path>` \u2014 the array's item schema. */\nfunction itemScope(scope: unknown, eachPath: string): unknown {\n if (!isPlainObject(scope) || eachPath === \".\") return undefined;\n let current: unknown = scope;\n for (const segment of eachPath.split(\".\")) {\n if (!isPlainObject(current) || !isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n return isPlainObject(current) && schemaType(current) === \"array\"\n ? current.items\n : undefined;\n}\n\nconst REMOVE = Symbol(\"remove\");\n\nfunction pathString(path: Path): string {\n let out = \"\";\n for (const step of path) {\n const segment = typeof step === \"number\" ? `children.${step}` : step;\n out = out === \"\" ? segment : `${out}.${segment}`;\n }\n return out;\n}\n\n/** Immutable set/remove at a node path (numbers index `children`). */\nfunction setNode(node: unknown, path: Path, next: unknown): unknown {\n if (path.length === 0) return next === REMOVE ? undefined : next;\n const [step, ...rest] = path as [string | number, ...Path];\n if (typeof step === \"number\") {\n if (!isPlainObject(node) || !Array.isArray(node.children)) return node;\n const children = [...(node.children as unknown[])];\n if (rest.length === 0 && next === REMOVE) {\n children.splice(step, 1);\n } else {\n children[step] = setNode(children[step], rest, next);\n }\n return { ...node, children };\n }\n if (!isPlainObject(node)) return node;\n if (rest.length === 0 && next === REMOVE) {\n const { [step]: _removed, ...remaining } = node;\n return remaining;\n }\n return { ...node, [step]: setNode(node[step], rest, next) };\n}\n\nfunction swapChildren(root: unknown, parent: Path, a: number, b: number): unknown {\n const holder = parent.length === 0 ? root : getNode(root, parent);\n if (!isPlainObject(holder) || !Array.isArray(holder.children)) return root;\n const children = [...(holder.children as unknown[])];\n if (a < 0 || b < 0 || a >= children.length || b >= children.length) return root;\n const [x, y] = [children[a], children[b]];\n children[a] = y;\n children[b] = x;\n const swapped = { ...holder, children };\n return parent.length === 0 ? swapped : setNode(root, parent, swapped);\n}\n\nfunction getNode(node: unknown, path: Path): unknown {\n let current = node;\n for (const step of path) {\n if (!isPlainObject(current)) return undefined;\n current =\n typeof step === \"number\"\n ? Array.isArray(current.children)\n ? (current.children as unknown[])[step]\n : undefined\n : current[step];\n }\n return current;\n}\n\nconst NODE_PRESETS: Record<string, () => unknown> = {\n text: () => \"text\",\n bind: () => ({ bind: \".\" }),\n element: () => ({ tag: \"div\", children: [] }),\n each: () => ({ each: \".\", template: \"item\" }),\n when: () => ({ when: \".\", template: \"shown\" })\n};\n\n/** What element bindings can reach: shared actions, secrets, schemas. */\nexport interface TemplateActionContext {\n actions: StoredAction[];\n secretNames: string[];\n schemas: SchemaEntry[];\n}\n\nexport interface TemplatePanelOptions {\n actionContext?: TemplateActionContext;\n}\n\n/** A bound attribute value, narrowed once per attribute row (a type literal: comparable with the raw record). */\ntype AttrBind = {\n bind: string;\n prefix?: string;\n map?: Record<string, string>;\n default?: string;\n};\n\nexport function mountTemplatePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n options: TemplatePanelOptions = {}\n): {\n element: HTMLElement;\n refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void;\n dispose(): void;\n} {\n const actionContext: TemplateActionContext = options.actionContext ?? { actions: [], secretNames: [], schemas: [] };\n // Shared refs the draft binds that no supplied action answers to.\n let unknownRefs = new Set<string>();\n const treeHost = h(\"div\", { class: \"wgd-tree\" });\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-template-json\",\n rows: \"14\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n attachJsonHighlight(jsonArea);\n jsonWrap.hidden = true;\n\n const treeTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Tree\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"JSON\"]);\n treeTab.addEventListener(\"click\", () => {\n treeHost.hidden = false;\n jsonWrap.hidden = true;\n });\n jsonTab.addEventListener(\"click\", () => {\n treeHost.hidden = true;\n jsonWrap.hidden = false;\n });\n\n const templateDiag = diagnosticLine(undefined);\n const element = h(\"details\", { class: \"wgd-section\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-section-title\" }, [\"Template\"]),\n h(\"div\", { class: \"wgd-section-body\" }, [\n h(\"div\", { class: \"wgd-row\" }, [treeTab, jsonTab]),\n templateDiag,\n treeHost,\n jsonWrap\n ])\n ]);\n\n function commit(next: unknown): void {\n store.update((draft) => ({ ...draft, template: next as WidgetTemplate }));\n }\n\n function commitAt(path: Path, next: unknown): void {\n commit(setNode(store.get().template, path, next));\n }\n\n // --- JSON pane: parse-gated projection --------------------------------\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n commit(parsed);\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (template keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n // --- Tree editor -------------------------------------------------------\n function changeInput(\n value: string,\n onCommit: (value: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLInputElement {\n const input = h(\"input\", { type: \"text\", class: className });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n /**\n * Collapse state, keyed by node path so it survives the full re-render\n * every draft edit triggers. Paths shift when siblings move or vanish \u2014\n * an accepted approximation, exactly like text-editor fold markers.\n */\n const collapsedPaths = new Set<string>();\n\n /**\n * One node = one header row: chevron, badge, the node's own value\n * control(s), then add/move/remove icons (revealed on hover). Sub-\n * structure (attrs, children, slots) nests below and folds away when\n * the node is collapsed; a muted summary keeps the hidden shape legible.\n */\n function nodeShell(\n /** Omitted for elements \u2014 their tag select already names the node. */\n badge: string | undefined,\n path: Path,\n inline: (Node | string)[],\n body: (Node | string)[],\n errorText: string | undefined,\n removable: boolean,\n moves?: { parent: Path; index: number; count: number },\n extras?: { icons?: (Node | string)[]; summary?: string }\n ): HTMLElement {\n const key = pathString(path);\n const collapsible = body.length > 0;\n const isCollapsed = collapsible && collapsedPaths.has(key);\n let chevron: HTMLElement;\n if (collapsible) {\n chevron = h(\n \"button\",\n {\n class: \"wgd-chevron\",\n type: \"button\",\n title: isCollapsed ? \"Expand\" : \"Collapse\"\n },\n [isCollapsed ? \"\u25B8\" : \"\u25BE\"]\n );\n chevron.addEventListener(\"click\", () => {\n if (isCollapsed) collapsedPaths.delete(key);\n else collapsedPaths.add(key);\n renderTree();\n });\n } else {\n // Every row reserves the chevron column so values align.\n chevron = h(\"span\", { class: \"wgd-chevron wgd-chevron-none\" });\n }\n const header: (Node | string)[] =\n badge === undefined\n ? [chevron, ...inline]\n : [chevron, h(\"span\", { class: \"wgd-node-badge\" }, [badge]), ...inline];\n if (isCollapsed && extras?.summary !== undefined) {\n header.push(h(\"span\", { class: \"wgd-node-summary\" }, [extras.summary]));\n }\n const icons: (Node | string)[] = [...(extras?.icons ?? [])];\n if (moves && moves.count > 1) {\n if (moves.index > 0) {\n const up = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move up\" }, [\"\u2191\"]);\n up.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index - 1))\n );\n icons.push(up);\n }\n if (moves.index < moves.count - 1) {\n const down = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move down\" }, [\"\u2193\"]);\n down.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index + 1))\n );\n icons.push(down);\n }\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () =>\n path.length === 0 ? commit(\"\") : commitAt(path, REMOVE)\n );\n icons.push(remove);\n }\n if (icons.length > 0) {\n header.push(h(\"span\", { class: \"wgd-node-icons\" }, icons));\n }\n const children: (Node | string)[] = [h(\"div\", { class: \"wgd-node-row\" }, header)];\n // Diagnostics stay visible even on a collapsed node \u2014 folding must\n // never hide an error.\n if (errorText !== undefined) children.push(diagnosticLine(errorText));\n if (!isCollapsed) children.push(...body);\n return h(\"div\", { class: \"wgd-node\", \"data-path\": key }, children);\n }\n\n /** Tags the built-in styles and typical widget markup actually use. */\n const TAG_OPTIONS = [\n \"div\", \"span\", \"p\", \"section\", \"article\", \"header\", \"footer\",\n \"h1\", \"h2\", \"h3\", \"h4\", \"strong\", \"em\", \"small\", \"code\", \"pre\",\n \"ul\", \"ol\", \"li\", \"dl\", \"dt\", \"dd\",\n \"table\", \"thead\", \"tbody\", \"tr\", \"th\", \"td\",\n \"img\", \"a\", \"figure\", \"figcaption\", \"hr\", \"br\", \"label\"\n ];\n\n /**\n * Data-path control. With a schema in scope it is a select of the paths\n * that scope actually offers (plus the current value if it is off-schema,\n * and a custom escape); without one it stays a free-text input.\n */\n function pathControl(\n value: string,\n scope: unknown,\n use: PathUse,\n onCommit: (path: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLElement {\n const options = isPlainObject(scope) ? pathOptions(scope, use) : [];\n if (options.length === 0) {\n return changeInput(value, onCommit, className);\n }\n const select = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n for (const option of known ? options : [value, ...options]) {\n select.append(\n h(\"option\", { value: option }, [\n option === value && !known ? `${option} (off-schema)` : option\n ])\n );\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = value;\n fitSelect(select);\n const custom = changeInput(value, onCommit, className);\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n // The wrap carries the row-shape marker (e.g. wgd-attr-value) so rows\n // read the same whether the value is a select or free text.\n const marker = className.includes(\"wgd-attr-value\") ? \" wgd-attr-value\" : \"\";\n return h(\"span\", { class: `wgd-pathwrap${marker}` }, [select, custom]);\n }\n\n function tagControl(tag: string, onCommit: (tag: string) => void): HTMLElement {\n const select = h(\"select\", { class: \"wgd-select wgd-tag\" });\n const options = TAG_OPTIONS.includes(tag) ? TAG_OPTIONS : [tag, ...TAG_OPTIONS];\n for (const option of options) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = tag;\n fitSelect(select);\n const custom = changeInput(tag, onCommit, \"wgd-input wgd-tag-custom\");\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n return h(\"span\", { class: \"wgd-tagwrap\" }, [select, custom]);\n }\n\n function slotEditor(\n label: string,\n parentPath: Path,\n slot: \"template\" | \"empty\" | \"else\",\n node: unknown,\n required: boolean,\n errorPath: string | undefined,\n scope: unknown\n ): HTMLElement {\n const slotPath = [...parentPath, slot];\n if (node === undefined) {\n const menu = menuButton(\n `+ ${label}`,\n `Set '${label}' to a node`,\n Object.keys(NODE_PRESETS),\n (name) => {\n const preset = NODE_PRESETS[name];\n if (preset) commitAt(slotPath, preset());\n }\n );\n return required\n ? h(\"div\", { class: \"wgd-slot\" }, [\n diagnosticLine(`Missing required '${label}'.`),\n menu\n ])\n : h(\"div\", { class: \"wgd-slot wgd-slot-unset\" }, [menu]);\n }\n return h(\"div\", { class: \"wgd-slot\" }, [\n h(\"span\", { class: \"wgd-slot-label\" }, [label]),\n renderNode(node, slotPath, errorPath, !required, undefined, scope)\n ]);\n }\n\n function renderNode(\n node: unknown,\n path: Path,\n errorPath: string | undefined,\n removable = true,\n moves?: { parent: Path; index: number; count: number },\n scope?: unknown\n ): HTMLElement {\n const here = pathString(path);\n const errorHere =\n errorPath !== undefined &&\n (errorPath === here ||\n ((errorPath.startsWith(here === \"\" ? \"attrs.\" : `${here}.attrs.`) ||\n errorPath.startsWith(here === \"\" ? \"action\" : `${here}.action`)) &&\n isPlainObject(node) &&\n typeof node.tag === \"string\"))\n ? currentError\n : undefined;\n\n if (typeof node === \"string\") {\n return nodeShell(\n \"text\",\n path,\n [changeInput(node, (value) => commitAt(path, value))],\n [],\n errorHere,\n removable,\n moves\n );\n }\n if (!isPlainObject(node)) {\n return nodeShell(\n \"invalid\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Not a template node.\",\n removable,\n moves\n );\n }\n if (typeof node.bind === \"string\") {\n return nodeShell(\n \"bind\",\n path,\n [\n pathControl(node.bind, scope, \"bind\", (value) =>\n commitAt(path, { bind: value })\n )\n ],\n [],\n errorHere,\n removable,\n moves\n );\n }\n if (typeof node.each === \"string\") {\n return nodeShell(\n \"each\",\n path,\n [\n pathControl(node.each, scope, \"each\", (value) =>\n commitAt(path, { ...node, each: value })\n )\n ],\n [\n // Inside an each, the scope becomes the array's item schema.\n slotEditor(\n \"template\",\n path,\n \"template\",\n node.template,\n true,\n errorPath,\n itemScope(scope, node.each)\n ),\n slotEditor(\n \"empty\",\n path,\n \"empty\",\n node.empty,\n false,\n errorPath,\n scope\n )\n ],\n errorHere,\n removable,\n moves,\n { summary: node.empty !== undefined ? \"template \u00B7 empty\" : \"template\" }\n );\n }\n if (typeof node.when === \"string\") {\n return nodeShell(\n \"when\",\n path,\n [\n pathControl(node.when, scope, \"when\", (value) =>\n commitAt(path, { ...node, when: value })\n )\n ],\n [\n slotEditor(\"template\", path, \"template\", node.template, true, errorPath, scope),\n slotEditor(\"else\", path, \"else\", node.else, false, errorPath, scope)\n ],\n errorHere,\n removable,\n moves,\n { summary: node.else !== undefined ? \"template \u00B7 else\" : \"template\" }\n );\n }\n if (typeof node.tag === \"string\") {\n const attrs = isPlainObject(node.attrs) ? node.attrs : {};\n const binding = isPlainObject(node.action) ? (node.action as ActionBinding) : undefined;\n const attrRows = Object.entries(attrs).map(([name, value]) => {\n // The bind's transform fields, when present. Every write goes\n // through rebuild() so editing one field never drops the others.\n // `bound` is meaningful only while `isBind`; narrowed once here.\n const bound: AttrBind =\n isPlainObject(value) && typeof value.bind === \"string\" ? (value as AttrBind) : { bind: \"\" };\n const isBind = isPlainObject(value) && typeof value.bind === \"string\";\n const bindValue = isBind ? bound : undefined;\n const rebuild = (fields: {\n bind: string;\n prefix?: string | undefined;\n map?: Record<string, string> | undefined;\n default?: string | undefined;\n }): Record<string, unknown> => {\n const out: Record<string, unknown> = { bind: fields.bind };\n if (fields.map !== undefined) {\n out.map = fields.map;\n if (fields.default !== undefined && fields.default !== \"\") {\n out.default = fields.default;\n }\n } else if (fields.prefix !== undefined && fields.prefix !== \"\") {\n out.prefix = fields.prefix;\n }\n return out;\n };\n const setAttr = (nextValue: unknown): void => {\n commitAt(path, { ...node, attrs: { ...attrs, [name]: nextValue } });\n };\n const nameInput = changeInput(\n name,\n (nextName) => {\n const entries = Object.entries(attrs).map(([k, v]) =>\n k === name ? ([nextName, v] as const) : ([k, v] as const)\n );\n commitAt(path, { ...node, attrs: Object.fromEntries(entries) });\n },\n \"wgd-input wgd-attr-name\"\n );\n const mode = h(\"select\", { class: \"wgd-select wgd-attr-mode\" });\n mode.append(h(\"option\", { value: \"literal\" }, [\"literal\"]));\n mode.append(h(\"option\", { value: \"bind\" }, [\"bind\"]));\n mode.value = isBind ? \"bind\" : \"literal\";\n fitSelect(mode);\n // Literal: free text. Bind: the same path dropdown the bind/each/when nodes use.\n const literalInput = changeInput(String(isBind ? \"\" : value), (next) => setAttr(next), \"wgd-input wgd-attr-value\");\n const valueInput: HTMLElement = isBind\n ? pathControl(\n bound.bind,\n scope,\n \"bind\",\n (next) => setAttr(rebuild({ ...bound, bind: next })),\n \"wgd-input wgd-attr-value\"\n )\n : literalInput;\n mode.addEventListener(\"change\", () => {\n // Switching modes carries the current text across as a starting point.\n const current = isBind ? bound.bind : literalInput.value;\n setAttr(mode.value === \"bind\" ? { bind: current || \".\" } : current);\n });\n const removeAttr = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove attribute\" }, [\"\u2715\"]);\n removeAttr.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = attrs;\n commitAt(path, { ...node, attrs: rest });\n });\n\n const row: (Node | string)[] = [nameInput, mode, valueInput];\n const hasMap = bindValue?.map !== undefined;\n const hasPrefix =\n bindValue?.prefix !== undefined && bindValue.prefix !== \"\";\n if (isBind && !hasMap) {\n // Literal prefix (mailto:/tel: links). Hidden while a map is\n // active \u2014 one transform per value, mirroring the validator.\n const prefixInput = changeInput(\n bindValue?.prefix ?? \"\",\n (next) => setAttr(rebuild({ ...bound, map: undefined, prefix: next })),\n \"wgd-input wgd-attr-prefix\"\n );\n prefixInput.placeholder = \"prefix\";\n prefixInput.title = \"Literal prefix, e.g. mailto: \u2014 emitted only when the bound value is non-empty\";\n row.push(prefixInput);\n }\n if (isBind && !hasMap && !hasPrefix) {\n const addMap = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Map values to authored literals (e.g. status \u2192 class)\" },\n [\"map\"]\n );\n addMap.addEventListener(\"click\", () =>\n setAttr(rebuild({ ...bound, prefix: undefined, map: {} }))\n );\n row.push(h(\"span\", { class: \"wgd-node-icons\" }, [addMap, removeAttr]));\n } else {\n row.push(removeAttr);\n }\n\n const attrRow = h(\"div\", { class: \"wgd-attr-row\" }, row);\n const parts: (Node | string)[] = [attrRow];\n if (isBind && hasMap) {\n // The map block: data value \u2192 authored literal rows, plus the\n // miss default. Emptying the record drops the transform.\n const mapEditor = createRecordEditor(\n bound.map,\n { key: \"data value\", value: \"authored literal\", add: \"+ mapping\" },\n (nextMap) => {\n setAttr(\n nextMap === undefined\n ? { bind: bound.bind }\n : rebuild({ ...bound, map: nextMap })\n );\n }\n );\n const defaultInput = changeInput(\n bound.default ?? \"\",\n (next) => setAttr(rebuild({ ...bound, default: next })),\n \"wgd-input wgd-attr-map-default\"\n );\n defaultInput.placeholder = \"default (on miss)\";\n parts.push(\n h(\"div\", { class: \"wgd-attr-map\" }, [\n mapEditor.element,\n h(\"div\", { class: \"wgd-rec-row\" }, [\n h(\"span\", { class: \"wgd-st-colon\" }, [\"\u21B3\"]),\n defaultInput\n ])\n ])\n );\n }\n return parts.length === 1\n ? attrRow\n : h(\"div\", { class: \"wgd-attr\" }, parts);\n });\n const childNodes = Array.isArray(node.children) ? (node.children as unknown[]) : [];\n // One add menu per element covers attributes and every child form \u2014\n // the tree carries no persistent per-form button rows.\n const addMenu = menuButton(\n \"+\",\n \"Add attribute or child node\",\n // Actions belong on activatable elements: buttons and links.\n [\n \"attribute\",\n ...(binding === undefined && (node.tag === \"button\" || node.tag === \"a\") ? [\"action\"] : []),\n ...Object.keys(NODE_PRESETS)\n ],\n (choice) => {\n collapsedPaths.delete(pathString(path)); // never add into a fold\n const preset = NODE_PRESETS[choice];\n if (choice === \"attribute\") {\n commitAt(path, { ...node, attrs: { ...attrs, \"\": \"\" } });\n } else if (choice === \"action\") {\n const first = actionContext.actions[0];\n commitAt(path, {\n ...node,\n action: first !== undefined ? { ref: first.name } : { definition: { kind: \"prompt\", text: [\"Tell me more\"] } }\n });\n } else if (preset) {\n commitAt([...path, childNodes.length], preset());\n }\n }\n );\n const body: (Node | string)[] = [];\n if (attrRows.length > 0) body.push(h(\"div\", { class: \"wgd-attrs\" }, attrRows));\n // Action binding: the element becomes activatable in Apps hosts. The\n // editor commits the whole binding; `undefined` drops the key.\n if (binding !== undefined) {\n const scopePaths = isPlainObject(scope) ? pathOptions(scope, \"when\") : [];\n const bindingEditor = createBindingEditor(\n binding,\n {\n ...actionContext,\n scopePaths,\n // The widget's effective data schema drives output-map targets.\n getDataSchema: () => effectiveDataSchema(store.get(), actionContext.schemas)\n },\n (next) => {\n if (next === undefined) {\n const { action: _gone, ...rest } = node;\n commitAt(path, rest);\n } else {\n commitAt(path, { ...node, action: next });\n }\n }\n );\n const actionParts: (Node | string)[] = [h(\"span\", { class: \"wgd-slot-label\" }, [\"action\"]), bindingEditor.element];\n // An unknown shared ref is flagged at the element carrying it.\n const ref = \"ref\" in binding && typeof binding.ref === \"string\" ? binding.ref : undefined;\n if (ref !== undefined && unknownRefs.has(ref)) {\n actionParts.push(diagnosticLine(`Unknown shared action '${ref}' \u2014 this element renders disabled.`));\n }\n body.push(h(\"div\", { class: \"wgd-attrs wgd-node-action\" }, actionParts));\n }\n if (childNodes.length > 0) {\n body.push(\n h(\n \"div\",\n { class: \"wgd-children\" },\n childNodes.map((child, index) =>\n renderNode(\n child,\n [...path, index],\n errorPath,\n true,\n { parent: path, index, count: childNodes.length },\n scope\n )\n )\n )\n );\n }\n const summaryParts: string[] = [];\n if (attrRows.length > 0) {\n summaryParts.push(`${attrRows.length} attr${attrRows.length === 1 ? \"\" : \"s\"}`);\n }\n if (binding !== undefined) summaryParts.push(\"action\");\n if (childNodes.length > 0) {\n summaryParts.push(\n `${childNodes.length} ${childNodes.length === 1 ? \"child\" : \"children\"}`\n );\n }\n return nodeShell(\n undefined, // the tag select is the node's label\n path,\n [tagControl(node.tag, (value) => commitAt(path, { ...node, tag: value }))],\n body,\n errorHere,\n removable,\n moves,\n { icons: [addMenu], summary: summaryParts.join(\" \u00B7 \") }\n );\n }\n return nodeShell(\n \"unknown\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Unknown template node form.\",\n removable,\n moves\n );\n }\n\n let currentError: string | undefined;\n let lastDraft: WidgetDraft | undefined;\n let lastErrorPath: string | undefined;\n\n /** Rebuild the tree from the last refresh inputs (collapse toggles). */\n function renderTree(): void {\n if (lastDraft === undefined) return;\n // Shared refs resolve like inline schemas \u2014 a ref-based widget gets the same path completions.\n treeHost.replaceChildren(\n renderNode(\n lastDraft.template,\n [],\n lastErrorPath,\n true,\n undefined,\n effectiveDataSchema(lastDraft, actionContext.schemas)\n )\n );\n }\n\n function refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void {\n currentError = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}`\n : undefined;\n lastDraft = draft;\n lastErrorPath = diagnostics.template?.path;\n const known = new Set(actionContext.actions.map((action) => action.name));\n unknownRefs = new Set(collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref)));\n const templateMessage = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path !== undefined && diagnostics.template.path !== \"\"\n ? ` (at ${diagnostics.template.path})`\n : \"\")\n : diagnostics.actionRefs;\n templateDiag.hidden = templateMessage === undefined;\n templateDiag.textContent = templateMessage ?? \"\";\n if (!treeHost.hidden || treeHost.childNodes.length === 0) {\n renderTree();\n }\n if (document.activeElement !== jsonArea) {\n jsonArea.value = JSON.stringify(draft.template, null, 2);\n repaintHighlight(jsonArea);\n }\n }\n\n refreshers.push(() => undefined); // template refresh runs via refresh() below\n\n return { element, refresh, dispose: () => element.remove() };\n}\n", "/**\n * Preview controls in the widget designer: which of the host-supplied\n * named themes the DRAFT renders under \u2014 plus a read-only reference of\n * the effective tokens, so style authoring can reach for\n * `var(--wg-\u2026)` by sight instead of memory.\n *\n * Theme *authoring* lives in the standalone theme designer \u2014 this panel\n * only selects and displays. There is deliberately no preview-kind\n * selector: the widget designer previews the draft, and previewing\n * arbitrary kinds under a theme is the theme designer's job.\n */\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { TOKEN_SPECS } from \"@widgentic/core\";\nimport { diagnosticLine, h, section } from \"./dom.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport function mountThemePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n themes: ThemeEntry[] = []\n): {\n element: HTMLElement;\n /** Show the theme validator's error \u2014 this panel owns the value. */\n setDiagnostic(message: string | undefined): void;\n dispose(): void;\n} {\n // Theme validation errors were computed and dropped before this: the\n // panel that owns the offending value showed nothing at all.\n const themeDiag = diagnosticLine(undefined);\n // Theme selector: \"none\" plus whatever the host supplied.\n const themeSelect = h(\"select\", {\n class: \"wgd-select wgd-theme-select\"\n });\n themeSelect.append(h(\"option\", { value: \"\" }, [\"(none \u2014 defaults)\"]));\n for (const entry of themes) {\n themeSelect.append(\n h(\"option\", { value: entry.name }, [entry.label ?? entry.name])\n );\n }\n themeSelect.addEventListener(\"change\", () => {\n const entry = themes.find((candidate) => candidate.name === themeSelect.value);\n store.update((draft) => {\n if (entry === undefined) {\n const { theme: _gone, ...rest } = draft;\n return rest;\n }\n return { ...draft, theme: entry.tokens };\n });\n });\n\n // Token reference: the EFFECTIVE preview tokens \u2014 the selected entry\n // merged over the registry defaults \u2014 plus the entry's x-* customs.\n // Types come from TOKEN_SPECS metadata (color \u2192 swatch), never inferred.\n const tokenList = h(\"div\", { class: \"wgd-token-ref\" });\n\n function renderTokenReference(theme: Record<string, string> | undefined): void {\n tokenList.replaceChildren();\n for (const [name, spec] of Object.entries(TOKEN_SPECS)) {\n const value = theme?.[name] ?? spec.default;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: spec.use }, [\n spec.type === \"color\"\n ? h(\"span\", {\n class: \"wgd-token-ref-swatch\",\n style: `background: ${value}`\n })\n : h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n for (const [name, value] of Object.entries(theme ?? {})) {\n if (!name.startsWith(\"x-\")) continue;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: \"Custom variable\" }, [\n h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n }\n renderTokenReference(store.get().theme);\n\n refreshers.push((draft) => {\n // Reflect programmatic theme loads; an unrecognized map shows as none.\n if (draft.theme === undefined) {\n themeSelect.value = \"\";\n } else {\n const match = themes.find(\n (entry) => JSON.stringify(entry.tokens) === JSON.stringify(draft.theme)\n );\n themeSelect.value = match?.name ?? \"\";\n }\n renderTokenReference(draft.theme);\n });\n\n const rows: (Node | string)[] = [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview theme\"]),\n themeSelect\n ]),\n h(\"span\", { class: \"wgd-field-label\" }, [\n themes.length === 0\n ? \"No themes supplied by the host \u2014 design themes in the theme designer.\"\n : \"Themes come from the host; edit them in the theme designer.\"\n ]),\n themeDiag,\n h(\"details\", { class: \"wgd-token-ref-details\" }, [\n h(\"summary\", { class: \"wgd-field-label\" }, [\n \"Theme tokens (reference for styles)\"\n ]),\n tokenList\n ])\n ];\n\n const element = section(\"Preview\", rows);\n return {\n element,\n setDiagnostic(message) {\n themeDiag.hidden = message === undefined;\n themeDiag.textContent = message ?? \"\";\n },\n dispose: () => element.remove()\n };\n}\n", "/**\n * Editor panels: plain modules over the draft store. Refresh discipline:\n * every store change re-derives diagnostics and refreshes bound controls,\n * but never overwrites the control the user is typing in\n * (`document.activeElement` wins) \u2014 the store is the single model, the\n * DOM is a projection.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { diagnosticLine, h, section, textArea, textField, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { mountIoPanel } from \"./io.js\";\nimport { createJsonTreeEditor } from \"./json-tree-editor.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport { createStylesEditor } from \"./styles-editor.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { mountTemplatePanel } from \"./template-panel.js\";\nimport type { TemplateActionContext } from \"./template-panel.js\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { mountThemePanel } from \"./theme-panel.js\";\nimport { deriveDiagnostics, effectiveDataSchema } from \"./validate.js\";\n\n/** Tabbed container: first tab visible, buttons switch panes. */\nfunction tabs(entries: { label: string; element: HTMLElement }[]): HTMLElement {\n const buttons = entries.map((entry, index) => {\n const button = h(\n \"button\",\n { class: `wgd-button wgd-tab${index === 0 ? \" wgd-tab-active\" : \"\"}`, type: \"button\" },\n [entry.label]\n );\n button.addEventListener(\"click\", () => {\n entries.forEach((other, i) => {\n other.element.hidden = i !== index;\n buttons[i]?.classList.toggle(\"wgd-tab-active\", i === index);\n });\n });\n entry.element.hidden = index !== 0;\n return button;\n });\n return h(\"div\", { class: \"wgd-tabs\" }, [\n h(\"div\", { class: \"wgd-row\" }, buttons),\n ...entries.map((entry) => entry.element)\n ]);\n}\n\n/** Column layout: definition (exported) on the left, presentation on the right. */\nexport interface PanelColumns {\n left: HTMLElement;\n right: HTMLElement;\n}\n\ntype Refresher = (draft: WidgetDraft) => void;\n\n/**\n * JSON-valued textarea with parse gating: invalid JSON never reaches the\n * store (last-valid-wins) \u2014 the parse error shows beside the field.\n */\nfunction jsonField(\n label: string,\n read: (draft: WidgetDraft) => unknown,\n write: (draft: WidgetDraft, value: unknown) => WidgetDraft,\n clear: ((draft: WidgetDraft) => WidgetDraft) | undefined,\n store: DraftStore,\n refreshers: Refresher[],\n rows = 6\n): HTMLElement {\n const parseError = diagnosticLine(undefined);\n const initial = read(store.get());\n const field = textArea(\n label,\n initial === undefined ? \"\" : JSON.stringify(initial, null, 2),\n (text) => {\n if (text.trim() === \"\") {\n parseError.hidden = true;\n if (clear) store.update((draft) => clear(draft));\n return;\n }\n try {\n const value: unknown = JSON.parse(text);\n parseError.hidden = true;\n parseError.textContent = \"\";\n store.update((draft) => write(draft, value));\n } catch (error) {\n parseError.hidden = false;\n parseError.textContent = `Invalid JSON (draft keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n },\n rows\n );\n const area = requireChild(field, \"textarea\");\n attachJsonHighlight(area);\n refreshers.push((draft) => {\n if (document.activeElement === area) return;\n const value = read(draft);\n area.value = value === undefined ? \"\" : JSON.stringify(value, null, 2);\n repaintHighlight(area); // programmatic writes fire no input event\n });\n return h(\"div\", undefined, [field, parseError]);\n}\n\nexport function mountPanels(\n store: DraftStore,\n columns: PanelColumns,\n themes: ThemeEntry[] = [],\n schemas: SchemaEntry[] = [],\n actionContext: TemplateActionContext = { actions: [], secretNames: [], schemas: [] }\n): { dispose(): void } {\n const refreshers: Refresher[] = [];\n const disposers: (() => void)[] = [];\n\n function bindText(\n label: string,\n read: (draft: WidgetDraft) => string,\n write: (draft: WidgetDraft, value: string) => WidgetDraft\n ): HTMLElement {\n const field = textField(label, read(store.get()), (value) =>\n store.update((draft) => write(draft, value))\n );\n const input = requireChild(field, \"input\");\n refreshers.push((draft) => {\n if (document.activeElement !== input) input.value = read(draft);\n });\n return field;\n }\n\n // --- General: kind + prose descriptor fields (left) -------------------\n const kindDiag = diagnosticLine(undefined);\n // Hints: name\u2192doc rows beside the parse-gated JSON pane \u2014 the same\n // Tree/JSON pair as styles, scaled down to a flat record.\n const hintsEditor = createRecordEditor(\n store.get().descriptor.hints,\n { key: \"hint name\", value: \"what the hint does\", add: \"+ hint\" },\n (hints) =>\n store.update((d) => {\n if (hints === undefined) {\n const { hints: _h, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, hints } };\n })\n );\n refreshers.push((draft) => hintsEditor.setValue(draft.descriptor.hints));\n const generalPanel = section(\"General\", [\n bindText(\"Kind (id)\", (d) => d.kind, (d, v) => ({ ...d, kind: v })),\n kindDiag,\n bindText(\n \"Description\",\n (d) => d.descriptor.description ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, description: v } })\n ),\n bindText(\n \"Data shape (prose)\",\n (d) => d.descriptor.dataShape ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataShape: v } })\n ),\n h(\"div\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Hints\"]),\n tabs([\n { label: \"Tree\", element: hintsEditor.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"\",\n (d) => d.descriptor.hints,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n const hints = Object.fromEntries(\n Object.entries(v).map(([k, doc]) => [k, String(doc)])\n ) as Record<string, string>;\n return { ...d, descriptor: { ...d.descriptor, hints } };\n },\n (d) => {\n const { hints: _hints, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers,\n 3\n )\n }\n ])\n ])\n ]);\n\n // --- Data schema (left, definition): inline editing OR a shared ref ----\n // Two modes, mirroring the store's contract: an inline dataSchema, or a\n // dataSchemaRef into the host-supplied shared schemas \u2014 never both.\n const schemaBuilder = createSchemaBuilder(store.get().descriptor.dataSchema, (schema) =>\n store.update((d) => {\n if (schema === undefined) {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, dataSchema: schema } };\n })\n );\n refreshers.push((draft) => schemaBuilder.setValue(draft.descriptor.dataSchema));\n const inlineEditors = tabs([\n { label: \"Builder\", element: schemaBuilder.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataSchema (JSON-Schema subset: type/properties/required/items/enum/pattern)\",\n (d) => d.descriptor.dataSchema,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n return { ...d, descriptor: { ...d.descriptor, dataSchema: v } };\n },\n (d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]);\n\n const modeSelect = h(\"select\", { class: \"wgd-select wgd-schema-mode\" });\n modeSelect.append(h(\"option\", { value: \"inline\" }, [\"define inline\"]));\n const sharedOption = h(\"option\", { value: \"shared\" }, [\"use shared\"]);\n if (schemas.length === 0) sharedOption.disabled = true;\n modeSelect.append(sharedOption);\n\n const refSelect = h(\"select\", { class: \"wgd-select wgd-schema-ref\" });\n for (const entry of schemas) {\n refSelect.append(h(\"option\", { value: entry.name }, [entry.label ?? entry.name]));\n }\n refSelect.addEventListener(\"change\", () => {\n store.update((d) => ({\n ...d,\n descriptor: { ...d.descriptor, dataSchemaRef: refSelect.value }\n }));\n });\n\n // The shared schema shows read-only: editing it from inside a widget\n // draft would be edit-at-a-distance \u2014 that belongs to the schema section.\n const sharedView = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-shared\",\n rows: \"10\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const schemaRefDiag = diagnosticLine(undefined);\n const sharedWrap = h(\"div\", undefined, [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Shared schema\"]),\n refSelect\n ]),\n sharedView,\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Read-only here \u2014 edit shared schemas in the Data schemas section.\"\n ])\n ]);\n\n modeSelect.addEventListener(\"change\", () => {\n if (modeSelect.value === \"shared\") {\n const name =\n store.get().descriptor.dataSchemaRef ?? schemas[0]?.name ?? \"\";\n store.update((d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: { ...rest, dataSchemaRef: name } };\n });\n } else {\n // Back to inline: seed with the resolved shared schema (a copy), so\n // \"customize from here\" is one switch away.\n const resolved = effectiveDataSchema(store.get(), schemas);\n store.update((d) => {\n const { dataSchemaRef: _r, ...rest } = d.descriptor;\n return {\n ...d,\n descriptor: {\n ...rest,\n dataSchema: (resolved ?? { type: \"object\" }) as Record<string, unknown>\n }\n };\n });\n }\n });\n\n function refreshSchemaMode(draft: WidgetDraft): void {\n const ref = draft.descriptor.dataSchemaRef;\n const shared = typeof ref === \"string\";\n modeSelect.value = shared ? \"shared\" : \"inline\";\n inlineEditors.hidden = shared;\n sharedWrap.hidden = !shared;\n if (shared) {\n if (refSelect.value !== ref) refSelect.value = ref;\n const resolved = schemas.find((entry) => entry.name === ref)?.schema;\n sharedView.value =\n resolved === undefined ? \"\" : JSON.stringify(resolved, null, 2);\n repaintHighlight(sharedView); // programmatic writes fire no input event\n }\n }\n refreshers.push(refreshSchemaMode);\n refreshSchemaMode(store.get());\n\n const schemaPanel = section(\n \"Data schema\",\n [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Source\"]),\n modeSelect\n ]),\n schemaRefDiag,\n inlineEditors,\n sharedWrap\n ],\n false\n );\n // The highlight layer wraps the textarea in place, so attach after the\n // section assembly gives it a parent.\n attachJsonHighlight(sharedView);\n\n /**\n * Adaptive data editor: schema-driven form when a dataSchema exists,\n * generic JSON tree otherwise \u2014 rebuilt when the schema changes; the raw\n * JSON textarea remains as a sibling tab either way.\n */\n function adaptiveDataEditor(\n read: (d: WidgetDraft) => unknown,\n write: (d: WidgetDraft, v: unknown) => WidgetDraft\n ): HTMLElement {\n const hostEl = h(\"div\");\n let schemaKey = \"\";\n let editor:\n | { element: HTMLElement; setValue(v: unknown): void }\n | undefined;\n\n function rebuild(draft: WidgetDraft): void {\n const schema = effectiveDataSchema(draft, schemas);\n const key = schema === undefined ? \"\" : JSON.stringify(schema);\n if (editor !== undefined && key === schemaKey) {\n editor.setValue(read(draft));\n return;\n }\n schemaKey = key;\n const onChange = (value: unknown): void =>\n store.update((d) => write(d, value));\n editor =\n schema !== undefined && isPlainObject(schema)\n ? createSchemaForm(schema as DataSchema, read(draft), onChange)\n : createJsonTreeEditor(read(draft), onChange);\n hostEl.replaceChildren(editor.element);\n }\n\n rebuild(store.get());\n refreshers.push(rebuild);\n return hostEl;\n }\n\n // --- Sample data = the descriptor's dataExample (left, exported) -------\n const exampleDiag = diagnosticLine(undefined);\n const samplePanel = section(\n \"Sample data\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"dataExample \u2014 ships with the widget as the example agents imitate\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataExample (JSON)\",\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } }),\n (d) => {\n const { dataExample: _e, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]),\n exampleDiag\n ],\n false\n );\n\n // --- Data for preview (right, session-only) ----------------------------\n const sampleDiag = diagnosticLine(undefined);\n const previewDataPanel = section(\n \"Data for preview\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Overrides dataExample in the preview only (not exported)\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"Preview data (JSON)\",\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v }),\n (d) => {\n const { sampleData: _s, ...rest } = d;\n return rest;\n },\n store,\n refreshers,\n 4\n )\n }\n ]),\n sampleDiag\n ],\n false\n );\n\n // --- Styles panel (right, presentation): Tree + JSON tabs --------------\n // Two projections of the one draft value, exactly like the template's\n // tree/JSON pair: the tree enforces the string-only two-level shape,\n // the JSON pane stays parse-gated.\n const stylesDiag = h(\"div\");\n const stylesEditor = createStylesEditor(store.get().descriptor.styles, (styles) =>\n store.update((d) => {\n if (styles === undefined) {\n const { styles: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, styles } };\n })\n );\n refreshers.push((draft) => stylesEditor.setValue(draft.descriptor.styles));\n const stylesPanel = section(\"Styles (.wg- selectors, guarded like the server)\", [\n tabs([\n { label: \"Tree\", element: stylesEditor.element },\n {\n label: \"JSON\",\n // No legend \u2014 the section title already names the shape.\n element: jsonField(\n \"\",\n (d) => d.descriptor.styles,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n return {\n ...d,\n descriptor: {\n ...d.descriptor,\n styles: v as Record<string, Record<string, string>>\n }\n };\n },\n (d) => {\n const { styles: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]),\n stylesDiag\n ]);\n\n const templatePanel = mountTemplatePanel(store, refreshers, { actionContext });\n const themePanel = mountThemePanel(store, refreshers, themes);\n\n // --- Load: the widget-level http GET action run once per instance -------\n const loadDiag = diagnosticLine(undefined);\n const loadEditor = createBindingEditor(\n store.get().load,\n {\n ...actionContext,\n loadOnly: true,\n getDataSchema: () => effectiveDataSchema(store.get(), schemas)\n },\n (binding: ActionBinding | undefined) =>\n store.update((d) => {\n if (binding === undefined) {\n const { load: _l, ...rest } = d;\n return rest;\n }\n return { ...d, load: binding };\n })\n );\n refreshers.push((draft) => {\n if (!loadEditor.element.contains(document.activeElement)) loadEditor.setValue(draft.load);\n });\n // Same compact chrome as an element's binding editor in the tree.\n const loadPanel = section(\n \"Load action (http GET, runs once when the widget first renders in an Apps host)\",\n [h(\"div\", { class: \"wgd-compact wgd-load\" }, [loadEditor.element]), loadDiag],\n false\n );\n const ioPanel = mountIoPanel(store);\n\n // Read-only marks the right column's EDITING sections; the theme panel\n // (preview selector + token reference) stays live in that mode.\n previewDataPanel.classList.add(\"wgd-edit-only\");\n stylesPanel.classList.add(\"wgd-edit-only\");\n\n // Left: the widget definition (what export produces). Right: presentation.\n columns.left.append(\n generalPanel,\n schemaPanel,\n samplePanel,\n templatePanel.element,\n loadPanel,\n ioPanel.element\n );\n columns.right.append(previewDataPanel, stylesPanel, themePanel.element);\n disposers.push(templatePanel.dispose, themePanel.dispose, ioPanel.dispose);\n\n // Diagnostics refresh: derive once per change here (cheap, pure) \u2014 and\n // once immediately, so the tree/JSON projections render before any edit.\n function applyDiagnostics(draft: WidgetDraft): void {\n const diagnostics = deriveDiagnostics(draft, { schemas, actions: actionContext.actions });\n kindDiag.hidden = diagnostics.kind === undefined;\n // Unknown refs are flagged in the template panel, at the element; the\n // Load section only ever speaks about the load binding.\n loadDiag.hidden = diagnostics.load === undefined;\n loadDiag.textContent = diagnostics.load ?? \"\";\n kindDiag.textContent = diagnostics.kind ?? \"\";\n exampleDiag.hidden = diagnostics.example === undefined;\n exampleDiag.textContent = diagnostics.example\n ? `dataExample vs dataSchema: ${diagnostics.example.code} at ${diagnostics.example.path} \u2014 ${diagnostics.example.message}`\n : \"\";\n sampleDiag.hidden = diagnostics.sample === undefined;\n sampleDiag.textContent = diagnostics.sample\n ? `sample vs dataSchema: ${diagnostics.sample.code} at ${diagnostics.sample.path} \u2014 ${diagnostics.sample.message}`\n : \"\";\n schemaRefDiag.hidden = diagnostics.schemaRef === undefined;\n schemaRefDiag.textContent = diagnostics.schemaRef ?? \"\";\n themePanel.setDiagnostic(\n diagnostics.theme\n ? `${diagnostics.theme.code}: ${diagnostics.theme.message}`\n : undefined\n );\n stylesDiag.replaceChildren(\n ...diagnostics.styles.map((issue) =>\n diagnosticLine(\n `${issue.selector}${issue.property ? ` \u2192 ${issue.property}` : \"\"}: ${issue.message}`\n )\n )\n );\n for (const refresh of refreshers) refresh(draft);\n templatePanel.refresh(draft, diagnostics);\n }\n\n const off = store.subscribe(applyDiagnostics);\n disposers.push(off);\n applyDiagnostics(store.get());\n\n return {\n dispose() {\n for (const dispose of disposers) dispose();\n columns.left.replaceChildren();\n columns.right.replaceChildren();\n }\n };\n}\n", "/**\n * Live preview through the real pipeline: the draft template compiles into\n * a delegating renderer registered ONCE under a stable internal kind, so a\n * single `mountWidget` handle survives every template revision and updates\n * patch the DOM in place (`reactive-rendering` dogfooded). Built-in kinds\n * share the same scratch catalog for theme-designer previews.\n *\n * Invalid drafts freeze the last good render behind an error banner \u2014\n * never a blank pane (the app-template error-state lesson).\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { createCatalog, widgetStylesToCss } from \"@widgentic/core\";\nimport type { WidgetRenderer } from \"@widgentic/core\";\nimport type { WidgetPayload } from \"@widgentic/core\";\nimport { mountWidget } from \"@widgentic/core\";\nimport type { WidgetMount } from \"@widgentic/core\";\nimport { compileTemplate, validateTemplate } from \"@widgentic/core\";\nimport { applyTheme, injectBaseStyles } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\nimport type { StoredAction } from \"@widgentic/core\";\n\n/** Internal kind the draft renders under (stable across recompiles). */\nexport const PREVIEW_KIND = \"designer-preview\";\n\n/**\n * A host-supplied definition the preview can render by kind. `descriptor`\n * stays `unknown` on purpose: hosts hand these straight off the wire, so\n * the preview narrows what it needs and ignores the rest.\n */\nexport interface PreviewWidget {\n kind: string;\n template: unknown;\n descriptor?: unknown;\n}\n\nexport interface PreviewOptions {\n /**\n * Custom widget definitions to make previewable by kind \u2014 a theme is\n * judged against the widgets it will actually dress, not only the\n * built-ins. Definitions that fail template validation are skipped.\n */\n widgets?: PreviewWidget[];\n /** Shared actions, so `{ ref }` bindings preview with their real kind. */\n actions?: StoredAction[];\n}\n\nexport interface PreviewController {\n readonly pane: HTMLElement;\n /** Selectable kinds: built-ins plus the registered customs. */\n readonly kinds: string[];\n /**\n * Re-render for a draft revision. The WIDGET designer always renders\n * the draft (no `previewKind`); the optional kind parameter exists for\n * the THEME designer, whose job is previewing catalog kinds under a\n * theme.\n */\n update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void;\n dispose(): void;\n}\n\nexport function createPreview(options: PreviewOptions = {}): PreviewController {\n injectBaseStyles(document);\n\n const banner = h(\"div\", { class: \"wgd-banner\" });\n banner.hidden = true;\n const kindStyles = h(\"style\");\n const mountRoot = h(\"div\", { class: \"wgd-preview\" });\n const pane = h(\"div\", { class: \"wgd-preview-pane\" }, [banner, kindStyles, mountRoot]);\n\n const catalog = createCatalog();\n let renderer: WidgetRenderer = () => ({ tag: \"div\", children: [\"\u2026\"] });\n catalog.register(\n PREVIEW_KIND,\n (payload: WidgetPayload) => renderer(payload),\n {\n description: \"Designer preview delegate.\",\n dataShape: \"Defined by the draft being designed.\"\n }\n );\n\n // Host-supplied customs join the scratch catalog so the theme designer\n // can preview them. Each carries its own styles, emitted when selected.\n const customStyles = new Map<string, string>();\n for (const widget of options.widgets ?? []) {\n const validated = validateTemplate(widget.template);\n // Untrusted-ish input: a bad definition is skipped, never fatal.\n if (!validated.ok || typeof widget.kind !== \"string\" || widget.kind === \"\") continue;\n const compiled = compileTemplate(validated.template);\n const descriptor = isPlainObject(widget.descriptor) ? widget.descriptor : {};\n try {\n catalog.register(widget.kind, (payload: WidgetPayload) => compiled(payload), {\n description: `Custom widget '${widget.kind}' supplied for preview.`,\n dataShape: \"Defined by the supplied definition.\",\n ...(descriptor.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {})\n });\n } catch {\n continue; // a reserved/duplicate kind never breaks the designer\n }\n if (isPlainObject(descriptor.styles)) {\n customStyles.set(\n widget.kind,\n widgetStylesToCss(descriptor.styles as Record<string, Record<string, string>>)\n );\n }\n }\n const kinds = catalog.kinds().filter((kind) => kind !== PREVIEW_KIND);\n\n let mount: WidgetMount | undefined;\n\n function update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void {\n const renderingDraft = previewKind === undefined || previewKind === PREVIEW_KIND;\n if (renderingDraft && !diagnostics.previewable) {\n const issue =\n diagnostics.kind ??\n (diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path ? ` (at ${diagnostics.template.path})` : \"\")\n : \"Draft is not previewable.\");\n banner.hidden = false;\n // Freezing needs something to freeze ON. On the first update there\n // is no mount yet \u2014 reachable whenever a host supplies an invalid\n // or reserved-kind `initialWidget` \u2014 and returning here left the\n // pane blank, the one state the contract forbids.\n if (mount === undefined) {\n banner.textContent = `Nothing to preview yet \u2014 ${issue}`;\n mountRoot.replaceChildren(\n h(\"div\", { class: \"wgd-preview-empty\" }, [\n \"No preview: the draft has never been valid.\"\n ])\n );\n return;\n }\n banner.textContent = `Preview frozen on the last valid draft \u2014 ${issue}`;\n return; // keep the last good render mounted\n }\n // A first valid render replaces the empty state.\n mountRoot.querySelector(\".wgd-preview-empty\")?.remove();\n banner.hidden = true;\n banner.textContent = \"\";\n\n if (renderingDraft) {\n const validated = validateTemplate(draft.template);\n if (!validated.ok) return; // defensive: previewable implies ok\n const shared = options.actions ?? [];\n renderer = compileTemplate(validated.template, {\n actions: (ref) => shared.find((action) => action.name === ref)?.definition\n });\n }\n // Styles follow whatever is on screen: the draft's own, or the\n // selected custom kind's (a built-in needs none).\n kindStyles.textContent = renderingDraft\n ? draft.descriptor.styles\n ? widgetStylesToCss(draft.descriptor.styles)\n : \"\"\n : customStyles.get(previewKind as string) ?? \"\";\n // Unsafe values are also skipped inside applyTheme (lenient layer).\n applyTheme(mountRoot, draft.theme ?? {});\n\n const payload = {\n kind: renderingDraft ? PREVIEW_KIND : (previewKind as string),\n data: renderingDraft\n ? draft.sampleData ?? draft.descriptor.dataExample ?? null\n : sampleFor(previewKind as string)\n };\n if (mount === undefined) {\n // No onAction: the preview never executes anything; bound elements\n // only wear the inert badge below.\n mount = mountWidget(payload, mountRoot, { catalog });\n } else {\n mount.update(payload);\n }\n for (const bound of mountRoot.querySelectorAll(\"[data-wg-action]\")) {\n bound.classList.add(\"wg-designer-action\");\n }\n }\n\n /** Built-in preview data for the THEME designer's kind previews. */\n function sampleFor(kind: string): unknown {\n return catalog.describe(kind)?.dataExample ?? { value: \"preview\" };\n }\n\n return {\n pane,\n kinds,\n update,\n dispose() {\n mount?.dispose();\n mount = undefined;\n pane.replaceChildren();\n }\n };\n}\n", "/**\n * Designer draft store: one micro-store per designer instance \u2014 get,\n * immutable update, subscribe, and a bounded undo stack. Deliberately\n * framework-free (the \"Arrow JS direction\": fine-grained subscriptions,\n * no VDOM) so the designer stays a zero-dependency embeddable.\n */\nimport type { WidgetDescriptorInput } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { WidgetTheme } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\n\n/** The draft being designed \u2014 the server's `CustomWidget` shape plus session extras. */\nexport interface WidgetDraft {\n kind: string;\n template: WidgetTemplate;\n /**\n * Mirrors the store's shape: `dataSchemaRef` names a shared schema in\n * place of an inline `dataSchema` (never both). Export carries the ref\n * as authored \u2014 resolution belongs to the server's composition.\n */\n descriptor: WidgetDescriptorInput & { dataSchemaRef?: string };\n /** Optional http GET action run once when the widget first renders. */\n load?: ActionBinding;\n /** Optional preview data overriding `descriptor.dataExample`. */\n sampleData?: unknown;\n /** Preview theme (also the theme-designer working copy). */\n theme?: WidgetTheme;\n}\n\nexport type DraftListener = (draft: WidgetDraft) => void;\n\nconst UNDO_LIMIT = 50;\n\nexport interface DraftStore {\n get(): WidgetDraft;\n /** Replace the draft via an updater; records undo history. */\n update(updater: (draft: WidgetDraft) => WidgetDraft): void;\n /** Replace wholesale (imports/loads); clears history. */\n replace(draft: WidgetDraft): void;\n undo(): boolean;\n subscribe(listener: DraftListener): () => void;\n}\n\n/** Structured-clone with JSON semantics \u2014 drafts are serializable by contract. */\nexport function cloneDraft(draft: WidgetDraft): WidgetDraft {\n return JSON.parse(JSON.stringify(draft)) as WidgetDraft;\n}\n\nexport function starterDraft(): WidgetDraft {\n // Everything the starter binds is DECLARED in its dataSchema \u2014 the\n // preferred pattern: schema-declared properties validate, `$meta.*`\n // paths do not, so new drafts start on the validated side.\n return {\n kind: \"my-widget\",\n template: {\n tag: \"div\",\n attrs: { class: \"wg-template\" },\n children: [{ tag: \"h2\", children: [{ bind: \"title\" }] }, { bind: \"message\" }]\n },\n descriptor: {\n description: \"Describe what this widget is for.\",\n dataShape: \"{ title?, message }\",\n dataExample: {\n title: \"My widget\",\n message: \"Hello from the widgentic designer\"\n },\n dataSchema: {\n type: \"object\",\n required: [\"message\"],\n properties: {\n title: { type: \"string\" },\n message: { type: \"string\" }\n }\n }\n }\n };\n}\n\nexport function createDraftStore(initial?: WidgetDraft): DraftStore {\n let current = cloneDraft(initial ?? starterDraft());\n const history: WidgetDraft[] = [];\n const listeners = new Set<DraftListener>();\n\n function notify(): void {\n for (const listener of [...listeners]) listener(current);\n }\n\n return {\n get: () => current,\n update(updater) {\n history.push(current);\n if (history.length > UNDO_LIMIT) history.shift();\n current = cloneDraft(updater(cloneDraft(current)));\n notify();\n },\n replace(draft) {\n history.length = 0;\n current = cloneDraft(draft);\n notify();\n },\n undo() {\n const previous = history.pop();\n if (previous === undefined) return false;\n current = previous;\n notify();\n return true;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n };\n}\n", "/**\n * The designer shell: layout, store wiring, and the embedding handle.\n * Panels and the preview are plain modules receiving the store \u2014 every\n * designer instance is fully closure-scoped so multiple instances coexist\n * in one document.\n */\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetTheme } from \"@widgentic/core\";\nimport { applyChrome, h, injectDesignerStyles } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { applyDefinition, checkDefinition } from \"./io.js\";\nimport type { WidgetDefinition } from \"./io.js\";\nimport { mountPanels } from \"./panels.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport type { StoredAction } from \"@widgentic/core\";\nimport { createPreview } from \"./preview.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport { cloneDraft, createDraftStore, starterDraft } from \"./store.js\";\nimport { deriveDiagnostics } from \"./validate.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\nexport type { WidgetDefinition } from \"./io.js\";\n\nexport interface DesignerOptions {\n initialWidget?: WidgetDefinition;\n initialTheme?: WidgetTheme;\n /**\n * Named themes offered as preview options. Theme authoring belongs to\n * the standalone theme designer; the widget designer only selects.\n */\n themes?: ThemeEntry[];\n /**\n * Shared data schemas the draft may reference by name (the Data schema\n * section's \"use shared\" mode). Schema authoring belongs to the\n * standalone schema designer; the widget designer only selects.\n */\n schemas?: SchemaEntry[];\n /**\n * Shared actions the draft may bind by name (element `action` bindings\n * and the widget-level `load`). Action authoring belongs to the\n * standalone action designer; the widget designer only binds.\n */\n actions?: StoredAction[];\n /** Secret names offered when an inline http action needs a header or query secret. */\n secretNames?: string[];\n /**\n * Designer chrome appearance. \"auto\" (default) follows the host's\n * `prefers-color-scheme`; the explicit values pin it. This is the\n * designer's own UI \u2014 the widget preview uses the draft's theme.\n */\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its theme selector operate. Toggle later via\n * `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type LoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface DesignerHandle {\n getDraft(): WidgetDraft;\n loadWidget(definition: unknown): LoadResult;\n loadTheme(theme: unknown): LoadResult;\n /** Disable/enable editing; the preview and theme selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(\n listener: (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n ): () => void;\n dispose(): void;\n}\n\nexport function createDesigner(\n container: Element,\n options: DesignerOptions = {}\n): DesignerHandle {\n injectDesignerStyles(document);\n\n const base: WidgetDraft = options.initialWidget\n ? cloneDraft({ ...options.initialWidget })\n : starterDraft();\n const initial: WidgetDraft =\n options.initialTheme !== undefined ? { ...base, theme: options.initialTheme } : base;\n const store = createDraftStore(initial);\n\n const listeners = new Set<\n (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n >();\n\n const preview = createPreview({ actions: options.actions ?? [] });\n const leftColumn = h(\"div\", { class: \"wgd-panels\" });\n const rightSections = h(\"div\", { class: \"wgd-preview-pane\" });\n const rightColumn = h(\"div\", { class: \"wgd-side\" }, [preview.pane, rightSections]);\n const root = h(\"div\", { class: \"wgd-root\" }, [leftColumn, rightColumn]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const actionContext = {\n actions: options.actions ?? [],\n secretNames: options.secretNames ?? [],\n schemas: options.schemas ?? []\n };\n const panels = mountPanels(\n store,\n { left: leftColumn, right: rightSections },\n options.themes ?? [],\n options.schemas ?? [],\n actionContext\n );\n\n function refresh(draft: WidgetDraft): void {\n const diagnostics = deriveDiagnostics(draft, {\n schemas: options.schemas ?? [],\n actions: options.actions ?? []\n });\n preview.update(draft, diagnostics);\n for (const listener of [...listeners]) listener(draft, diagnostics);\n }\n\n const unsubscribe = store.subscribe(refresh);\n refresh(store.get());\n\n /**\n * Read-only: every editing surface goes inert (visible, inoperable \u2014\n * section summaries stay clickable so content can still be inspected),\n * while the preview and the theme panel's selector keep working. inert\n * is applied to section BODIES, which are stable elements: panel\n * re-renders replace children inside them, never the bodies themselves.\n */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n // Complex selectors inside :not() are not universally supported, so\n // the view-only exclusion is filtered here rather than in the query.\n const bodies = [\n ...root.querySelectorAll(\n \".wgd-panels .wgd-section-body, .wgd-edit-only > .wgd-section-body\"\n )\n ].filter((body) => !body.parentElement?.classList.contains(\"wgd-view-only\"));\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getDraft: () => cloneDraft(store.get()),\n setReadOnly,\n loadWidget(definition) {\n const errors = checkDefinition(definition);\n if (errors.length > 0) return { ok: false, errors };\n applyDefinition(store, definition as unknown as WidgetDefinition);\n return { ok: true };\n },\n loadTheme(theme) {\n const validated = validateTheme(theme);\n if (!validated.ok) {\n return { ok: false, errors: [validated.error.message] };\n }\n store.update((draft) => ({ ...draft, theme: validated.theme }));\n return { ok: true };\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n unsubscribe();\n panels.dispose();\n preview.dispose();\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone schema designer: edits a stored-schema entry\n * (`{ name, label?, description?, schema }` \u2014 the widget-store's shape)\n * so one definition (`person`) can serve many widgets. Split out like the\n * theme designer: an app routes to \"design a schema\" as its own\n * destination, and a host embedding one designer should not ship the\n * others. Shares the chrome, the schema builder, and the parse-gated\n * JSON discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\n\n/** The store's identifier charset \u2014 kept local: `@widgentic/mcp/store` is a\n * Node-only entry and the designer runs in browsers. */\nconst SAFE_NAME = /^[a-zA-Z0-9._-]+$/;\n\nexport interface SchemaEntry {\n name: string;\n label?: string;\n description?: string;\n schema: Record<string, unknown>;\n}\n\nexport interface SchemaDesignerOptions {\n initialSchema?: SchemaEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert. Toggle\n * later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type SchemaLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface SchemaDesignerHandle {\n getSchema(): SchemaEntry;\n loadSchema(entry: unknown): SchemaLoadResult;\n /** Disable/enable editing. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: SchemaEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): SchemaEntry {\n return {\n name: \"my-schema\",\n label: \"My schema\",\n schema: { type: \"object\", properties: {} }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkSchemaEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Schema entry must be an object.\"];\n if (typeof entry.name !== \"string\" || entry.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n } else if (!SAFE_NAME.test(entry.name)) {\n errors.push(\n `'${entry.name}' is not a valid schema name \u2014 use letters, digits, '.', '_' or '-'.`\n );\n }\n if (!isPlainObject(entry.schema)) {\n errors.push(\"'schema' must be a plain object.\");\n }\n return errors;\n}\n\nexport function createSchemaDesigner(\n container: Element,\n options: SchemaDesignerOptions = {}\n): SchemaDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: SchemaEntry = options.initialSchema\n ? (JSON.parse(JSON.stringify(options.initialSchema)) as SchemaEntry)\n : starterEntry();\n const listeners = new Set<(entry: SchemaEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-schema-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n function getEntry(): SchemaEntry {\n return JSON.parse(JSON.stringify(entry)) as SchemaEntry;\n }\n\n function notify(): void {\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity panel ----------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n const identity = section(\"Schema\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n const bad = value.trim() === \"\" || !SAFE_NAME.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad\n ? \"Name must be non-empty using letters, digits, '.', '_' or '-'.\"\n : \"\";\n notify();\n }\n ),\n nameDiag,\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n notify();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n notify();\n }\n )\n ]);\n\n // --- Definition panel: builder + parse-gated JSON, one view at a time --\n const builder = createSchemaBuilder(entry.schema as DataSchema, (schema) => {\n entry = { ...entry, schema: (schema ?? {}) as Record<string, unknown> };\n syncJson();\n notify();\n });\n\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"12\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n if (!isPlainObject(parsed)) throw new Error(\"schema must be an object\");\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, schema: parsed };\n builder.setValue(parsed as DataSchema);\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (schema keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n repaintHighlight(jsonArea);\n }\n\n const builderTab = h(\n \"button\",\n { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" },\n [\"Builder\"]\n );\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\n \"JSON\"\n ]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n builder.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n builder.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n builder.element,\n jsonWrap\n ]);\n\n // --- Import / Export: the agent hand-off -------------------------------\n // Live testing surfaced this within a day of list_schemas shipping: an\n // agent drafts the complete entry JSON from the guide, and Import is\n // where the user pastes it. Same two-section shape as the siblings.\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-import\",\n rows: \"6\",\n spellcheck: \"false\"\n });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadSchema(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Import schema entry JSON ({ name, label?, description?, schema })\"\n ]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export schema entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n // Export copies out what is on screen \u2014 read-only leaves it operable.\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, importSection, exportSection);\n // The JSON layer wraps the textareas in place, so attach after assembly.\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadSchema(input: unknown): SchemaLoadResult {\n const errors = checkSchemaEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = JSON.parse(JSON.stringify(input)) as SchemaEntry;\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n builder.setValue(entry.schema as DataSchema);\n syncJson();\n notify();\n return { ok: true };\n }\n\n /** Same mechanism as the other designers: inert the section bodies \u2014\n * except the view-only Export, which restricts nothing. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getSchema: getEntry,\n loadSchema,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone theme designer: edits a NAMED theme entry\n * (`{ name, label?, description?, tokens }` \u2014 the theme registry's shape,\n * which is also what a host persists) with live preview against any\n * catalog kind.\n *\n * Split from the widget designer on purpose: an app routes to \"design a\n * theme\" and \"design a widget\" as separate destinations, and a host\n * embedding one should not ship the other. Both share the preview\n * controller, chrome, and store discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { createCatalog } from \"@widgentic/core\";\nimport {\n THEME_TOKENS,\n TOKEN_DEFAULTS,\n TOKEN_SPECS,\n isSafeTokenValue,\n validateTheme\n} from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetThemeInput } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { createPreview } from \"./preview.js\";\nimport type { PreviewWidget } from \"./preview.js\";\nimport { starterDraft } from \"./store.js\";\nimport type { WidgetDraft } from \"./store.js\";\n\nconst BASE_KINDS = createCatalog().kinds();\n\n/** Hex form the native color input accepts. */\nconst HEX = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i;\nconst CUSTOM_NAME = /^x-[a-z0-9][a-z0-9-]*$/;\n\nfunction toHexInput(value: string): string | undefined {\n if (!HEX.test(value)) return undefined;\n if (value.length === 7) return value.toLowerCase();\n const [, r, g, b] = value.toLowerCase();\n return `#${r}${r}${g}${g}${b}${b}`;\n}\n\nexport interface ThemeDesignerOptions {\n initialTheme?: ThemeEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Custom widget definitions to offer in the preview-kind selector\n * beside the built-ins \u2014 a theme is judged against the widgets it will\n * actually dress. Invalid definitions are skipped.\n */\n widgets?: PreviewWidget[];\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its kind selector operate. Toggle later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type ThemeLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ThemeDesignerHandle {\n getTheme(): ThemeEntry;\n loadTheme(entry: unknown): ThemeLoadResult;\n /** Disable/enable editing; the preview and kind selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ThemeEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ThemeEntry {\n return { name: \"my-theme\", label: \"My theme\", tokens: {} };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkThemeEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n return [\"Theme entry must be an object.\"];\n }\n const candidate = entry as Record<string, unknown>;\n if (typeof candidate.name !== \"string\" || candidate.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n }\n const validated = validateTheme(candidate.tokens ?? {});\n if (!validated.ok) {\n errors.push(`tokens: ${validated.error.code} \u2014 ${validated.error.message}`);\n }\n return errors;\n}\n\nexport function createThemeDesigner(\n container: Element,\n options: ThemeDesignerOptions = {}\n): ThemeDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ThemeEntry = options.initialTheme\n ? (JSON.parse(JSON.stringify(options.initialTheme)) as ThemeEntry)\n : starterEntry();\n const listeners = new Set<(entry: ThemeEntry) => void>();\n\n const preview = createPreview(\n options.widgets ? { widgets: options.widgets } : {}\n );\n // Built-ins plus whatever custom definitions the host supplied.\n const previewKinds = preview.kinds.length > 0 ? preview.kinds : BASE_KINDS;\n let previewKind = previewKinds[0] ?? \"card\";\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const side = h(\"div\", { class: \"wgd-side\" }, [preview.pane]);\n const root = h(\"div\", { class: \"wgd-root wgd-theme-designer\" }, [panels, side]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n /** A draft carrying only what the preview needs: kind + this theme. */\n function previewDraft(): WidgetDraft {\n return { ...starterDraft(), theme: entry.tokens };\n }\n\n function refresh(): void {\n preview.update(previewDraft(), { styles: [], previewable: true }, previewKind);\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n function getEntry(): ThemeEntry {\n return JSON.parse(JSON.stringify(entry)) as ThemeEntry;\n }\n\n function setToken(key: string, value: string): void {\n const tokens = { ...entry.tokens } as Record<string, string>;\n if (value === \"\") delete tokens[key];\n else tokens[key] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n refresh();\n }\n\n // --- Identity panel ----------------------------------------------------\n /** Bind a text field and register its refresher (import must update it). */\n const identityRefreshers: (() => void)[] = [];\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n const identity = section(\"Theme\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n refresh();\n }\n ),\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n refresh();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n refresh();\n }\n )\n ]);\n\n // The kind selector is a PREVIEW control, so it lives beside the\n // preview, outside the editing panels \u2014 read-only mode keeps it live.\n const kindSelect = h(\"select\", {\n class: \"wgd-select wgd-preview-kind\"\n });\n for (const kind of previewKinds) {\n kindSelect.append(h(\"option\", { value: kind }, [kind]));\n }\n kindSelect.value = previewKind;\n kindSelect.addEventListener(\"change\", () => {\n previewKind = kindSelect.value;\n refresh();\n });\n side.prepend(\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview kind\"]),\n kindSelect\n ])\n );\n\n // --- Token panel -------------------------------------------------------\n const tokenRefreshers: (() => void)[] = [];\n const tokenRows: (Node | string)[] = [];\n for (const token of THEME_TOKENS) {\n const input = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\",\n placeholder: TOKEN_DEFAULTS[token]\n });\n input.value = entry.tokens[token] ?? \"\";\n const issue = diagnosticLine(undefined);\n // Control choice comes from the token's declared type \u2014 no guessing.\n const swatch = TOKEN_SPECS[token].type === \"color\"\n ? (h(\"input\", {\n type: \"color\",\n class: \"wgd-swatch\",\n title: `Pick --wg-${token}`\n }))\n : undefined;\n\n const paint = (value: string): void => {\n const effective = value === \"\" ? TOKEN_DEFAULTS[token] : value;\n if (swatch !== undefined) {\n const hex = toHexInput(effective);\n if (hex !== undefined) swatch.value = hex;\n swatch.style.background = isSafeTokenValue(effective) ? effective : \"transparent\";\n }\n };\n paint(input.value);\n swatch?.addEventListener(\"input\", () => {\n input.value = swatch.value;\n input.dispatchEvent(new Event(\"input\", { bubbles: true }));\n });\n input.addEventListener(\"input\", () => {\n const unsafe = input.value !== \"\" && !isSafeTokenValue(input.value);\n issue.hidden = !unsafe;\n issue.textContent = unsafe\n ? \"INVALID_TOKEN_VALUE: unsafe value withheld from the preview (no ;{}<> url() expression()).\"\n : \"\";\n paint(input.value);\n setToken(token, input.value);\n });\n tokenRefreshers.push(() => {\n if (document.activeElement !== input) {\n input.value = entry.tokens[token] ?? \"\";\n paint(input.value);\n }\n });\n tokenRows.push(\n h(\"div\", undefined, [\n h(\"label\", { class: \"wgd-field\", title: TOKEN_SPECS[token].use }, [\n h(\"span\", { class: \"wgd-field-label\" }, [`--wg-${token}`]),\n h(\n \"div\",\n { class: \"wgd-token-row\" },\n swatch === undefined ? [input] : [input, swatch]\n )\n ]),\n issue\n ])\n );\n }\n const tokenPanel = section(\"Tokens\", tokenRows);\n\n // --- Custom variables --------------------------------------------------\n const customHost = h(\"div\", { class: \"wgd-jt-children\" });\n const customError = diagnosticLine(undefined);\n\n function customEntries(): [string, string][] {\n return Object.entries(entry.tokens).filter(([key]) =>\n CUSTOM_NAME.test(key)\n ) as [string, string][];\n }\n\n function renderCustom(): void {\n const rows = customEntries().map(([key, value]) => {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n nameInput.value = key;\n nameInput.addEventListener(\"change\", () => {\n const next = nameInput.value;\n if (!CUSTOM_NAME.test(next)) {\n customError.hidden = false;\n customError.textContent = `'${next}' is not a valid custom name \u2014 use x-<lowercase-kebab>.`;\n nameInput.value = key;\n return;\n }\n customError.hidden = true;\n const tokens = { ...entry.tokens } as Record<string, string>;\n delete tokens[key];\n tokens[next] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n renderCustom();\n refresh();\n });\n const valueInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\"\n });\n valueInput.value = value;\n valueInput.addEventListener(\"input\", () => setToken(key, valueInput.value));\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n setToken(key, \"\");\n renderCustom();\n });\n return h(\"div\", { class: \"wgd-attr-row\" }, [nameInput, valueInput, remove]);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ variable\"\n ]);\n add.addEventListener(\"click\", () => {\n let name = \"x-custom\";\n for (let i = 1; name in entry.tokens; i++) name = `x-custom${i}`;\n setToken(name, \"0\");\n renderCustom();\n });\n customHost.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n renderCustom();\n const customPanel = section(\"Custom variables (--wg-x-*)\", [\n customHost,\n customError\n ]);\n\n // --- Import / export ---------------------------------------------------\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export theme entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n });\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"5\",\n spellcheck: \"false\"\n });\n const importError = diagnosticLine(undefined);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadTheme(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n // Two independent sections, import first \u2014 the same shape the widget\n // designer uses, so both designers read alike.\n const importPanel = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import theme entry JSON\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const exportPanel = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n exportPanel.classList.add(\"wgd-view-only\");\n\n panels.append(identity, tokenPanel, customPanel, importPanel, exportPanel);\n\n function loadTheme(input: unknown): ThemeLoadResult {\n const errors = checkThemeEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = JSON.parse(JSON.stringify(input)) as ThemeEntry;\n for (const refreshIdentity of identityRefreshers) refreshIdentity();\n for (const refreshToken of tokenRefreshers) refreshToken();\n renderCustom();\n refresh();\n return { ok: true };\n }\n\n refresh();\n\n /** Same mechanism as the widget designer: inert the section bodies. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getTheme: getEntry,\n loadTheme,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n preview.dispose();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone action designer: edits a stored-action entry\n * (`{ name, label?, description?, definition }` \u2014 the widget-store's\n * shape). Split out like the theme and schema designers. The Test control\n * appears only when the host supplies `options.testCall`: the library\n * performs no network I/O, and a test call must run through the host's\n * production execution path (secrets, SSRF guard, redaction).\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { ActionDefinition, HttpActionDefinition, StoredAction } from \"@widgentic/core\";\nimport { ACTION_NAME, validateActionDefinition } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { createDefinitionEditor } from \"./action-editor.js\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\n\nexport type ActionEntry = StoredAction;\n\nexport interface ActionDesignerOptions {\n initialAction?: ActionEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n readOnly?: boolean;\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n /**\n * Host-supplied test call (the production execute path). Without it no\n * Test control renders. Resolves to whatever the host wants shown \u2014\n * typically the redacted response or a structured error.\n */\n testCall?: (definition: HttpActionDefinition, args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type ActionLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ActionDesignerHandle {\n getAction(): ActionEntry;\n loadAction(entry: unknown): ActionLoadResult;\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ActionEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ActionEntry {\n return {\n name: \"my-action\",\n label: \"My action\",\n definition: { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkActionEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Action entry must be an object.\"];\n if (typeof entry.name !== \"string\" || !ACTION_NAME.test(entry.name)) {\n errors.push(\"'name' must be lowercase letters, digits and dashes, starting with a letter (max 64).\");\n }\n for (const field of [\"label\", \"description\"] as const) {\n if (entry[field] !== undefined && typeof entry[field] !== \"string\") {\n errors.push(`'${field}' must be a string when present.`);\n }\n }\n const problem = validateActionDefinition(entry.definition, \"definition\");\n if (problem) errors.push(`${problem.message} (at ${problem.path})`);\n return errors;\n}\n\n/** A checked entry with only the fields the shape declares; empty texts are dropped. */\nfunction normalizeEntry(input: Record<string, unknown>): ActionEntry {\n const entry: ActionEntry = { name: input.name as string, definition: clone(input.definition as ActionDefinition) };\n if (typeof input.label === \"string\" && input.label !== \"\") entry.label = input.label;\n if (typeof input.description === \"string\" && input.description !== \"\") entry.description = input.description;\n return entry;\n}\n\n/** Set or drop an optional text field: an emptied field leaves the entry. */\nfunction withText(current: ActionEntry, field: \"label\" | \"description\", value: string): ActionEntry {\n const { [field]: _gone, ...rest } = current;\n return value === \"\" ? rest : { ...rest, [field]: value };\n}\n\nexport function createActionDesigner(\n container: Element,\n options: ActionDesignerOptions = {}\n): ActionDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ActionEntry = options.initialAction ? clone(options.initialAction) : starterEntry();\n const testCall = options.testCall;\n const listeners = new Set<(entry: ActionEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-action-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const getEntry = (): ActionEntry => clone(entry);\n function notify(): void {\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity --------------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n function identityField(label: string, read: () => string, write: (value: string) => void): HTMLElement {\n const field = textField(label, read(), write);\n const inputEl = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== inputEl) inputEl.value = read();\n });\n return field;\n }\n const identity = section(\"Action\", [\n identityField(\"Name (id)\", () => entry.name, (value) => {\n entry = { ...entry, name: value };\n const bad = !ACTION_NAME.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad ? \"Name must be lowercase letters, digits and dashes, starting with a letter.\" : \"\";\n notify();\n }),\n nameDiag,\n identityField(\"Label\", () => entry.label ?? \"\", (value) => {\n entry = withText(entry, \"label\", value);\n notify();\n }),\n identityField(\"Description\", () => entry.description ?? \"\", (value) => {\n entry = withText(entry, \"description\", value);\n notify();\n })\n ]);\n\n // --- Definition: editor + parse-gated JSON -----------------------------\n const definitionDiag = diagnosticLine(undefined);\n const editor = createDefinitionEditor(\n entry.definition,\n { ...(options.schemas ? { schemas: options.schemas } : {}), ...(options.secretNames ? { secretNames: options.secretNames } : {}) },\n (definition) => {\n entry = { ...entry, definition };\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n }\n );\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", { class: \"wgd-textarea\", rows: \"12\", spellcheck: \"false\" });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n const problem = validateActionDefinition(parsed, \"definition\");\n if (problem) throw new Error(`${problem.message} (at ${problem.path})`);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, definition: parsed as ActionDefinition };\n editor.setValue(entry.definition);\n refreshDefinitionDiag();\n refreshTest();\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid (definition keeps the last valid value): ${errorMessage(error)}`;\n }\n });\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n repaintHighlight(jsonArea);\n }\n function refreshDefinitionDiag(): void {\n const problem = validateActionDefinition(entry.definition, \"definition\");\n definitionDiag.hidden = problem === undefined;\n definitionDiag.textContent = problem ? `${problem.message} (at ${problem.path})` : \"\";\n }\n refreshDefinitionDiag();\n\n const builderTab = h(\"button\", { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" }, [\"Editor\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\"JSON\"]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n editor.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n editor.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n definitionDiag,\n editor.element,\n jsonWrap\n ]);\n\n // --- Test (host-supplied) ------------------------------------------------\n const testHost = h(\"div\", { class: \"wgd-action-test\" });\n const testSection = section(\"Test\", [testHost]);\n let testArgs: Record<string, unknown> = {};\n // Arguments belong to one input schema: a different schema starts them over.\n let testInputJson: string | undefined;\n function refreshTest(): void {\n if (testCall === undefined) return;\n testHost.replaceChildren();\n if (entry.definition.kind !== \"http\") {\n testInputJson = undefined;\n testArgs = {};\n testHost.append(h(\"p\", { class: \"wgd-diagnostic\" }, [\"Prompt actions run in the host's composer; nothing to test.\"]));\n return;\n }\n const definitionNow = entry.definition;\n const inputJson = JSON.stringify(definitionNow.input);\n if (inputJson !== testInputJson) testArgs = {};\n testInputJson = inputJson;\n const form = createSchemaForm(definitionNow.input as DataSchema, testArgs, (value) => {\n testArgs = isPlainObject(value) ? value : {};\n });\n testArgs = isPlainObject(form.getValue()) ? (form.getValue() as Record<string, unknown>) : {};\n const output = h(\"pre\", { class: \"wgd-test-output\" });\n const run = h(\"button\", { class: \"wgd-button wgd-add wgd-test-run\", type: \"button\" }, [\"Test call\"]);\n run.addEventListener(\"click\", () => {\n run.disabled = true;\n run.classList.add(\"wgd-busy\");\n run.setAttribute(\"aria-busy\", \"true\");\n output.textContent = \"\u2026\";\n void testCall(definitionNow, testArgs)\n .then((result) => {\n output.textContent = typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n })\n .catch((error: Error) => {\n output.textContent = `Test failed: ${error.message}`;\n })\n .finally(() => {\n run.disabled = false;\n run.classList.remove(\"wgd-busy\");\n run.removeAttribute(\"aria-busy\");\n });\n });\n testHost.append(h(\"span\", { class: \"wgd-field-label\" }, [\"Arguments\"]), form.element, h(\"div\", { class: \"wgd-row\" }, [run]), output);\n }\n refreshTest();\n\n // --- Import / Export ------------------------------------------------------\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", { class: \"wgd-textarea wgd-action-import\", rows: \"6\", spellcheck: \"false\" });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadAction(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import action entry JSON ({ name, label?, description?, definition })\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const output = h(\"textarea\", { class: \"wgd-textarea\", rows: \"8\", readonly: \"\", spellcheck: \"false\" });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"Export action entry\"]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]), output]);\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, ...(testCall === undefined ? [] : [testSection]), importSection, exportSection);\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadAction(input: unknown): ActionLoadResult {\n const errors = checkActionEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = normalizeEntry(input as Record<string, unknown>);\n testArgs = {};\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n editor.setValue(entry.definition);\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n return { ok: true };\n }\n\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getAction: getEntry,\n loadAction,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Opt-in custom element wrapping the factory. Registration only ever\n * happens through the explicit call \u2014 importing this module has no\n * custom-element registry side effects, so hosts stay in control.\n */\nimport { createDesigner } from \"./shell.js\";\nimport type { DesignerHandle } from \"./shell.js\";\nimport { createSchemaDesigner } from \"./schema-designer.js\";\nimport type { SchemaDesignerHandle } from \"./schema-designer.js\";\nimport { createThemeDesigner } from \"./theme-designer.js\";\nimport type { ThemeDesignerHandle } from \"./theme-designer.js\";\nimport { createActionDesigner } from \"./action-designer.js\";\nimport type { ActionDesignerHandle } from \"./action-designer.js\";\nimport { parseChromeAttribute } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\n\n/**\n * The attributes every designer element shares, read once at connect:\n * `appearance` pins the chrome scheme, `chrome` (JSON) hands over the\n * host's chrome tokens. Anything invalid is ignored, never thrown.\n */\nfunction elementOptions(\n element: Element\n): { appearance?: \"light\" | \"dark\"; chrome?: ChromeOptions } {\n const appearance = element.getAttribute(\"appearance\");\n const chrome = parseChromeAttribute(element.getAttribute(\"chrome\"));\n return {\n ...(appearance === \"light\" || appearance === \"dark\" ? { appearance } : {}),\n ...(chrome === undefined ? {} : { chrome })\n };\n}\n\nexport const DEFAULT_TAG = \"widgentic-designer\";\nexport const DEFAULT_THEME_TAG = \"widgentic-theme-designer\";\nexport const DEFAULT_SCHEMA_TAG = \"widgentic-schema-designer\";\nexport const DEFAULT_ACTION_TAG = \"widgentic-action-designer\";\n\nexport function defineDesignerElement(tagName: string = DEFAULT_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticDesignerElement extends HTMLElement {\n #handle: DesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((draft, diagnostics) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", {\n detail: { draft, diagnostics },\n bubbles: true\n })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n /** The embedding host's programmatic access to the wrapped handle. */\n get designer(): DesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticDesignerElement);\n}\n\n/** Sibling registrar for the standalone theme designer. */\nexport function defineThemeDesignerElement(tagName: string = DEFAULT_THEME_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticThemeDesignerElement extends HTMLElement {\n #handle: ThemeDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createThemeDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { theme: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ThemeDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticThemeDesignerElement);\n}\n\n/** Sibling registrar for the standalone schema designer. */\nexport function defineSchemaDesignerElement(tagName: string = DEFAULT_SCHEMA_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticSchemaDesignerElement extends HTMLElement {\n #handle: SchemaDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createSchemaDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { schema: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): SchemaDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticSchemaDesignerElement);\n}\n\n/** Sibling registrar for the standalone action designer. */\nexport function defineActionDesignerElement(tagName: string = DEFAULT_ACTION_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticActionDesignerElement extends HTMLElement {\n #handle: ActionDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createActionDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { action: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ActionDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticActionDesignerElement);\n}\n", "/**\n * Browser bundle entry (`@widgentic/designer/browser`): loading this module\n * from a <script type=\"module\"> registers the designer custom elements, so a\n * page without a bundler can host the designers. Bundler users import the\n * package root instead.\n */\nimport { defineActionDesignerElement, defineDesignerElement, defineSchemaDesignerElement, defineThemeDesignerElement } from \"./index.js\";\n\ndefineActionDesignerElement();\ndefineDesignerElement();\ndefineSchemaDesignerElement();\ndefineThemeDesignerElement();\n\nexport {};\n"],
5
+ "mappings": "AAgBA,SAASA,GAAcC,EAAkD,CACvE,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC5E,CASO,SAASC,GACdC,EACAC,EAA2B,CAAC,EACZ,CAChB,GAAI,CAACJ,GAAcG,CAAK,EACtB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,GACN,QAAS,iCACX,CACF,EAGF,GAAI,EAAE,SAAUA,GACd,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,2CACX,CACF,EAGF,IAAME,EAAOF,EAAM,KACnB,GAAI,OAAOE,GAAS,SAClB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,OACN,QAAS,gCACX,CACF,EAEF,GAAIA,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OWED_SCHEMES", "cleanUrl", "value", "isSafeUrl", "match", "scheme", "isLinkableUrl", "DATA_IMAGE", "HTTP_URL", "isSafeImageSrc", "cleaned", "IMAGE_EXTENSION", "looksLikeImageUrl", "el", "tag", "attrs", "children", "node", "BUILTIN_DESCRIPTORS", "NESTED_QUANTIFIER", "compileSafePattern", "pattern", "isPlainObject", "value", "matchesSingleType", "type", "data", "matchesType", "candidate", "enumMatches", "allowed", "formatType", "validateDataAgainstSchema", "schema", "path", "regex", "key", "subschema", "error", "i", "isPlainObject", "value", "formatValue", "applyPattern", "pattern", "linkOrText", "key", "raw", "hints", "display", "hint", "href", "isLinkableUrl", "el", "SHAPES", "resolveImage", "key", "value", "hints", "defaultShape", "hint", "isPlainObject", "isSafeImageSrc", "looksLikeImageUrl", "imageNode", "src", "shape", "el", "renderCard", "payload", "data", "meta", "fieldFormat", "isPlainObject", "title", "subtitle", "fieldEntries", "value", "key", "formatValue", "children", "el", "fieldValue", "image", "resolveImage", "display", "imageNode", "raw", "pattern", "text", "applyPattern", "linkOrText", "renderTable", "payload", "rows", "fieldFormat", "isPlainObject", "records", "row", "hintColumns", "columns", "column", "seen", "record", "key", "chrome", "title", "subtitle", "parts", "el", "formatValue", "value", "image", "resolveImage", "display", "imageNode", "raw", "pattern", "text", "applyPattern", "linkOrText", "renderTree", "payload", "depthHint", "expandDepth", "roots", "list", "el", "node", "renderNode", "title", "formatValue", "nodeLabel", "isPlainObject", "_children", "rest", "depth", "hasChildren", "attrs", "children", "child", "renderCustom", "payload", "text", "el", "GROUP_MAX_ITEMS", "GROUP_LAYOUTS", "GROUP_GAPS", "GROUP_MAX_COLUMNS", "checkGroupEnvelope", "data", "isPlainObject", "items", "checked", "i", "item", "entry", "renderGroupContainer", "hints", "children", "h", "layout", "known", "gap", "classes", "raw", "columns", "el", "stampActionLocation", "node", "location", "raw", "attrs", "descriptor", "children", "child", "DuplicateKindError", "kind", "createCatalog", "renderers", "descriptors", "catalog", "renderer", "payload", "validated", "validateWidgetPayload", "schema", "schemaError", "validateDataAgainstSchema", "envelope", "checkGroupEnvelope", "i", "item", "sub", "subPath", "renderGroupContainer", "thrown", "renderCard", "BUILTIN_DESCRIPTORS", "renderTable", "renderTree", "renderCustom", "result", "UNSAFE", "PROPERTY_NAME", "isSafeSelector", "selector", "parts", "part", "isSafeValue", "value", "widgetStylesToCss", "styles", "rules", "declarations", "lines", "property", "TOKEN_SPECS", "TOKEN_DEFAULTS", "name", "spec", "THEME_TOKENS", "isSafeTokenValue", "value", "v", "token", "TOKEN_DEFAULTS", "tokenDefaultsBlock", "THEME_TOKENS", "baseStylesheet", "STYLE_MARKER", "injectBaseStyles", "doc", "style", "isPlainObject", "value", "KNOWN_TOKENS", "THEME_TOKENS", "CUSTOM_VARIABLE", "customKeys", "theme", "key", "propertyName", "validateTheme", "input", "token", "isSafeTokenValue", "withFallbacks", "source", "filled", "fallback", "TOKEN_SPECS", "inherited", "applyTheme", "container", "style", "i", "property", "keys", "isPlainObject", "value", "FORBIDDEN_ATTR", "FORBIDDEN_TAGS", "RESERVED_ATTR", "URL_ATTRS", "MAX_TEMPLATE_DEPTH", "RESERVED", "parsePath", "value", "tokens", "i", "base", "up", "rest", "segment", "SECRET_NAME", "ACTION_NAME", "OUTPUT_MODES", "HTTP_METHODS", "join", "path", "segment", "fail", "message", "HEADER_TOKEN", "RESERVED_HEADERS", "FORBIDDEN_SEGMENTS", "isDataPath", "value", "checkHeaderValue", "isPlainObject", "SECRET_NAME", "containsSecretRef", "checkUrl", "url", "parsed", "validateActionDefinition", "input", "options", "literal", "HTTP_METHODS", "m", "urlError", "field", "map", "name", "namePath", "error", "definitionOf", "binding", "validateActionBinding", "definitionError", "definition", "declared", "fieldPath", "outPath", "mode", "target", "OUTPUT_MODES", "entries", "key", "entryPath", "validateLoadBinding", "join", "path", "segment", "nodeError", "message", "checkPathSyntax", "value", "parsePath", "check", "node", "depth", "MAX_TEMPLATE_DEPTH", "isPlainObject", "pathError", "templateError", "FORBIDDEN_TAGS", "name", "attrPath", "FORBIDDEN_ATTR", "RESERVED_ATTR", "hasMap", "hasPrefix", "entry", "actionError", "validateActionBinding", "i", "childError", "validateTemplate", "input", "error", "eachBinding", "template", "load", "onBinding", "visit", "node", "isPlainObject", "key", "child", "collectActionRefs", "refs", "binding", "join", "path", "segment", "resolvePath", "frames", "meta", "parsed", "parsePath", "current", "depth", "frame", "index", "isPlainObject", "DEFAULT_MAX_NODES", "buildDescriptor", "binding", "id", "ctx", "definition", "unresolved", "text", "segments", "formatValue", "prompt", "args", "field", "value", "resolved", "descriptor", "interpretNode", "node", "budget", "tpath", "items", "out", "itemPath", "i", "truthy", "branch", "FORBIDDEN_TAGS", "attrs", "name", "raw", "FORBIDDEN_ATTR", "RESERVED_ATTR", "key", "hit", "lower", "URL_ATTRS", "imageContext", "isSafeUrl", "isSafeImageSrc", "children", "child", "element", "compileTemplate", "template", "options", "maxNodes", "DEFAULT_MAX_NODES", "ctx", "payload", "budget", "frames", "nodes", "interpretNode", "only", "attrs", "buildDom", "node", "doc", "element", "name", "value", "child", "patchNode", "prev", "next", "dom", "patchElement", "doc", "replacement", "buildDom", "element", "prevAttrs", "nextAttrs", "name", "value", "patchChildren", "domChildren", "i", "child", "shared", "prevChild", "nextChild", "childDom", "extra", "surplus", "mountWidget", "payload", "container", "options", "catalog", "createCatalog", "current", "root", "disposed", "mountedPayload", "onAction", "parseDescriptor", "el", "parsed", "activation", "event", "key", "descriptor", "update", "nextPayload", "rendered", "built", "buildDom", "patchNode", "dispose", "CHROME_TOKENS", "TYPOGRAPHY", "CHROME_DEFAULTS", "declarations", "scheme", "prefix", "indent", "token", "chromeCss", "palette", "options", "selector", "darkMediaSelector", "blocks", "requireChild", "parent", "selector", "found", "h", "tag", "attrs", "children", "element", "name", "value", "child", "textField", "label", "onInput", "input", "textArea", "rows", "area", "section", "title", "open", "fitSelect", "select", "fit", "menuButton", "options", "onPick", "wrap", "toggle", "menu", "close", "onOutside", "onKey", "event", "option", "item", "diagnosticLine", "text", "el", "CHROME_TOKEN_SET", "CHROME_TOKENS", "CSS_WIDE_KEYWORD", "applyChrome", "root", "chrome", "token", "parseChromeAttribute", "parsed", "STYLE_MARKER", "injectDesignerStyles", "doc", "style", "chromeCss", "CHROME_DEFAULTS", "clone", "value", "errorMessage", "error", "JSON_TOKENS", "tokenizeJson", "text", "out", "last", "match", "paint", "layer", "nodes", "token", "span", "attachJsonHighlight", "textarea", "parent", "wrap", "sync", "syncScroll", "onTab", "event", "selectionStart", "selectionEnd", "value", "repaintHighlight", "checkDefinition", "definition", "errors", "isPlainObject", "template", "validateTemplate", "problem", "validateLoadBinding", "value", "parsePath", "exportWidgetJson", "draft", "exportThemeJson", "importWidgetJson", "text", "parsed", "error", "errorMessage", "applyDefinition", "store", "theme", "camelCase", "kind", "part", "i", "toTypeScriptModule", "mountIoPanel", "output", "h", "button", "label", "produce", "el", "repaintHighlight", "importError", "diagnosticLine", "importField", "textArea", "importArea", "requireChild", "attachJsonHighlight", "importButton", "result", "importSection", "section", "exportSection", "element", "TYPE_OPTIONS", "typeOf", "value", "defaultFor", "type", "previous", "parsed", "setAt", "root", "path", "remove", "step", "rest", "copy", "renameKey", "from", "to", "holder", "node", "entries", "k", "v", "createJsonTreeEditor", "initial", "onChange", "current", "element", "h", "commit", "next", "render", "commitText", "text", "typeSelect", "select", "option", "valueControl", "box", "input", "entryRow", "keyLabel", "removable", "row", "wrap", "renderContainer", "body", "item", "index", "add", "key", "keyInput", "name", "i", "TYPES", "ENUM_TYPES", "createSchemaBuilder", "initial", "onChange", "current", "element", "h", "commit", "next", "rerender", "render", "withKey", "node", "key", "value", "copy", "renderNode", "apply", "depth", "lead", "trail", "rows", "typeSelect", "t", "rawType", "typeList", "nullable", "currentType", "type", "fitSelect", "nullBox", "typeValue", "selected", "allowNull", "constraints", "pattern", "enumError", "diagnosticLine", "enumInput", "parsed", "error", "errorMessage", "properties", "isPlainObject", "required", "k", "cards", "name", "sub", "nameInput", "entries", "v", "nextRequired", "requiredBox", "removeProp", "_gone", "rest", "nextSub", "addProp", "i", "nextItems", "start", "clear", "schema", "createRecordEditor", "initial", "placeholders", "onChange", "current", "element", "h", "commit", "next", "render", "changeInput", "value", "placeholder", "className", "onCommit", "input", "record", "rows", "key", "keyInput", "entries", "v", "valueInput", "remove", "_gone", "rest", "add", "i", "firstType", "schema", "type", "primary", "t", "seedFor", "seed", "isPlainObject", "key", "createSchemaForm", "initial", "onChange", "current", "element", "h", "setAt", "root", "path", "value", "remove", "step", "rest", "copy", "holder", "commit", "rerender", "render", "control", "node", "label", "select", "option", "field", "box", "input", "parsed", "body", "properties", "required", "name", "sub", "isRequired", "itemsSchema", "items", "item", "index", "row", "add", "controlEl", "createStylesEditor", "initial", "onChange", "current", "element", "h", "commit", "next", "render", "changeInput", "value", "placeholder", "className", "onCommit", "input", "renderSelector", "selector", "declarations", "styles", "rename", "entries", "k", "v", "addDecl", "removeSelector", "_gone", "rest", "declRows", "property", "propInput", "valueInput", "removeDecl", "addSelector", "name", "i", "isPlainObject", "schemaType", "schema", "isPlainObject", "type", "primary", "t", "collectPaths", "prefix", "out", "depth", "name", "sub", "path", "schemaAt", "current", "segment", "typesConflict", "a", "b", "norm", "allPaths", "entries", "entry", "CUSTOM_PATH", "starterPromptDefinition", "starterHttpDefinition", "isRefBinding", "binding", "textInput", "value", "className", "onCommit", "placeholder", "el", "h", "select", "options", "onChange", "option", "fitSelect", "label", "text", "removeButton", "onClick", "button", "pathSelect", "sel", "known", "listed", "custom", "headerMapEditor", "initial", "secretNames", "labels", "current", "clone", "pending", "element", "duplicate", "diagnosticLine", "commit", "next", "render", "flagDuplicate", "name", "valueControl", "onValue", "isSecret", "isPlainObject", "mode", "names", "picker", "n", "nameInput", "entries", "k", "v", "controls", "remove", "_gone", "rest", "row", "index", "add", "segmentsEditor", "segment", "isBind", "copy", "_", "i", "addText", "addBind", "createDefinitionEditor", "ctx", "headEl", "schemasEl", "mapsEl", "http", "rerender", "renderSchemas", "schemaSection", "title", "which", "builder", "createSchemaBuilder", "schema", "parts", "shared", "copyFrom", "s", "entry", "renderHead", "kind", "method", "HTTP_METHODS", "m", "url", "renderMaps", "headers", "_h", "query", "_q", "definition", "createBindingEditor", "inputEl", "outputEl", "definitionOf", "a", "inputOf", "outputOf", "renderInput", "renderOutput", "withMapping", "input", "output", "helperPaths", "allPaths", "p", "modeSelect", "ref", "refSelect", "editor", "properties", "scopePaths", "pathOptions", "mapping", "rows", "field", "isConst", "kindSelect", "nextMapping", "literal", "valueInput", "modeSel", "OUTPUT_MODES", "nextOutput", "outputRow", "outputMapEditor", "map", "onMap", "container", "widgetSchema", "base", "targetRoot", "schemaAt", "targetOptions", "sourceOptions", "mismatch", "commitMap", "flag", "targetControl", "target", "onTarget", "control", "problems", "source", "targetType", "schemaType", "sourceType", "typesConflict", "targetInput", "sourceInput", "effectiveDataSchema", "draft", "schemas", "ref", "entry", "inline", "isPlainObject", "BASE_KINDS", "createCatalog", "auditStyles", "styles", "issues", "selector", "declarations", "widgetStylesToCss", "property", "value", "deriveDiagnostics", "options", "diagnostics", "template", "validateTemplate", "issue", "path", "schema", "error", "validateDataAgainstSchema", "problem", "validateLoadBinding", "parsePath", "known", "action", "unknown", "collectActionRefs", "theme", "validateTheme", "pathOptions", "scope", "use", "entries", "collectPaths", "scalars", "paths", "schema", "type", "schemaType", "entry", "itemScope", "eachPath", "isPlainObject", "current", "segment", "REMOVE", "pathString", "path", "out", "step", "setNode", "node", "next", "rest", "children", "_removed", "remaining", "swapChildren", "root", "parent", "a", "b", "holder", "getNode", "x", "y", "swapped", "NODE_PRESETS", "mountTemplatePanel", "store", "refreshers", "options", "actionContext", "unknownRefs", "treeHost", "h", "jsonError", "diagnosticLine", "jsonArea", "jsonWrap", "attachJsonHighlight", "treeTab", "jsonTab", "templateDiag", "element", "commit", "draft", "commitAt", "parsed", "error", "errorMessage", "changeInput", "value", "onCommit", "className", "input", "collapsedPaths", "nodeShell", "badge", "inline", "body", "errorText", "removable", "moves", "extras", "key", "collapsible", "isCollapsed", "chevron", "renderTree", "header", "icons", "up", "down", "remove", "TAG_OPTIONS", "pathControl", "select", "known", "option", "fitSelect", "custom", "marker", "tagControl", "tag", "slotEditor", "label", "parentPath", "slot", "required", "errorPath", "slotPath", "menu", "menuButton", "name", "preset", "renderNode", "here", "errorHere", "currentError", "attrs", "binding", "attrRows", "bound", "isBind", "bindValue", "rebuild", "fields", "setAttr", "nextValue", "nameInput", "nextName", "k", "v", "mode", "literalInput", "valueInput", "removeAttr", "_gone", "row", "hasMap", "hasPrefix", "prefixInput", "addMap", "attrRow", "parts", "mapEditor", "createRecordEditor", "nextMap", "defaultInput", "childNodes", "addMenu", "choice", "first", "scopePaths", "bindingEditor", "createBindingEditor", "effectiveDataSchema", "actionParts", "ref", "child", "index", "summaryParts", "lastDraft", "lastErrorPath", "refresh", "diagnostics", "action", "collectActionRefs", "templateMessage", "repaintHighlight", "mountThemePanel", "store", "refreshers", "themes", "themeDiag", "diagnosticLine", "themeSelect", "h", "entry", "candidate", "draft", "_gone", "rest", "tokenList", "renderTokenReference", "theme", "name", "spec", "TOKEN_SPECS", "value", "row", "match", "rows", "element", "section", "message", "tabs", "entries", "buttons", "entry", "index", "button", "h", "other", "i", "jsonField", "label", "read", "write", "clear", "store", "refreshers", "rows", "parseError", "diagnosticLine", "initial", "field", "textArea", "text", "draft", "value", "error", "errorMessage", "area", "requireChild", "attachJsonHighlight", "repaintHighlight", "mountPanels", "columns", "themes", "schemas", "actionContext", "disposers", "bindText", "textField", "input", "kindDiag", "hintsEditor", "createRecordEditor", "hints", "d", "_h", "rest", "generalPanel", "section", "v", "isPlainObject", "k", "doc", "_hints", "schemaBuilder", "createSchemaBuilder", "schema", "_s", "inlineEditors", "modeSelect", "sharedOption", "refSelect", "sharedView", "schemaRefDiag", "sharedWrap", "name", "resolved", "effectiveDataSchema", "_r", "refreshSchemaMode", "ref", "shared", "schemaPanel", "adaptiveDataEditor", "hostEl", "schemaKey", "editor", "rebuild", "key", "onChange", "createSchemaForm", "createJsonTreeEditor", "exampleDiag", "samplePanel", "_e", "sampleDiag", "previewDataPanel", "stylesDiag", "stylesEditor", "createStylesEditor", "styles", "stylesPanel", "templatePanel", "mountTemplatePanel", "themePanel", "mountThemePanel", "loadDiag", "loadEditor", "createBindingEditor", "binding", "_l", "loadPanel", "ioPanel", "mountIoPanel", "applyDiagnostics", "diagnostics", "deriveDiagnostics", "issue", "refresh", "off", "dispose", "PREVIEW_KIND", "createPreview", "options", "injectBaseStyles", "banner", "h", "kindStyles", "mountRoot", "pane", "catalog", "createCatalog", "renderer", "payload", "customStyles", "widget", "validated", "validateTemplate", "compiled", "compileTemplate", "descriptor", "isPlainObject", "widgetStylesToCss", "kinds", "kind", "mount", "update", "draft", "diagnostics", "previewKind", "renderingDraft", "issue", "shared", "ref", "action", "applyTheme", "sampleFor", "mountWidget", "bound", "cloneDraft", "draft", "starterDraft", "createDraftStore", "initial", "current", "history", "listeners", "notify", "listener", "updater", "previous", "createDesigner", "container", "options", "injectDesignerStyles", "base", "cloneDraft", "starterDraft", "initial", "store", "createDraftStore", "listeners", "preview", "createPreview", "leftColumn", "h", "rightSections", "rightColumn", "root", "applyChrome", "actionContext", "panels", "mountPanels", "refresh", "draft", "diagnostics", "deriveDiagnostics", "listener", "unsubscribe", "setReadOnly", "readOnly", "bodies", "body", "definition", "errors", "checkDefinition", "applyDefinition", "theme", "validated", "validateTheme", "SAFE_NAME", "starterEntry", "checkSchemaEntry", "entry", "errors", "isPlainObject", "createSchemaDesigner", "container", "options", "injectDesignerStyles", "listeners", "panels", "h", "root", "applyChrome", "getEntry", "notify", "listener", "identityRefreshers", "nameDiag", "diagnosticLine", "identityField", "label", "read", "write", "field", "textField", "input", "requireChild", "identity", "section", "value", "bad", "builder", "createSchemaBuilder", "schema", "syncJson", "jsonError", "jsonArea", "jsonWrap", "parsed", "error", "errorMessage", "repaintHighlight", "builderTab", "jsonTab", "definition", "importError", "importArea", "importButton", "result", "loadSchema", "importSection", "output", "exportButton", "exportSection", "attachJsonHighlight", "refresh", "setReadOnly", "readOnly", "bodies", "body", "BASE_KINDS", "createCatalog", "HEX", "CUSTOM_NAME", "toHexInput", "value", "r", "g", "b", "starterEntry", "checkThemeEntry", "entry", "errors", "candidate", "validated", "validateTheme", "createThemeDesigner", "container", "options", "injectDesignerStyles", "listeners", "preview", "createPreview", "previewKinds", "previewKind", "panels", "h", "side", "root", "applyChrome", "previewDraft", "starterDraft", "refresh", "listener", "getEntry", "setToken", "key", "tokens", "identityRefreshers", "identityField", "label", "read", "write", "field", "textField", "input", "requireChild", "identity", "section", "kindSelect", "kind", "tokenRefreshers", "tokenRows", "token", "THEME_TOKENS", "TOKEN_DEFAULTS", "issue", "diagnosticLine", "swatch", "TOKEN_SPECS", "paint", "effective", "hex", "isSafeTokenValue", "unsafe", "tokenPanel", "customHost", "customError", "customEntries", "renderCustom", "rows", "nameInput", "next", "valueInput", "remove", "add", "name", "i", "customPanel", "output", "exportButton", "importArea", "importError", "importButton", "parsed", "error", "errorMessage", "result", "loadTheme", "importPanel", "exportPanel", "refreshIdentity", "refreshToken", "setReadOnly", "readOnly", "bodies", "body", "starterEntry", "checkActionEntry", "entry", "errors", "isPlainObject", "ACTION_NAME", "field", "problem", "validateActionDefinition", "normalizeEntry", "input", "clone", "withText", "current", "value", "_gone", "rest", "createActionDesigner", "container", "options", "injectDesignerStyles", "testCall", "listeners", "panels", "h", "root", "applyChrome", "getEntry", "notify", "listener", "identityRefreshers", "nameDiag", "diagnosticLine", "identityField", "label", "read", "write", "textField", "inputEl", "requireChild", "identity", "section", "bad", "definitionDiag", "editor", "createDefinitionEditor", "definition", "syncJson", "refreshDefinitionDiag", "refreshTest", "jsonError", "jsonArea", "jsonWrap", "parsed", "error", "errorMessage", "repaintHighlight", "builderTab", "jsonTab", "testHost", "testSection", "testArgs", "testInputJson", "definitionNow", "inputJson", "form", "createSchemaForm", "output", "run", "result", "importError", "importArea", "importButton", "loadAction", "importSection", "exportButton", "exportSection", "attachJsonHighlight", "refresh", "setReadOnly", "readOnly", "bodies", "body", "elementOptions", "element", "appearance", "chrome", "parseChromeAttribute", "DEFAULT_TAG", "DEFAULT_THEME_TAG", "DEFAULT_SCHEMA_TAG", "DEFAULT_ACTION_TAG", "defineDesignerElement", "tagName", "WidgenticDesignerElement", "#handle", "#unsubscribe", "createDesigner", "draft", "diagnostics", "defineThemeDesignerElement", "WidgenticThemeDesignerElement", "createThemeDesigner", "entry", "defineSchemaDesignerElement", "WidgenticSchemaDesignerElement", "createSchemaDesigner", "defineActionDesignerElement", "WidgenticActionDesignerElement", "createActionDesigner", "defineActionDesignerElement", "defineDesignerElement", "defineSchemaDesignerElement", "defineThemeDesignerElement"]
7
7
  }