@snowcone-app/canvas 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/STYLING_CONTRACT.md +2 -2
  2. package/dist/{CanvasRenderer-BEf0hXeF.js → CanvasRenderer-hpJ05JGO.js} +4 -4
  3. package/dist/{CanvasRenderer-BEf0hXeF.js.map → CanvasRenderer-hpJ05JGO.js.map} +1 -1
  4. package/dist/{CanvasStateV1-BDSyYo4A.js → CanvasStateV1-jLOibojY.js} +11 -4
  5. package/dist/{CanvasStateV1-BDSyYo4A.js.map → CanvasStateV1-jLOibojY.js.map} +1 -1
  6. package/dist/{ContextualToolbars-C3D_6sep.js → ContextualToolbars-DRbuUE7W.js} +2086 -1985
  7. package/dist/ContextualToolbars-DRbuUE7W.js.map +1 -0
  8. package/dist/{EditorCanvasImpl-DXeBz2CX.js → EditorCanvasImpl-P2GHPNA3.js} +19 -20
  9. package/dist/{EditorCanvasImpl-DXeBz2CX.js.map → EditorCanvasImpl-P2GHPNA3.js.map} +1 -1
  10. package/dist/{ExportManager-DUdis6se.js → ExportManager-Bkzzyxgw.js} +400 -261
  11. package/dist/ExportManager-Bkzzyxgw.js.map +1 -0
  12. package/dist/{FontAnalyzer-DKG5JK0x.js → FontAnalyzer-BYhwxDhe.js} +1084 -1034
  13. package/dist/FontAnalyzer-BYhwxDhe.js.map +1 -0
  14. package/dist/{ImagePanel-CBgGqmVV.js → ImagePanel-CEr0_FYy.js} +49 -49
  15. package/dist/{ImagePanel-CBgGqmVV.js.map → ImagePanel-CEr0_FYy.js.map} +1 -1
  16. package/dist/{SnowconeCanvas-BWPBngvI.js → SnowconeCanvas-Fa0isFpO.js} +27 -27
  17. package/dist/{SnowconeCanvas-BWPBngvI.js.map → SnowconeCanvas-Fa0isFpO.js.map} +1 -1
  18. package/dist/advanced.mjs +14 -14
  19. package/dist/components/ImageToolbar.d.ts +4 -0
  20. package/dist/components/toolbars/EmbeddedToolbarLayout.d.ts +2 -0
  21. package/dist/components/toolbars/SecondaryPanels.d.ts +17 -1
  22. package/dist/components/toolbars/index.d.ts +2 -2
  23. package/dist/components/ui/SliderRow.d.ts +6 -0
  24. package/dist/components/ui/toolbar-button.d.ts +2 -2
  25. package/dist/core/image-adjustments.d.ts +32 -0
  26. package/dist/{custom-icons-BIaRovwG.js → custom-icons-Co4rcW0S.js} +7 -7
  27. package/dist/{custom-icons-BIaRovwG.js.map → custom-icons-Co4rcW0S.js.map} +1 -1
  28. package/dist/design-builder-CBG2hKc8.js +1672 -0
  29. package/dist/design-builder-CBG2hKc8.js.map +1 -0
  30. package/dist/{embed-Csez1hui.js → embed-D4TIzO7g.js} +110 -111
  31. package/dist/{embed-Csez1hui.js.map → embed-D4TIzO7g.js.map} +1 -1
  32. package/dist/embed.mjs +53 -54
  33. package/dist/embed.mjs.map +1 -1
  34. package/dist/{guards-BSoX73yg.js → guards-DgZuwVgu.js} +2 -2
  35. package/dist/{guards-BSoX73yg.js.map → guards-DgZuwVgu.js.map} +1 -1
  36. package/dist/hooks/elementPatch.d.ts +7 -2
  37. package/dist/index.mjs +41 -41
  38. package/dist/internals.mjs +196 -127
  39. package/dist/internals.mjs.map +1 -1
  40. package/dist/rendering/element-painters.d.ts +0 -13
  41. package/dist/rendering/element-serializer.d.ts +3 -1
  42. package/dist/rendering/image-adjustments.d.ts +24 -0
  43. package/dist/rendering/renderer-types.d.ts +8 -1
  44. package/dist/state/CanvasStateV1.d.ts +5 -0
  45. package/dist/template-fields-CvFcr5zy.js +505 -0
  46. package/dist/template-fields-CvFcr5zy.js.map +1 -0
  47. package/dist/testing.mjs +40 -41
  48. package/dist/testing.mjs.map +1 -1
  49. package/dist/types/index.d.ts +21 -0
  50. package/dist/{UnifiedFontService-Co9tQ59z.js → useCommands-bPXY9rCh.js} +2344 -2103
  51. package/dist/useCommands-bPXY9rCh.js.map +1 -0
  52. package/dist/{usePieceGuideBundle-CRLY2iQa.js → usePieceGuideBundle-Bj98nPk0.js} +2 -2
  53. package/dist/{usePieceGuideBundle-CRLY2iQa.js.map → usePieceGuideBundle-Bj98nPk0.js.map} +1 -1
  54. package/dist/utils/featureApplied.d.ts +2 -0
  55. package/dist/{validation-BGEl9rrE.js → validation-CsTlSvJJ.js} +465 -465
  56. package/dist/{validation-BGEl9rrE.js.map → validation-CsTlSvJJ.js.map} +1 -1
  57. package/dist/workers/export-worker.bundle.string.d.ts +1 -1
  58. package/example/package.json +1 -1
  59. package/package.json +1 -1
  60. package/dist/ContextualToolbars-C3D_6sep.js.map +0 -1
  61. package/dist/ExportManager-DUdis6se.js.map +0 -1
  62. package/dist/FontAnalyzer-DKG5JK0x.js.map +0 -1
  63. package/dist/UnifiedFontService-Co9tQ59z.js.map +0 -1
  64. package/dist/design-builder-JYLO_Hyi.js +0 -470
  65. package/dist/design-builder-JYLO_Hyi.js.map +0 -1
  66. package/dist/editorErrors-WzaNxU1Y.js +0 -1206
  67. package/dist/editorErrors-WzaNxU1Y.js.map +0 -1
  68. package/dist/template-fields-DYPW7bVU.js +0 -716
  69. package/dist/template-fields-DYPW7bVU.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template-fields-CvFcr5zy.js","sources":["../src/components/editor/designStateStore.ts","../src/components/editor/commerceStore.ts","../src/hooks/useSelectedElement.ts","../src/hooks/useDeadBindingWarning.ts","../src/hooks/bindingGuards.ts","../src/hooks/useTextBinding.ts","../src/hooks/useImageBinding.ts","../src/hooks/useColorBinding.ts","../src/hooks/useFontBinding.ts","../src/hooks/useElementByName.ts","../src/design/template-fields.ts"],"sourcesContent":["/**\n * The ONE live design-state value under an `Editor.Root` (ADR-0085 §3 / T2).\n *\n * Today's turnkey flow is two stores, one-way, one-shot: the design seeds the\n * canvas once and edits never flow back, so the seed goes stale after the\n * first edit. This store fixes that by construction — seeded from the design\n * at Root mount, updated by every canvas change AND every TextField write,\n * last-write-wins. `Editor.Buy` (and `assertRenders`, P2) read THIS, never\n * the seed, so design staleness can't corrupt an order.\n *\n * TextField ─┐\n * ├─→ DesignStateStore ─→ pushRender ─→ session ─→ Preview(s)\n * Canvas ───┘\n *\n * (With a mounted Canvas the editor document is the write authority and this\n * store derives from its `onChange`; without one, this store IS the\n * authority. The routing lives in the parts — see EditorTextField.)\n *\n * Deliberately a tiny hand-rolled external store (subscribe + snapshot for\n * `useSyncExternalStore`) — narrow subscriptions without re-rendering the\n * whole Root tree per keystroke. Alternate state libraries were considered\n * and rejected (plan decision D3-C).\n */\n\nimport type { AnyElementConfig } from '../../types/index.js';\nimport { EditorError } from '../../errors/editorError.js';\nimport { layerKindOfConfig } from '../../design/design-builder.js';\n\n/** Editor-shape design state — the same shape `design.toJSON()` produces and\n * `<SnowconeCanvas onChange>` emits (and `serializeStateForServer` accepts). */\nexport interface DesignState {\n elements: AnyElementConfig[];\n artboards: Array<{\n name: string;\n width: number;\n height: number;\n backgroundColor?: string;\n exportBackground?: boolean;\n }>;\n activeArtboard: string;\n}\n\nfunction textOf(el: AnyElementConfig): string | undefined {\n return (el as { text?: string }).text;\n}\n\nfunction nameOf(el: AnyElementConfig): string | undefined {\n return (el as { name?: string }).name;\n}\n\nexport class DesignStateStore {\n private state: DesignState;\n /** Frozen snapshot of the values the design was seeded with — Buy's\n * \"differs from seed\" completeness rule (C3) compares against this. */\n private readonly seedTextByName: ReadonlyMap<string, string>;\n private readonly listeners = new Set<() => void>();\n\n constructor(seed: DesignState) {\n this.state = seed;\n const seedTexts = new Map<string, string>();\n for (const el of seed.elements) {\n const name = nameOf(el);\n const text = textOf(el);\n if (name && typeof text === 'string') seedTexts.set(name, text);\n }\n this.seedTextByName = seedTexts;\n }\n\n // Arrow on purpose: handed bare to `useSyncExternalStore` as the snapshot.\n getState = (): DesignState => {\n return this.state;\n };\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n /** Replace the whole state (the canvas `onChange` path). */\n setState(next: DesignState): void {\n this.state = next;\n this.emit();\n }\n\n /** The seed value of a named text layer (for completeness rule C3). */\n seedTextOf(name: string): string | undefined {\n return this.seedTextByName.get(name);\n }\n\n /** Current text of a named text layer, or undefined when absent. */\n textOf(name: string): string | undefined {\n const el = this.state.elements.find((e) => nameOf(e) === name);\n return el ? textOf(el) : undefined;\n }\n\n /** Kind of the named layer in the CURRENT state ('text' | 'image' | null\n * for unbindable), or undefined when no layer has the name. */\n layerKindOf(name: string): 'text' | 'image' | null | undefined {\n const el = this.state.elements.find((e) => nameOf(e) === name);\n return el ? layerKindOfConfig(el) : undefined;\n }\n\n /** Names of bindable layers in the current state, for error messages. */\n bindableLayerNames(): string[] {\n return this.state.elements\n .filter((e) => layerKindOfConfig(e) !== null)\n .map(nameOf)\n .filter((n): n is string => Boolean(n));\n }\n\n /**\n * Direct write path for `Editor.TextField` when NO canvas is mounted (with\n * one, writes route through the editor command path and arrive back here\n * via `setState`). Immutable update; last-write-wins.\n */\n updateTextLayer(name: string, text: string): void {\n let found = false;\n const elements = this.state.elements.map((el) => {\n if (nameOf(el) !== name) return el;\n found = true;\n return { ...el, text } as AnyElementConfig;\n });\n if (!found) {\n throw new EditorError(\n 'E_LAYER_NOT_FOUND',\n `no layer \"${name}\" in the current design state. Bindable layers: ` +\n `${JSON.stringify(this.bindableLayerNames())}.`,\n { layerName: name, validNames: this.bindableLayerNames(), docSlug: 'embed-mode' },\n );\n }\n this.setState({ ...this.state, elements });\n }\n\n /** ≥1 element with visible content (completeness rule C4): non-empty text,\n * an image with a URL, or a shape. Hidden elements don't count. */\n hasRenderableElement(): boolean {\n return this.state.elements.some((el) => {\n if ((el as { visible?: boolean }).visible === false) return false;\n const t = (el as { transformType?: string }).transformType;\n if (t === 'image') return Boolean((el as { imageUrl?: string }).imageUrl);\n if (t === 'shape') return true;\n if (t === 'group' || t === 'path') return true;\n const text = textOf(el);\n return typeof text === 'string' && text.trim().length > 0;\n });\n }\n\n private emit(): void {\n for (const l of [...this.listeners]) l();\n }\n}\n","/**\n * The ONE commerce-selection state under an `Editor.Root` (ADR-0085 §2, P2 —\n * \"Buy-owned variant + quantity state\").\n *\n * Ownership model: `Editor.Buy` OWNS this state (it gates on it and assembles\n * the cart payload from it); the HOST renders the variant-selection UI and\n * reads/writes the same state through `useProductSelection()` — parts carry\n * behavior, hosts own layout/markup (the rendering contract). The state does\n * NOT live on Root props: changing `product.variantId` up there re-keys the\n * whole RenderSession (WS teardown + re-grant + reconnect per color click),\n * which is session identity, not user selection.\n *\n * host variant UI ──select()──┐\n * ├─→ CommerceStateStore ─→ resolvedVariantId ─→ session.setProduct\n * Editor.Buy ──reads─────────┘ │ (live config, no re-key) + re-push state\n * └─→ completeness (C1/C5) + cart payload\n *\n * Selection resolution is the SDK's: `validateProductSelection` +\n * `findBestCombination` (the C1 amendment: full resolution replaces the\n * color-axis-only gate). Like `DesignStateStore`, this is a tiny hand-rolled\n * external store — narrow `useSyncExternalStore` subscriptions, no state lib.\n */\n\nimport {\n computeDisabledChoices,\n findBestCombination,\n getMissingSelections,\n toCombinations,\n toOptionAttributes,\n validateProductSelection,\n type Combination,\n type OptionAttribute,\n type OptionSelection,\n type RenderProduct,\n} from '@snowcone-app/sdk';\nimport { EditorError } from '../../errors/editorError.js';\n\n/**\n * One choice of a variant attribute as the commerce store HANDS IT OUT —\n * always the catalog's choice OBJECT (`toOptionAttributes` normalizes bare\n * strings to `{ label }`). A `hex` marks a color-axis choice (render it as a\n * swatch). NOTE the currency mismatch this type exists to make honest: the\n * SDK's `OptionAttribute` declares `choices: string[]` for its selection\n * math, but the runtime objects flowing through this store are these.\n */\nexport interface ProductOptionChoice {\n label?: string;\n hex?: string;\n [key: string]: unknown;\n}\n\n/** An attribute as `useProductSelection().attributes` returns it: the SDK\n * shape with the choices typed as the objects they actually are. The\n * CURRENCY for `select()` / `selection` / `disabledChoices` is the choice's\n * `label` STRING — pass `choice.label`, never the object. */\nexport interface ProductSelectionAttribute extends Omit<OptionAttribute, 'choices'> {\n choices: ProductOptionChoice[];\n}\n\n/** The label strings of an attribute's choices (legacy attrs may carry bare\n * strings; normalized attrs carry `{ label, hex?, … }` objects). */\nexport function choiceLabelsOf(attr: OptionAttribute | ProductSelectionAttribute): string[] {\n return ((attr.choices ?? []) as Array<string | ProductOptionChoice>)\n .map((c) => (typeof c === 'string' ? c : (c.label ?? '')))\n .filter((label) => label !== '');\n}\n\n/** Derive the seed selection from the product's initial `variantId` — the\n * combination it resolves to pins one value per variant-affecting attribute.\n * No `variantId` (or no match) seeds an empty selection. */\nexport function seedSelectionOf(product: RenderProduct, combinations: Combination[]): OptionSelection {\n if (!product.variantId) return {};\n const combination = combinations.find((c) => c.variantId === product.variantId);\n if (!combination) return {};\n const selection: OptionSelection = {};\n for (const [key, value] of Object.entries(combination)) {\n if (key === 'variantId' || key === 'price') continue;\n if (typeof value === 'string') selection[key] = value;\n else if (typeof value === 'number') selection[key] = String(value);\n }\n return selection;\n}\n\nexport class CommerceStateStore {\n private product: RenderProduct;\n private attrs: Record<string, OptionAttribute>;\n private combos: Combination[];\n private selection: OptionSelection;\n private quantity = 1;\n private version = 0;\n private readonly listeners = new Set<() => void>();\n\n constructor(product: RenderProduct) {\n this.product = product;\n this.attrs = toOptionAttributes({ options: product.options } as Parameters<typeof toOptionAttributes>[0]);\n this.combos = toCombinations({ options: product.options } as Parameters<typeof toCombinations>[0]);\n this.selection = seedSelectionOf(product, this.combos);\n }\n\n // Arrows on purpose: handed bare to `useSyncExternalStore`.\n getVersion = (): number => this.version;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n getAttributes(): Record<string, ProductSelectionAttribute> {\n // `toOptionAttributes` always normalizes choices to objects (bare strings\n // become `{ label }`), so this narrowing is true by construction. The SDK\n // type's `choices: string[]` describes its selection-math currency, not\n // the runtime shape — hence the through-unknown cast.\n return this.attrs as unknown as Record<string, ProductSelectionAttribute>;\n }\n\n getSelection(): OptionSelection {\n return this.selection;\n }\n\n getQuantity(): number {\n return this.quantity;\n }\n\n /**\n * Select a choice for a variant attribute. Strict + loud (D4/E3): an\n * attribute key or choice that doesn't exist on the product is a wiring\n * mistake, not user state — throws `E_UNKNOWN_OPTION` listing what IS valid.\n */\n select(key: string, choice: string): void {\n const attr = this.attrs[key];\n if (!attr) {\n throw new EditorError(\n 'E_UNKNOWN_OPTION',\n `product ${this.product.productId} has no option \"${key}\". ` +\n `Valid option keys: ${JSON.stringify(Object.keys(this.attrs))}.`,\n { key, validKeys: Object.keys(this.attrs), docSlug: 'embed-mode' },\n );\n }\n const labels = choiceLabelsOf(attr);\n if (labels.length > 0 && !labels.includes(choice)) {\n throw new EditorError(\n 'E_UNKNOWN_OPTION',\n `\"${choice}\" is not a choice of option \"${key}\" on product ${this.product.productId}. ` +\n `Valid choices: ${JSON.stringify(labels)}.`,\n { key, choice, validChoices: labels, docSlug: 'embed-mode' },\n );\n }\n if (this.selection[key] === choice) return;\n this.selection = { ...this.selection, [key]: choice };\n this.bump();\n }\n\n /** Quantity is USER state (completeness rule C5 gates on it) — never throws. */\n setQuantity(quantity: number): void {\n if (this.quantity === quantity) return;\n this.quantity = quantity;\n this.bump();\n }\n\n /** Attribute keys still required (non-optional) but unselected — Buy's\n * `option:<key>` reason codes. */\n missingOptionKeys(): string[] {\n if (Object.keys(this.attrs).length === 0) return [];\n return getMissingSelections(this.attrs, this.selection);\n }\n\n /** Full selection resolution (the C1 amendment): true when every required\n * attribute is selected AND the selection matches a valid combination. */\n selectionValid(): boolean {\n if (Object.keys(this.attrs).length === 0) return true;\n return validateProductSelection(this.attrs, this.selection, this.combos);\n }\n\n /** The variant (gvid) the current selection resolves to. Falls back to the\n * product's initial `variantId` while nothing has been selected. */\n resolvedVariantId(): string | undefined {\n if (Object.keys(this.attrs).length === 0 || this.combos.length === 0) {\n return this.product.variantId;\n }\n if (!this.selectionValid()) return undefined;\n const best = findBestCombination(this.selection, this.combos, this.attrs);\n return (typeof best?.variantId === 'string' && best.variantId !== '' ? best.variantId : undefined) ?? this.product.variantId;\n }\n\n /**\n * The variant (gvid) to RENDER with — deliberately looser than\n * {@link resolvedVariantId}. That one is Buy's currency: it returns\n * `undefined` while the selection is incomplete so completeness can gate.\n * But the PRODUCT PHOTO must follow the shopper's picks immediately —\n * \"choose the Oak frame\" should render Oak even while an unrelated axis\n * (size, pocket) is still unselected. This resolves the best combination\n * matching the CURRENT (possibly partial) selection, falling back to the\n * product's initial variant. (Before this split, switching a color swatch\n * with any axis unselected rendered nothing — the mockup silently stayed\n * on the old color.)\n */\n renderVariantId(): string | undefined {\n if (Object.keys(this.attrs).length === 0 || this.combos.length === 0) {\n return this.product.variantId;\n }\n const best = findBestCombination(this.selection, this.combos, this.attrs);\n return (typeof best?.variantId === 'string' && best.variantId !== '' ? best.variantId : undefined) ?? this.product.variantId;\n }\n\n /** Price of the resolved combination, when the catalog carries one. */\n resolvedPrice(): number | undefined {\n if (!this.selectionValid()) return undefined;\n const best = findBestCombination(this.selection, this.combos, this.attrs);\n return typeof best?.price === 'number' ? best.price : undefined;\n }\n\n /** Choices invalid given the rest of the current selection — for hosts to\n * disable/grey out in their variant UI. */\n disabledChoices(): Record<string, string[]> {\n // computeDisabledChoices compares choice strings to combination values, so\n // feed it label-string choices.\n const stringAttrs: Record<string, OptionAttribute> = {};\n for (const [key, attr] of Object.entries(this.attrs)) {\n stringAttrs[key] = { ...attr, choices: choiceLabelsOf(attr) as OptionAttribute['choices'] };\n }\n return computeDisabledChoices(this.selection, stringAttrs, this.combos);\n }\n\n /** The combinations (for payload assembly via `createCartDetail`). */\n getCombinations(): Combination[] {\n return this.combos;\n }\n\n private bump(): void {\n this.version++;\n for (const l of [...this.listeners]) l();\n }\n}\n","import { useEditor } from '../contexts/EditorContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/**\n * Returns the currently selected element, or null if nothing is selected.\n *\n * This is a convenience wrapper around `useEditor()` that only extracts\n * selection state, keeping consumer components focused on what they need.\n *\n * @example\n * ```tsx\n * function PropertiesPanel() {\n * const selected = useSelectedElement();\n * if (!selected) return <p>Nothing selected</p>;\n * return <p>Selected: {selected.id}</p>;\n * }\n * ```\n */\nexport function useSelectedElement(): EditorElement | null {\n const { selectedElement } = useEditor();\n return selectedElement ?? null;\n}\n","/**\n * useDeadBindingWarning - Dev-only diagnostic for \"dead\" binding hooks.\n *\n * `useTextBinding('typo')` / `useImageBinding('typo')` on a layer name that\n * matches no element returns `isConnected: false` with no-op setters — by\n * design. But with no diagnostic, a typo'd layer name produces a dead control\n * with ZERO console output (the silent-failure finding from the embed-SDK DX\n * evaluation). This hook emits a one-time, dev-only `console.warn` naming the\n * requested layer and listing the canvas's named layers — the same\n * silent-blank-guard pattern as the SDK's `warnImagelessElements` /\n * `[RealtimeEmbed]` validateEmbed warnings.\n *\n * Timing is settle-aware: elements may legitimately arrive late\n * (`initialElements` seeding, an async state load), so warning on first render\n * would false-fire constantly. The `ElementStore` is immutable — every mutation\n * hands the context a NEW store instance, which re-runs the effect — so the\n * grace timer re-arms on every element change and only fires once the element\n * set has been quiet for {@link DEAD_BINDING_GRACE_MS} with still no match.\n * Connecting (or unmounting — StrictMode's throwaway first mount included)\n * clears the pending timer.\n *\n * @module\n */\n\nimport { useEffect } from 'react';\nimport type { ElementStore, StoreElement } from '../core/ElementStore.js';\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\n\n/** The binding hook flavor (font binds to TEXT layers — see TARGET_KIND). */\nexport type BindingKind = 'text' | 'image' | 'font';\n\n/**\n * How long the element set must be SETTLED (no store changes) with the binding\n * still unmatched before the warning fires. Long enough for `initialElements`\n * seeding and async state loads to land; short enough to surface a typo well\n * before the user gives up on the dead control.\n */\nexport const DEAD_BINDING_GRACE_MS = 3000;\n\nconst HOOK_NAME: Record<BindingKind, string> = {\n text: 'useTextBinding',\n image: 'useImageBinding',\n font: 'useFontBinding',\n};\n\nconst SETTER_NAME: Record<BindingKind, string> = {\n text: 'setText',\n image: 'setImageUrl',\n font: 'setFontFamily',\n};\n\n/** The element flavor each hook actually matches (font targets text layers). */\nconst TARGET_KIND: Record<BindingKind, 'text' | 'image'> = {\n text: 'text',\n image: 'image',\n font: 'text',\n};\n\n/** Layer names already warned about — the warning is one-time per page load. */\nconst warned = new Set<string>();\n\n/** Test-only: forget which dead bindings have already been warned about. */\nexport function resetDeadBindingWarnings(): void {\n warned.clear();\n}\n\nfunction kindOf(el: StoreElement): string {\n if (el instanceof TextElement) return 'text';\n if (el instanceof ImageElement) return 'image';\n return 'other';\n}\n\n/**\n * Build the dead-binding warning message. Exported for tests; the message\n * distinguishes the two failure shapes:\n * - the name matches a layer of the WRONG type → point at the right hook\n * - the name matches nothing → list the available named layers (or explain\n * how to name one when none carry a name)\n */\nexport function deadBindingWarning(kind: BindingKind, name: string, store: ElementStore): string {\n const tag = `[${HOOK_NAME[kind]}]`;\n const dead = `the binding is dead (isConnected: false, ${SETTER_NAME[kind]} is a no-op)`;\n\n const target = TARGET_KIND[kind];\n const sameName = store.getAllByName(name);\n if (sameName.length > 0) {\n const kinds = [...new Set(sameName.map(kindOf))];\n const other = target === 'text' ? 'image' : 'text';\n const hint =\n kinds.length === 1 && kinds[0] === other\n ? ` Bind it with ${HOOK_NAME[other]}(\"${name}\") instead.`\n : '';\n return (\n `${tag} the layer named \"${name}\" is ${kinds.join('/')}, not ${target} — ` +\n `${dead}.${hint}`\n );\n }\n\n const named = store\n .getAll()\n .filter((el) => el.name)\n .map((el) => `\"${el.name}\" (${kindOf(el)})`);\n const available = named.length\n ? `Named layers on this canvas: ${named.join(', ')}. Check the name for a typo.`\n : `No element on this canvas has a name — name one via design().${target}(…, ` +\n `{ name: '${name}' }) or the element's \\`name\\` property.`;\n return `${tag} no ${target} layer named \"${name}\" exists — ${dead}. ${available}`;\n}\n\n/**\n * Emit the one-time dead-binding warning once the element set settles with the\n * binding still disconnected. Used by `useTextBinding` / `useImageBinding`;\n * dev-only (compiled out of production via the `NODE_ENV` guard) and never\n * throws.\n */\nexport function useDeadBindingWarning(\n kind: BindingKind,\n name: string,\n store: ElementStore,\n isConnected: boolean,\n): void {\n useEffect(() => {\n if (isConnected) return;\n if (typeof process === 'undefined' || process.env?.NODE_ENV === 'production') return;\n const key = `${kind}:${name}`;\n if (warned.has(key)) return;\n\n // The store is immutable, so any element change re-runs this effect with a\n // new instance — re-arming the timer. It fires only once the element set\n // has been quiet for the full grace period with still no match.\n const timer = setTimeout(() => {\n if (warned.has(key)) return; // another component already warned for this name\n warned.add(key);\n console.warn(deadBindingWarning(kind, name, store));\n }, DEAD_BINDING_GRACE_MS);\n return () => clearTimeout(timer);\n }, [kind, name, store, isConnected]);\n}\n","/**\n * Shared fail-loud guards for the chrome-binding hooks (`useTextBinding`,\n * `useImageBinding`, `useFontBinding`, `useColorBinding`) when they run under\n * an `<Editor.Root>` (ADR-0085 compositions). Outside a Root — legacy chrome\n * inside a raw `EditorProvider`, `<RealtimeCanvas>` overlay children — both\n * guards are inert and the hooks keep their historical warn-only behavior.\n *\n * Guard 1 — canvas requirement: the bindings mutate the editor document via\n * the command path, and only a mounted `Editor.Canvas` syncs that document to\n * the design store / live renders. In a canvas-free composition the document\n * is EMPTY (Root seeds only the artboard), so every binding is a dead control\n * with no-op setters — a silent failure an agent cannot see. Registering with\n * the Root's parts registry turns it into the existing `E_REQUIRES_CANVAS`\n * mount throw (agentic-DX P0, docs/dx/agentic-editor-dx.md finding #1).\n *\n * Guard 2 — token validation: with a `design.layer()` token (a validated\n * claim, ADR-0085 §1) the dead-binding console.warn upgrades to a throw.\n * Elements reach Root's document only when the canvas chunk seeds it, so\n * validation runs once against the FIRST non-empty element snapshot: token\n * name absent → `E_LAYER_NOT_FOUND`; present with the wrong kind →\n * `E_LAYER_WRONG_KIND`. Render-time on purpose — Root's boundary contains\n * it, dev AND prod (strict-loud-failures house rule).\n */\n\nimport { useContext, useId, useLayoutEffect, useRef } from 'react';\nimport { EditorRootInternalsContext } from '../components/editor/RootInternals.js';\nimport { EditorError } from '../errors/editorError.js';\nimport { isLayerToken, type LayerKind, type LayerToken } from '../design/design-builder.js';\nimport type { ElementStore, StoreElement } from '../core/ElementStore.js';\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\n\n/**\n * Under `<Editor.Root>`, declare that this binding hook needs a mounted\n * `Editor.Canvas` — Root's registry validation throws `E_REQUIRES_CANVAS`\n * (its existing single validation point) when none is in the composition.\n * No-op outside a Root.\n */\nexport function useBindingRequiresCanvas(hookName: string): void {\n const internals = useContext(EditorRootInternalsContext);\n const instanceId = useId();\n useLayoutEffect(() => {\n if (!internals) return undefined;\n return internals.registry.requireCanvas(instanceId, hookName);\n }, [internals, instanceId, hookName]);\n}\n\nfunction elementKind(el: StoreElement): LayerKind | null {\n if (el instanceof TextElement) return 'text';\n if (el instanceof ImageElement) return 'image';\n return null;\n}\n\nconst HOOK_BY_KIND: Record<LayerKind, string> = {\n text: 'useTextBinding / useFontBinding',\n image: 'useImageBinding',\n};\n\n/**\n * Accept a binding hook's `string | LayerToken` argument and return the bare\n * layer name. With a token under `<Editor.Root>`, mount-validate it against\n * the first non-empty element snapshot (see module doc). Bare strings keep\n * the settle-aware dead-binding console.warn instead.\n */\nexport function useValidatedBindingLayer(\n layerOrName: string | LayerToken,\n expectedKind: LayerKind,\n elementStore: ElementStore,\n): string {\n const isToken = isLayerToken(layerOrName);\n const name = isToken ? layerOrName.name : layerOrName;\n const internals = useContext(EditorRootInternalsContext);\n const validatedRef = useRef<string | null>(null);\n\n if (isToken && layerOrName.kind !== expectedKind) {\n throw new EditorError(\n 'E_LAYER_WRONG_KIND',\n `layer \"${name}\" is a ${layerOrName.kind} token — this hook binds ${expectedKind} ` +\n `layers only (use ${HOOK_BY_KIND[layerOrName.kind]}).`,\n { layerName: name, actualKind: layerOrName.kind, expectedKind, docSlug: 'embed-mode' },\n );\n }\n\n // Token + under Root: validate once, against the first snapshot that has\n // elements at all (the canvas chunk seeds Root's document asynchronously —\n // an empty store is \"not loaded yet\", never \"your token is wrong\").\n if (isToken && internals && validatedRef.current !== name) {\n const all = elementStore.getAll();\n if (all.length > 0) {\n const matches = elementStore.getAllByName(name);\n if (matches.length === 0) {\n const named = all\n .map((el) => ({ name: (el as { name?: string }).name, kind: elementKind(el) }))\n .filter((e): e is { name: string; kind: LayerKind } => Boolean(e.name) && e.kind !== null);\n throw new EditorError(\n 'E_LAYER_NOT_FOUND',\n `no layer \"${name}\" in this Root's document — the token was minted from a ` +\n `different design than the one passed to <Editor.Root design={…}>, or the ` +\n `layer was deleted. Bindable layers here: ${JSON.stringify(named.map((e) => e.name))}.`,\n { layerName: name, validNames: named.map((e) => e.name), docSlug: 'embed-mode' },\n );\n }\n if (!matches.some((el) => elementKind(el) === expectedKind)) {\n const actual = elementKind(matches[0]!) ?? 'unbindable';\n throw new EditorError(\n 'E_LAYER_WRONG_KIND',\n `layer \"${name}\" is ${actual === 'unbindable' ? 'not a bindable kind' : `an ${actual} layer`} — ` +\n `this hook binds ${expectedKind} layers only.`,\n { layerName: name, actualKind: actual, expectedKind, docSlug: 'embed-mode' },\n );\n }\n validatedRef.current = name;\n }\n }\n\n return name;\n}\n","/**\n * useTextBinding - Bidirectional text binding between HTML inputs and canvas text elements.\n *\n * Links an external input to one or more canvas text elements by their `name` property.\n * Multiple elements can share the same name — `setText` updates all of them.\n * Changes flow both ways: input → canvas via `setText`, and canvas edits\n * propagate back through the element store re-render.\n *\n * @example\n * ```tsx\n * function NameInput() {\n * const { text, setText, isConnected } = useTextBinding('headline');\n * return (\n * <input\n * value={text}\n * onChange={(e) => setText(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { TextElement } from '../core/TextElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.js';\n\n/** Result returned by {@link useTextBinding}. */\nexport interface TextBindingResult {\n /** Current plain text content (from first bound element). Empty string if disconnected. */\n text: string;\n /** Update text on all bound elements. No-op if disconnected. */\n setText: (text: string) => void;\n /** The first bound element, or null if no matching text element exists. */\n element: EditorElement | null;\n /** All bound text elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching text element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Bind an HTML input to canvas text elements by their `name` property.\n *\n * Multiple elements can share the same name — `setText` updates all of them.\n * Text is read from the first matching element (render order).\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @returns Text value, setter, element references, and connection status.\n */\nexport function useTextBinding(layer: string | LayerToken<'text'>): TextBindingResult {\n const { elementStore } = useElementsContext();\n useBindingRequiresCanvas('useTextBinding()');\n const name = useValidatedBindingLayer(layer, 'text', elementStore);\n const { executeElementUpdate } = useCommandContext();\n\n const textElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is TextElement => el instanceof TextElement);\n }, [elementStore, name]);\n\n const setText = useCallback(\n (newText: string) => {\n for (const el of textElements) {\n const cloned = el.clone() as TextElement;\n cloned.setText(newText);\n executeElementUpdate(el, cloned);\n }\n },\n [textElements, executeElementUpdate],\n );\n\n // Dev-only: a name that never matches produces a dead control with no-op\n // setters — warn once the element set settles so a typo isn't silent.\n useDeadBindingWarning('text', name, elementStore, textElements.length > 0);\n\n if (textElements.length === 0) {\n return { text: '', setText: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n text: textElements[0].getText(),\n setText,\n element: textElements[0],\n elements: textElements,\n isConnected: true,\n };\n}\n","/**\n * useImageBinding - Bidirectional image URL binding between external inputs and canvas image elements.\n *\n * Links an external input to one or more canvas image elements by their `name` property.\n * Multiple elements can share the same name — `setImageUrl` updates all of them.\n * Changes flow both ways: input → canvas via `setImageUrl`, and canvas edits\n * propagate back through the element store re-render.\n *\n * @example\n * ```tsx\n * function LogoUpload() {\n * const { imageUrl, setImageUrl, isConnected } = useImageBinding('logo');\n * return (\n * <input\n * type=\"url\"\n * value={imageUrl}\n * onChange={(e) => setImageUrl(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback, useRef } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { ImageElement } from '../core/ImageElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.js';\n\n/** How the image fits the element bounds. */\nexport type ImageFitMode = 'cover' | 'contain';\n\n/** Options for {@link useImageBinding}. */\nexport interface ImageBindingOptions {\n /** How the image fits the element bounds. Default: \"cover\". */\n fit?: ImageFitMode;\n}\n\n/** Result returned by {@link useImageBinding}. */\nexport interface ImageBindingResult {\n /** Current image URL (from first bound element). Empty string if disconnected. */\n imageUrl: string;\n /** Update image URL on all bound elements. No-op if disconnected. */\n setImageUrl: (url: string) => void;\n /** The first bound element, or null if no matching image element exists. */\n element: EditorElement | null;\n /** All bound image elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching image element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Calculate center-crop values so the visible area fills the original element bounds.\n */\nfunction coverCrop(\n origWidth: number,\n origHeight: number,\n imageAspectRatio: number,\n) {\n const placeholderAR = origWidth / origHeight;\n\n if (imageAspectRatio >= placeholderAR) {\n // Image is wider — match height, crop width\n const frameHeight = origHeight;\n const frameWidth = frameHeight * imageAspectRatio;\n const cropWidth = origWidth / frameWidth;\n return {\n width: frameWidth,\n height: frameHeight,\n cropX: (1 - cropWidth) / 2,\n cropY: 0,\n cropWidth,\n cropHeight: 1,\n };\n } else {\n // Image is taller — match width, crop height\n const frameWidth = origWidth;\n const frameHeight = frameWidth / imageAspectRatio;\n const cropHeight = origHeight / frameHeight;\n return {\n width: frameWidth,\n height: frameHeight,\n cropX: 0,\n cropY: (1 - cropHeight) / 2,\n cropWidth: 1,\n cropHeight,\n };\n }\n}\n\n/**\n * Bind an external input to canvas image elements by their `name` property.\n *\n * Multiple elements can share the same name — `setImageUrl` updates all of them.\n * The image URL is read from the first matching element (render order).\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @param options - Optional configuration (fit mode, etc.).\n * @returns Image URL value, setter, element references, and connection status.\n */\nexport function useImageBinding(layer: string | LayerToken<'image'>, options?: ImageBindingOptions): ImageBindingResult {\n useBindingRequiresCanvas('useImageBinding()');\n const fit = options?.fit ?? 'cover';\n const { elementStore, setElements } = useElementsContext();\n const name = useValidatedBindingLayer(layer, 'image', elementStore);\n const { executeElementUpdate } = useCommandContext();\n\n const imageElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is ImageElement => el instanceof ImageElement);\n }, [elementStore, name]);\n\n // Capture the original placeholder dimensions once (from the first time we see each element).\n // All subsequent image replacements fit within this fixed box.\n const origDimsRef = useRef<Map<string, { width: number; height: number }>>(new Map());\n for (const el of imageElements) {\n if (!origDimsRef.current.has(el.id)) {\n const td = el.transformData;\n origDimsRef.current.set(el.id, {\n width: td.width * td.cropWidth,\n height: td.height * td.cropHeight,\n });\n }\n }\n\n // Use refs for values that change on every element update to keep setImageUrl stable.\n // Without this, setImageUrl gets a new identity after every executeElementUpdate call,\n // which causes infinite loops when used in useEffect dependency arrays.\n const imageElementsRef = useRef(imageElements);\n imageElementsRef.current = imageElements;\n const executeRef = useRef(executeElementUpdate);\n executeRef.current = executeElementUpdate;\n const setElementsRef = useRef(setElements);\n setElementsRef.current = setElements;\n\n const setImageUrl = useCallback(\n (url: string) => {\n const currentElements = imageElementsRef.current;\n const exec = executeRef.current;\n\n for (const el of currentElements) {\n const orig = origDimsRef.current.get(el.id);\n if (!orig) continue;\n const { width: origW, height: origH } = orig;\n\n const cloned = el.clone() as ImageElement;\n cloned.imageLoaded = false;\n cloned.imageElement = null;\n cloned.isCropping = false;\n cloned.imageUrl = url;\n\n if (fit === 'cover') {\n cloned.preserveDimensions = true;\n\n cloned.onLoadCallback = (loadedElement) => {\n const imgAR = loadedElement.imageAspectRatio || 1;\n const crop = coverCrop(origW, origH, imgAR);\n\n loadedElement.transformData.width = crop.width;\n loadedElement.transformData.height = crop.height;\n loadedElement.transformData.cropX = crop.cropX;\n loadedElement.transformData.cropY = crop.cropY;\n loadedElement.transformData.cropWidth = crop.cropWidth;\n loadedElement.transformData.cropHeight = crop.cropHeight;\n\n // Single atomic update: command history + element store.\n // This ensures auto-export only sees the final cropped state,\n // not an intermediate unloaded state that would produce wrong mockups.\n exec(el, loadedElement);\n };\n } else {\n cloned.preserveDimensions = false;\n\n cloned.onLoadCallback = (loadedElement) => {\n const w = loadedElement.transformData.width;\n const h = loadedElement.transformData.height;\n const scale = Math.min(origW / w, origH / h, 1);\n if (scale < 1) {\n loadedElement.transformData.width = w * scale;\n loadedElement.transformData.height = h * scale;\n }\n loadedElement.transformData.cropX = 0;\n loadedElement.transformData.cropY = 0;\n loadedElement.transformData.cropWidth = 1;\n loadedElement.transformData.cropHeight = 1;\n\n exec(el, loadedElement);\n };\n }\n\n // Start loading — onLoadCallback will update the store via exec()\n // once the image is ready with final dimensions/crop.\n cloned.loadImage(url);\n }\n },\n [fit], // Stable deps only — imageElements/executeElementUpdate/setElements accessed via refs\n );\n\n // Dev-only: a name that never matches produces a dead control with no-op\n // setters — warn once the element set settles so a typo isn't silent.\n useDeadBindingWarning('image', name, elementStore, imageElements.length > 0);\n\n if (imageElements.length === 0) {\n return { imageUrl: '', setImageUrl: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n imageUrl: imageElements[0].imageUrl,\n setImageUrl,\n element: imageElements[0],\n elements: imageElements,\n isConnected: true,\n };\n}\n","/**\n * useColorBinding - Bind an external color control to every element painted a given color.\n *\n * Unlike `useTextBinding` / `useImageBinding` (which bind by element `name`),\n * a color binding matches by VALUE: every element whose text color, shape\n * fill, path stroke color, or stroke-effect color equals the bound color is\n * updated together. This is how an editable template exposes \"Accent Color\" —\n * the designer picks a color once, and the buyer's swatch repaints every\n * element that used it.\n *\n * The hook tracks the *currently applied* color: after `setColor('#00FF00')`,\n * subsequent matches (and the next `setColor`) are computed against the new\n * color, so repeated changes keep following the same set of elements.\n *\n * @example\n * ```tsx\n * function AccentSwatch({ field }: { field: { color: string; label: string } }) {\n * const { color, setColor, isConnected } = useColorBinding(field.color);\n * return (\n * <input\n * type=\"color\"\n * value={color}\n * onChange={(e) => setColor(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useState, useCallback } from 'react';\nimport { isColorToken, type ColorToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas } from './bindingGuards.js';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/** Result returned by {@link useColorBinding}. */\nexport interface ColorBindingResult {\n /** The currently applied color (normalized uppercase hex). */\n color: string;\n /** Repaint all matching elements. No-op if the value is unchanged. */\n setColor: (color: string) => void;\n /** All elements currently matching the applied color. */\n elements: readonly EditorElement[];\n /** Whether at least one element currently carries the applied color. */\n isConnected: boolean;\n}\n\nconst EMPTY: readonly EditorElement[] = [];\n\n/** Normalize any hex color to uppercase 6-digit form (#RGB → #RRGGBB). */\nfunction normalizeHex(color: string): string {\n let hex = color.trim().toUpperCase();\n if (hex.length === 4 && hex.startsWith('#')) {\n hex = '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];\n }\n return hex;\n}\n\n/** The color-carrying slots a canvas element may have. */\ninterface ColorCarrier {\n color?: unknown;\n setColor?: (c: string) => void;\n transformData?: { fillColor?: unknown; strokeColor?: unknown };\n stroke?: { enabled?: boolean; color?: unknown };\n}\n\nfunction slotMatches(value: unknown, match: string): boolean {\n return typeof value === 'string' && normalizeHex(value) === match;\n}\n\n/** Whether any color slot on the element equals `match` (normalized hex). */\nfunction elementMatchesColor(el: EditorElement, match: string): boolean {\n const c = el as unknown as ColorCarrier;\n return (\n slotMatches(c.color, match) ||\n slotMatches(c.transformData?.fillColor, match) ||\n slotMatches(c.transformData?.strokeColor, match) ||\n (c.stroke?.enabled === true && slotMatches(c.stroke.color, match))\n );\n}\n\n/**\n * Repaint every matching slot on a clone of `el`. Returns the clone if any\n * slot matched, or null if the element doesn't carry the color.\n */\nfunction applyColorToClone(\n el: EditorElement,\n match: string,\n newColor: string,\n): EditorElement | null {\n if (!elementMatchesColor(el, match)) return null;\n\n const cloned = el.clone() as EditorElement;\n const src = el as unknown as ColorCarrier;\n const dst = cloned as unknown as ColorCarrier;\n\n // Text elements: use setColor so richText spans update too.\n if (slotMatches(src.color, match)) {\n if (typeof dst.setColor === 'function') {\n dst.setColor(newColor);\n } else {\n dst.color = newColor;\n }\n }\n\n // Shape/Path elements: fill and stroke colors live in transformData.\n if (slotMatches(src.transformData?.fillColor, match)) {\n dst.transformData = { ...dst.transformData, fillColor: newColor };\n }\n if (slotMatches(src.transformData?.strokeColor, match)) {\n dst.transformData = { ...dst.transformData, strokeColor: newColor };\n }\n\n // Stroke effect (outline) color.\n if (src.stroke?.enabled === true && slotMatches(src.stroke.color, match)) {\n dst.stroke = { ...dst.stroke, color: newColor };\n }\n\n return cloned;\n}\n\n/**\n * Bind an external color control to all elements painted `originalColor`.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param originalColor - The hex color to match (the template field's `color`).\n * @returns Applied color, setter, matching elements, and connection status.\n */\nexport function useColorBinding(original: string | ColorToken): ColorBindingResult {\n // `design.color('role')` tokens carry the role's value — one source of\n // truth for the chip and the painted elements (agentic-DX finding #2).\n const originalColor = isColorToken(original) ? original.value : original;\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n // Under <Editor.Root>, a canvas-free composition makes every color binding\n // a silent dead control — fail loud instead (E_REQUIRES_CANVAS).\n useBindingRequiresCanvas('useColorBinding()');\n\n const [applied, setApplied] = useState(() => normalizeHex(originalColor));\n\n // If the hook is re-bound to a different template field, restart tracking.\n const [prevOriginal, setPrevOriginal] = useState(originalColor);\n if (originalColor !== prevOriginal) {\n setPrevOriginal(originalColor);\n setApplied(normalizeHex(originalColor));\n }\n\n // ElementStore is immutable — every mutation hands the context a new store\n // instance, so this memo recomputes whenever elements change.\n const matching = useMemo(\n () => elementStore.getAll().filter((el) => elementMatchesColor(el, applied)),\n [elementStore, applied],\n );\n\n const setColor = useCallback(\n (newColor: string) => {\n const normalizedNew = normalizeHex(newColor);\n if (normalizedNew === applied) return;\n\n for (const el of elementStore.getAll()) {\n const cloned = applyColorToClone(el, applied, newColor);\n if (cloned) executeElementUpdate(el, cloned);\n }\n setApplied(normalizedNew);\n },\n [elementStore, applied, executeElementUpdate],\n );\n\n if (matching.length === 0) {\n return { color: applied, setColor, elements: EMPTY, isConnected: false };\n }\n\n return { color: applied, setColor, elements: matching, isConnected: true };\n}\n","/**\n * useFontBinding - Bind an external font picker to canvas text elements.\n *\n * Links a control to one or more canvas TEXT elements by their `name` property\n * (same matching as `useTextBinding`). `setFontFamily` updates all of them and\n * loads the Google Font into the document, so a family the page hasn't used\n * yet still renders. This is how an editable template exposes a\n * designer-curated font choice (a `select` template field with\n * `property: 'fontFamily'`).\n *\n * Fonts must be on Google Fonts — the picker ecosystem is Google-only so\n * designs render identically across platforms (system fonts are deny-listed).\n *\n * @example\n * ```tsx\n * function FontPicker({ options }: { options: string[] }) {\n * const { fontFamily, setFontFamily, isConnected } = useFontBinding('headline');\n * if (!isConnected) return null;\n * return (\n * <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)}>\n * {options.map((f) => <option key={f} value={f}>{f}</option>)}\n * </select>\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { TextElement } from '../core/TextElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { FontAnalyzer } from '../utils/FontAnalyzer.js';\nimport { UnifiedFontService } from '../utils/UnifiedFontService.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.js';\n\n/** Result returned by {@link useFontBinding}. */\nexport interface FontBindingResult {\n /** Current font family (from first bound element). Empty string if disconnected. */\n fontFamily: string;\n /** Update the font family on all bound text elements. No-op if disconnected. */\n setFontFamily: (fontFamily: string) => void;\n /** The first bound element, or null if no matching text element exists. */\n element: EditorElement | null;\n /** All bound text elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching text element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Bind a font control to canvas text elements by their `name` property.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @returns Font family, setter, element references, and connection status.\n */\nexport function useFontBinding(layer: string | LayerToken<'text'>): FontBindingResult {\n const { elementStore } = useElementsContext();\n useBindingRequiresCanvas('useFontBinding()');\n const name = useValidatedBindingLayer(layer, 'text', elementStore);\n const { executeElementUpdate } = useCommandContext();\n\n const textElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is TextElement => el instanceof TextElement);\n }, [elementStore, name]);\n\n const setFontFamily = useCallback(\n (newFamily: string) => {\n // Make sure the family is actually available in the document — a buyer\n // picking a font the page never used would otherwise see the fallback.\n UnifiedFontService.loadGoogleFontByName(newFamily);\n\n for (const el of textElements) {\n if (el.fontFamily === newFamily) continue;\n // Old-family glyph caches are per-font and large on iOS — drop them\n // when switching, same as the editor's own font picker.\n FontAnalyzer.clearCache(el.fontFamily);\n const cloned = el.clone() as TextElement;\n cloned.fontFamily = newFamily;\n executeElementUpdate(el, cloned);\n }\n },\n [textElements, executeElementUpdate],\n );\n\n useDeadBindingWarning('font', name, elementStore, textElements.length > 0);\n\n if (textElements.length === 0) {\n return { fontFamily: '', setFontFamily: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n fontFamily: textElements[0].fontFamily,\n setFontFamily,\n element: textElements[0],\n elements: textElements,\n isConnected: true,\n };\n}\n","/**\n * useElementByName - Look up an element by its `name` property.\n *\n * General-purpose complement to {@link useElementById}. Returns the first\n * element whose `name` matches, following render order.\n *\n * @example\n * ```tsx\n * function ElementInspector({ elementName }: { elementName: string }) {\n * const element = useElementByName(elementName);\n * if (!element) return <p>Element not found</p>;\n * return <p>Position: ({element.x}, {element.y})</p>;\n * }\n * ```\n *\n * @module\n */\n\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/**\n * Returns the first element matching the given name, or null.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to look up, or null to skip the lookup.\n * @returns The matching element, or null if no element matches.\n */\nexport function useElementByName(name: string | null): EditorElement | null {\n const { elementStore } = useElementsContext();\n if (!name) return null;\n return elementStore.getByName(name) ?? null;\n}\n","/**\n * Template fields — the manifest that turns a saved design into an editable template.\n *\n * An editable template is a saved canvas state plus a list of {@link TemplateField}s\n * describing which parts a buyer may change. Text and image fields reference\n * elements by their `name` property (the same names `useTextBinding` /\n * `useImageBinding` bind to); color fields match by value (`useColorBinding`).\n *\n * The fields are stored ON the state document itself under the\n * {@link TEMPLATE_FIELDS_KEY} key (`personalization`) — the same convention\n * snowcone.app's own editor uses, so a template authored in a host app\n * round-trips through Edit / Remix / the PDP unchanged:\n *\n * ```json\n * {\n * \"elements\": [...],\n * \"artboards\": [...],\n * \"activeArtboard\": \"Front\",\n * \"personalization\": [\n * { \"type\": \"text\", \"name\": \"headline\", \"label\": \"Your name\" }\n * ]\n * }\n * ```\n *\n * Write with {@link withTemplateFields}, read back with {@link readTemplateFields}.\n *\n * @module\n */\n\nimport { z } from 'zod';\nimport type { ImageFitMode } from '../hooks/useImageBinding.js';\n\n/** A buyer-editable text slot, bound to elements by their `name` property. */\nexport interface TemplateTextField {\n type: 'text';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Your name\"). */\n label: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /**\n * Designer's length limit for the buyer's text — long names overflow fixed\n * layouts. Intent, not enforcement: your control applies it (an input's\n * `maxLength`); the canvas itself doesn't truncate.\n */\n maxLength?: number;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** A buyer-swappable image slot, bound to elements by their `name` property. */\nexport interface TemplateImageField {\n type: 'image';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Upload your logo\"). */\n label: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /** How the buyer's image fits the original element bounds. Default: \"cover\". */\n fit?: ImageFitMode;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** A buyer-editable color, matched by value across all elements that use it. */\nexport interface TemplateColorField {\n type: 'color';\n /** Original hex color to match (e.g. \"#FF0000\"). */\n color: string;\n /** Label shown to the buyer (e.g. \"Accent color\"). */\n label: string;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/**\n * A pick-one choice over designer-authored options — \"one of these 3 badges\",\n * a curated font list, preset text variants. Binds to elements by `name` and\n * swaps ONE property on them, chosen by `property`:\n *\n * - `'text'` → apply via `useTextBinding(name).setText(value)`\n * - `'imageUrl'` → apply via `useImageBinding(name).setImageUrl(value)`\n * - `'fontFamily'` → apply via `useFontBinding(name).setFontFamily(value)`\n * (values must be Google Fonts families)\n */\nexport interface TemplateSelectField {\n type: 'select';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Badge\"). */\n label: string;\n /** Which property of the bound element(s) the chosen value sets. */\n property: 'text' | 'imageUrl' | 'fontFamily';\n /** The designer-authored choices, in display order. */\n options: Array<{ label: string; value: string }>;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** One buyer-editable aspect of a template. */\nexport type TemplateField =\n | TemplateTextField\n | TemplateImageField\n | TemplateColorField\n | TemplateSelectField;\n\n/**\n * The key template fields are stored under on the state document.\n * Kept as `personalization` for compatibility with designs saved on snowcone.app.\n */\nexport const TEMPLATE_FIELDS_KEY = 'personalization';\n\nconst templateFieldSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('text'),\n name: z.string().min(1),\n label: z.string(),\n placeholder: z.string().optional(),\n maxLength: z.number().int().positive().optional(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('image'),\n name: z.string().min(1),\n label: z.string(),\n placeholder: z.string().optional(),\n fit: z.union([z.literal('cover'), z.literal('contain')]).optional(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('color'),\n color: z.string().min(1),\n label: z.string(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('select'),\n name: z.string().min(1),\n label: z.string(),\n property: z.union([z.literal('text'), z.literal('imageUrl'), z.literal('fontFamily')]),\n options: z.array(z.object({ label: z.string(), value: z.string() })).min(1),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n]);\n\n/**\n * Read the template fields off a parsed state document.\n *\n * Accepts any JSON value — a `CanvasState` from `onChange`, a `CanvasStateV1`\n * document, or a raw `JSON.parse` of a stored state file. Legacy fields with\n * no `type` are normalized to text fields; malformed entries are dropped.\n * Returns `[]` when the document carries no fields (a plain, non-template design).\n */\nexport function readTemplateFields(state: unknown): TemplateField[] {\n if (!state || typeof state !== 'object') return [];\n const raw = (state as Record<string, unknown>)[TEMPLATE_FIELDS_KEY];\n if (!Array.isArray(raw)) return [];\n\n const fields: TemplateField[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== 'object') continue;\n const candidate = 'type' in entry ? entry : { ...entry, type: 'text' };\n const parsed = templateFieldSchema.safeParse(candidate);\n if (parsed.success) fields.push(parsed.data as TemplateField);\n }\n return fields;\n}\n\n/**\n * Attach template fields to a state document before persisting it.\n *\n * ```ts\n * onChange={(state) => setDraft(state)}\n * // …on save:\n * save(JSON.stringify(withTemplateFields(draft, fields)));\n * ```\n */\nexport function withTemplateFields<T extends object>(\n state: T,\n fields: TemplateField[],\n): T & { [TEMPLATE_FIELDS_KEY]: TemplateField[] } {\n return { ...state, [TEMPLATE_FIELDS_KEY]: fields };\n}\n"],"names":["textOf","el","nameOf","DesignStateStore","seed","listener","seedTexts","name","text","next","e","layerKindOfConfig","n","found","elements","EditorError","t","l","choiceLabelsOf","attr","c","label","seedSelectionOf","product","combinations","combination","selection","key","value","CommerceStateStore","toOptionAttributes","toCombinations","choice","labels","quantity","getMissingSelections","validateProductSelection","best","findBestCombination","stringAttrs","computeDisabledChoices","useSelectedElement","selectedElement","useEditor","DEAD_BINDING_GRACE_MS","HOOK_NAME","SETTER_NAME","TARGET_KIND","warned","kindOf","TextElement","ImageElement","deadBindingWarning","kind","store","tag","dead","target","sameName","kinds","other","hint","named","available","useDeadBindingWarning","isConnected","useEffect","process","timer","useBindingRequiresCanvas","hookName","internals","useContext","EditorRootInternalsContext","instanceId","useId","useLayoutEffect","elementKind","HOOK_BY_KIND","useValidatedBindingLayer","layerOrName","expectedKind","elementStore","isToken","isLayerToken","validatedRef","useRef","all","matches","actual","NOOP","EMPTY","useTextBinding","layer","useElementsContext","executeElementUpdate","useCommandContext","textElements","useMemo","setText","useCallback","newText","cloned","coverCrop","origWidth","origHeight","imageAspectRatio","placeholderAR","frameHeight","frameWidth","cropWidth","cropHeight","useImageBinding","options","fit","setElements","imageElements","origDimsRef","td","imageElementsRef","executeRef","setElementsRef","setImageUrl","url","currentElements","exec","orig","origW","origH","loadedElement","imgAR","crop","w","h","scale","normalizeHex","color","hex","slotMatches","match","elementMatchesColor","_a","_b","_c","applyColorToClone","newColor","src","dst","useColorBinding","original","originalColor","isColorToken","applied","setApplied","useState","prevOriginal","setPrevOriginal","matching","setColor","normalizedNew","useFontBinding","setFontFamily","newFamily","UnifiedFontService","FontAnalyzer","useElementByName","TEMPLATE_FIELDS_KEY","templateFieldSchema","z.discriminatedUnion","z.object","z.literal","z.string","z.number","z.union","z.array","readTemplateFields","state","raw","fields","entry","candidate","parsed","withTemplateFields"],"mappings":";;;;;;AA0CA,SAASA,EAAOC,GAA0C;AACxD,SAAQA,EAAyB;AACnC;AAEA,SAASC,EAAOD,GAA0C;AACxD,SAAQA,EAAyB;AACnC;AA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U,OAAOA,EAAE,EAAO,CAAG,CAAC,EAAE,IAAI,CAAC;AAAA,IAC1E,UAAUA,EAAE,EAAS,IAAI,CAAC,EAAE,SAAA;AAAA,IAC5B,OAAOA,EAAE,EAAS,SAAA;AAAA,EAAS,CAC5B;AACH,CAAC;AAUM,SAASI,GAAmBC,GAAiC;AAClE,MAAI,CAACA,KAAS,OAAOA,KAAU,iBAAiB,CAAA;AAChD,QAAMC,IAAOD,EAAkCV,EAAmB;AAClE,MAAI,CAAC,MAAM,QAAQW,CAAG,UAAU,CAAA;AAEhC,QAAMC,IAA0B,CAAA;AAChC,aAAWC,KAASF,GAAK;AACvB,QAAI,CAACE,KAAS,OAAOA,KAAU,SAAU;AACzC,UAAMC,IAAY,UAAUD,IAAQA,IAAQ,EAAE,GAAGA,GAAO,MAAM,OAAA,GACxDE,IAASd,GAAoB,UAAUa,CAAS;AACtD,IAAIC,EAAO,WAASH,EAAO,KAAKG,EAAO,IAAqB;AAAA,EAC9D;AACA,SAAOH;AACT;AAWO,SAASI,GACdN,GACAE,GACgD;AAChD,SAAO,EAAE,GAAGF,GAAO,CAACV,EAAmB,GAAGY,EAAA;AAC5C;"}
package/dist/testing.mjs CHANGED
@@ -1,12 +1,11 @@
1
- import { E as A } from "./editorErrors-WzaNxU1Y.js";
2
- import { i as ie, j as oe, k as ae } from "./editorErrors-WzaNxU1Y.js";
3
- import { fetchMockupImage as S, isSnowconeSdkError as b, RenderSession as _, mintRealtimeGrant as R } from "@snowcone-app/sdk";
4
- import { s as I, d as y } from "./design-builder-JYLO_Hyi.js";
5
- import { K as D, A as k, g as T, I as F, E as m } from "./FontAnalyzer-DKG5JK0x.js";
1
+ import { E as A, s as S, d as y } from "./design-builder-CBG2hKc8.js";
2
+ import { n as re, o as ie, q as oe } from "./design-builder-CBG2hKc8.js";
3
+ import { fetchMockupImage as b, isSnowconeSdkError as _, RenderSession as R, mintRealtimeGrant as I } from "@snowcone-app/sdk";
4
+ import { O as D, A as T, g as k, I as F, E as m } from "./FontAnalyzer-BYhwxDhe.js";
6
5
  import { jsx as u } from "react/jsx-runtime";
7
6
  import { useState as x } from "react";
8
7
  import { T as p } from "./ThemeContext-Rjz25x9X.js";
9
- const G = ({
8
+ const K = ({
10
9
  children: t,
11
10
  initialElements: n = [],
12
11
  initialArtboards: e,
@@ -38,15 +37,15 @@ const G = ({
38
37
  children: t
39
38
  }
40
39
  ) });
41
- }, J = ({
40
+ }, G = ({
42
41
  children: t,
43
42
  initialElements: n = [],
44
43
  initialSelection: e = null,
45
44
  initialMultiSelection: r = [],
46
45
  initialArtboardConfig: i = {}
47
46
  }) => /* @__PURE__ */ u(p, { children: /* @__PURE__ */ u(A, { initialArtboardConfig: i, children: t }) });
48
- function j(t = "custom", n = {}) {
49
- const e = T(t);
47
+ function J(t = "custom", n = {}) {
48
+ const e = k(t);
50
49
  if (!e || !e.Component)
51
50
  throw new Error(`Transform type "${t}" not found in registry`);
52
51
  return new e.Component({
@@ -72,8 +71,8 @@ function W(t = {}) {
72
71
  ...t
73
72
  });
74
73
  }
75
- function z(t = {}) {
76
- return new k({
74
+ function j(t = {}) {
75
+ return new T({
77
76
  name: "Test Artboard",
78
77
  width: 1200,
79
78
  height: 1200,
@@ -91,11 +90,11 @@ async function U(t, n = 5e3, e = 100) {
91
90
  await new Promise((i) => setTimeout(i, e));
92
91
  }
93
92
  }
94
- async function Q(t, n = 5e3) {
93
+ async function q(t, n = 5e3) {
95
94
  let e = null;
96
95
  return await U(() => !1, n), e;
97
96
  }
98
- function V(t, n = {}) {
97
+ function z(t, n = {}) {
99
98
  const e = new KeyboardEvent("keydown", {
100
99
  key: t,
101
100
  ctrlKey: n.ctrl,
@@ -107,11 +106,11 @@ function V(t, n = {}) {
107
106
  });
108
107
  document.dispatchEvent(e);
109
108
  }
110
- function Y(t = 800, n = 600) {
109
+ function Q(t = 800, n = 600) {
111
110
  const e = document.createElement("canvas");
112
111
  return e.width = t, e.height = n, e;
113
112
  }
114
- function q(t, n) {
113
+ function V(t, n) {
115
114
  Object.entries(n).forEach(([e, r]) => {
116
115
  if (t[e] !== r)
117
116
  throw new Error(
@@ -119,7 +118,7 @@ function q(t, n) {
119
118
  );
120
119
  });
121
120
  }
122
- function H(t) {
121
+ function Y(t) {
123
122
  const n = t.getBoundingBox();
124
123
  return {
125
124
  x: n.x,
@@ -165,7 +164,7 @@ async function E(t, n, e, r, i) {
165
164
  d && (clearTimeout(c), l(d));
166
165
  }), o.onError((s) => {
167
166
  clearTimeout(c), a(new m("E_RENDER_FAILED", `the ${i} render failed: ${s}`, { phase: i, error: s }));
168
- }), o.renderState(n, I(e)).catch((s) => {
167
+ }), o.renderState(n, S(e)).catch((s) => {
169
168
  clearTimeout(c);
170
169
  const d = s instanceof Error ? s.message : String(s);
171
170
  a(new m("E_RENDER_FAILED", `the ${i} render failed to dispatch: ${d}`, { phase: i, error: d }));
@@ -177,12 +176,12 @@ async function E(t, n, e, r, i) {
177
176
  }
178
177
  async function w(t, n, e) {
179
178
  try {
180
- const r = await S(t, {
179
+ const r = await b(t, {
181
180
  ...e.fetchImpl ? { fetchImpl: e.fetchImpl } : {}
182
181
  });
183
182
  return { bytes: r.bytes, kind: r.kind };
184
183
  } catch (r) {
185
- throw b(r) ? r.code === "ASSET_FORBIDDEN" ? new m(
184
+ throw _(r) ? r.code === "ASSET_FORBIDDEN" ? new m(
186
185
  "E_ASSET_FORBIDDEN",
187
186
  `the shop's asset-origin allowlist denied an asset in this design (${n} render). Allow the asset's origin on the shop (or host it on the shop's storage origin).`,
188
187
  { phase: n, url: t, failedAssets: r.data.failedAssets, docSlug: "embed-mode" }
@@ -193,13 +192,13 @@ async function w(t, n, e) {
193
192
  }) : r;
194
193
  }
195
194
  }
196
- async function X(t, n, e) {
197
- const r = e.timeoutMs ?? 3e4, i = t.toJSON(), o = i.activeArtboard, l = (e.mutate ?? N)(i), a = e.grant, c = typeof a == "function" ? a : a ? () => Promise.resolve(a) : () => R({
195
+ async function H(t, n, e) {
196
+ const r = e.timeoutMs ?? 3e4, i = t.toJSON(), o = i.activeArtboard, l = (e.mutate ?? N)(i), a = e.grant, c = typeof a == "function" ? a : a ? () => Promise.resolve(a) : () => I({
198
197
  shop: e.shop,
199
198
  ...e.apiKey ? { apiKey: e.apiKey } : {},
200
199
  ...e.grantBase ? { base: e.grantBase } : {},
201
200
  ...e.fetchImpl ? { fetch: e.fetchImpl } : {}
202
- }), s = () => new _({
201
+ }), s = () => new R({
203
202
  shop: e.shop,
204
203
  product: n,
205
204
  ...e.wsUrl ? { wsUrl: e.wsUrl } : {},
@@ -222,35 +221,35 @@ async function X(t, n, e) {
222
221
  };
223
222
  }
224
223
  const v = "https://assets.test-403.invalid/denied.png";
225
- function Z() {
224
+ function X() {
226
225
  return y({ name: "Front", width: 1e3, height: 1e3 }).background(v, { aspectRatio: 1, name: "art" }).text("ALLOWLIST DENIAL FIXTURE", { anchor: "top", name: "headline" });
227
226
  }
228
- function ee() {
227
+ function Z() {
229
228
  return y({ name: "Front", width: 1e3, height: 1e3 }).text("YOUR NAME", { anchor: "center", name: "name" });
230
229
  }
231
- function te(t = "failing-grant fixture: grant endpoint unavailable") {
230
+ function ee(t = "failing-grant fixture: grant endpoint unavailable") {
232
231
  return () => Promise.reject(new Error(t));
233
232
  }
234
233
  export {
235
- G as MockEditorProvider,
236
- J as MockEditorProviderWithState,
234
+ K as MockEditorProvider,
235
+ G as MockEditorProviderWithState,
237
236
  v as TEST_403_ASSET_URL,
238
- q as assertElementProperties,
239
- X as assertRenders,
240
- z as createMockArtboard,
241
- Y as createMockCanvas,
242
- j as createMockElement,
237
+ V as assertElementProperties,
238
+ H as assertRenders,
239
+ j as createMockArtboard,
240
+ Q as createMockCanvas,
241
+ J as createMockElement,
243
242
  W as createMockImageElement,
244
- ie as expectNoEditorErrors,
245
- te as failingGrant,
246
- oe as getContainedEditorErrors,
247
- H as getElementBounds,
243
+ re as expectNoEditorErrors,
244
+ ee as failingGrant,
245
+ ie as getContainedEditorErrors,
246
+ Y as getElementBounds,
248
247
  N as mutateNamedTextLayers,
249
- ae as resetContainedEditorErrors,
250
- V as simulateKeyPress,
251
- Z as test403Design,
252
- ee as testIncompleteDesign,
248
+ oe as resetContainedEditorErrors,
249
+ z as simulateKeyPress,
250
+ X as test403Design,
251
+ Z as testIncompleteDesign,
253
252
  U as waitFor,
254
- Q as waitForExport
253
+ q as waitForExport
255
254
  };
256
255
  //# sourceMappingURL=testing.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"testing.mjs","sources":["../src/testing/MockEditorProvider.tsx","../src/testing/utils.ts","../src/testing/assertRenders.ts","../src/testing/failureFixtures.ts"],"sourcesContent":["/**\n * MockEditorProvider - Lightweight mock for testing custom components\n * Compatible with Vitest (does not require Jest)\n *\n * @example\n * ```tsx\n * import { render } from '@testing-library/react';\n * import { MockEditorProvider } from '@snowcone-app/canvas/embed';\n *\n * test('my component renders', () => {\n * render(\n * <MockEditorProvider>\n * <MyCustomComponent />\n * </MockEditorProvider>\n * );\n * });\n * ```\n */\n\nimport React, { useState, ReactNode } from 'react';\nimport { EditorProvider } from '../contexts/EditorContext.js';\nimport { ThemeProvider } from '../contexts/ThemeContext.js';\nimport { ArtboardManager } from '../core/ArtboardManager.js';\nimport { ArtboardElement } from '../core/ArtboardElement.js';\nimport type { TextElement } from '../core/TextElement.js';\nimport type { ImageElement } from '../core/ImageElement.js';\nimport type { GroupElement } from '../core/GroupElement.js';\nimport type { ShapeElement } from '../core/ShapeElement.js';\n\nexport type MockEditorElement = TextElement | ImageElement | GroupElement | ShapeElement;\n\nexport interface MockEditorProviderProps {\n children: ReactNode;\n\n /**\n * Initial elements to populate the editor\n */\n initialElements?: MockEditorElement[];\n\n /**\n * Initial artboards (default: one artboard)\n */\n initialArtboards?: ArtboardElement[];\n\n /**\n * Initial selection\n */\n initialSelection?: string | null;\n\n /**\n * Initial multi-selection\n */\n initialMultiSelection?: string[];\n\n /**\n * Initial artboard configuration\n */\n initialArtboardConfig?: {\n name?: string;\n width?: number;\n height?: number;\n backgroundColor?: string;\n };\n}\n\n/**\n * MockEditorProvider - Wraps EditorProvider with test-friendly defaults\n *\n * This is a lightweight wrapper that provides the same EditorContext\n * as the real app, making it perfect for testing custom components.\n */\nexport const MockEditorProvider: React.FC<MockEditorProviderProps> = ({\n children,\n initialElements: _initialElements = [],\n initialArtboards,\n initialSelection: _initialSelection = null,\n initialMultiSelection: _initialMultiSelection = [],\n initialArtboardConfig = {},\n}) => {\n // Create artboard manager if artboards provided\n const [_artboardManager] = useState(() => {\n const manager = new ArtboardManager();\n\n if (initialArtboards && initialArtboards.length > 0) {\n // Use provided artboards\n initialArtboards.forEach(artboard => {\n manager.createArtboard({\n name: artboard.name,\n width: artboard.width,\n height: artboard.height,\n backgroundColor: artboard.backgroundColor,\n });\n });\n } else {\n // Create default artboard\n manager.createArtboard({\n name: 'Test Artboard',\n width: 1200,\n height: 1200,\n backgroundColor: '#FFFFFF',\n ...initialArtboardConfig,\n });\n }\n\n return manager;\n });\n\n // Simple wrapper that passes children through to real EditorProvider\n // The EditorProvider will handle all the state management\n // ThemeProvider is required because CanvasEditor uses useTheme()\n return (\n <ThemeProvider>\n <EditorProvider\n initialArtboardConfig={initialArtboardConfig}\n >\n {children}\n </EditorProvider>\n </ThemeProvider>\n );\n};\n\n/**\n * MockEditorProviderWithState - For tests that need to control state directly\n *\n * Use this when you need fine-grained control over the editor state.\n * Most tests should use the simpler MockEditorProvider above.\n */\nexport const MockEditorProviderWithState: React.FC<MockEditorProviderProps> = ({\n children,\n initialElements: _initialElements = [],\n initialSelection: _initialSelection = null,\n initialMultiSelection: _initialMultiSelection = [],\n initialArtboardConfig = {},\n}) => {\n return (\n <ThemeProvider>\n <EditorProvider initialArtboardConfig={initialArtboardConfig}>\n {children}\n </EditorProvider>\n </ThemeProvider>\n );\n};\n","/**\n * Testing Utilities - Helpers for creating mock elements and artboards\n * Compatible with Vitest\n */\n\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\nimport { ArtboardElement } from '../core/ArtboardElement.js';\nimport { getTransformById } from '../transforms/registry.js';\nimport type { TransformType, ImageElementConfig } from '../types/index.js';\n\n/**\n * Create a mock text element with sensible defaults\n *\n * @example\n * ```tsx\n * const element = createMockElement('custom', {\n * text: 'Hello World',\n * fontSize: 48,\n * fontColor: '#FF0000'\n * });\n * ```\n */\nexport function createMockElement(\n transformType: TransformType = 'custom',\n overrides: Partial<TextElement> = {}\n): TextElement {\n // Get the correct concrete class from registry\n const transformDef = getTransformById(transformType);\n if (!transformDef || !transformDef.Component) {\n throw new Error(`Transform type \"${transformType}\" not found in registry`);\n }\n\n // Create element using the concrete class\n const element = new transformDef.Component({\n transformType,\n text: 'Test Text',\n fontSize: 32,\n color: '#000000',\n fontFamily: 'Arial',\n x: 100,\n y: 100,\n rotation: 0,\n ...overrides,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- test utility: overrides merge Partial<TextElement> properties with config, which are structurally compatible but not type-assignable\n } as any);\n\n return element as TextElement;\n}\n\n/**\n * Create a mock image element\n *\n * @example\n * ```tsx\n * const image = createMockImageElement({\n * imageUrl: 'data:image/png;base64,...',\n * width: 200,\n * height: 200\n * });\n * ```\n */\nexport function createMockImageElement(\n overrides: Partial<ImageElementConfig> = {}\n): ImageElement {\n const element = new ImageElement({\n imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',\n imageAspectRatio: 1,\n x: 100,\n y: 100,\n rotation: 0,\n ...overrides,\n });\n\n return element;\n}\n\n/**\n * Create a mock artboard\n *\n * @example\n * ```tsx\n * const artboard = createMockArtboard({\n * name: 'Front',\n * width: 1200,\n * height: 1200,\n * backgroundColor: '#FFFFFF'\n * });\n * ```\n */\nexport function createMockArtboard(\n overrides: Partial<{\n name: string;\n width: number;\n height: number;\n x: number;\n y: number;\n backgroundColor: string;\n }> = {}\n): ArtboardElement {\n const artboard = new ArtboardElement({\n name: 'Test Artboard',\n width: 1200,\n height: 1200,\n x: 0,\n y: 0,\n backgroundColor: '#FFFFFF',\n ...overrides,\n });\n\n return artboard;\n}\n\n/**\n * Wait for a condition to become true\n * Useful for async testing\n *\n * @example\n * ```tsx\n * await waitFor(() => screen.getByText('Loaded'), 5000);\n * ```\n */\nexport async function waitFor(\n condition: () => boolean,\n timeout = 5000,\n interval = 100\n): Promise<void> {\n const startTime = Date.now();\n\n while (!condition()) {\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for condition after ${timeout}ms`);\n }\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n}\n\n/**\n * Wait for an export to complete\n * Polls until dataUrl is available\n *\n * @example\n * ```tsx\n * const dataUrl = await waitForExport('artboard-1', 5000);\n * expect(dataUrl).toContain('data:image/png');\n * ```\n */\nexport async function waitForExport(\n _artboardId: string,\n timeout = 5000\n): Promise<string | null> {\n let dataUrl: string | null = null;\n\n await waitFor(() => {\n // Check if export completed (this would need to be implemented based on your export state)\n // For now, just return false as a placeholder\n return false;\n }, timeout);\n\n return dataUrl;\n}\n\n/**\n * Simulate a keyboard event\n * Useful for testing keyboard shortcuts\n *\n * @example\n * ```tsx\n * simulateKeyPress('c', { meta: true }); // Cmd+C\n * ```\n */\nexport function simulateKeyPress(\n key: string,\n options: {\n ctrl?: boolean;\n shift?: boolean;\n alt?: boolean;\n meta?: boolean;\n } = {}\n): void {\n const event = new KeyboardEvent('keydown', {\n key,\n ctrlKey: options.ctrl,\n shiftKey: options.shift,\n altKey: options.alt,\n metaKey: options.meta,\n bubbles: true,\n cancelable: true,\n });\n\n document.dispatchEvent(event);\n}\n\n/**\n * Create a mock canvas element for testing\n * Returns an HTMLCanvasElement with mocked context\n *\n * @example\n * ```tsx\n * const canvas = createMockCanvas(800, 600);\n * const ctx = canvas.getContext('2d');\n * ```\n */\nexport function createMockCanvas(\n width = 800,\n height = 600\n): HTMLCanvasElement {\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n\n return canvas;\n}\n\n/**\n * Assert that an element has certain properties\n * Useful for programmatic assertions\n *\n * @example\n * ```tsx\n * assertElementProperties(element, {\n * text: 'Hello',\n * fontSize: 48,\n * fontColor: '#FF0000'\n * });\n * ```\n */\nexport function assertElementProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Test utility: accepts any element type and checks arbitrary properties\n element: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Test utility: expected values can be any type\n expected: Record<string, any>\n): void {\n Object.entries(expected).forEach(([key, value]) => {\n if (element[key] !== value) {\n throw new Error(\n `Expected element.${key} to be ${value}, got ${element[key]}`\n );\n }\n });\n}\n\n/**\n * Get element bounding box for testing\n * Returns computed bounds from the element\n *\n * @example\n * ```tsx\n * const bounds = getElementBounds(element);\n * expect(bounds.width).toBeGreaterThan(0);\n * ```\n */\nexport function getElementBounds(element: TextElement | ImageElement): {\n x: number;\n y: number;\n width: number;\n height: number;\n} {\n const bbox = element.getBoundingBox();\n\n return {\n x: bbox.x,\n y: bbox.y,\n width: bbox.width,\n height: bbox.height,\n };\n}\n","/**\n * `assertRenders(design, product, opts)` — the TWO-RENDER live contract check\n * (agent-DX decision F4, ADR-0085 plan).\n *\n * WHY TWO RENDERS: \"the URL returns an image\" can't catch a DEAD BINDING — a\n * wrong layer name still renders the seed beautifully. So this renders the\n * design twice: once as seeded, once with the personalization bindings\n * mutated, and asserts the encoded image BYTES differ (mockup delivery is\n * deterministic per state, so byte-identical means pixel-identical means the\n * mutation never reached the render).\n *\n * What it proves, in order:\n * 1. the seed design renders: HTTP 200 + real raster bytes (non-blank);\n * 2. the mutated design renders the same way;\n * 3. the two renders DIFFER — the binding is alive.\n *\n * Failures are the structured error contract (E3), never prose-only:\n * - `E_ASSET_FORBIDDEN` — the shop's asset-origin allowlist denied a design\n * asset (translated from the server's 403; `data.failedAssets` names it);\n * - `E_RENDER_FAILED` — render error / timeout / non-image response;\n * - `E_BINDING_INERT` — both renders byte-identical (dead binding);\n * - `E_NO_MUTABLE_BINDING` — nothing to mutate and no `mutate` given.\n * - The SDK's `SHOP_NOT_PROPAGATED` passes through: a freshly minted shop\n * that never becomes visible is an environment fault, named as such.\n *\n * This talks to the REAL realtime render path (network). Use it in nightly /\n * acceptance jobs and agent verify loops — per-PR unit tests should mock the\n * SDK transport instead (plan: per-PR replay, nightly network-real).\n */\n\nimport {\n RenderSession,\n fetchMockupImage,\n mintRealtimeGrant,\n type MockupResult,\n type RealtimeGrant,\n type RenderProduct,\n} from '@snowcone-app/sdk';\nimport { isSnowconeSdkError } from '@snowcone-app/sdk';\nimport { serializeStateForServer } from '../rendering/serialize-for-server.js';\nimport { EditorError } from '../errors/editorError.js';\nimport type { DesignState } from '../components/editor/designStateStore.js';\n\n/** Anything `design()` produces (or a compatible shape). */\nexport interface RenderableDesign {\n toJSON(): DesignState;\n}\n\nexport interface AssertRendersOptions {\n /** Publishable shop id (= shop.id). */\n shop: string;\n /** Secret API key (sk_) for the grant; omit for the keyless publishable\n * path (sandbox/trial shops — the F1 bootstrap default). */\n apiKey?: string;\n /** Pre-fetched grant or grant factory — overrides the mint entirely. */\n grant?: RealtimeGrant | (() => Promise<RealtimeGrant>);\n /** Backend base for the keyless/sk grant mint (defaults to prod). */\n grantBase?: string;\n /** Override the realtime WS endpoint. */\n wsUrl?: string;\n /**\n * Produce the mutated state for the second render. Default: rewrite the\n * text of EVERY named text layer to a sentinel (`ASSERT_RENDERS_<name>`).\n * Throws `E_NO_MUTABLE_BINDING` if the design has no named text layer and\n * no override is given.\n */\n mutate?: (seed: DesignState) => DesignState;\n /** Per-render timeout (ms). Default 30_000. */\n timeoutMs?: number;\n /** Override fetch for the image downloads (tests). */\n fetchImpl?: typeof fetch;\n}\n\nexport interface AssertRendersResult {\n /** The seed render's mockup URL + encoded size. */\n seed: { url: string; bytes: number; kind: string };\n /** The mutated render's mockup URL + encoded size. */\n mutated: { url: string; bytes: number; kind: string };\n}\n\n/** Default mutation: every NAMED text layer gets a sentinel value. */\nexport function mutateNamedTextLayers(seed: DesignState): DesignState {\n let mutatedAny = false;\n const elements = seed.elements.map((el) => {\n const name = (el as { name?: string }).name;\n const text = (el as { text?: string }).text;\n if (!name || typeof text !== 'string') return el;\n mutatedAny = true;\n return { ...el, text: `ASSERT_RENDERS_${name.toUpperCase()}` } as typeof el;\n });\n if (!mutatedAny) {\n throw new EditorError(\n 'E_NO_MUTABLE_BINDING',\n 'this design has no NAMED text layer to mutate for the two-render check. Name one ' +\n '(design().text(\"…\", { name: \"headline\" })) or pass opts.mutate to define the mutation.',\n { docSlug: 'embed-mode' },\n );\n }\n return { ...seed, elements };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Render one state on a FRESH session and resolve the first mockup result.\n * One session per render on purpose: a session keeps emitting trailing mockup\n * results (multi-mockup products emit per scene), so reusing it for the\n * second render could resolve the mutated phase with a stale seed emission —\n * and with content-addressed delivery a dead binding makes the two\n * indistinguishable by URL. A fresh session has no history to confuse.\n */\nasync function renderOnce(\n makeSession: () => RenderSession,\n placement: string,\n state: DesignState,\n timeoutMs: number,\n label: 'seed' | 'mutated',\n): Promise<MockupResult> {\n const session = makeSession();\n try {\n return await new Promise<MockupResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new EditorError('E_RENDER_FAILED', `the ${label} render produced no mockup within ${timeoutMs}ms.`, {\n phase: label,\n timeoutMs,\n }),\n );\n }, timeoutMs);\n session.onMockups((results) => {\n const withImage = results.find((r) => r.imageUrl);\n if (!withImage) return;\n clearTimeout(timer);\n resolve(withImage);\n });\n session.onError((message) => {\n clearTimeout(timer);\n reject(new EditorError('E_RENDER_FAILED', `the ${label} render failed: ${message}`, { phase: label, error: message }));\n });\n void session.renderState(placement, serializeStateForServer(state)).catch((err) => {\n clearTimeout(timer);\n const message = err instanceof Error ? err.message : String(err);\n reject(new EditorError('E_RENDER_FAILED', `the ${label} render failed to dispatch: ${message}`, { phase: label, error: message }));\n });\n });\n } finally {\n session.close();\n }\n}\n\n/** Fetch + validate one rendered image, translating SDK failures (asset-403 →\n * `E_ASSET_FORBIDDEN`) into the editor error contract. */\nasync function fetchRender(url: string, label: 'seed' | 'mutated', opts: AssertRendersOptions): Promise<{ bytes: Uint8Array; kind: string }> {\n try {\n const img = await fetchMockupImage(url, {\n ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n });\n return { bytes: img.bytes, kind: img.kind };\n } catch (err) {\n if (isSnowconeSdkError(err)) {\n if (err.code === 'ASSET_FORBIDDEN') {\n throw new EditorError(\n 'E_ASSET_FORBIDDEN',\n `the shop's asset-origin allowlist denied an asset in this design (${label} render). ` +\n `Allow the asset's origin on the shop (or host it on the shop's storage origin).`,\n { phase: label, url, failedAssets: err.data.failedAssets, docSlug: 'embed-mode' },\n );\n }\n if (err.code === 'SHOP_NOT_PROPAGATED') throw err; // already structured + named\n throw new EditorError('E_RENDER_FAILED', `the ${label} render's image fetch failed: ${err.message}`, {\n phase: label,\n url,\n ...err.data,\n });\n }\n throw err;\n }\n}\n\n/**\n * Prove a design + product render AND that the design's bindings are alive\n * (two-render contract). See the module doc for the failure catalog.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport async function assertRenders(\n design: RenderableDesign,\n product: RenderProduct,\n opts: AssertRendersOptions,\n): Promise<AssertRendersResult> {\n const timeoutMs = opts.timeoutMs ?? 30_000;\n const seed = design.toJSON();\n const placement = seed.activeArtboard;\n const mutated = (opts.mutate ?? mutateNamedTextLayers)(seed);\n\n const grant = opts.grant;\n const getToken =\n typeof grant === 'function'\n ? grant\n : grant\n ? () => Promise.resolve(grant)\n : () =>\n mintRealtimeGrant({\n shop: opts.shop,\n ...(opts.apiKey ? { apiKey: opts.apiKey } : {}),\n ...(opts.grantBase ? { base: opts.grantBase } : {}),\n ...(opts.fetchImpl ? { fetch: opts.fetchImpl } : {}),\n });\n\n const makeSession = () =>\n new RenderSession({\n shop: opts.shop,\n product,\n ...(opts.wsUrl ? { wsUrl: opts.wsUrl } : {}),\n getToken,\n });\n\n const seedResult = await renderOnce(makeSession, placement, seed, timeoutMs, 'seed');\n const seedImage = await fetchRender(seedResult.imageUrl!, 'seed', opts);\n\n const mutatedResult = await renderOnce(makeSession, placement, mutated, timeoutMs, 'mutated');\n const mutatedImage = await fetchRender(mutatedResult.imageUrl!, 'mutated', opts);\n\n if (bytesEqual(seedImage.bytes, mutatedImage.bytes)) {\n throw new EditorError(\n 'E_BINDING_INERT',\n 'the mutated render is byte-identical to the seed render — the mutation never reached ' +\n 'the server, so the binding under test is DEAD. Usual causes: the mutated layer name ' +\n \"doesn't exist in the design (check design.layer() names), or opts.mutate returned the \" +\n 'seed unchanged.',\n {\n seedUrl: seedResult.imageUrl,\n mutatedUrl: mutatedResult.imageUrl,\n bytes: seedImage.bytes.byteLength,\n docSlug: 'embed-mode',\n },\n );\n }\n\n return {\n seed: { url: seedResult.imageUrl!, bytes: seedImage.bytes.byteLength, kind: seedImage.kind },\n mutated: { url: mutatedResult.imageUrl!, bytes: mutatedImage.bytes.byteLength, kind: mutatedImage.kind },\n };\n}\n","/**\n * Deterministic failure-mode fixtures (ADR-0085 plan, P2 — the magic-test-card\n * equivalent): trigger each commerce/render failure ON DEMAND so integrators\n * build their error UI against real failures instead of waiting for prod to\n * produce one.\n *\n * These are the CLIENT-ACHIEVABLE fixtures — each works against any shop\n * (including a fresh sandbox shop) with no server cooperation:\n *\n * - {@link test403Design} — asset-origin allowlist denial. References an\n * asset on an origin no shop allowlists, so the server's asset fetch is\n * denied deterministically. Surfaces as a render error (live path) or\n * `E_ASSET_FORBIDDEN` from `assertRenders`.\n * - {@link testIncompleteDesign} — Buy completeness failure. A design whose\n * only personalization layer still carries its seed value, so\n * `<Editor.Buy>` gates with `layer-seed:<name>` (and `layer:<name>` once\n * cleared). Pair with `<Editor.TextField layer={d.layer('name')} />`.\n * - {@link failingGrant} — grant failure. A grant factory that always\n * rejects; pass as `<Editor.Root grant={failingGrant()}>` to exercise the\n * \"grant fetch fails\" surface (`onRenderError` + the Preview's\n * `data-sc-part=\"preview-error\"` state).\n *\n * Server-triggered fixtures (a `test-slow` product for the timeout path, a\n * forced render-error token) need render-edge cooperation and are tracked\n * separately — they are NOT silently stubbed here.\n */\n\nimport { design } from '../design/design-builder.js';\nimport type { RealtimeGrant } from '@snowcone-app/sdk';\n\n/**\n * An origin that is deliberately on NO shop's asset-origin allowlist. The\n * `.invalid` TLD is reserved (RFC 2606) — it can never resolve, and the\n * allowlist check denies it before any fetch is attempted, so the failure is\n * deterministic and free.\n */\nexport const TEST_403_ASSET_URL = 'https://assets.test-403.invalid/denied.png';\n\n/**\n * A design whose background asset the shop's allowlist is guaranteed to deny —\n * the deterministic allowlist-denial (403) trigger.\n */\nexport function test403Design() {\n return design({ name: 'Front', width: 1000, height: 1000 })\n .background(TEST_403_ASSET_URL, { aspectRatio: 1, name: 'art' })\n .text('ALLOWLIST DENIAL FIXTURE', { anchor: 'top', name: 'headline' });\n}\n\n/**\n * A design that gates `<Editor.Buy>` out of the box: its one personalization\n * layer (`'name'`, seed `'YOUR NAME'`) is required and still equals its seed,\n * so Buy renders `data-sc-buy-state=\"incomplete\"` with\n * `data-sc-buy-missing=\"layer-seed:name\"` until a real value is typed.\n */\nexport function testIncompleteDesign() {\n return design({ name: 'Front', width: 1000, height: 1000 })\n .text('YOUR NAME', { anchor: 'center', name: 'name' });\n}\n\n/**\n * A grant factory that always rejects — the deterministic \"grant fetch\n * failed\" trigger. The rejection reason is stable for assertions.\n */\nexport function failingGrant(reason = 'failing-grant fixture: grant endpoint unavailable'): () => Promise<RealtimeGrant> {\n return () => Promise.reject(new Error(reason));\n}\n"],"names":["MockEditorProvider","children","_initialElements","initialArtboards","_initialSelection","_initialMultiSelection","initialArtboardConfig","_artboardManager","useState","manager","ArtboardManager","artboard","ThemeProvider","jsx","EditorProvider","MockEditorProviderWithState","createMockElement","transformType","overrides","transformDef","getTransformById","createMockImageElement","ImageElement","createMockArtboard","ArtboardElement","waitFor","condition","timeout","interval","startTime","resolve","waitForExport","_artboardId","dataUrl","simulateKeyPress","key","options","event","createMockCanvas","width","height","canvas","assertElementProperties","element","expected","value","getElementBounds","bbox","mutateNamedTextLayers","seed","mutatedAny","elements","el","name","text","EditorError","bytesEqual","a","b","i","renderOnce","makeSession","placement","state","timeoutMs","label","session","reject","timer","results","withImage","r","message","serializeStateForServer","err","fetchRender","url","opts","img","fetchMockupImage","isSnowconeSdkError","assertRenders","design","product","mutated","grant","getToken","mintRealtimeGrant","RenderSession","seedResult","seedImage","mutatedResult","mutatedImage","TEST_403_ASSET_URL","test403Design","testIncompleteDesign","failingGrant","reason"],"mappings":";;;;;;;;AAuEO,MAAMA,IAAwD,CAAC;AAAA,EACpE,UAAAC;AAAA,EACA,iBAAiBC,IAAmB,CAAA;AAAA,EACpC,kBAAAC;AAAA,EACA,kBAAkBC,IAAoB;AAAA,EACtC,uBAAuBC,IAAyB,CAAA;AAAA,EAChD,uBAAAC,IAAwB,CAAA;AAC1B,MAAM;AAEJ,QAAM,CAACC,CAAgB,IAAIC,EAAS,MAAM;AACxC,UAAMC,IAAU,IAAIC,EAAA;AAEpB,WAAIP,KAAoBA,EAAiB,SAAS,IAEhDA,EAAiB,QAAQ,CAAAQ,MAAY;AACnC,MAAAF,EAAQ,eAAe;AAAA,QACrB,MAAME,EAAS;AAAA,QACf,OAAOA,EAAS;AAAA,QAChB,QAAQA,EAAS;AAAA,QACjB,iBAAiBA,EAAS;AAAA,MAAA,CAC3B;AAAA,IACH,CAAC,IAGDF,EAAQ,eAAe;AAAA,MACrB,MAAM;AAAA,MACN,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,iBAAiB;AAAA,MACjB,GAAGH;AAAA,IAAA,CACJ,GAGIG;AAAA,EACT,CAAC;AAKD,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,KAAA;AAAA,EAAK;AAE3G;ACtNO,MAAMC,IAAqB;AAM3B,SAASC,IAAgB;AAC9B,SAAOZ,EAAO,EAAE,MAAM,SAAS,OAAO,KAAM,QAAQ,IAAA,CAAM,EACvD,WAAWW,GAAoB,EAAE,aAAa,GAAG,MAAM,MAAA,CAAO,EAC9D,KAAK,4BAA4B,EAAE,QAAQ,OAAO,MAAM,WAAA,CAAY;AACzE;AAQO,SAASE,KAAuB;AACrC,SAAOb,EAAO,EAAE,MAAM,SAAS,OAAO,KAAM,QAAQ,IAAA,CAAM,EACvD,KAAK,aAAa,EAAE,QAAQ,UAAU,MAAM,QAAQ;AACzD;AAMO,SAASc,GAAaC,IAAS,qDAAmF;AACvH,SAAO,MAAM,QAAQ,OAAO,IAAI,MAAMA,CAAM,CAAC;AAC/C;"}
1
+ {"version":3,"file":"testing.mjs","sources":["../src/testing/MockEditorProvider.tsx","../src/testing/utils.ts","../src/testing/assertRenders.ts","../src/testing/failureFixtures.ts"],"sourcesContent":["/**\n * MockEditorProvider - Lightweight mock for testing custom components\n * Compatible with Vitest (does not require Jest)\n *\n * @example\n * ```tsx\n * import { render } from '@testing-library/react';\n * import { MockEditorProvider } from '@snowcone-app/canvas/embed';\n *\n * test('my component renders', () => {\n * render(\n * <MockEditorProvider>\n * <MyCustomComponent />\n * </MockEditorProvider>\n * );\n * });\n * ```\n */\n\nimport React, { useState, ReactNode } from 'react';\nimport { EditorProvider } from '../contexts/EditorContext.js';\nimport { ThemeProvider } from '../contexts/ThemeContext.js';\nimport { ArtboardManager } from '../core/ArtboardManager.js';\nimport { ArtboardElement } from '../core/ArtboardElement.js';\nimport type { TextElement } from '../core/TextElement.js';\nimport type { ImageElement } from '../core/ImageElement.js';\nimport type { GroupElement } from '../core/GroupElement.js';\nimport type { ShapeElement } from '../core/ShapeElement.js';\n\nexport type MockEditorElement = TextElement | ImageElement | GroupElement | ShapeElement;\n\nexport interface MockEditorProviderProps {\n children: ReactNode;\n\n /**\n * Initial elements to populate the editor\n */\n initialElements?: MockEditorElement[];\n\n /**\n * Initial artboards (default: one artboard)\n */\n initialArtboards?: ArtboardElement[];\n\n /**\n * Initial selection\n */\n initialSelection?: string | null;\n\n /**\n * Initial multi-selection\n */\n initialMultiSelection?: string[];\n\n /**\n * Initial artboard configuration\n */\n initialArtboardConfig?: {\n name?: string;\n width?: number;\n height?: number;\n backgroundColor?: string;\n };\n}\n\n/**\n * MockEditorProvider - Wraps EditorProvider with test-friendly defaults\n *\n * This is a lightweight wrapper that provides the same EditorContext\n * as the real app, making it perfect for testing custom components.\n */\nexport const MockEditorProvider: React.FC<MockEditorProviderProps> = ({\n children,\n initialElements: _initialElements = [],\n initialArtboards,\n initialSelection: _initialSelection = null,\n initialMultiSelection: _initialMultiSelection = [],\n initialArtboardConfig = {},\n}) => {\n // Create artboard manager if artboards provided\n const [_artboardManager] = useState(() => {\n const manager = new ArtboardManager();\n\n if (initialArtboards && initialArtboards.length > 0) {\n // Use provided artboards\n initialArtboards.forEach(artboard => {\n manager.createArtboard({\n name: artboard.name,\n width: artboard.width,\n height: artboard.height,\n backgroundColor: artboard.backgroundColor,\n });\n });\n } else {\n // Create default artboard\n manager.createArtboard({\n name: 'Test Artboard',\n width: 1200,\n height: 1200,\n backgroundColor: '#FFFFFF',\n ...initialArtboardConfig,\n });\n }\n\n return manager;\n });\n\n // Simple wrapper that passes children through to real EditorProvider\n // The EditorProvider will handle all the state management\n // ThemeProvider is required because CanvasEditor uses useTheme()\n return (\n <ThemeProvider>\n <EditorProvider\n initialArtboardConfig={initialArtboardConfig}\n >\n {children}\n </EditorProvider>\n </ThemeProvider>\n );\n};\n\n/**\n * MockEditorProviderWithState - For tests that need to control state directly\n *\n * Use this when you need fine-grained control over the editor state.\n * Most tests should use the simpler MockEditorProvider above.\n */\nexport const MockEditorProviderWithState: React.FC<MockEditorProviderProps> = ({\n children,\n initialElements: _initialElements = [],\n initialSelection: _initialSelection = null,\n initialMultiSelection: _initialMultiSelection = [],\n initialArtboardConfig = {},\n}) => {\n return (\n <ThemeProvider>\n <EditorProvider initialArtboardConfig={initialArtboardConfig}>\n {children}\n </EditorProvider>\n </ThemeProvider>\n );\n};\n","/**\n * Testing Utilities - Helpers for creating mock elements and artboards\n * Compatible with Vitest\n */\n\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\nimport { ArtboardElement } from '../core/ArtboardElement.js';\nimport { getTransformById } from '../transforms/registry.js';\nimport type { TransformType, ImageElementConfig } from '../types/index.js';\n\n/**\n * Create a mock text element with sensible defaults\n *\n * @example\n * ```tsx\n * const element = createMockElement('custom', {\n * text: 'Hello World',\n * fontSize: 48,\n * fontColor: '#FF0000'\n * });\n * ```\n */\nexport function createMockElement(\n transformType: TransformType = 'custom',\n overrides: Partial<TextElement> = {}\n): TextElement {\n // Get the correct concrete class from registry\n const transformDef = getTransformById(transformType);\n if (!transformDef || !transformDef.Component) {\n throw new Error(`Transform type \"${transformType}\" not found in registry`);\n }\n\n // Create element using the concrete class\n const element = new transformDef.Component({\n transformType,\n text: 'Test Text',\n fontSize: 32,\n color: '#000000',\n fontFamily: 'Arial',\n x: 100,\n y: 100,\n rotation: 0,\n ...overrides,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- test utility: overrides merge Partial<TextElement> properties with config, which are structurally compatible but not type-assignable\n } as any);\n\n return element as TextElement;\n}\n\n/**\n * Create a mock image element\n *\n * @example\n * ```tsx\n * const image = createMockImageElement({\n * imageUrl: 'data:image/png;base64,...',\n * width: 200,\n * height: 200\n * });\n * ```\n */\nexport function createMockImageElement(\n overrides: Partial<ImageElementConfig> = {}\n): ImageElement {\n const element = new ImageElement({\n imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',\n imageAspectRatio: 1,\n x: 100,\n y: 100,\n rotation: 0,\n ...overrides,\n });\n\n return element;\n}\n\n/**\n * Create a mock artboard\n *\n * @example\n * ```tsx\n * const artboard = createMockArtboard({\n * name: 'Front',\n * width: 1200,\n * height: 1200,\n * backgroundColor: '#FFFFFF'\n * });\n * ```\n */\nexport function createMockArtboard(\n overrides: Partial<{\n name: string;\n width: number;\n height: number;\n x: number;\n y: number;\n backgroundColor: string;\n }> = {}\n): ArtboardElement {\n const artboard = new ArtboardElement({\n name: 'Test Artboard',\n width: 1200,\n height: 1200,\n x: 0,\n y: 0,\n backgroundColor: '#FFFFFF',\n ...overrides,\n });\n\n return artboard;\n}\n\n/**\n * Wait for a condition to become true\n * Useful for async testing\n *\n * @example\n * ```tsx\n * await waitFor(() => screen.getByText('Loaded'), 5000);\n * ```\n */\nexport async function waitFor(\n condition: () => boolean,\n timeout = 5000,\n interval = 100\n): Promise<void> {\n const startTime = Date.now();\n\n while (!condition()) {\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for condition after ${timeout}ms`);\n }\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n}\n\n/**\n * Wait for an export to complete\n * Polls until dataUrl is available\n *\n * @example\n * ```tsx\n * const dataUrl = await waitForExport('artboard-1', 5000);\n * expect(dataUrl).toContain('data:image/png');\n * ```\n */\nexport async function waitForExport(\n _artboardId: string,\n timeout = 5000\n): Promise<string | null> {\n let dataUrl: string | null = null;\n\n await waitFor(() => {\n // Check if export completed (this would need to be implemented based on your export state)\n // For now, just return false as a placeholder\n return false;\n }, timeout);\n\n return dataUrl;\n}\n\n/**\n * Simulate a keyboard event\n * Useful for testing keyboard shortcuts\n *\n * @example\n * ```tsx\n * simulateKeyPress('c', { meta: true }); // Cmd+C\n * ```\n */\nexport function simulateKeyPress(\n key: string,\n options: {\n ctrl?: boolean;\n shift?: boolean;\n alt?: boolean;\n meta?: boolean;\n } = {}\n): void {\n const event = new KeyboardEvent('keydown', {\n key,\n ctrlKey: options.ctrl,\n shiftKey: options.shift,\n altKey: options.alt,\n metaKey: options.meta,\n bubbles: true,\n cancelable: true,\n });\n\n document.dispatchEvent(event);\n}\n\n/**\n * Create a mock canvas element for testing\n * Returns an HTMLCanvasElement with mocked context\n *\n * @example\n * ```tsx\n * const canvas = createMockCanvas(800, 600);\n * const ctx = canvas.getContext('2d');\n * ```\n */\nexport function createMockCanvas(\n width = 800,\n height = 600\n): HTMLCanvasElement {\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n\n return canvas;\n}\n\n/**\n * Assert that an element has certain properties\n * Useful for programmatic assertions\n *\n * @example\n * ```tsx\n * assertElementProperties(element, {\n * text: 'Hello',\n * fontSize: 48,\n * fontColor: '#FF0000'\n * });\n * ```\n */\nexport function assertElementProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Test utility: accepts any element type and checks arbitrary properties\n element: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Test utility: expected values can be any type\n expected: Record<string, any>\n): void {\n Object.entries(expected).forEach(([key, value]) => {\n if (element[key] !== value) {\n throw new Error(\n `Expected element.${key} to be ${value}, got ${element[key]}`\n );\n }\n });\n}\n\n/**\n * Get element bounding box for testing\n * Returns computed bounds from the element\n *\n * @example\n * ```tsx\n * const bounds = getElementBounds(element);\n * expect(bounds.width).toBeGreaterThan(0);\n * ```\n */\nexport function getElementBounds(element: TextElement | ImageElement): {\n x: number;\n y: number;\n width: number;\n height: number;\n} {\n const bbox = element.getBoundingBox();\n\n return {\n x: bbox.x,\n y: bbox.y,\n width: bbox.width,\n height: bbox.height,\n };\n}\n","/**\n * `assertRenders(design, product, opts)` — the TWO-RENDER live contract check\n * (agent-DX decision F4, ADR-0085 plan).\n *\n * WHY TWO RENDERS: \"the URL returns an image\" can't catch a DEAD BINDING — a\n * wrong layer name still renders the seed beautifully. So this renders the\n * design twice: once as seeded, once with the personalization bindings\n * mutated, and asserts the encoded image BYTES differ (mockup delivery is\n * deterministic per state, so byte-identical means pixel-identical means the\n * mutation never reached the render).\n *\n * What it proves, in order:\n * 1. the seed design renders: HTTP 200 + real raster bytes (non-blank);\n * 2. the mutated design renders the same way;\n * 3. the two renders DIFFER — the binding is alive.\n *\n * Failures are the structured error contract (E3), never prose-only:\n * - `E_ASSET_FORBIDDEN` — the shop's asset-origin allowlist denied a design\n * asset (translated from the server's 403; `data.failedAssets` names it);\n * - `E_RENDER_FAILED` — render error / timeout / non-image response;\n * - `E_BINDING_INERT` — both renders byte-identical (dead binding);\n * - `E_NO_MUTABLE_BINDING` — nothing to mutate and no `mutate` given.\n * - The SDK's `SHOP_NOT_PROPAGATED` passes through: a freshly minted shop\n * that never becomes visible is an environment fault, named as such.\n *\n * This talks to the REAL realtime render path (network). Use it in nightly /\n * acceptance jobs and agent verify loops — per-PR unit tests should mock the\n * SDK transport instead (plan: per-PR replay, nightly network-real).\n */\n\nimport {\n RenderSession,\n fetchMockupImage,\n mintRealtimeGrant,\n type MockupResult,\n type RealtimeGrant,\n type RenderProduct,\n} from '@snowcone-app/sdk';\nimport { isSnowconeSdkError } from '@snowcone-app/sdk';\nimport { serializeStateForServer } from '../rendering/serialize-for-server.js';\nimport { EditorError } from '../errors/editorError.js';\nimport type { DesignState } from '../components/editor/designStateStore.js';\n\n/** Anything `design()` produces (or a compatible shape). */\nexport interface RenderableDesign {\n toJSON(): DesignState;\n}\n\nexport interface AssertRendersOptions {\n /** Publishable shop id (= shop.id). */\n shop: string;\n /** Secret API key (sk_) for the grant; omit for the keyless publishable\n * path (sandbox/trial shops — the F1 bootstrap default). */\n apiKey?: string;\n /** Pre-fetched grant or grant factory — overrides the mint entirely. */\n grant?: RealtimeGrant | (() => Promise<RealtimeGrant>);\n /** Backend base for the keyless/sk grant mint (defaults to prod). */\n grantBase?: string;\n /** Override the realtime WS endpoint. */\n wsUrl?: string;\n /**\n * Produce the mutated state for the second render. Default: rewrite the\n * text of EVERY named text layer to a sentinel (`ASSERT_RENDERS_<name>`).\n * Throws `E_NO_MUTABLE_BINDING` if the design has no named text layer and\n * no override is given.\n */\n mutate?: (seed: DesignState) => DesignState;\n /** Per-render timeout (ms). Default 30_000. */\n timeoutMs?: number;\n /** Override fetch for the image downloads (tests). */\n fetchImpl?: typeof fetch;\n}\n\nexport interface AssertRendersResult {\n /** The seed render's mockup URL + encoded size. */\n seed: { url: string; bytes: number; kind: string };\n /** The mutated render's mockup URL + encoded size. */\n mutated: { url: string; bytes: number; kind: string };\n}\n\n/** Default mutation: every NAMED text layer gets a sentinel value. */\nexport function mutateNamedTextLayers(seed: DesignState): DesignState {\n let mutatedAny = false;\n const elements = seed.elements.map((el) => {\n const name = (el as { name?: string }).name;\n const text = (el as { text?: string }).text;\n if (!name || typeof text !== 'string') return el;\n mutatedAny = true;\n return { ...el, text: `ASSERT_RENDERS_${name.toUpperCase()}` } as typeof el;\n });\n if (!mutatedAny) {\n throw new EditorError(\n 'E_NO_MUTABLE_BINDING',\n 'this design has no NAMED text layer to mutate for the two-render check. Name one ' +\n '(design().text(\"…\", { name: \"headline\" })) or pass opts.mutate to define the mutation.',\n { docSlug: 'embed-mode' },\n );\n }\n return { ...seed, elements };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Render one state on a FRESH session and resolve the first mockup result.\n * One session per render on purpose: a session keeps emitting trailing mockup\n * results (multi-mockup products emit per scene), so reusing it for the\n * second render could resolve the mutated phase with a stale seed emission —\n * and with content-addressed delivery a dead binding makes the two\n * indistinguishable by URL. A fresh session has no history to confuse.\n */\nasync function renderOnce(\n makeSession: () => RenderSession,\n placement: string,\n state: DesignState,\n timeoutMs: number,\n label: 'seed' | 'mutated',\n): Promise<MockupResult> {\n const session = makeSession();\n try {\n return await new Promise<MockupResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new EditorError('E_RENDER_FAILED', `the ${label} render produced no mockup within ${timeoutMs}ms.`, {\n phase: label,\n timeoutMs,\n }),\n );\n }, timeoutMs);\n session.onMockups((results) => {\n const withImage = results.find((r) => r.imageUrl);\n if (!withImage) return;\n clearTimeout(timer);\n resolve(withImage);\n });\n session.onError((message) => {\n clearTimeout(timer);\n reject(new EditorError('E_RENDER_FAILED', `the ${label} render failed: ${message}`, { phase: label, error: message }));\n });\n void session.renderState(placement, serializeStateForServer(state)).catch((err) => {\n clearTimeout(timer);\n const message = err instanceof Error ? err.message : String(err);\n reject(new EditorError('E_RENDER_FAILED', `the ${label} render failed to dispatch: ${message}`, { phase: label, error: message }));\n });\n });\n } finally {\n session.close();\n }\n}\n\n/** Fetch + validate one rendered image, translating SDK failures (asset-403 →\n * `E_ASSET_FORBIDDEN`) into the editor error contract. */\nasync function fetchRender(url: string, label: 'seed' | 'mutated', opts: AssertRendersOptions): Promise<{ bytes: Uint8Array; kind: string }> {\n try {\n const img = await fetchMockupImage(url, {\n ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n });\n return { bytes: img.bytes, kind: img.kind };\n } catch (err) {\n if (isSnowconeSdkError(err)) {\n if (err.code === 'ASSET_FORBIDDEN') {\n throw new EditorError(\n 'E_ASSET_FORBIDDEN',\n `the shop's asset-origin allowlist denied an asset in this design (${label} render). ` +\n `Allow the asset's origin on the shop (or host it on the shop's storage origin).`,\n { phase: label, url, failedAssets: err.data.failedAssets, docSlug: 'embed-mode' },\n );\n }\n if (err.code === 'SHOP_NOT_PROPAGATED') throw err; // already structured + named\n throw new EditorError('E_RENDER_FAILED', `the ${label} render's image fetch failed: ${err.message}`, {\n phase: label,\n url,\n ...err.data,\n });\n }\n throw err;\n }\n}\n\n/**\n * Prove a design + product render AND that the design's bindings are alive\n * (two-render contract). See the module doc for the failure catalog.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport async function assertRenders(\n design: RenderableDesign,\n product: RenderProduct,\n opts: AssertRendersOptions,\n): Promise<AssertRendersResult> {\n const timeoutMs = opts.timeoutMs ?? 30_000;\n const seed = design.toJSON();\n const placement = seed.activeArtboard;\n const mutated = (opts.mutate ?? mutateNamedTextLayers)(seed);\n\n const grant = opts.grant;\n const getToken =\n typeof grant === 'function'\n ? grant\n : grant\n ? () => Promise.resolve(grant)\n : () =>\n mintRealtimeGrant({\n shop: opts.shop,\n ...(opts.apiKey ? { apiKey: opts.apiKey } : {}),\n ...(opts.grantBase ? { base: opts.grantBase } : {}),\n ...(opts.fetchImpl ? { fetch: opts.fetchImpl } : {}),\n });\n\n const makeSession = () =>\n new RenderSession({\n shop: opts.shop,\n product,\n ...(opts.wsUrl ? { wsUrl: opts.wsUrl } : {}),\n getToken,\n });\n\n const seedResult = await renderOnce(makeSession, placement, seed, timeoutMs, 'seed');\n const seedImage = await fetchRender(seedResult.imageUrl!, 'seed', opts);\n\n const mutatedResult = await renderOnce(makeSession, placement, mutated, timeoutMs, 'mutated');\n const mutatedImage = await fetchRender(mutatedResult.imageUrl!, 'mutated', opts);\n\n if (bytesEqual(seedImage.bytes, mutatedImage.bytes)) {\n throw new EditorError(\n 'E_BINDING_INERT',\n 'the mutated render is byte-identical to the seed render — the mutation never reached ' +\n 'the server, so the binding under test is DEAD. Usual causes: the mutated layer name ' +\n \"doesn't exist in the design (check design.layer() names), or opts.mutate returned the \" +\n 'seed unchanged.',\n {\n seedUrl: seedResult.imageUrl,\n mutatedUrl: mutatedResult.imageUrl,\n bytes: seedImage.bytes.byteLength,\n docSlug: 'embed-mode',\n },\n );\n }\n\n return {\n seed: { url: seedResult.imageUrl!, bytes: seedImage.bytes.byteLength, kind: seedImage.kind },\n mutated: { url: mutatedResult.imageUrl!, bytes: mutatedImage.bytes.byteLength, kind: mutatedImage.kind },\n };\n}\n","/**\n * Deterministic failure-mode fixtures (ADR-0085 plan, P2 — the magic-test-card\n * equivalent): trigger each commerce/render failure ON DEMAND so integrators\n * build their error UI against real failures instead of waiting for prod to\n * produce one.\n *\n * These are the CLIENT-ACHIEVABLE fixtures — each works against any shop\n * (including a fresh sandbox shop) with no server cooperation:\n *\n * - {@link test403Design} — asset-origin allowlist denial. References an\n * asset on an origin no shop allowlists, so the server's asset fetch is\n * denied deterministically. Surfaces as a render error (live path) or\n * `E_ASSET_FORBIDDEN` from `assertRenders`.\n * - {@link testIncompleteDesign} — Buy completeness failure. A design whose\n * only personalization layer still carries its seed value, so\n * `<Editor.Buy>` gates with `layer-seed:<name>` (and `layer:<name>` once\n * cleared). Pair with `<Editor.TextField layer={d.layer('name')} />`.\n * - {@link failingGrant} — grant failure. A grant factory that always\n * rejects; pass as `<Editor.Root grant={failingGrant()}>` to exercise the\n * \"grant fetch fails\" surface (`onRenderError` + the Preview's\n * `data-sc-part=\"preview-error\"` state).\n *\n * Server-triggered fixtures (a `test-slow` product for the timeout path, a\n * forced render-error token) need render-edge cooperation and are tracked\n * separately — they are NOT silently stubbed here.\n */\n\nimport { design } from '../design/design-builder.js';\nimport type { RealtimeGrant } from '@snowcone-app/sdk';\n\n/**\n * An origin that is deliberately on NO shop's asset-origin allowlist. The\n * `.invalid` TLD is reserved (RFC 2606) — it can never resolve, and the\n * allowlist check denies it before any fetch is attempted, so the failure is\n * deterministic and free.\n */\nexport const TEST_403_ASSET_URL = 'https://assets.test-403.invalid/denied.png';\n\n/**\n * A design whose background asset the shop's allowlist is guaranteed to deny —\n * the deterministic allowlist-denial (403) trigger.\n */\nexport function test403Design() {\n return design({ name: 'Front', width: 1000, height: 1000 })\n .background(TEST_403_ASSET_URL, { aspectRatio: 1, name: 'art' })\n .text('ALLOWLIST DENIAL FIXTURE', { anchor: 'top', name: 'headline' });\n}\n\n/**\n * A design that gates `<Editor.Buy>` out of the box: its one personalization\n * layer (`'name'`, seed `'YOUR NAME'`) is required and still equals its seed,\n * so Buy renders `data-sc-buy-state=\"incomplete\"` with\n * `data-sc-buy-missing=\"layer-seed:name\"` until a real value is typed.\n */\nexport function testIncompleteDesign() {\n return design({ name: 'Front', width: 1000, height: 1000 })\n .text('YOUR NAME', { anchor: 'center', name: 'name' });\n}\n\n/**\n * A grant factory that always rejects — the deterministic \"grant fetch\n * failed\" trigger. The rejection reason is stable for assertions.\n */\nexport function failingGrant(reason = 'failing-grant fixture: grant endpoint unavailable'): () => Promise<RealtimeGrant> {\n return () => Promise.reject(new Error(reason));\n}\n"],"names":["MockEditorProvider","children","_initialElements","initialArtboards","_initialSelection","_initialMultiSelection","initialArtboardConfig","_artboardManager","useState","manager","ArtboardManager","artboard","ThemeProvider","jsx","EditorProvider","MockEditorProviderWithState","createMockElement","transformType","overrides","transformDef","getTransformById","createMockImageElement","ImageElement","createMockArtboard","ArtboardElement","waitFor","condition","timeout","interval","startTime","resolve","waitForExport","_artboardId","dataUrl","simulateKeyPress","key","options","event","createMockCanvas","width","height","canvas","assertElementProperties","element","expected","value","getElementBounds","bbox","mutateNamedTextLayers","seed","mutatedAny","elements","el","name","text","EditorError","bytesEqual","a","b","i","renderOnce","makeSession","placement","state","timeoutMs","label","session","reject","timer","results","withImage","r","message","serializeStateForServer","err","fetchRender","url","opts","img","fetchMockupImage","isSnowconeSdkError","assertRenders","design","product","mutated","grant","getToken","mintRealtimeGrant","RenderSession","seedResult","seedImage","mutatedResult","mutatedImage","TEST_403_ASSET_URL","test403Design","testIncompleteDesign","failingGrant","reason"],"mappings":";;;;;;;AAuEO,MAAMA,IAAwD,CAAC;AAAA,EACpE,UAAAC;AAAA,EACA,iBAAiBC,IAAmB,CAAA;AAAA,EACpC,kBAAAC;AAAA,EACA,kBAAkBC,IAAoB;AAAA,EACtC,uBAAuBC,IAAyB,CAAA;AAAA,EAChD,uBAAAC,IAAwB,CAAA;AAC1B,MAAM;AAEJ,QAAM,CAACC,CAAgB,IAAIC,EAAS,MAAM;AACxC,UAAMC,IAAU,IAAIC,EAAA;AAEpB,WAAIP,KAAoBA,EAAiB,SAAS,IAEhDA,EAAiB,QAAQ,CAAAQ,MAAY;AACnC,MAAAF,EAAQ,eAAe;AAAA,QACrB,MAAME,EAAS;AAAA,QACf,OAAOA,EAAS;AAAA,QAChB,QAAQA,E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,MAAM;AAAA,QACvB,SAAS;AAAA,MAAA;AAAA,IACX;AAIJ,SAAO;AAAA,IACL,MAAM,EAAE,KAAKD,EAAW,UAAW,OAAOC,EAAU,MAAM,YAAY,MAAMA,EAAU,KAAA;AAAA,IACtF,SAAS,EAAE,KAAKC,EAAc,UAAW,OAAOC,EAAa,MAAM,YAAY,MAAMA,EAAa,KAAA;AAAA,EAAK;AAE3G;ACtNO,MAAMC,IAAqB;AAM3B,SAASC,IAAgB;AAC9B,SAAOZ,EAAO,EAAE,MAAM,SAAS,OAAO,KAAM,QAAQ,IAAA,CAAM,EACvD,WAAWW,GAAoB,EAAE,aAAa,GAAG,MAAM,MAAA,CAAO,EAC9D,KAAK,4BAA4B,EAAE,QAAQ,OAAO,MAAM,WAAA,CAAY;AACzE;AAQO,SAASE,IAAuB;AACrC,SAAOb,EAAO,EAAE,MAAM,SAAS,OAAO,KAAM,QAAQ,IAAA,CAAM,EACvD,KAAK,aAAa,EAAE,QAAQ,UAAU,MAAM,QAAQ;AACzD;AAMO,SAASc,GAAaC,IAAS,qDAAmF;AACvH,SAAO,MAAM,QAAQ,OAAO,IAAI,MAAMA,CAAM,CAAC;AAC/C;"}
@@ -63,6 +63,25 @@ export interface FlagTransformData {
63
63
  /** Container width for text layout */
64
64
  width: number;
65
65
  }
66
+ /**
67
+ * Color adjustments for image elements. Each channel is a multiplier where
68
+ * `1` is neutral (no change); the canonical neutral state is the ABSENCE of
69
+ * the `adjustments` object (omit = neutral, never `{1, 1, 1}`).
70
+ *
71
+ * Semantics match the CSS Filter Effects spec functions `brightness()`,
72
+ * `contrast()` and `saturate()`, applied in that order to the SOURCE bitmap
73
+ * before crop / flip / border-radius compositing. The math lives in
74
+ * `rendering/image-adjustments.ts` and is shared verbatim by the live
75
+ * renderer and the export worker, so live and exported pixels always match.
76
+ */
77
+ export interface ImageAdjustments {
78
+ /** Brightness multiplier — 1 neutral, 0 black, > 1 brighter. */
79
+ brightness: number;
80
+ /** Contrast multiplier — 1 neutral, 0 solid grey, > 1 punchier. */
81
+ contrast: number;
82
+ /** Saturation multiplier — 1 neutral, 0 grayscale, > 1 more vivid. */
83
+ saturation: number;
84
+ }
66
85
  export interface ImageTransformData {
67
86
  type: 'image';
68
87
  width: number;
@@ -74,6 +93,8 @@ export interface ImageTransformData {
74
93
  flipHorizontal: boolean;
75
94
  flipVertical: boolean;
76
95
  borderRadius: number;
96
+ /** Brightness/contrast/saturation — omitted when neutral. See {@link ImageAdjustments}. */
97
+ adjustments?: ImageAdjustments;
77
98
  }
78
99
  export interface GroupTransformData {
79
100
  type: 'group';