@jbpark/live-editor 6.0.0 → 6.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.ko.md +8 -0
  2. package/README.md +8 -0
  3. package/dist/{boundary-CySnDUs2.js → boundary-CLMNMZFa.js} +4 -4
  4. package/dist/boundary-CLMNMZFa.js.map +1 -0
  5. package/dist/{cn-CAnad2vL.js → compile-BWZ5U59y.js} +135 -2
  6. package/dist/compile-BWZ5U59y.js.map +1 -0
  7. package/dist/{context-Bjq0CvBE.js → context-DJxX9epB.js} +2 -3
  8. package/dist/context-DJxX9epB.js.map +1 -0
  9. package/dist/{core-BNVuH8-l.js → core-BfJwD8Jx.js} +3 -6
  10. package/dist/core-BfJwD8Jx.js.map +1 -0
  11. package/dist/dnd/index.js +2 -2
  12. package/dist/{dnd-BvjEDo-x.js → dnd-DAGjlJ0_.js} +241 -170
  13. package/dist/dnd-DAGjlJ0_.js.map +1 -0
  14. package/dist/{document-uHqw0mvr.js → document-MkQGxfry.js} +1182 -636
  15. package/dist/document-MkQGxfry.js.map +1 -0
  16. package/dist/editor/index.js +2 -2
  17. package/dist/{editor-CvnzrM9J.js → editor-B_VOz3Q0.js} +2 -2
  18. package/dist/{editor-CvnzrM9J.js.map → editor-B_VOz3Q0.js.map} +1 -1
  19. package/dist/editor-caches-DXYXgWeD.js +63 -0
  20. package/dist/editor-caches-DXYXgWeD.js.map +1 -0
  21. package/dist/error/index.d.ts +1 -1
  22. package/dist/error/index.js +2 -2
  23. package/dist/{error-CFzvnLCf.js → error-E3T5CS3m.js} +13 -12
  24. package/dist/error-E3T5CS3m.js.map +1 -0
  25. package/dist/{index-DfIvkht8.d.ts → index-BC9hY7dI.d.ts} +5 -5
  26. package/dist/{index-CqsS207F.d.ts → index-D-Dfv65w.d.ts} +3 -2
  27. package/dist/index.d.ts +4 -4
  28. package/dist/index.js +5 -5
  29. package/dist/preview/index.d.ts +1 -1
  30. package/dist/preview/index.js +1 -1
  31. package/dist/{preview-B05MkVIQ.js → preview-DFb1pOqJ.js} +30 -11
  32. package/dist/preview-DFb1pOqJ.js.map +1 -0
  33. package/dist/provider/index.js +1 -1
  34. package/dist/{sections-DhH_aVf5.js → sections-CnG7OLr8.js} +3 -3
  35. package/dist/{sections-DhH_aVf5.js.map → sections-CnG7OLr8.js.map} +1 -1
  36. package/dist/states-Ci1AvoQ9.js.map +1 -1
  37. package/dist/style.css +74 -74
  38. package/dist/ui-kit/index.js +2 -2
  39. package/dist/ui-kit/style.css +22 -6
  40. package/dist/{update-BuYQJqjq.js → update-DnX2ibYn.js} +162 -43
  41. package/dist/update-DnX2ibYn.js.map +1 -0
  42. package/dist/{use-dynamic-tailwind-B3l1qZRW.js → use-dynamic-tailwind-CjXeHjsr.js} +115 -40
  43. package/dist/use-dynamic-tailwind-CjXeHjsr.js.map +1 -0
  44. package/dist/{use-field-state-iQGW0vc6.js → use-field-state-B1VLhWfr.js} +2 -2
  45. package/dist/{use-field-state-iQGW0vc6.js.map → use-field-state-B1VLhWfr.js.map} +1 -1
  46. package/dist/utils/ast/index.js +1 -86
  47. package/dist/utils/index.js +3 -4
  48. package/package.json +3 -4
  49. package/dist/boundary-CySnDUs2.js.map +0 -1
  50. package/dist/cn-CAnad2vL.js.map +0 -1
  51. package/dist/compile-my0AjsCw.js +0 -136
  52. package/dist/compile-my0AjsCw.js.map +0 -1
  53. package/dist/constants-st9gnJ5g.js +0 -55
  54. package/dist/constants-st9gnJ5g.js.map +0 -1
  55. package/dist/context-Bjq0CvBE.js.map +0 -1
  56. package/dist/core-BNVuH8-l.js.map +0 -1
  57. package/dist/detect-typescript-CMF0FVKD.js +0 -10
  58. package/dist/detect-typescript-CMF0FVKD.js.map +0 -1
  59. package/dist/dnd-BvjEDo-x.js.map +0 -1
  60. package/dist/document-uHqw0mvr.js.map +0 -1
  61. package/dist/editor-caches-ClMvdcQF.js +0 -23
  62. package/dist/editor-caches-ClMvdcQF.js.map +0 -1
  63. package/dist/error-CFzvnLCf.js.map +0 -1
  64. package/dist/preview-B05MkVIQ.js.map +0 -1
  65. package/dist/update-BuYQJqjq.js.map +0 -1
  66. package/dist/use-dynamic-tailwind-B3l1qZRW.js.map +0 -1
  67. package/dist/utils/ast/index.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-DnX2ibYn.js","names":["t.stringLiteral","t.numericLiteral","t.jsxExpressionContainer","t.unaryExpression","t.isTSAsExpression","t.isTSSatisfiesExpression","t.isTSNonNullExpression","t.isTSTypeAssertion","t.isParenthesizedExpression","t.isStringLiteral","t.isNumericLiteral","t.isBooleanLiteral","t.isNullLiteral","t.isUnaryExpression","t.isTemplateLiteral","t.isArrayExpression","t.isObjectExpression","t.isObjectProperty","t.isIdentifier","t.isJSXElement","t.isJSXFragment","t.isArrayExpression","t.isSpreadElement","t.isObjectExpression","t.isObjectProperty","t.isIdentifier","t.isStringLiteral","t.isNumericLiteral","t.isBooleanLiteral","t.isUnaryExpression","t.isTemplateLiteral","t.isJSXElement","t.isJSXFragment","t.isObjectExpression","t.isObjectProperty","t.isIdentifier","t.isStringLiteral","t.isTemplateLiteral","t.isJSXText","t.jsxIdentifier","t.jsxMemberExpression","t.isJSXAttribute","t.isJSXIdentifier","isStringLiteral","t.isStringLiteral","t.isJSXExpressionContainer","t.isArrayExpression","t.isObjectExpression","t.jsxText","t.jsxFragment","t.jsxOpeningFragment","t.jsxClosingFragment","t.jsxAttribute","t.jsxOpeningElement","t.jsxClosingElement","t.jsxElement","t.isJSXElement","t.isJSXFragment","t.isObjectProperty","t.isIdentifier","t.isParenthesizedExpression","t.isJSXOpeningElement","t.isJSXAttribute","t.isJSXIdentifier","t.isJSXSpreadAttribute","t.isStringLiteral","t.isJSXElement","t.isJSXFragment","t.unaryExpression","t.numericLiteral","t.booleanLiteral","t.stringLiteral","t.nullLiteral","t.arrayExpression","t.objectProperty","t.objectExpression","t.isJSXAttribute","t.isJSXIdentifier","t.isJSXText","t.jsxAttribute","t.jsxIdentifier","t.jsxExpressionContainer","t.objectExpression","t.objectProperty","t.identifier","t.stringLiteral","t.isJSXExpressionContainer","t.isArrayExpression","t.isObjectExpression","t.isJSXEmptyExpression","t.isJSXAttribute","t.isJSXIdentifier","t.isStringLiteral","t.isJSXExpressionContainer"],"sources":["../src/utils/ast/types.ts","../src/utils/ast/helpers.ts","../src/utils/ast/value.ts","../src/utils/ast/editable-value.ts","../src/utils/ast/binding.ts","../src/utils/selection.ts","../src/utils/ast/extract.ts","../src/utils/ast/children.ts","../src/utils/ast/value-expression.ts","../src/utils/ast/edit-source.ts","../src/utils/ast/update.ts"],"sourcesContent":["export interface Attribute {\n name: string;\n value: string | null;\n isStringLiteral?: boolean;\n}\n\nexport interface DataAttrNode {\n id?: string;\n tagName: string;\n attributes: Attribute[];\n dataAttributes: Attribute[];\n textContent: string;\n rawChildren?: string;\n // Exact structural child source, used to validate source-preserving edits.\n source?: string;\n loc?: {\n start: { line: number; column: number };\n end: { line: number; column: number };\n };\n children?: DataAttrNode[];\n isFragment?: boolean;\n bindings?: BindingItem[];\n}\n\nexport interface BindingOption {\n label: string;\n value: string;\n}\n\n// The kinds of data a binding can hold: what a value is, not how to draw\n// it. How to draw it is `widget`, which the library passes through without\n// reading; the built-in panel renders the default control for each kind.\nexport const BINDING_TYPES = [\n 'array',\n 'object',\n 'string',\n 'number',\n 'boolean',\n 'color',\n 'jsx',\n 'richtext',\n 'date',\n 'url',\n 'email',\n 'tel',\n 'time',\n 'datetime',\n] as const;\n\nexport type BindingType = (typeof BINDING_TYPES)[number];\n\n// How to draw one field, as opposed to `type`, which is what its data is.\n// Written as a control name (`widget: 'slider'`) or as this object; parsing\n// turns the string into `{ type }`, so consumers see one shape.\n//\n// Constraints (`min`, `max`, `pattern`, `required` and the rest listed on\n// `BindingFieldSpec`) stay on the binding, not here, so\n// `validateBindingValue` checks them with or without a widget.\nexport interface BindingWidget {\n // The control name, any string (such as `'slider'`). A custom panel\n // switches on it; the built-in panel ignores it.\n type: string;\n // Common presentation hints, typed.\n step?: number;\n unit?: string;\n // Any other config for the control, kept as written (#234).\n [key: string]: unknown;\n}\n\n// The fields a binding declares about itself. Shared by `BindingItem` and\n// render-map leaves, so a nested field can say everything a top-level one\n// can (#383).\nexport interface BindingFieldSpec {\n // What the value is. A closed set, because validation and parsing switch\n // on it.\n type?: BindingType;\n // How to draw it, always in object form. See `BindingWidget`.\n widget?: BindingWidget;\n options?: BindingOption[];\n render?: BindingRenderMap;\n min?: number;\n max?: number;\n pattern?: string;\n // Shown instead of the provider's `pattern` message when `pattern` fails,\n // to say what the format is.\n patternMessage?: string;\n required?: boolean;\n // Length limits for a string value, in characters (an emoji counts once).\n minLength?: number;\n maxLength?: number;\n // A number value must be `min` (or 0) plus a whole number of steps, so\n // `step: 1` allows integers only.\n step?: number;\n // Item count limits for an array value. The built-in editor never removes\n // the last item (#316), so a `minItems` below 1 acts as 1 there.\n minItems?: number;\n maxItems?: number;\n // The earliest and latest `date` or `datetime` value, as `YYYY-MM-DD` or\n // `YYYY-MM-DDTHH:mm`. A date-only bound includes that whole day. Separate\n // from `min` and `max`, which are numbers.\n minDate?: string;\n maxDate?: string;\n // The schemes a `url` value may use, such as `['https:', 'mailto:']`. The\n // trailing colon is optional. Unset allows any scheme.\n protocols?: string[];\n // The app's own keys, anything not listed above, such as `group` or `tab`.\n // Kept apart so they can't collide with a field added later. Config for\n // the control goes in `widget` instead. `undefined` when there are none\n // (#234).\n meta?: Record<string, unknown>;\n}\n\n// A render-map entry is a leaf when it declares `type`, even an unknown\n// one, which then shows as an untyped field (#234). `label` and `property`\n// default to the entry's key.\nexport interface BindingRenderLeaf extends BindingFieldSpec {\n label?: string;\n property?: string;\n}\n\nexport interface BindingRenderMap {\n [key: string]: BindingRenderLeaf | BindingRenderMap;\n}\n\nexport interface BindingItem extends BindingFieldSpec {\n label: string;\n property: string;\n}\n\n// A component's tag name as written in the source: a member path\n// (`ui.Button`) or an identifier that doesn't start with a lowercase letter\n// (`Button`). Lowercase names are HTML elements.\nexport type BindingComponentName = `${string}.${string}` | Capitalize<string>;\n\n// One entry of `bindings` or `bindingKeys`, as written: a `BindingItem` plus\n// any key of the app's own (`group`, `tab`, `description`, ...), which\n// arrives in `binding.meta` just as it does from an inline `data-binding`.\n// `meta` itself isn't one of them: it's where those keys end up, so writing\n// it here would nest it under `meta.meta`.\nexport interface BindingSchema extends Omit<BindingItem, 'meta'> {\n [key: string]: unknown;\n}\n\n// Bindings for every element of a component, keyed by its tag name as\n// written, so markup doesn't have to repeat the same `data-binding` on each\n// one (#509). Components only: an entry for an HTML element such as `p` or\n// `h2` would make every one of them in every section editable, so those keys\n// are rejected by the type and ignored at runtime. An element's own\n// `data-binding`, even an empty one, takes precedence over its component's\n// entry. Matched elements still need a `data-id` to be edited.\nexport type BindingRegistry = Partial<\n Record<BindingComponentName, BindingSchema[]>\n>;\n\n// Bindings an element asks for by name, with `data-binding-key=\"hero-title\"`\n// in its markup, on an HTML element or a component alike (#513). Plain data,\n// so a host can load it from JSON or a CMS.\nexport type BindingKeyMap = Record<string, BindingSchema[]>;\n\n// Where bindings come from besides an element's own `data-binding`, in\n// order of precedence: the key its `data-binding-key` names in\n// `bindingKeys`, then its component's entry in `bindings`.\nexport interface BindingOptions {\n bindings?: BindingRegistry;\n bindingKeys?: BindingKeyMap;\n}\n\nexport type NodeValueType =\n 'boolean' | 'number' | 'string' | 'null' | 'array' | 'object' | 'unknown';\n\nexport interface ExtractedNodeValue {\n type: NodeValueType;\n value: string | number | boolean | null;\n}\n","import generate from '@babel/generator';\nimport { parse, parseExpression } from '@babel/parser';\nimport * as t from '@babel/types';\n\nimport { REGEX } from '../../constants';\nimport type { Attribute } from './types';\n\nexport const wrap = (code: string) => {\n return `<>${code}</>`;\n};\n\nexport const unwrap = (generated: string) => {\n return generated\n .replace(/^<>\\s*/g, '')\n .replace(/\\s*<\\/>\\s*;?\\s*$/g, '')\n .trim();\n};\n\n// Throws Babel's error when `code`, JSX such as a section's source, doesn't\n// parse. Strict, like the document parse, unlike `extract()`, which recovers\n// from errors.\nexport const assertJsxParses = (code: string) => {\n parse(wrap(code), {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n};\n\nexport const attrValue = ({\n value,\n isStringLiteral,\n}: Attribute): t.JSXAttribute['value'] => {\n if (value === null) {\n return null;\n }\n\n if (isStringLiteral) {\n return t.stringLiteral(value);\n }\n\n const trimmed = value.trim();\n\n if (REGEX.NUMBER.test(trimmed)) {\n const magnitude = t.numericLiteral(Math.abs(parseFloat(trimmed)));\n\n // A negative is `-n`: Babel rejects a negative `numericLiteral` (#712).\n return t.jsxExpressionContainer(\n trimmed.startsWith('-') ? t.unaryExpression('-', magnitude) : magnitude,\n );\n }\n\n if (REGEX.BOOLEAN_OR_NULL.test(trimmed)) {\n const expr = parseExpression(trimmed, {\n plugins: ['jsx', 'typescript'],\n });\n return t.jsxExpressionContainer(expr);\n }\n\n try {\n const expr = parseExpression(trimmed, {\n plugins: ['jsx', 'typescript'],\n });\n return t.jsxExpressionContainer(expr);\n } catch {\n return t.stringLiteral(trimmed);\n }\n};\n\nexport const generateCode = (node: t.Node): string => {\n return generate(node, { jsescOption: { minimal: true } }).code;\n};\n","import { parseExpression } from '@babel/parser';\nimport * as t from '@babel/types';\n\nimport { REGEX } from '../../constants';\nimport { generateCode } from './helpers';\nimport type { ExtractedNodeValue } from './types';\n\n// Reads values out of the AST without running code: literals, binding values\n// and array or object expressions.\n\nconst dedent = (str: string): string => {\n const lines = str\n .replace(/^\\n/, '')\n .replace(/\\n\\s*$/, '')\n .split('\\n');\n\n const indent = lines.reduce((min, line) => {\n if (!line.trim()) {\n return min;\n }\n const match = line.match(/^(\\s*)/);\n return Math.min(min, match?.[1]?.length ?? 0);\n }, Infinity);\n\n return indent === Infinity\n ? str.trim()\n : lines.map(line => line.slice(indent)).join('\\n');\n};\n\n// Removes type-only wrappers (`satisfies`, `as const`, type assertions) and\n// parentheses, so the literal underneath can be read. Without this, a\n// `data-binding={[...] satisfies BindingItem[]}` would read as no bindings.\nexport const unwrapExpression = (node: t.Node): t.Node => {\n let current = node;\n\n while (\n t.isTSAsExpression(current) ||\n t.isTSSatisfiesExpression(current) ||\n t.isTSNonNullExpression(current) ||\n t.isTSTypeAssertion(current) ||\n t.isParenthesizedExpression(current)\n ) {\n current = current.expression;\n }\n\n return current;\n};\n\n// Whether `evaluateLiteral()` and `valueToExpression()` can round-trip the\n// value without losing calls, references, spreads, holes or computed keys.\n// The panel uses it to disable editors, and edits use it as the last check,\n// so both agree on what is editable.\nexport const isLosslesslyEvaluable = (node: t.Node): boolean => {\n const value = unwrapExpression(node);\n\n if (\n t.isStringLiteral(value) ||\n t.isNumericLiteral(value) ||\n t.isBooleanLiteral(value) ||\n t.isNullLiteral(value)\n ) {\n return true;\n }\n\n if (\n t.isUnaryExpression(value) &&\n value.operator === '-' &&\n t.isNumericLiteral(value.argument)\n ) {\n return true;\n }\n\n if (t.isTemplateLiteral(value)) {\n return value.expressions.length === 0;\n }\n\n if (t.isArrayExpression(value)) {\n return value.elements.every(\n element => element !== null && isLosslesslyEvaluable(element),\n );\n }\n\n if (t.isObjectExpression(value)) {\n return value.properties.every(\n property =>\n t.isObjectProperty(property) &&\n !property.computed &&\n (t.isIdentifier(property.key) ||\n t.isStringLiteral(property.key) ||\n t.isNumericLiteral(property.key)) &&\n isLosslesslyEvaluable(property.value),\n );\n }\n\n return false;\n};\n\nexport const canLosslesslyEvaluateSource = (source: string): boolean => {\n try {\n return isLosslesslyEvaluable(\n parseExpression(source, { plugins: ['jsx', 'typescript'] }),\n );\n } catch {\n return false;\n }\n};\n\n// Reads a literal's value from its AST without running any code. Calls,\n// references and other non-literal expressions give `undefined`, so reading\n// a field never executes the document's code.\nexport const evaluateLiteral = (rawNode: t.Node): unknown => {\n const node = unwrapExpression(rawNode);\n\n if (t.isStringLiteral(node)) {\n return node.value;\n }\n\n if (t.isNumericLiteral(node)) {\n return node.value;\n }\n\n if (t.isBooleanLiteral(node)) {\n return node.value;\n }\n\n if (t.isNullLiteral(node)) {\n return null;\n }\n\n if (t.isIdentifier(node) && node.name === 'undefined') {\n return undefined;\n }\n\n if (\n t.isUnaryExpression(node) &&\n node.operator === '-' &&\n t.isNumericLiteral(node.argument)\n ) {\n return -node.argument.value;\n }\n\n if (t.isTemplateLiteral(node) && node.expressions.length === 0) {\n return node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw ?? '';\n }\n\n if (t.isJSXElement(node) || t.isJSXFragment(node)) {\n return generateCode(node);\n }\n\n if (t.isArrayExpression(node)) {\n return node.elements.map(element =>\n element ? evaluateLiteral(element) : null,\n );\n }\n\n if (t.isObjectExpression(node)) {\n const result: Record<string, unknown> = {};\n\n for (const prop of node.properties) {\n if (!t.isObjectProperty(prop)) {\n continue;\n }\n\n let key: string | null = null;\n\n if (t.isIdentifier(prop.key)) {\n key = prop.key.name;\n } else if (t.isStringLiteral(prop.key)) {\n key = prop.key.value;\n } else if (t.isNumericLiteral(prop.key)) {\n key = String(prop.key.value);\n }\n\n if (key === null) {\n continue;\n }\n\n result[key] = evaluateLiteral(prop.value);\n }\n\n return result;\n }\n\n return undefined;\n};\n\nexport const parseValue = (value: unknown): unknown => {\n if (typeof value !== 'string') {\n return value;\n }\n\n const trimmed = value.trim();\n\n if (!trimmed) {\n return value;\n }\n\n if (REGEX.NUMBER.test(trimmed)) {\n return parseFloat(trimmed);\n }\n\n if (REGEX.BOOLEAN_OR_NULL.test(trimmed)) {\n if (trimmed === 'true') {\n return true;\n }\n if (trimmed === 'false') {\n return false;\n }\n if (trimmed === 'null') {\n return null;\n }\n if (trimmed === 'undefined') {\n return undefined;\n }\n }\n\n if (\n (trimmed.startsWith('{') && trimmed.endsWith('}')) ||\n (trimmed.startsWith('[') && trimmed.endsWith(']'))\n ) {\n try {\n const ast = parseExpression(trimmed, {\n plugins: ['jsx', 'typescript'],\n });\n\n if (t.isObjectExpression(ast) || t.isArrayExpression(ast)) {\n return evaluateLiteral(ast);\n }\n } catch {\n /* Not an object or array literal: keep the string. */\n }\n\n return value;\n }\n\n return value;\n};\n\nexport const extractNodeValue = (node: t.Node): ExtractedNodeValue => {\n if (t.isBooleanLiteral(node)) {\n return { type: 'boolean', value: node.value };\n }\n\n if (t.isNumericLiteral(node)) {\n return { type: 'number', value: node.value };\n }\n\n if (\n t.isUnaryExpression(node) &&\n node.operator === '-' &&\n t.isNumericLiteral(node.argument)\n ) {\n return { type: 'number', value: -node.argument.value };\n }\n\n if (t.isStringLiteral(node)) {\n return { type: 'string', value: node.value };\n }\n\n if (t.isTemplateLiteral(node)) {\n if (node.expressions.length === 0 && node.quasis.length === 1) {\n return {\n type: 'string',\n value: dedent(\n node.quasis[0]!.value.cooked ?? node.quasis[0]!.value.raw,\n ),\n };\n }\n return { type: 'string', value: generateCode(node) };\n }\n\n if (t.isNullLiteral(node)) {\n return { type: 'null', value: null };\n }\n\n if (t.isArrayExpression(node)) {\n return { type: 'array', value: generateCode(node) };\n }\n\n if (t.isObjectExpression(node)) {\n return { type: 'object', value: generateCode(node) };\n }\n\n if (t.isJSXElement(node) || t.isJSXFragment(node)) {\n return { type: 'string', value: generateCode(node) };\n }\n\n return { type: 'unknown', value: null };\n};\n\nexport const parseArrayExpression = (value: string) => {\n try {\n const ast = unwrapExpression(\n parseExpression(value, {\n plugins: ['jsx', 'typescript'],\n }),\n );\n\n if (!t.isArrayExpression(ast)) {\n return null;\n }\n\n return ast;\n } catch (error) {\n console.error('❌ Array parsing error:', error);\n return null;\n }\n};\n\nexport const extractObjectProperties = (\n element: t.ObjectExpression,\n): Record<string, ExtractedNodeValue & { astNode: t.Node }> => {\n const properties: Record<string, ExtractedNodeValue & { astNode: t.Node }> =\n {};\n\n element.properties.forEach(prop => {\n if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) {\n const key = prop.key.name;\n\n // `children` and other JSX-valued properties (such as `label`) are\n // edited through `useDndItems`'s nested elements instead (#298).\n if (\n key === 'children' ||\n t.isJSXElement(prop.value) ||\n t.isJSXFragment(prop.value)\n ) {\n return;\n }\n\n const extracted = extractNodeValue(prop.value);\n\n properties[key] = {\n ...extracted,\n astNode: prop.value,\n };\n }\n });\n\n return properties;\n};\n","import { parseExpression } from '@babel/parser';\nimport * as t from '@babel/types';\n\nimport { parseValue, unwrapExpression } from './value';\n\n// The editable leaves of an object or array value: listing them with their\n// paths, and replacing one while keeping the rest of the source as written.\n\nexport type EditablePathSegment = string | number;\n\nexport type EditablePrimitive = string | number | boolean;\n\nexport interface EditableValueEntry {\n path: EditablePathSegment[];\n value: EditablePrimitive;\n}\n\nconst MAX_FLATTEN_DEPTH = 20;\n\nexport const isEditablePrimitive = (\n value: unknown,\n): value is EditablePrimitive =>\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean';\n\n// Lists the editable leaves of an object or array value, with their paths.\n// It follows the value's own shape, so it works without a `render` map\n// (#225), as for `style` or an `items` array of `{ key, children }`. Strings,\n// numbers and booleans are leaves, whatever a string contains. Deeply nested\n// values stop at a fixed depth, and anything deeper is left out.\nexport const flattenEditableValue = (\n value: string,\n): EditableValueEntry[] | null => {\n const parsed = parseValue(value);\n\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Object.keys(parsed).length === 0\n ) {\n return null;\n }\n\n const entries: EditableValueEntry[] = [];\n\n const walk = (node: unknown, path: EditablePathSegment[], depth: number) => {\n if (depth > MAX_FLATTEN_DEPTH) {\n return;\n }\n\n if (isEditablePrimitive(node)) {\n entries.push({ path, value: node });\n return;\n }\n\n if (Array.isArray(node)) {\n node.forEach((item, index) => walk(item, [...path, index], depth + 1));\n return;\n }\n\n if (typeof node === 'object' && node !== null) {\n Object.entries(node).forEach(([key, item]) =>\n walk(item, [...path, key], depth + 1),\n );\n }\n\n // `null`, `undefined`, functions and symbols have no editable form and\n // are left out.\n };\n\n walk(parsed, [], 0);\n\n return entries.length ? entries : null;\n};\n\n// Finds the node `flattenEditableValue` reported at `path`, walking the\n// same literal structure `evaluateLiteral` reads. Returns null for anything\n// it can't point at with certainty: a missing key or index, a step through\n// something that isn't an object or array, or a spread that could replace\n// the entry at runtime.\nconst findEditableLeaf = (\n root: t.Node,\n path: EditablePathSegment[],\n): t.Node | null => {\n let node = unwrapExpression(root);\n\n for (const segment of path) {\n if (t.isArrayExpression(node)) {\n if (typeof segment !== 'number') {\n return null;\n }\n\n const elements = node.elements.slice(0, segment + 1);\n const element = node.elements[segment];\n\n if (!element || elements.some(item => t.isSpreadElement(item))) {\n return null;\n }\n\n node = unwrapExpression(element);\n continue;\n }\n\n if (t.isObjectExpression(node)) {\n const key = String(segment);\n const matches = (property: t.ObjectExpression['properties'][number]) =>\n t.isObjectProperty(property) &&\n !property.computed &&\n ((t.isIdentifier(property.key) && property.key.name === key) ||\n (t.isStringLiteral(property.key) && property.key.value === key) ||\n (t.isNumericLiteral(property.key) &&\n String(property.key.value) === key));\n // The last match is the one a duplicate key leaves in effect, and the\n // one `evaluateLiteral` reports.\n let index = node.properties.length - 1;\n\n while (index >= 0 && !matches(node.properties[index]!)) {\n index--;\n }\n\n const property = node.properties[index];\n\n if (\n !property ||\n !t.isObjectProperty(property) ||\n node.properties.slice(index + 1).some(item => t.isSpreadElement(item))\n ) {\n return null;\n }\n\n node = unwrapExpression(property.value);\n continue;\n }\n\n return null;\n }\n\n return node;\n};\n\nconst isEditableLeaf = (node: t.Node): boolean =>\n t.isStringLiteral(node) ||\n t.isNumericLiteral(node) ||\n t.isBooleanLiteral(node) ||\n (t.isUnaryExpression(node) &&\n node.operator === '-' &&\n t.isNumericLiteral(node.argument)) ||\n (t.isTemplateLiteral(node) && node.expressions.length === 0) ||\n t.isJSXElement(node) ||\n t.isJSXFragment(node);\n\nconst quoteString = (text: string, quote: string): string => {\n if (quote === '`') {\n return `\\`${text.replace(/[\\\\`]|\\$\\{/g, match => `\\\\${match}`)}\\``;\n }\n\n const escaped = JSON.stringify(text).slice(1, -1);\n\n return quote === '\"'\n ? `\"${escaped}\"`\n : `'${escaped.replace(/\\\\\"/g, '\"').replace(/'/g, \"\\\\'\")}'`;\n};\n\nconst isJSXSource = (text: string): boolean => {\n try {\n const expression = parseExpression(text, { plugins: ['jsx'] });\n\n return t.isJSXElement(expression) || t.isJSXFragment(expression);\n } catch {\n return false;\n }\n};\n\n// Source text for `next` in place of `leaf`, keeping the leaf's own form\n// where it has one: a string keeps its quotes, and a JSX leaf, which\n// `flattenEditableValue` reports as its source text, stays JSX when the\n// edited text still is.\nconst leafSource = (\n value: string,\n leaf: t.Node,\n next: EditablePrimitive,\n): string => {\n if (typeof next !== 'string') {\n return String(next);\n }\n\n if ((t.isJSXElement(leaf) || t.isJSXFragment(leaf)) && isJSXSource(next)) {\n return next.trim();\n }\n\n const quote =\n t.isStringLiteral(leaf) || t.isTemplateLiteral(leaf)\n ? value[leaf.start!]!\n : \"'\";\n\n return quoteString(next, quote);\n};\n\n// Replaces the leaf at `path` (as `flattenEditableValue` reports it) and\n// returns `value` with only that leaf's source changed, so formatting,\n// comments, JSX, functions and references stay (#427). The result is a\n// string for `PanelBinding.onChange`. A path it can't find, or a `value`\n// that doesn't parse, returns `value` unchanged. It never adds a key or\n// grows an array.\nexport const setEditableValue = (\n value: string,\n path: EditablePathSegment[],\n next: EditablePrimitive,\n): string => {\n if (!path.length) {\n return value;\n }\n\n let leaf: t.Node | null;\n\n try {\n leaf = findEditableLeaf(\n parseExpression(value, { plugins: ['jsx', 'typescript'] }),\n path,\n );\n } catch {\n return value;\n }\n\n if (\n !leaf ||\n !isEditableLeaf(leaf) ||\n leaf.start == null ||\n leaf.end == null\n ) {\n return value;\n }\n\n return `${value.slice(0, leaf.start)}${leafSource(value, leaf, next)}${value.slice(leaf.end)}`;\n};\n\n// The object or array literal at `path` in `value`, or `null` when the path\n// doesn't lead to one or `value` doesn't parse.\nconst findStructuredNode = (\n value: string,\n path: EditablePathSegment[],\n): t.ObjectExpression | t.ArrayExpression | null => {\n let node: t.Node | null;\n\n try {\n node = findEditableLeaf(\n parseExpression(value, { plugins: ['jsx', 'typescript'] }),\n path,\n );\n } catch {\n return null;\n }\n\n return node &&\n (t.isObjectExpression(node) || t.isArrayExpression(node)) &&\n node.start != null &&\n node.end != null\n ? node\n : null;\n};\n\n// The source of the object or array at `path`, as written, so an editor for\n// that nested value works on its source rather than on a reprint (#722).\nexport const getEditableSource = (\n value: string,\n path: EditablePathSegment[],\n): string | null => {\n const node = findStructuredNode(value, path);\n\n return node ? value.slice(node.start!, node.end!) : null;\n};\n\n// Replaces the object or array at `path` with `source` and keeps the rest of\n// `value` as written: what a nested editor's edit becomes in the value that\n// holds it (#722). `null` when the path doesn't lead to one.\nexport const setEditableSource = (\n value: string,\n path: EditablePathSegment[],\n source: string,\n): string | null => {\n const node = findStructuredNode(value, path);\n\n return node\n ? `${value.slice(0, node.start!)}${source}${value.slice(node.end!)}`\n : null;\n};\n","import { parseExpression } from '@babel/parser';\nimport * as t from '@babel/types';\n\nimport { BINDING_PROP, DATA_ATTR } from '../../constants';\nimport {\n BINDING_TYPES,\n type BindingItem,\n type BindingKeyMap,\n type BindingOption,\n type BindingOptions,\n type BindingRegistry,\n type BindingRenderLeaf,\n type BindingRenderMap,\n type BindingType,\n type BindingWidget,\n type DataAttrNode,\n} from './types';\nimport { evaluateLiteral, parseArrayExpression, parseValue } from './value';\n\n// Each check gives the value when it's well formed and `undefined` when it\n// isn't. Every key is checked on its own, so a malformed value becomes absent\n// instead of failing the whole binding, and a typo in `min` loses only `min`\n// (#234). Plain checks rather than a schema library, which cost every\n// consumer of `Live.Dnd` or `./utils/ast` about 17 KB gzip for these (#718).\ntype Check<T> = (value: unknown) => T | undefined;\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst string: Check<string> = value =>\n typeof value === 'string' ? value : undefined;\n\nconst boolean: Check<boolean> = value =>\n typeof value === 'boolean' ? value : undefined;\n\n// Finite only: `NaN` and `Infinity` are no bound or step.\nconst number: Check<number> = value =>\n typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n\nconst positiveNumber: Check<number> = value => {\n const checked = number(value);\n\n return checked !== undefined && checked > 0 ? checked : undefined;\n};\n\n// A length or an item count.\nconst count: Check<number> = value =>\n Number.isSafeInteger(value) && (value as number) >= 0\n ? (value as number)\n : undefined;\n\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2})?$/;\n\nconst date: Check<string> = value =>\n typeof value === 'string' && DATE.test(value) ? value : undefined;\n\nconst bindingType: Check<BindingType> = value =>\n (BINDING_TYPES as readonly unknown[]).includes(value)\n ? (value as BindingType)\n : undefined;\n\n// Non-empty strings, as a new array.\nconst protocols: Check<string[]> = value =>\n Array.isArray(value) &&\n value.every(item => typeof item === 'string' && item.length > 0)\n ? [...(value as string[])]\n : undefined;\n\n// `{ label, value }` and nothing else from the option.\nconst bindingOption: Check<BindingOption> = value =>\n isObject(value) &&\n typeof value.label === 'string' &&\n typeof value.value === 'string'\n ? { label: value.label, value: value.value }\n : undefined;\n\n// `widget.type` is any string, not an enum: the library implements no\n// widgets, so every value belongs to a custom panel (#236). The rest of the\n// object is kept, as that control's own config, such as\n// `{ type: 'slider', snapTo: [...] }`.\nconst bindingWidget: Check<BindingWidget> = value => {\n if (\n !isObject(value) ||\n typeof value.type !== 'string' ||\n value.type.length === 0\n ) {\n return undefined;\n }\n\n if (value.step !== undefined && number(value.step) === undefined) {\n return undefined;\n }\n\n if (value.unit !== undefined && typeof value.unit !== 'string') {\n return undefined;\n }\n\n return { ...value } as BindingWidget;\n};\n\n// Turns the string form (`widget: 'slider'`) into `{ type }`, so consumers\n// see one shape.\nconst sanitizeWidget = (value: unknown): BindingWidget | undefined => {\n if (typeof value === 'string') {\n return value ? { type: value } : undefined;\n }\n\n return bindingWidget(value);\n};\n\n// Drops only the malformed options and keeps the valid ones.\nconst sanitizeOptions = (value: unknown): BindingOption[] | undefined => {\n if (!Array.isArray(value)) {\n return undefined;\n }\n\n const options = value.flatMap(option => {\n const parsed = bindingOption(option);\n\n return parsed ? [parsed] : [];\n });\n\n return options.length > 0 ? options : undefined;\n};\n\n// Every key the library reads from a binding. Any other key is the app's\n// own and goes into `meta`.\nconst KNOWN_BINDING_KEYS = new Set([\n 'label',\n 'property',\n 'type',\n 'widget',\n 'options',\n 'render',\n 'min',\n 'max',\n 'pattern',\n 'patternMessage',\n 'required',\n 'minLength',\n 'maxLength',\n 'step',\n 'minItems',\n 'maxItems',\n 'minDate',\n 'maxDate',\n 'protocols',\n]);\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n// Sanitizes the fields a binding declares. Shared by top-level bindings and\n// render-map leaves, so a new field reaches both. Absent fields are left\n// off, not set to `undefined`.\nconst sanitizeField = (raw: Record<string, unknown>): BindingRenderLeaf => {\n const metaEntries = Object.entries(raw).filter(\n ([key]) => !KNOWN_BINDING_KEYS.has(key),\n );\n const field: BindingRenderLeaf = {\n label: string(raw.label),\n property: string(raw.property),\n type: bindingType(raw.type),\n widget: sanitizeWidget(raw.widget),\n options: sanitizeOptions(raw.options),\n render: sanitizeRenderMap(raw.render),\n min: number(raw.min),\n max: number(raw.max),\n pattern: string(raw.pattern),\n patternMessage: string(raw.patternMessage),\n required: boolean(raw.required),\n minLength: count(raw.minLength),\n maxLength: count(raw.maxLength),\n step: positiveNumber(raw.step),\n minItems: count(raw.minItems),\n maxItems: count(raw.maxItems),\n minDate: date(raw.minDate),\n maxDate: date(raw.maxDate),\n protocols: protocols(raw.protocols),\n meta: metaEntries.length > 0 ? Object.fromEntries(metaEntries) : undefined,\n };\n\n return Object.fromEntries(\n Object.entries(field).filter(([, value]) => value !== undefined),\n );\n};\n\n// A render map entry is a leaf (it has `type`) or a nested map. Anything\n// else is dropped, without failing the whole map.\nfunction sanitizeRenderMap(value: unknown): BindingRenderMap | undefined {\n if (!isPlainObject(value)) {\n return undefined;\n }\n\n const map: BindingRenderMap = {};\n\n for (const [key, raw] of Object.entries(value)) {\n if (!isPlainObject(raw)) {\n continue;\n }\n\n if ('type' in raw) {\n // Keep the `type` key even when its value was dropped, so\n // `'type' in leaf` still marks it as a leaf: an unknown type shows as a\n // plain field instead of disappearing (#234).\n map[key] = { type: undefined, ...sanitizeField(raw) };\n continue;\n }\n\n const nested = sanitizeRenderMap(raw);\n\n if (nested) {\n map[key] = nested;\n }\n }\n\n return Object.keys(map).length > 0 ? map : undefined;\n}\n\n// Validates an evaluated `data-binding` array into `BindingItem[]`. Used by\n// `parseBinding` (from a string) and `parseBindingExpression` (from an AST).\nconst buildBindingItems = (raw: unknown): BindingItem[] => {\n if (!Array.isArray(raw)) {\n return [];\n }\n\n return raw.flatMap(rawItem => {\n if (!isPlainObject(rawItem)) {\n return [];\n }\n\n const { label, property, ...field } = sanitizeField(rawItem);\n\n if (label === undefined) {\n return [];\n }\n\n if (property === undefined && field.type !== 'richtext') {\n return [];\n }\n\n return [{ label, property: property ?? BINDING_PROP.INNER_HTML, ...field }];\n });\n};\n\n// Registry entries are validated like an inline `data-binding`. Cached per\n// registry object, which a host defines once rather than every render.\nconst registryEntries = new WeakMap<\n BindingRegistry,\n Map<string, BindingItem[]>\n>();\n\n// Whether a tag name is a component rather than an HTML element, by JSX's\n// own rule: a member path, or an identifier that doesn't start with a\n// lowercase letter. A namespaced name (`svg:rect`) resolves to `''` and is\n// neither.\nexport const isComponentTagName = (tagName: string): boolean =>\n tagName !== '' && (tagName.includes('.') || !/^[a-z]/.test(tagName));\n\n// The bindings `registry` gives an element of `tagName`, or `undefined` when\n// it has no entry for that component. HTML elements never match, even when\n// the registry has a key for them.\nexport const getRegistryBindings = (\n registry: BindingRegistry | undefined,\n tagName: string,\n): BindingItem[] | undefined => {\n if (!registry) {\n return undefined;\n }\n\n let entries = registryEntries.get(registry);\n\n if (!entries) {\n entries = new Map();\n registryEntries.set(registry, entries);\n\n // Once per registry, so a key the type would have rejected doesn't go\n // unnoticed in plain JavaScript or behind a cast.\n const ignored = Object.keys(registry).filter(\n key => !isComponentTagName(key),\n );\n\n if (ignored.length > 0) {\n console.warn(\n `Live.Dnd \\`bindings\\` only applies to components. Ignored: ${ignored.join(', ')}. Bind an HTML element with its own data-binding.`,\n );\n }\n }\n\n if (!isComponentTagName(tagName) || !Object.hasOwn(registry, tagName)) {\n return undefined;\n }\n\n let bindings = entries.get(tagName);\n\n if (!bindings) {\n bindings = buildBindingItems(\n (registry as Record<string, BindingItem[] | undefined>)[tagName],\n );\n entries.set(tagName, bindings);\n }\n\n return bindings;\n};\n\n// Key map entries are validated like inline ones and cached per map, as\n// registry entries are.\nconst keyEntries = new WeakMap<BindingKeyMap, Map<string, BindingItem[]>>();\n\n// Each problem is reported once per key, not on every read of a section.\nconst warnedKeys = new Set<string>();\n\nconst warnOnce = (id: string, message: string) => {\n if (!warnedKeys.has(id)) {\n warnedKeys.add(id);\n console.warn(message);\n }\n};\n\n// The bindings `bindingKeys` has under `key`, or `undefined` when it has no\n// such entry.\nexport const getKeyBindings = (\n bindingKeys: BindingKeyMap | undefined,\n key: string,\n): BindingItem[] | undefined => {\n if (!bindingKeys || !Object.hasOwn(bindingKeys, key)) {\n return undefined;\n }\n\n let entries = keyEntries.get(bindingKeys);\n\n if (!entries) {\n entries = new Map();\n keyEntries.set(bindingKeys, entries);\n }\n\n let bindings = entries.get(key);\n\n if (!bindings) {\n bindings = buildBindingItems(bindingKeys[key]);\n entries.set(key, bindings);\n }\n\n return bindings;\n};\n\n// One element's bindings, from the most specific source it has (#513):\n//\n// 1. `own`, its `data-binding`, parsed. `undefined` when it has none; an\n// empty array is still its own, which is how an element opts out.\n// 2. `key`, the string its `data-binding-key` names in `bindingKeys`.\n// `undefined` without the attribute, `null` when the attribute isn't a\n// plain string. A key with no entry gives no fields rather than falling\n// through to the registry.\n// 3. Its component's entry in `bindings`.\nexport const resolveBindings = (\n own: BindingItem[] | undefined,\n key: string | null | undefined,\n tagName: string,\n options: BindingOptions = {},\n): BindingItem[] => {\n if (own) {\n if (key !== undefined) {\n warnOnce(\n `both:${key}`,\n `Live.Dnd: an element has both data-binding and data-binding-key=\"${key ?? ''}\". Its data-binding is used; remove one of them.`,\n );\n }\n\n return own;\n }\n\n if (key === null) {\n warnOnce(\n 'not-a-string',\n 'Live.Dnd: data-binding-key must be a plain string, such as data-binding-key=\"hero-title\". The element has no fields.',\n );\n\n return [];\n }\n\n if (key !== undefined) {\n const bindings = getKeyBindings(options.bindingKeys, key);\n\n if (!bindings) {\n warnOnce(\n `missing:${key}`,\n `Live.Dnd: data-binding-key=\"${key}\" isn't in bindingKeys. The element has no fields.`,\n );\n }\n\n return bindings ?? [];\n }\n\n return getRegistryBindings(options.bindings, tagName) ?? [];\n};\n\nexport const parseBinding = (bindingValue: string | null): BindingItem[] => {\n if (!bindingValue) {\n return [];\n }\n\n const ast = parseArrayExpression(bindingValue);\n\n if (!ast) {\n return [];\n }\n\n return buildBindingItems(evaluateLiteral(ast));\n};\n\n// `parseBinding` for an array expression that is already parsed, as\n// `extract` has it. Saves printing it and parsing it again (#241).\nexport const parseBindingExpression = (\n expression: t.ArrayExpression,\n): BindingItem[] => buildBindingItems(evaluateLiteral(expression));\n\nexport const getCurrentValue = (\n node: DataAttrNode,\n property: string,\n): string => {\n switch (property) {\n case BINDING_PROP.INNER_TEXT: {\n return node.textContent || '';\n }\n\n case BINDING_PROP.INNER_HTML: {\n // A `richtext` value lives in `dangerouslySetInnerHTML={{ __html }}`.\n const dsiAttr = node.attributes.find(\n a => a.name === 'dangerouslySetInnerHTML',\n );\n if (dsiAttr?.value) {\n try {\n const expr = parseExpression(dsiAttr.value, {\n plugins: ['jsx', 'typescript'],\n });\n if (t.isObjectExpression(expr)) {\n const htmlProp = expr.properties.find(\n p =>\n t.isObjectProperty(p) &&\n t.isIdentifier(p.key) &&\n p.key.name === '__html',\n ) as t.ObjectProperty | undefined;\n if (htmlProp) {\n if (t.isStringLiteral(htmlProp.value)) {\n return htmlProp.value.value;\n }\n if (\n t.isTemplateLiteral(htmlProp.value) &&\n htmlProp.value.expressions.length === 0\n ) {\n return (\n htmlProp.value.quasis[0]?.value.cooked ??\n htmlProp.value.quasis[0]?.value.raw ??\n ''\n );\n }\n }\n }\n } catch {\n // Not a readable object: fall back to the children below.\n }\n }\n return node.rawChildren || node.textContent || '';\n }\n\n case BINDING_PROP.CHILDREN: {\n return JSON.stringify(node?.children || []);\n }\n\n default: {\n const customAttr = node.attributes.find(attr => attr.name === property);\n const value = customAttr?.value || '';\n\n return value;\n }\n }\n};\n\n// Types whose value stays a string, even when the text looks like a number\n// or an object. `jsx` and `richtext` hold source code, which `update` writes\n// back as an expression.\nexport const STRING_VALUED_TYPES: ReadonlySet<BindingType> = new Set([\n 'string',\n 'url',\n 'email',\n 'tel',\n 'date',\n 'time',\n 'datetime',\n 'color',\n 'jsx',\n 'richtext',\n]);\n\n// The value as its JS type (number, boolean, object, array or string), for\n// `PanelBinding.value`. `getCurrentValue` gives the source text, for\n// `PanelBinding.rawValue` (#238). A string literal in the source stays a\n// string whatever it contains; only expressions such as `count={3}` or\n// `data={[...]}` are read into their real shape.\nexport const getStructuredValue = (\n node: DataAttrNode,\n property: string,\n type?: BindingType,\n): unknown => {\n switch (property) {\n case BINDING_PROP.INNER_TEXT:\n case BINDING_PROP.INNER_HTML: {\n return getCurrentValue(node, property);\n }\n\n case BINDING_PROP.CHILDREN: {\n return node.children ?? [];\n }\n\n default: {\n const raw = getCurrentValue(node, property);\n const attr = node.attributes.find(a => a.name === property);\n\n if (attr?.isStringLiteral || (type && STRING_VALUED_TYPES.has(type))) {\n return raw;\n }\n\n return parseValue(raw);\n }\n }\n};\n\n// The node's bindings. `extract()` resolves them from all three sources\n// (#509, #513); a node built some other way may only have its\n// `data-binding` attribute, which is parsed here.\nexport const readNodeBindings = (node: DataAttrNode): BindingItem[] => {\n if (node.bindings) {\n return node.bindings;\n }\n\n const bindingAttr = node.dataAttributes.find(\n attr => attr.name === DATA_ATTR.BINDING,\n );\n\n return bindingAttr?.value ? parseBinding(bindingAttr.value) : [];\n};\n\nconst hasEditableBindings = (node: DataAttrNode): boolean =>\n readNodeBindings(node).length > 0;\n\nexport const findEditableChildren = (node: DataAttrNode): DataAttrNode[] => {\n const editableChildren: DataAttrNode[] = [];\n\n const traverse = (children: DataAttrNode[] | undefined) => {\n if (!children) {\n return;\n }\n\n for (const child of children) {\n if (hasEditableBindings(child)) {\n editableChildren.push(child);\n }\n traverse(child.children);\n }\n };\n\n traverse(node.children);\n\n return editableChildren;\n};\n","export const removeIndices = <T>(items: T[], indices: Set<number>): T[] => {\n return items.filter((_, index) => !indices.has(index));\n};\n\n/**\n * Shifts every selected index up/down by one step as a block, preserving\n * relative order — scattered selections stop moving individually once they\n * hit an unselected neighbor, so the whole group slides together instead of\n * items passing through each other.\n */\nexport const moveSelectedIndices = <T>(\n items: T[],\n indices: Set<number>,\n direction: 'up' | 'down',\n): { items: T[]; indices: Set<number> } => {\n const next = [...items];\n const nextIndices = new Set(indices);\n\n const ordered = [...indices].sort((a, b) =>\n direction === 'up' ? a - b : b - a,\n );\n\n for (const index of ordered) {\n const target = direction === 'up' ? index - 1 : index + 1;\n\n if (target < 0 || target >= next.length || nextIndices.has(target)) {\n continue;\n }\n\n [next[index], next[target]] = [next[target]!, next[index]!];\n nextIndices.delete(index);\n nextIndices.add(target);\n }\n\n return { items: next, indices: nextIndices };\n};\n","import { parse } from '@babel/parser';\nimport * as t from '@babel/types';\nimport { nanoid } from 'nanoid';\n\nimport { BINDING_PROP, CONFIG, DATA_ATTR } from '../../constants';\nimport { type BoundedCache, createBoundedCache } from '../cache';\nimport { registerEditorCache } from '../editor-caches';\nimport {\n parseBinding,\n parseBindingExpression,\n resolveBindings,\n} from './binding';\nimport { traverse } from './document';\nimport { attrValue, generateCode, wrap } from './helpers';\nimport { getJSXTagName } from './jsx-name';\nimport type {\n Attribute,\n BindingItem,\n BindingOptions,\n DataAttrNode,\n} from './types';\nimport { unwrapExpression } from './value';\n\nconst collectText = (\n children: (\n | t.JSXText\n | t.JSXExpressionContainer\n | t.JSXElement\n | t.JSXFragment\n | t.JSXSpreadChild\n )[],\n) => {\n return children\n .filter(c => t.isJSXText(c))\n .map(c => (c as t.JSXText).value.trim())\n .filter(v => v.length)\n .join(' ');\n};\n\nconst parseJSXName = (\n tagName: string,\n): t.JSXIdentifier | t.JSXMemberExpression => {\n const parts = tagName.split('.');\n\n if (parts.length === 1) {\n return t.jsxIdentifier(parts[0]!);\n }\n\n let expr: t.JSXIdentifier | t.JSXMemberExpression = t.jsxIdentifier(\n parts[0]!,\n );\n\n for (let i = 1; i < parts.length; i++) {\n expr = t.jsxMemberExpression(expr, t.jsxIdentifier(parts[i]!));\n }\n\n return expr;\n};\n\nconst extractCache = createBoundedCache<string, DataAttrNode[]>(\n CONFIG.CACHE_LIMIT,\n);\n\n// One cache per combination of `bindings` and `bindingKeys`, since they\n// change what the same source extracts to (#509, #513). An absent map is\n// keyed by `NO_MAP`.\nconst NO_MAP = {};\nlet optionExtractCaches = new WeakMap<\n object,\n WeakMap<object, BoundedCache<string, DataAttrNode[]>>\n>();\n\nconst cacheFor = ({ bindings, bindingKeys }: BindingOptions) => {\n if (!bindings && !bindingKeys) {\n return extractCache;\n }\n\n let byKeys = optionExtractCaches.get(bindings ?? NO_MAP);\n\n if (!byKeys) {\n byKeys = new WeakMap();\n optionExtractCaches.set(bindings ?? NO_MAP, byKeys);\n }\n\n let cache = byKeys.get(bindingKeys ?? NO_MAP);\n\n if (!cache) {\n cache = createBoundedCache<string, DataAttrNode[]>(CONFIG.CACHE_LIMIT);\n byKeys.set(bindingKeys ?? NO_MAP, cache);\n }\n\n return cache;\n};\n\nconst extractAttributes = (\n attributes: (t.JSXAttribute | t.JSXSpreadAttribute)[],\n source?: string,\n): { allAttrs: Attribute[]; dataAttrs: Attribute[] } => {\n const allAttrs: Attribute[] = [];\n const dataAttrs: Attribute[] = [];\n\n for (const attr of attributes) {\n if (!t.isJSXAttribute(attr) || !t.isJSXIdentifier(attr.name)) {\n continue;\n }\n\n const name = attr.name.name;\n let value: string | null = null;\n let isStringLiteral = false;\n\n if (attr.value) {\n if (t.isStringLiteral(attr.value)) {\n value = attr.value.value;\n isStringLiteral = true;\n } else if (t.isJSXExpressionContainer(attr.value)) {\n try {\n const expression = attr.value.expression;\n const structural =\n t.isArrayExpression(unwrapExpression(expression)) ||\n t.isObjectExpression(unwrapExpression(expression));\n value =\n source &&\n structural &&\n expression.start != null &&\n expression.end != null\n ? source.slice(expression.start, expression.end)\n : generateCode(expression);\n isStringLiteral = false;\n } catch {\n value = null;\n }\n }\n }\n\n const entry = { name, value, isStringLiteral };\n\n allAttrs.push(entry);\n\n if (name.startsWith('data-')) {\n dataAttrs.push(entry);\n }\n }\n\n return { allAttrs, dataAttrs };\n};\n\nconst buildChildElements = (\n node: DataAttrNode,\n): (t.JSXText | t.JSXElement | t.JSXFragment)[] => {\n const childElements: (t.JSXText | t.JSXElement | t.JSXFragment)[] = [];\n\n if (node.textContent) {\n childElements.push(t.jsxText(node.textContent));\n }\n\n node.children?.forEach(child => {\n const childJSX = nodeToJSX(child);\n if (childJSX) {\n childElements.push(childJSX);\n }\n });\n\n return childElements;\n};\n\nexport const nodeToJSX = (\n node: DataAttrNode,\n): t.JSXElement | t.JSXFragment | null => {\n try {\n if (node.isFragment) {\n const childElements = buildChildElements(node);\n\n return t.jsxFragment(\n t.jsxOpeningFragment(),\n t.jsxClosingFragment(),\n childElements,\n );\n }\n\n if (\n node.tagName === 'div' &&\n node.dataAttributes.some(attr => attr.name === 'data-item')\n ) {\n if (node.children) {\n return nodeToJSX(node.children[0]!);\n }\n return null;\n }\n\n const attributes = node.attributes.map(attr => {\n const attrName = t.jsxIdentifier(attr.name);\n\n if (!attr.value) {\n return t.jsxAttribute(attrName, null);\n }\n\n return t.jsxAttribute(attrName, attrValue(attr));\n });\n\n const elementName = parseJSXName(node.tagName);\n\n const openingElement = t.jsxOpeningElement(elementName, attributes);\n\n const closingElement = t.jsxClosingElement(elementName);\n const children = buildChildElements(node);\n\n return t.jsxElement(openingElement, closingElement, children);\n } catch (error) {\n console.error('❌ DataAttrNode to JSX conversion error:', error);\n return null;\n }\n};\n\nconst createWrapperNode = (\n textContent: string,\n children: DataAttrNode[],\n): DataAttrNode => ({\n tagName: 'div',\n id: nanoid(6),\n attributes: [{ name: DATA_ATTR.ITEM, value: 'true' }],\n dataAttributes: [{ name: DATA_ATTR.ITEM, value: 'true' }],\n textContent,\n children,\n});\n\nconst createFragmentNode = (\n textContent: string,\n children: DataAttrNode[],\n): DataAttrNode => ({\n tagName: '',\n id: nanoid(6),\n attributes: [],\n dataAttributes: [],\n textContent,\n children,\n isFragment: true,\n});\n\nconst processChildrenBinding = (\n jsxElement: t.JSXElement,\n processedNodes?: WeakSet<t.JSXElement | t.JSXFragment>,\n shouldWrap: boolean = true,\n source?: string,\n options?: BindingOptions,\n): DataAttrNode[] | undefined => {\n const jsxChildren = jsxElement.children.filter(\n child => t.isJSXElement(child) || t.isJSXFragment(child),\n );\n\n if (!jsxChildren.length) {\n return undefined;\n }\n\n const childrenNodes: DataAttrNode[] = [];\n\n jsxChildren.forEach(child => {\n if (t.isJSXElement(child)) {\n const childResults = extractFromNode(\n child,\n processedNodes,\n source,\n options,\n );\n\n if (shouldWrap) {\n const wrapperNode = createWrapperNode(\n collectText(child.children),\n childResults,\n );\n wrapperNode.source = source?.slice(child.start!, child.end!);\n const dataId = childResults[0]?.dataAttributes.find(\n attr => attr.name === DATA_ATTR.ID,\n )?.value;\n\n if (dataId) {\n wrapperNode.id = `child:${dataId}`;\n }\n\n childrenNodes.push(wrapperNode);\n } else {\n childrenNodes.push(...childResults);\n }\n } else if (t.isJSXFragment(child)) {\n processedNodes?.add(child);\n\n const fragmentChildren: DataAttrNode[] = [];\n\n child.children.forEach(fragmentChild => {\n if (t.isJSXElement(fragmentChild)) {\n const childResults = extractFromNode(\n fragmentChild,\n processedNodes,\n source,\n options,\n );\n fragmentChildren.push(...childResults);\n }\n });\n\n if (fragmentChildren.length) {\n const fragmentNode = createFragmentNode(\n collectText(child.children),\n fragmentChildren,\n );\n fragmentNode.source = source?.slice(child.start!, child.end!);\n childrenNodes.push(fragmentNode);\n }\n }\n });\n\n return childrenNodes.length ? childrenNodes : undefined;\n};\n\nconst skipItemsChildren = (\n jsxElement: t.JSXElement,\n processedNodes: WeakSet<t.JSXElement | t.JSXFragment>,\n propertyName: string = 'items',\n): void => {\n const opening = jsxElement.openingElement;\n\n const itemsAttr = opening.attributes.find(\n attr =>\n t.isJSXAttribute(attr) &&\n t.isJSXIdentifier(attr.name) &&\n attr.name.name === propertyName,\n );\n\n if (!itemsAttr || !t.isJSXAttribute(itemsAttr)) {\n return;\n }\n\n if (\n itemsAttr.value &&\n t.isJSXExpressionContainer(itemsAttr.value) &&\n t.isArrayExpression(itemsAttr.value.expression)\n ) {\n const arrayExpr = itemsAttr.value.expression;\n\n arrayExpr.elements.forEach(element => {\n if (t.isObjectExpression(element)) {\n element.properties.forEach(prop => {\n if (\n t.isObjectProperty(prop) &&\n t.isIdentifier(prop.key) &&\n t.isJSXElement(prop.value)\n ) {\n markProcessedJSX(prop.value, processedNodes);\n }\n });\n }\n });\n }\n};\n\nconst markProcessedJSX = (\n node: t.Node,\n processedNodes: WeakSet<t.JSXElement | t.JSXFragment>,\n): void => {\n if (t.isJSXElement(node) || t.isJSXFragment(node)) {\n processedNodes.add(node as t.JSXElement | t.JSXFragment);\n node.children.forEach(child => markProcessedJSX(child, processedNodes));\n return;\n }\n\n const expression =\n t.isJSXExpressionContainer(node) || t.isParenthesizedExpression(node);\n\n if (expression) {\n markProcessedJSX(node.expression, processedNodes);\n }\n};\n\ninterface NodeBindingInfo {\n tagName: string;\n allAttrs: Attribute[];\n dataAttrs: Attribute[];\n bindings: BindingItem[];\n childrenBinding: BindingItem | undefined;\n arrayBindings: BindingItem[];\n rawChildren: string | undefined;\n}\n\n// The `data-binding` array expression, so bindings can be read from the AST\n// without printing and parsing it again. `null` when the attribute is\n// missing or a plain string, which goes through `parseBinding` instead.\nconst getBindingExpression = (\n opening: t.JSXOpeningElement,\n): t.ArrayExpression | null => {\n for (const attr of opening.attributes) {\n if (\n t.isJSXAttribute(attr) &&\n t.isJSXIdentifier(attr.name) &&\n attr.name.name === DATA_ATTR.BINDING &&\n attr.value &&\n t.isJSXExpressionContainer(attr.value)\n ) {\n // Unwrap `satisfies BindingItem[]`, `as const` and parentheses.\n const expression = unwrapExpression(attr.value.expression);\n\n if (t.isArrayExpression(expression)) {\n return expression;\n }\n }\n }\n\n return null;\n};\n\n// Reads one element's tag name, attributes and bindings. Shared by the\n// top-level visitor in `parseToNodes` and by `extractFromNode`.\nconst readNodeBindingInfo = (\n node: t.JSXElement,\n source?: string,\n options?: BindingOptions,\n): NodeBindingInfo => {\n const opening = node.openingElement;\n const tagName = getJSXTagName(opening);\n const { allAttrs, dataAttrs } = extractAttributes(opening.attributes, source);\n\n const bindingAttr = dataAttrs.find(attr => attr.name === DATA_ATTR.BINDING);\n const bindingExpr = getBindingExpression(opening);\n const keyAttr = dataAttrs.find(attr => attr.name === DATA_ATTR.BINDING_KEY);\n // Its own `data-binding` first, even an empty one (how an element opts\n // out), then its `data-binding-key`, then its component's entry\n // (#509, #513).\n const bindings = resolveBindings(\n bindingExpr\n ? parseBindingExpression(bindingExpr)\n : bindingAttr\n ? parseBinding(bindingAttr.value)\n : undefined,\n keyAttr && (keyAttr.isStringLiteral ? keyAttr.value : null),\n tagName,\n options,\n );\n\n const childrenBinding = bindings.find(\n b => b.property === BINDING_PROP.CHILDREN,\n );\n const arrayBindings = bindings.filter(\n b => b.property === BINDING_PROP.ITEMS || b.type === 'array',\n );\n\n const innerHtmlBinding = bindings.find(\n b => b.property === BINDING_PROP.INNER_HTML,\n );\n\n let rawChildren: string | undefined;\n if (innerHtmlBinding && node.children.length > 0) {\n rawChildren = node.children\n .map(child => generateCode(child))\n .join('')\n .trim();\n }\n\n return {\n tagName,\n allAttrs,\n dataAttrs,\n bindings,\n childrenBinding,\n arrayBindings,\n rawChildren,\n };\n};\n\nconst parseToNodes = (\n raw: string,\n options?: BindingOptions,\n): DataAttrNode[] => {\n const wrapped = wrap(raw);\n const ast = parse(wrapped, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n errorRecovery: true,\n });\n\n const results: DataAttrNode[] = [];\n\n // Elements already recorded as another result's children, or skipped\n // inside an `items` array. `traverse()` visits every element, so the\n // visitor skips these to avoid recording them twice.\n const processedNodes = new WeakSet<t.JSXElement | t.JSXFragment>();\n\n traverse(ast, {\n JSXElement(path) {\n if (processedNodes.has(path.node)) {\n return;\n }\n\n const {\n tagName,\n allAttrs,\n dataAttrs,\n bindings,\n childrenBinding,\n arrayBindings,\n rawChildren,\n } = readNodeBindingInfo(path.node, wrapped, options);\n\n if (!tagName || !dataAttrs.length) {\n return;\n }\n\n let childrenNodes: DataAttrNode[] | undefined;\n\n if (childrenBinding) {\n childrenNodes = processChildrenBinding(\n path.node,\n processedNodes,\n true,\n wrapped,\n options,\n );\n }\n\n for (const arrayBinding of arrayBindings) {\n skipItemsChildren(path.node, processedNodes, arrayBinding.property);\n }\n\n results.push({\n tagName,\n attributes: allAttrs,\n dataAttributes: dataAttrs,\n textContent: collectText(path.node.children),\n rawChildren,\n children: childrenNodes,\n bindings,\n loc: path.node.loc\n ? {\n start: {\n line: path.node.loc.start.line,\n column: path.node.loc.start.column,\n },\n end: {\n line: path.node.loc.end.line,\n column: path.node.loc.end.column,\n },\n }\n : undefined,\n });\n },\n });\n\n return results;\n};\n\n// The elements of `raw` that carry `data-*` attributes, with their\n// bindings, as `DataAttrNode`s. Cached. `options` supplies bindings for\n// elements without their own `data-binding` (#509, #513).\nexport function extract(\n raw: string,\n options: BindingOptions = {},\n): DataAttrNode[] {\n const cache = cacheFor(options);\n\n if (cache.has(raw)) {\n return cache.get(raw)!;\n }\n\n const results = parseToNodes(raw, options);\n\n cache.set(raw, results);\n\n return results;\n}\n\nfunction extractFromNode(\n node: t.JSXElement,\n processedNodes?: WeakSet<t.JSXElement | t.JSXFragment>,\n source?: string,\n options?: BindingOptions,\n): DataAttrNode[] {\n processedNodes?.add(node);\n\n const {\n tagName,\n allAttrs,\n dataAttrs,\n bindings,\n childrenBinding,\n arrayBindings,\n rawChildren,\n } = readNodeBindingInfo(node, source, options);\n\n // The Items editor reads the JSX inside an array value itself, as the\n // top-level visitor does: listing it here too shows it twice (#308, #723).\n if (processedNodes) {\n for (const arrayBinding of arrayBindings) {\n skipItemsChildren(node, processedNodes, arrayBinding.property);\n }\n }\n\n let childrenNodes: DataAttrNode[] | undefined;\n\n if (childrenBinding) {\n childrenNodes = processChildrenBinding(\n node,\n processedNodes,\n true,\n source,\n options,\n );\n }\n\n if (!childrenNodes) {\n childrenNodes = processChildrenBinding(\n node,\n processedNodes,\n false,\n source,\n options,\n );\n }\n\n return [\n {\n tagName,\n attributes: allAttrs,\n dataAttributes: dataAttrs,\n textContent: collectText(node.children),\n rawChildren,\n children: childrenNodes,\n bindings,\n },\n ];\n}\n\nexport function clearExtractCache() {\n extractCache.clear();\n optionExtractCaches = new WeakMap();\n}\n\nregisterEditorCache(clearExtractCache);\n","import { parseExpression } from '@babel/parser';\nimport * as t from '@babel/types';\nimport { nanoid } from 'nanoid';\n\nimport { moveSelectedIndices } from '../selection';\nimport { extract, nodeToJSX } from './extract';\nimport { generateCode } from './helpers';\nimport { type SourceEdit, applyEdits } from './patch';\nimport type { BindingOptions, DataAttrNode } from './types';\n\nexport type ChildrenAction =\n | { type: 'move'; from: number; to: number }\n | { type: 'move-selected'; indices: number[]; direction: 'up' | 'down' }\n | { type: 'remove' | 'duplicate'; indices: number[] }\n | { type: 'append' };\n\nexport interface ChildrenEdit {\n kind: 'children-edit';\n expected: string[];\n action: ChildrenAction;\n}\n\n// Signatures address the extracted list, not synthetic wrapper IDs. The\n// source editor checks them against the latest parent before using indices.\nconst modeledSignatures = (nodes: DataAttrNode[]): string[] =>\n nodes.map(node => {\n const jsx = nodeToJSX(node);\n\n if (!jsx) {\n throw new Error('Invalid child node');\n }\n\n return generateCode(jsx);\n });\n\nexport const getChildrenSignatures = (nodes: DataAttrNode[]): string[] => {\n const modeled = modeledSignatures(nodes);\n\n return nodes.map((node, index) =>\n JSON.stringify([node.source ?? null, modeled[index]]),\n );\n};\n\nconst indicesAreValid = (\n indices: unknown,\n count: number,\n): indices is number[] =>\n Array.isArray(indices) &&\n new Set(indices).size === indices.length &&\n indices.every(\n index => Number.isInteger(index) && index >= 0 && index < count,\n );\n\n// Only ID attributes are replaced: expressions, spreads, comments and text\n// in a copied subtree retain their exact source. Dynamic IDs are ambiguous.\nconst copySource = (source: string, usedIds: Set<string>): string => {\n const node = parseExpression(source, { plugins: ['jsx', 'typescript'] });\n const edits: SourceEdit[] = [];\n const newId = () => {\n let id = nanoid(12);\n\n while (usedIds.has(id)) {\n id = nanoid(12);\n }\n\n usedIds.add(id);\n\n return id;\n };\n\n t.traverseFast(node, child => {\n if (!t.isJSXOpeningElement(child)) {\n return;\n }\n\n const ids = child.attributes.filter(\n (attr): attr is t.JSXAttribute =>\n t.isJSXAttribute(attr) &&\n t.isJSXIdentifier(attr.name, { name: 'data-id' }),\n );\n\n if (ids.length > 1) {\n throw new Error('Duplicate data-id attributes');\n }\n\n const attr = ids[0];\n\n if (\n attr &&\n child.attributes\n .slice(child.attributes.indexOf(attr) + 1)\n .some(attribute => t.isJSXSpreadAttribute(attribute))\n ) {\n throw new Error('A spread may override the copied data-id');\n }\n\n if (attr) {\n const value = attr.value;\n\n if (\n !t.isStringLiteral(value) ||\n value.start == null ||\n value.end == null\n ) {\n throw new Error('Cannot copy a dynamic data-id');\n }\n\n edits.push({\n start: value.start,\n end: value.end,\n content: JSON.stringify(newId()),\n });\n } else {\n const at = child.attributes.at(-1)?.end ?? child.name.end;\n\n if (at == null) {\n throw new Error('Missing opening element span');\n }\n\n edits.push({\n start: at,\n end: at,\n content: ` data-id=\"${newId()}\"`,\n });\n }\n });\n\n return applyEdits(source, edits);\n};\n\n// The edit that adds new children after the existing ones. In a parent\n// written one child per line, each new child goes on its own line under the\n// last one, with the same indentation and line ending, so the list keeps its\n// layout. Anything else, such as a parent on one line or a comment after the\n// last child on its line, puts them right before the closing tag, where\n// nothing around them can move.\nconst insertChildren = (\n source: string,\n parent: t.JSXElement,\n last: t.JSXElement | t.JSXFragment | undefined,\n copies: string[],\n): SourceEdit => {\n const closing = parent.closingElement!.start!;\n\n if (last?.start != null && last.end != null) {\n const lineStart = source.lastIndexOf('\\n', last.start - 1) + 1;\n const indent = source.slice(lineStart, last.start);\n const after = /^[ \\t]*(\\r?\\n)/.exec(source.slice(last.end, closing));\n\n if (after && /^[ \\t]*$/.test(indent)) {\n return {\n start: last.end,\n end: last.end,\n content: copies.map(copy => `${after[1]}${indent}${copy}`).join(''),\n };\n }\n }\n\n return { start: closing, end: closing, content: copies.join('') };\n};\n\n// Coordinates refer to the caller's wrapped source, just like other update\n// editors. Non-element gaps stay at their original positions; moving a JSX\n// child moves its entire subtree but never regenerates intervening content.\nexport const editChildrenSource = (\n source: string,\n parent: t.JSXElement,\n input: unknown,\n // The binding sources the caller extracted the children with, so they're\n // modeled the same way here (#509, #513).\n options?: BindingOptions,\n): SourceEdit[] | null => {\n try {\n if (!parent.closingElement || parent.start == null || parent.end == null) {\n return null;\n }\n\n const value = typeof input === 'string' ? JSON.parse(input) : input;\n const children = parent.children.filter(\n (child): child is t.JSXElement | t.JSXFragment =>\n t.isJSXElement(child) || t.isJSXFragment(child),\n );\n const raw = children.map(child => source.slice(child.start!, child.end!));\n const models =\n extract(source.slice(parent.start, parent.end), options)[0]?.children ??\n [];\n\n // The extractor currently omits some empty/expression-only fragments.\n // Never interpret its visible indices as different source children.\n if (models.length !== children.length) {\n return null;\n }\n\n const signatures = modeledSignatures(models);\n const replaceSlots = (next: string[]): SourceEdit[] => {\n const edits = children.map((child, index) => ({\n start: child.start!,\n end: child.end!,\n content: next[index] ?? '',\n }));\n\n if (next.length > children.length) {\n edits.push(\n insertChildren(\n source,\n parent,\n children.at(-1),\n next.slice(children.length),\n ),\n );\n }\n\n return edits;\n };\n\n if (Array.isArray(value)) {\n // A full list of children (the JSON form). Unchanged children keep\n // their original source; other replacements are allowed only when\n // every original child can be represented without loss.\n const desired = modeledSignatures(value);\n const lossless = raw.every(\n (text, index) =>\n generateCode(\n parseExpression(text, { plugins: ['jsx', 'typescript'] }),\n ) === signatures[index],\n );\n const consumed = new Set<number>();\n const next = desired.map((signature, position) => {\n const index = signatures.findIndex(\n (candidate, i) =>\n candidate === signature &&\n !consumed.has(i) &&\n (value[position].source === undefined ||\n value[position].source === raw[i]),\n );\n\n if (index >= 0) {\n consumed.add(index);\n\n return raw[index]!;\n }\n\n if (\n !lossless ||\n (value[position].source !== undefined &&\n !raw.includes(value[position].source))\n ) {\n throw new Error(\n 'Use children commands to copy or edit unsupported source',\n );\n }\n\n return signature;\n });\n\n // The list may contain new children. Refuse a repeated `data-id`,\n // which would make later edits ambiguous.\n const countIds = (text: string) => {\n const counts = new Map<string, number>();\n t.traverseFast(\n parseExpression(text, { plugins: ['jsx', 'typescript'] }),\n node => {\n if (\n t.isJSXAttribute(node) &&\n t.isJSXIdentifier(node.name, { name: 'data-id' }) &&\n t.isStringLiteral(node.value)\n ) {\n counts.set(\n node.value.value,\n (counts.get(node.value.value) ?? 0) + 1,\n );\n }\n },\n );\n\n return counts;\n };\n const previousIds = countIds(source);\n const updatedParent = applyEdits(source, replaceSlots(next));\n const nextIds = countIds(updatedParent);\n\n if (\n [...nextIds].some(\n ([id, count]) => count > 1 && count > (previousIds.get(id) ?? 0),\n )\n ) {\n return null;\n }\n\n return replaceSlots(next);\n }\n\n const request = value as ChildrenEdit | null;\n\n if (\n request?.kind !== 'children-edit' ||\n !Array.isArray(request.expected) ||\n request.expected.length !== signatures.length ||\n !getChildrenSignatures(models).every(\n (signature, index) => signature === request.expected[index],\n ) ||\n !request.action\n ) {\n return null;\n }\n\n const { action } = request;\n const usedIds = new Set<string>();\n\n t.traverseFast(parent, node => {\n if (\n t.isJSXAttribute(node) &&\n t.isJSXIdentifier(node.name, { name: 'data-id' }) &&\n t.isStringLiteral(node.value)\n ) {\n usedIds.add(node.value.value);\n }\n });\n\n switch (action.type) {\n case 'move': {\n if (\n !indicesAreValid([action.from], raw.length) ||\n !indicesAreValid([action.to], raw.length)\n ) {\n return null;\n }\n\n const next = [...raw];\n const [moved] = next.splice(action.from, 1);\n next.splice(action.to, 0, moved!);\n\n return replaceSlots(next);\n }\n case 'move-selected': {\n if (\n !indicesAreValid(action.indices, raw.length) ||\n !['up', 'down'].includes(action.direction)\n ) {\n return null;\n }\n\n return replaceSlots(\n moveSelectedIndices(raw, new Set(action.indices), action.direction)\n .items,\n );\n }\n case 'remove': {\n if (!indicesAreValid(action.indices, raw.length)) {\n return null;\n }\n\n return action.indices.map(index => ({\n start: children[index]!.start!,\n end: children[index]!.end!,\n content: '',\n }));\n }\n case 'duplicate': {\n if (!indicesAreValid(action.indices, raw.length)) {\n return null;\n }\n\n const copies = [...action.indices]\n .sort((a, b) => a - b)\n .map(index => copySource(raw[index]!, usedIds));\n\n return [insertChildren(source, parent, children.at(-1), copies)];\n }\n case 'append': {\n const copy = copySource(raw[0] ?? '<div></div>', usedIds);\n\n return [insertChildren(source, parent, children.at(-1), [copy])];\n }\n default:\n return null;\n }\n } catch {\n return null;\n }\n};\n","import * as t from '@babel/types';\n\nimport type { NodeValueType } from './types';\n\n// Builds AST expressions and source text from JS values: the inverse of\n// reading them in `value.ts`.\n\n// A number literal, with a negative written as `-n`: Babel rejects a\n// negative `numericLiteral`. `null` for `NaN` and `Infinity`, which have no\n// literal form (#712).\nconst numberToExpression = (value: number): t.Expression | null => {\n if (!Number.isFinite(value)) {\n return null;\n }\n\n if (value < 0 || Object.is(value, -0)) {\n return t.unaryExpression('-', t.numericLiteral(-value));\n }\n\n return t.numericLiteral(value);\n};\n\nexport const createNodeFromValue = (\n type: NodeValueType,\n value: unknown,\n): t.Expression | null => {\n switch (type) {\n case 'boolean': {\n return t.booleanLiteral(value === true);\n }\n case 'number': {\n return numberToExpression(Number(value));\n }\n case 'string': {\n return t.stringLiteral(String(value));\n }\n case 'null': {\n return t.nullLiteral();\n }\n case 'array':\n case 'object':\n case 'unknown': {\n return null;\n }\n default: {\n return null;\n }\n }\n};\n\n// Builds an expression for a JS value: the inverse of `evaluateLiteral`\n// (#238). Each JS type maps to one kind of literal. Values with no literal\n// form (`undefined`, functions, symbols) give `null`. Inside an object the\n// property is left out; inside an array the item becomes `null`.\nexport const valueToExpression = (value: unknown): t.Expression | null => {\n if (typeof value === 'string') {\n return t.stringLiteral(value);\n }\n\n if (typeof value === 'number') {\n return numberToExpression(value);\n }\n\n if (typeof value === 'boolean') {\n return t.booleanLiteral(value);\n }\n\n if (value === null) {\n return t.nullLiteral();\n }\n\n if (Array.isArray(value)) {\n return t.arrayExpression(\n value.map(item => valueToExpression(item) ?? t.nullLiteral()),\n );\n }\n\n if (typeof value === 'object') {\n const properties: t.ObjectProperty[] = [];\n\n for (const [key, item] of Object.entries(value)) {\n const expr = valueToExpression(item);\n if (expr === null) {\n continue;\n }\n properties.push(t.objectProperty(t.stringLiteral(key), expr));\n }\n\n return t.objectExpression(properties);\n }\n\n return null;\n};\n","import { parseExpression } from '@babel/parser';\nimport * as t from '@babel/types';\n\nimport { STRING_VALUED_TYPES } from './binding';\nimport { generateCode } from './helpers';\nimport type { SourceEdit } from './patch';\nimport type { BindingType } from './types';\nimport { isLosslesslyEvaluable, unwrapExpression } from './value';\nimport { valueToExpression } from './value-expression';\n\n// The source editors behind `update`: each turns one property edit on one\n// element into source spans, and never touches the tree.\n\n// What each editor below returns: the source spans to change, never a\n// changed tree, so everything else stays byte-identical (#239). An empty\n// array means \"handled, nothing to write\"; `null` means the edit failed.\nexport type EditResult = SourceEdit[] | null;\n\n// The span between `>` and `</`, i.e. everything the element encloses.\n// `null` for a self-closing element, which has nowhere to put children.\nexport const childrenRange = (\n element: t.JSXElement,\n): { start: number; end: number } | null => {\n const { openingElement, closingElement } = element;\n\n if (\n !closingElement ||\n openingElement.end == null ||\n closingElement.start == null\n ) {\n return null;\n }\n\n return { start: openingElement.end, end: closingElement.start };\n};\n\nexport const findAttribute = (\n opening: t.JSXOpeningElement,\n propertyName: string,\n): t.JSXAttribute | undefined => {\n return opening.attributes.find(\n (attr): attr is t.JSXAttribute =>\n t.isJSXAttribute(attr) &&\n t.isJSXIdentifier(attr.name) &&\n attr.name.name === propertyName,\n );\n};\n\n// Where a new attribute goes: after the last attribute, or after the\n// element name when there are none.\nconst attributeInsertPoint = (opening: t.JSXOpeningElement): number | null => {\n const last = opening.attributes[opening.attributes.length - 1];\n\n return last?.end ?? opening.name.end ?? null;\n};\n\n// Escapes a string for JSX text, where `<`, `>`, `{` and `}` are syntax and\n// `&` starts an entity. They are written as entities, which the panel reads\n// back as the typed characters. `&` is escaped only when it starts something\n// entity-like, so a typed `&amp;` stays literal and `Tom & Jerry` is written\n// as is. `&` goes first, so the entities added below aren't escaped again.\nconst escapeJsxText = (value: string): string =>\n value\n .replace(/&(?=#?[A-Za-z0-9]+;)/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\\{/g, '&#123;')\n .replace(/\\}/g, '&#125;');\n\n// Replaces the element's text. With a single text child, only the trimmed\n// text is replaced, so the line breaks and indentation around it stay\n// (#239). Otherwise every text child is removed and `value` is written just\n// before the closing tag; nested elements stay.\n//\n// A self-closing element has nowhere to put text: this returns no edits,\n// and `update` reports success without changing anything.\nexport const editInnerText = (\n source: string,\n element: t.JSXElement,\n value: string,\n): EditResult => {\n const range = childrenRange(element);\n\n if (!range) {\n return [];\n }\n\n const text = escapeJsxText(value);\n const [only] = element.children;\n\n if (\n element.children.length === 1 &&\n t.isJSXText(only) &&\n only.start != null &&\n only.end != null\n ) {\n // Measure the raw source, not `only.value`: Babel decodes entities and\n // CRLF in `value`, so its lengths don't match the source offsets.\n // `&nbsp;Old&nbsp;` would otherwise become `&New;`.\n const raw = source.slice(only.start, only.end);\n\n if (raw.trim() !== '') {\n const leadingSpace = raw.slice(0, raw.length - raw.trimStart().length);\n const trailingSpace = raw.slice(raw.trimEnd().length);\n // Only whitespace with a line break is layout. JSX keeps same-line\n // whitespace in the string while the panel value hides it, so the\n // edit overwrites that.\n const leading = /[\\r\\n]/.test(leadingSpace) ? leadingSpace.length : 0;\n const trailing = /[\\r\\n]/.test(trailingSpace) ? trailingSpace.length : 0;\n\n return [\n {\n start: only.start + leading,\n end: only.end - trailing,\n content: text,\n },\n ];\n }\n }\n\n const edits: SourceEdit[] = [];\n\n for (const child of element.children) {\n if (t.isJSXText(child) && child.start != null && child.end != null) {\n edits.push({ start: child.start, end: child.end, content: '' });\n }\n }\n\n edits.push({ start: range.end, end: range.end, content: text });\n\n return edits;\n};\n\n// Replaces the element's children with the raw HTML, as written.\nexport const editInnerHTML = (\n element: t.JSXElement,\n value: string,\n): EditResult => {\n const range = childrenRange(element);\n\n if (!range) {\n return [];\n }\n\n return [{ start: range.start, end: range.end, content: value }];\n};\n\nexport const editRichtext = (\n element: t.JSXElement,\n value: string,\n): EditResult => {\n const edits: SourceEdit[] = [];\n const range = childrenRange(element);\n\n // richtext owns the element's content, so any prior markup goes.\n if (range && range.start !== range.end) {\n edits.push({ start: range.start, end: range.end, content: '' });\n }\n\n const opening = element.openingElement;\n const attribute = t.jsxAttribute(\n t.jsxIdentifier('dangerouslySetInnerHTML'),\n t.jsxExpressionContainer(\n t.objectExpression([\n t.objectProperty(t.identifier('__html'), t.stringLiteral(value)),\n ]),\n ),\n );\n const content = generateCode(attribute);\n const existing = findAttribute(opening, 'dangerouslySetInnerHTML');\n\n if (existing && existing.start != null && existing.end != null) {\n edits.push({\n start: existing.start,\n end: existing.end,\n content,\n indent: true,\n });\n\n return edits;\n }\n\n const insertAt = attributeInsertPoint(opening);\n\n if (insertAt == null) {\n return null;\n }\n\n edits.push({\n start: insertAt,\n end: insertAt,\n content: ` ${content}`,\n indent: true,\n });\n\n return edits;\n};\n\n// A `type: 'jsx'` value is arbitrary user-authored JSX, so it goes in as\n// written rather than being parsed into nodes and printed back out.\nexport const editJsxAttribute = (\n opening: t.JSXOpeningElement,\n propertyName: string,\n value: unknown,\n): EditResult => {\n const attribute = findAttribute(opening, propertyName);\n\n if (!attribute) {\n return null;\n }\n\n const content = `{${String(value).trim()}}`;\n\n if (attribute.value?.start != null && attribute.value.end != null) {\n return [\n {\n start: attribute.value.start,\n end: attribute.value.end,\n content,\n },\n ];\n }\n\n // Valueless shorthand (`<Icon icon />`): there is no value span to\n // overwrite, so append one after the attribute name.\n const insertAt = attribute.name.end;\n\n if (insertAt == null) {\n return null;\n }\n\n return [{ start: insertAt, end: insertAt, content: `=${content}` }];\n};\n\n// Whether the attribute holds an array or object literal, such as\n// `items={[...]}`. Other expressions (`className={cn(...)}`,\n// `items={rows}`) don't count: the panel doesn't edit their source, so a\n// string committed to them stays a string.\nconst holdsStructuralExpression = (value?: t.JSXAttribute['value']): boolean =>\n t.isJSXExpressionContainer(value) &&\n (t.isArrayExpression(unwrapExpression(value.expression)) ||\n t.isObjectExpression(unwrapExpression(value.expression)));\n\n// Parses committed text as an array or object literal, or `null`. Only\n// those shapes are accepted: `hello` also parses, as an identifier, and\n// writing `items={hello}` would turn a value into a variable reference.\nconst structuralSource = (value: string): t.Expression | null => {\n try {\n const expression = parseExpression(value.trim(), {\n plugins: ['jsx', 'typescript'],\n });\n\n return t.isArrayExpression(unwrapExpression(expression)) ||\n t.isObjectExpression(unwrapExpression(expression))\n ? expression\n : null;\n } catch {\n return null;\n }\n};\n\n// Whether a string has a control character: a line break, a tab, and so on.\nconst hasControlCharacter = (value: string): boolean =>\n Array.from(value).some(char => char.charCodeAt(0) < 0x20);\n\n// A string as the value of a JSX attribute, which has its own rules: no\n// backslash escapes, and `&` starts an entity. Babel prints a string literal\n// by JavaScript rules (`\"a\\\"b\"`, `\"C:\\\\dir\"`), which JSX would read as a\n// different value or fail to parse, so the text is written as given\n// (`extra.raw`).\n//\n// - A control character goes in `{\"...\"}`. A line break in an attribute\n// string followed by spaces compiles to one space, so only the expression\n// form keeps it.\n// - Otherwise the quote with fewer escapes: `'` for a value that has `\"` and\n// no `'`, else `\"` with `&quot;` for any `\"` inside.\n// - `&` becomes `&amp;` when it starts something entity-like, so a typed\n// `&amp;` stays literal. A lone `&` is written as is.\nconst jsxStringValue = (\n value: string,\n): t.StringLiteral | t.JSXExpressionContainer => {\n if (hasControlCharacter(value)) {\n return t.jsxExpressionContainer(t.stringLiteral(value));\n }\n\n const quote = value.includes('\"') && !value.includes(\"'\") ? \"'\" : '\"';\n const text = value.replace(/&(?=#?[A-Za-z0-9]+;)/g, '&amp;');\n const escaped = quote === '\"' ? text.replace(/\"/g, '&quot;') : text;\n const literal = t.stringLiteral(value);\n\n literal.extra = { raw: `${quote}${escaped}${quote}`, rawValue: value };\n\n return literal;\n};\n\n// Builds the JSX attribute value for a value and its declared `type`\n// (#238). `current` is the value being replaced. Without a declared type,\n// as in most `items` bindings, `current` decides whether the value is\n// source code or a string, the same way `getStructuredValue` reads it.\nconst buildAttributeValue = (\n value: unknown,\n type?: BindingType,\n current?: t.JSXAttribute['value'],\n): t.JSXAttribute['value'] => {\n // Declared object or array: an expression. A string here is source text\n // from the Items or object editor, so parse it instead of quoting it.\n if (type === 'array' || type === 'object') {\n if (typeof value === 'string') {\n try {\n return t.jsxExpressionContainer(\n parseExpression(value.trim(), { plugins: ['jsx', 'typescript'] }),\n );\n } catch {\n return jsxStringValue(value);\n }\n }\n\n const expr = valueToExpression(value);\n return expr ? t.jsxExpressionContainer(expr) : t.stringLiteral('');\n }\n\n // Otherwise each JS type maps to one kind of literal. A string stays a\n // string literal whatever it contains.\n if (typeof value === 'string') {\n // Except when the attribute holds an array or object literal: then the\n // string is its source text from the array editor. Quoting it would turn\n // `items={[...]}` into a string and break the document.\n if (\n holdsStructuralExpression(current) &&\n !(type && STRING_VALUED_TYPES.has(type))\n ) {\n const structural = structuralSource(value);\n\n if (structural) {\n return t.jsxExpressionContainer(structural);\n }\n }\n\n return jsxStringValue(value);\n }\n\n const expr = valueToExpression(value);\n return expr ? t.jsxExpressionContainer(expr) : jsxStringValue(String(value));\n};\n\nexport const editAttribute = (\n opening: t.JSXOpeningElement,\n propertyName: string,\n value: unknown,\n type?: BindingType,\n): EditResult => {\n const attribute = findAttribute(opening, propertyName);\n\n if (!attribute || attribute.start == null || attribute.end == null) {\n return null;\n }\n\n // Array or object source from the editors: check its shape, then replace\n // only the expression, so the unchanged items keep their formatting.\n if (\n typeof value === 'string' &&\n (type === 'array' ||\n type === 'object' ||\n (holdsStructuralExpression(attribute.value) &&\n !(type && STRING_VALUED_TYPES.has(type))))\n ) {\n const expression = structuralSource(value);\n\n if (expression && t.isJSXExpressionContainer(attribute.value)) {\n const text = value.trim();\n const lineComment = expression.trailingComments?.some(\n comment => comment.type === 'CommentLine',\n );\n\n return [\n {\n start: attribute.value.expression.start!,\n end: attribute.value.expression.end!,\n content: `${text}${lineComment ? '\\n' : ''}`,\n },\n ];\n }\n }\n\n // Print the whole attribute, so Babel decides the quoting and escaping.\n // The parsed name node is reused, so namespaced and dashed names stay as\n // written.\n const content = generateCode(\n t.jsxAttribute(\n attribute.name,\n buildAttributeValue(value, type, attribute.value),\n ),\n );\n\n return [\n { start: attribute.start, end: attribute.end, content, indent: true },\n ];\n};\n\n// Up to and including the line break: spaces, single-line block comments\n// and one line comment.\nconst TRAILING_COMMENTS =\n /^[ \\t]*(?:\\/\\*[^\\r\\n]*?\\*\\/[ \\t]*)*(?:\\/\\/[^\\r\\n]*)?\\r?\\n/;\n\n// Removes an attribute and the whitespace before it, leaving no gap. A\n// caller asks for this with `undefined`, since React treats an `undefined`\n// prop like a missing one (#426). An attribute alone on its line goes with\n// the comments after it, so they don't end up beside the previous attribute.\nexport const removeAttribute = (\n source: string,\n attribute: t.JSXAttribute,\n): EditResult => {\n if (attribute.start == null || attribute.end == null) {\n return null;\n }\n\n const lineStart = source.lastIndexOf('\\n', attribute.start - 1) + 1;\n const rest = TRAILING_COMMENTS.exec(source.slice(attribute.end));\n\n if (/^[ \\t]*$/.test(source.slice(lineStart, attribute.start)) && rest) {\n return [\n { start: lineStart, end: attribute.end + rest[0].length, content: '' },\n ];\n }\n\n let start = attribute.start;\n\n while (start > 0 && /\\s/.test(source[start - 1]!)) {\n start -= 1;\n }\n\n return [{ start, end: attribute.end, content: '' }];\n};\n\n// Adds a missing attribute after the last one. Only for a real value:\n// clearing a field never creates the attribute (#426). When the last\n// attribute is on its own line, the new one goes on the next line with the\n// same indentation.\nexport const addAttribute = (\n source: string,\n opening: t.JSXOpeningElement,\n propertyName: string,\n value: unknown,\n type?: BindingType,\n): EditResult => {\n const insertAt = attributeInsertPoint(opening);\n\n if (insertAt == null) {\n return null;\n }\n\n // With `indent: true`, a newline is enough to line the new attribute up\n // under the last one.\n const lastStart = opening.attributes[opening.attributes.length - 1]?.start;\n const lineStart =\n lastStart == null ? -1 : source.lastIndexOf('\\n', lastStart - 1) + 1;\n const ownLine =\n lastStart != null &&\n lineStart > 0 &&\n /^\\s*$/.test(source.slice(lineStart, lastStart));\n const separator = ownLine ? '\\n' : ' ';\n\n const content =\n type === 'jsx'\n ? `${propertyName}={${String(value).trim()}}`\n : generateCode(\n t.jsxAttribute(\n t.jsxIdentifier(propertyName),\n buildAttributeValue(value, type),\n ),\n );\n\n return [\n {\n start: insertAt,\n end: insertAt,\n content: `${separator}${content}`,\n indent: true,\n },\n ];\n};\n\nexport const canEditAttributeValue = (\n attribute: t.JSXAttribute,\n value: unknown,\n type?: BindingType,\n) => {\n if (\n !t.isJSXExpressionContainer(attribute.value) ||\n t.isJSXEmptyExpression(attribute.value.expression) ||\n isLosslesslyEvaluable(attribute.value.expression)\n ) {\n return true;\n }\n\n // The array and object editors commit checked source text, which keeps\n // every expression, so accept it.\n return (\n typeof value === 'string' &&\n holdsStructuralExpression(attribute.value) &&\n !(type && STRING_VALUED_TYPES.has(type)) &&\n structuralSource(value) !== null\n );\n};\n","import { parse } from '@babel/parser';\nimport * as t from '@babel/types';\n\nimport {\n BINDING_PROP,\n DATA_ATTR,\n RESERVED_BINDING_PROPERTIES,\n} from '../../constants';\nimport { parseBinding, resolveBindings } from './binding';\nimport { editChildrenSource } from './children';\nimport { traverse } from './document';\nimport {\n type EditResult,\n addAttribute,\n canEditAttributeValue,\n childrenRange,\n editAttribute,\n editInnerHTML,\n editInnerText,\n editJsxAttribute,\n editRichtext,\n findAttribute,\n removeAttribute,\n} from './edit-source';\nimport { generateCode, unwrap, wrap } from './helpers';\nimport { getJSXTagName } from './jsx-name';\nimport { type SourceEdit, applyEdits } from './patch';\nimport type { BindingItem, BindingOptions } from './types';\n\n// Why an edit failed, with what a caller needs to name the cause (#270).\n// The cause is usually a wrong `property` or `label` in the element's\n// `data-binding`, not the value just typed.\nexport type UpdateFailure =\n | { reason: 'element-not-found'; dataId: string }\n | { reason: 'no-binding'; dataId: string }\n // The binding targets an attribute the editor owns (`data-id`,\n // `data-name`, `data-binding`), which a panel edit must not rewrite.\n | { reason: 'reserved-property'; dataId: string; property: string }\n // Asked to remove (`undefined`) a property whose binding is `required`.\n | { reason: 'required-property'; dataId: string; property: string }\n | {\n reason: 'binding-not-declared';\n dataId: string;\n label: string;\n property?: string;\n }\n | {\n reason: 'duplicate-binding';\n dataId: string;\n label: string;\n property?: string;\n count: number;\n }\n | { reason: 'attribute-not-found'; dataId: string; property: string }\n // `innerText` or `innerHTML` written to a self-closing element, which has\n // nowhere between its tags to put them (#552).\n | { reason: 'self-closing'; dataId: string; property: string }\n | { reason: 'unsupported-syntax'; dataId: string; property: string }\n | { reason: 'parse-error'; error: unknown };\n\nexport interface UpdateResult {\n code: string;\n success: boolean;\n // Set when `success` is false.\n failure?: UpdateFailure;\n}\n\n// What one `update` call asks for.\ninterface UpdateRequest {\n dataId: string;\n label: string;\n value: unknown;\n property?: string;\n options: BindingOptions;\n}\n\n// One element's outcome: the spans to write (possibly none, which still\n// counts as handled), or why it was refused.\ntype ElementEdit = { edits: SourceEdit[] } | { failure: UpdateFailure };\n\nconst hasDataId = (opening: t.JSXOpeningElement, dataId: string) =>\n opening.attributes.some(\n attr =>\n t.isJSXAttribute(attr) &&\n t.isJSXIdentifier(attr.name) &&\n attr.name.name === DATA_ATTR.ID &&\n attr.value &&\n t.isStringLiteral(attr.value) &&\n attr.value.value === dataId,\n );\n\nconst findJSXAttribute = (opening: t.JSXOpeningElement, name: string) =>\n opening.attributes.find(\n (attr): attr is t.JSXAttribute =>\n t.isJSXAttribute(attr) &&\n t.isJSXIdentifier(attr.name) &&\n attr.name.name === name,\n );\n\n// Step 1: the element's binding for the request, from the same sources\n// `extract` reads (#509, #513). Found by `property` when given, otherwise by\n// `label`. More than one match is an authoring mistake, reported rather than\n// resolved by picking one (#240).\nconst findBinding = (\n opening: t.JSXOpeningElement,\n { dataId, label, property, options }: UpdateRequest,\n): { binding: BindingItem } | { failure: UpdateFailure } => {\n const bindingAttr = findJSXAttribute(opening, DATA_ATTR.BINDING);\n\n // An attribute with no value declares nothing to check against.\n if (bindingAttr && !bindingAttr.value) {\n return { failure: { reason: 'no-binding', dataId } };\n }\n\n let own: BindingItem[] | undefined;\n\n if (bindingAttr?.value) {\n let bindingValue = '';\n\n if (t.isStringLiteral(bindingAttr.value)) {\n bindingValue = bindingAttr.value.value;\n } else if (t.isJSXExpressionContainer(bindingAttr.value)) {\n try {\n bindingValue = generateCode(bindingAttr.value.expression);\n } catch (error) {\n return { failure: { reason: 'parse-error', error } };\n }\n }\n\n own = parseBinding(bindingValue);\n }\n\n const keyAttr = findJSXAttribute(opening, DATA_ATTR.BINDING_KEY);\n const bindings = resolveBindings(\n own,\n keyAttr &&\n (keyAttr.value && t.isStringLiteral(keyAttr.value)\n ? keyAttr.value.value\n : null),\n getJSXTagName(opening),\n options,\n );\n\n if (!own && bindings.length === 0) {\n return { failure: { reason: 'no-binding', dataId } };\n }\n\n const matches = bindings.filter(binding =>\n property !== undefined\n ? binding.property === property\n : binding.label === label,\n );\n\n if (matches.length === 0) {\n return {\n failure: { reason: 'binding-not-declared', dataId, label, property },\n };\n }\n\n if (matches.length > 1) {\n return {\n failure: {\n reason: 'duplicate-binding',\n dataId,\n label,\n property,\n count: matches.length,\n },\n };\n }\n\n return { binding: matches[0]! };\n};\n\n// Step 2: what no edit may do, whatever the property: rewrite an attribute\n// the editor owns, or remove a `required` one (#426).\nconst checkEdit = (\n binding: BindingItem,\n { dataId, value }: UpdateRequest,\n): UpdateFailure | undefined => {\n const property = binding.property;\n\n if (RESERVED_BINDING_PROPERTIES.includes(property)) {\n return { reason: 'reserved-property', dataId, property };\n }\n\n if (value === undefined && binding.required) {\n return { reason: 'required-property', dataId, property };\n }\n\n return undefined;\n};\n\n// An editor's result as an `ElementEdit`: `null` becomes `onNull`'s failure.\nconst toElementEdit = (\n result: EditResult,\n onNull: () => UpdateFailure,\n): ElementEdit => (result ? { edits: result } : { failure: onNull() });\n\n// Step 3: the spans that set `binding`'s property on `element`. `undefined`\n// asks for the property to go: an attribute is removed, content is emptied.\nconst editProperty = (\n source: string,\n element: t.JSXElement,\n binding: BindingItem,\n { dataId, value, options }: UpdateRequest,\n): ElementEdit => {\n const opening = element.openingElement;\n const prop = binding.property;\n const unset = value === undefined;\n const couldNotUpdate = (): UpdateFailure => ({\n reason: 'parse-error',\n error: new Error(`could not update \"${prop}\"`),\n });\n\n // Text and HTML go between the tags, so a self-closing element can't take\n // them. Clearing them is fine: there's nothing to clear (#552).\n const contentWithoutSlot =\n !unset && String(value) !== '' && !childrenRange(element);\n\n switch (prop) {\n case BINDING_PROP.INNER_TEXT: {\n if (contentWithoutSlot) {\n return { failure: { reason: 'self-closing', dataId, property: prop } };\n }\n\n return toElementEdit(\n editInnerText(source, element, unset ? '' : String(value)),\n couldNotUpdate,\n );\n }\n\n case BINDING_PROP.INNER_HTML: {\n // `richtext` is written to an attribute, so it doesn't need one.\n if (contentWithoutSlot && binding.type !== 'richtext') {\n return { failure: { reason: 'self-closing', dataId, property: prop } };\n }\n\n return toElementEdit(\n binding.type === 'richtext'\n ? editRichtext(element, unset ? '' : String(value))\n : editInnerHTML(element, unset ? '' : String(value)),\n couldNotUpdate,\n );\n }\n\n case BINDING_PROP.CHILDREN: {\n // Children are edited one at a time (move, add, remove), so they can't\n // be removed as a whole.\n if (unset) {\n return {\n failure: { reason: 'unsupported-syntax', dataId, property: prop },\n };\n }\n\n return toElementEdit(\n editChildrenSource(source, element, value, options),\n () => ({\n reason: 'parse-error',\n error: new Error(\n 'Unsupported or stale children edit; source was preserved',\n ),\n }),\n );\n }\n\n default: {\n const attribute = findAttribute(opening, prop);\n\n if (unset) {\n // Already absent: nothing to remove, and nothing went wrong.\n return toElementEdit(\n attribute ? removeAttribute(source, attribute) : [],\n () => ({\n reason: 'parse-error',\n error: new Error(`could not remove \"${prop}\"`),\n }),\n );\n }\n\n // A declared property the element doesn't have yet is added when it's\n // given a real value, so a field that was switched off can be switched\n // on again. An empty string leaves it absent (#426).\n if (!attribute) {\n return toElementEdit(\n value === ''\n ? []\n : addAttribute(source, opening, prop, value, binding.type),\n () => ({ reason: 'attribute-not-found', dataId, property: prop }),\n );\n }\n\n if (\n binding.type !== 'jsx' &&\n !canEditAttributeValue(attribute, value, binding.type)\n ) {\n return {\n failure: { reason: 'unsupported-syntax', dataId, property: prop },\n };\n }\n\n return toElementEdit(\n binding.type === 'jsx'\n ? editJsxAttribute(opening, prop, value)\n : editAttribute(opening, prop, value, binding.type),\n () => ({ reason: 'attribute-not-found', dataId, property: prop }),\n );\n }\n }\n};\n\n// The three steps for one element.\nconst editElement = (\n source: string,\n element: t.JSXElement,\n request: UpdateRequest,\n): ElementEdit => {\n const found = findBinding(element.openingElement, request);\n\n if ('failure' in found) {\n return found;\n }\n\n const refused = checkEdit(found.binding, request);\n\n if (refused) {\n return { failure: refused };\n }\n\n return editProperty(source, element, found.binding, request);\n};\n\n// Sets one bound property of the element with `dataId` to `value`, and\n// returns the new source or why it couldn't.\n//\n// The binding is found by `property` when given, otherwise by `label`.\n// Pass `property` when you have it: a label is display text and can repeat\n// (#240). `options` are the binding sources the bindings were read with\n// (#509, #513).\nexport const update = (\n code: string,\n dataId: string,\n label: string,\n value: unknown,\n property?: string,\n options: BindingOptions = {},\n): UpdateResult => {\n const request: UpdateRequest = { dataId, label, value, property, options };\n\n try {\n const wrapped = wrap(code);\n const ast = parse(wrapped, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n let changed = false;\n let failure: UpdateFailure | undefined;\n const edits: SourceEdit[] = [];\n\n // Every element carrying `dataId` is edited, so a duplicated id edits\n // each copy; the last refusal is the one reported.\n traverse(ast, {\n JSXElement(path) {\n if (!hasDataId(path.node.openingElement, dataId)) {\n return;\n }\n\n const result = editElement(wrapped, path.node, request);\n\n if ('failure' in result) {\n failure = result.failure;\n\n return;\n }\n\n edits.push(...result.edits);\n changed = true;\n },\n });\n\n if (!changed) {\n return {\n code,\n success: false,\n // No specific reason recorded means the traversal never reached the\n // target element at all.\n failure: failure ?? { reason: 'element-not-found', dataId },\n };\n }\n\n // Patch the original source: everything outside the recorded spans is\n // copied unchanged (#239).\n return { code: unwrap(applyEdits(wrapped, edits)), success: true };\n } catch (error) {\n console.error('❌ Code update error:', error);\n return { code, success: false, failure: { reason: 'parse-error', error } };\n }\n};\n\nexport interface UpdateEntry {\n dataId: string;\n label: string;\n value: unknown;\n property?: string;\n}\n\n// The result of `updateAll`: every entry applied, or none. On failure `code`\n// is the source as it came in, `index` says which entry was refused, and\n// `failure` says why.\nexport type UpdateAllResult =\n | { success: true; code: string }\n | { success: false; code: string; failure: UpdateFailure; index: number };\n\n// Applies several edits as one: all of them, in array order, or none. The\n// first entry that fails stops the run and the source comes back untouched,\n// so a caller can commit the result as a single change (#425). An entry sees\n// the source the earlier ones left, and a later entry for the same\n// `dataId`/`property` wins.\n//\n// Each entry re-parses the source the one before it produced, so every offset\n// is fresh, and the outcome matches applying the entries one at a time (#239).\nexport const updateAll = (\n raw: string,\n entries: UpdateEntry[],\n options: BindingOptions = {},\n): UpdateAllResult => {\n let current = raw;\n\n for (const [index, entry] of entries.entries()) {\n const result = update(\n current,\n entry.dataId,\n entry.label,\n entry.value,\n entry.property,\n options,\n );\n\n if (!result.success) {\n return {\n success: false,\n code: raw,\n failure: result.failure ?? {\n reason: 'element-not-found',\n dataId: entry.dataId,\n },\n index,\n };\n }\n\n current = result.code;\n }\n\n return { success: true, code: current };\n};\n"],"mappings":";;;;AAgCA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;ACxCA,MAAa,QAAQ,SAAiB;CACpC,OAAO,KAAK,KAAK;AACnB;AAEA,MAAa,UAAU,cAAsB;CAC3C,OAAO,UACJ,QAAQ,WAAW,EAAE,CAAC,CACtB,QAAQ,qBAAqB,EAAE,CAAC,CAChC,KAAK;AACV;AAKA,MAAa,mBAAmB,SAAiB;CAC/C,MAAM,KAAK,IAAI,GAAG;EAChB,YAAY;EACZ,SAAS,CAAC,OAAO,YAAY;CAC/B,CAAC;AACH;AAEA,MAAa,aAAa,EACxB,OACA,sBACwC;CACxC,IAAI,UAAU,MACZ,OAAO;CAGT,IAAI,iBACF,OAAOA,cAAgB,KAAK;CAG9B,MAAM,UAAU,MAAM,KAAK;CAE3B,IAAI,MAAM,OAAO,KAAK,OAAO,GAAG;EAC9B,MAAM,YAAYC,eAAiB,KAAK,IAAI,WAAW,OAAO,CAAC,CAAC;EAGhE,OAAOC,uBACL,QAAQ,WAAW,GAAG,IAAIC,gBAAkB,KAAK,SAAS,IAAI,SAChE;CACF;CAEA,IAAI,MAAM,gBAAgB,KAAK,OAAO,GAAG;EACvC,MAAM,OAAO,gBAAgB,SAAS,EACpC,SAAS,CAAC,OAAO,YAAY,EAC/B,CAAC;EACD,OAAOD,uBAAyB,IAAI;CACtC;CAEA,IAAI;EACF,MAAM,OAAO,gBAAgB,SAAS,EACpC,SAAS,CAAC,OAAO,YAAY,EAC/B,CAAC;EACD,OAAOA,uBAAyB,IAAI;CACtC,QAAQ;EACN,OAAOF,cAAgB,OAAO;CAChC;AACF;AAEA,MAAa,gBA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,KAAK;EAC3C,OAAO;GAAE;GAAM,SAAS;GAAO,SAAS;IAAE,QAAQ;IAAe;GAAM;EAAE;CAC3E;AACF;AAwBA,MAAa,aACX,KACA,SACA,UAA0B,CAAC,MACP;CACpB,IAAI,UAAU;CAEd,KAAK,MAAM,CAAC,OAAO,UAAU,QAAQ,QAAQ,GAAG;EAC9C,MAAM,SAAS,OACb,SACA,MAAM,QACN,MAAM,OACN,MAAM,OACN,MAAM,UACN,OACF;EAEA,IAAI,CAAC,OAAO,SACV,OAAO;GACL,SAAS;GACT,MAAM;GACN,SAAS,OAAO,WAAW;IACzB,QAAQ;IACR,QAAQ,MAAM;GAChB;GACA;EACF;EAGF,UAAU,OAAO;CACnB;CAEA,OAAO;EAAE,SAAS;EAAM,MAAM;CAAQ;AACxC"}
@@ -1,8 +1,8 @@
1
1
  import { i as useLiveMessages } from "./messages-DrINcRdG.js";
2
- import { i as withScriptBlobs, n as compile } from "./compile-my0AjsCw.js";
3
- import { createElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import { i as withScriptBlobs, n as compile } from "./compile-BWZ5U59y.js";
3
+ import { Component, createElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
4
  import { jsx } from "react/jsx-runtime";
5
- import { useDebouncedCallback, useEventListener, useMutationObserver, useResizeObserver, useStableValue } from "@jbpark/use-hooks";
5
+ import { useAsync, useDebouncedCallback, useEventListener, useLatest, useMutationObserver, useResizeObserver, useStableValue } from "@jbpark/use-hooks";
6
6
  import { createPortal } from "react-dom";
7
7
  //#region src/components/frame/auto-height/measure.ts
8
8
  const verticalInsets = (style) => [
@@ -268,23 +268,42 @@ const syncInjectedAssets = (doc, styles, stylesheets, previous) => {
268
268
  //#endregion
269
269
  //#region src/components/frame/style-sync.ts
270
270
  const SYNCED_STYLE_ATTR = "data-live-editor-synced-style";
271
- const createStyleSyncManager = () => ({ clones: /* @__PURE__ */ new Map() });
271
+ const createStyleSyncManager = () => ({
272
+ clones: /* @__PURE__ */ new Map(),
273
+ transformed: /* @__PURE__ */ new WeakMap()
274
+ });
272
275
  const isDocument = (target) => target.nodeType === Node.DOCUMENT_NODE;
273
276
  const sourceStyles = (document) => Array.from(document.head.querySelectorAll("link[rel=\"stylesheet\"], style"));
274
- const copyAttributes = (source, clone, transformStyle) => {
277
+ const transformedText = (source, manager, transformStyle) => {
278
+ const text = source.textContent || "";
279
+ const cached = manager.transformed.get(source);
280
+ if (cached && cached.text === text && cached.transform === transformStyle) return cached.output;
281
+ const output = transformStyle(text);
282
+ manager.transformed.set(source, {
283
+ text,
284
+ transform: transformStyle,
285
+ output
286
+ });
287
+ return output;
288
+ };
289
+ const copyAttributes = (source, clone, manager, transformStyle) => {
275
290
  Array.from(clone.attributes).forEach((attribute) => {
276
291
  if (attribute.name !== SYNCED_STYLE_ATTR && !source.hasAttribute(attribute.name)) clone.removeAttribute(attribute.name);
277
292
  });
278
293
  Array.from(source.attributes).forEach((attribute) => {
279
- clone.setAttribute(attribute.name, attribute.value);
294
+ if (clone.getAttribute(attribute.name) !== attribute.value) clone.setAttribute(attribute.name, attribute.value);
280
295
  });
281
- if (source.tagName === "LINK" && clone.tagName === "LINK") clone.disabled = source.disabled;
282
- clone.textContent = source.tagName === "STYLE" ? transformStyle(source.textContent || "") : source.textContent;
296
+ if (source.tagName === "LINK" && clone.tagName === "LINK") {
297
+ const disabled = source.disabled;
298
+ if (clone.disabled !== disabled) clone.disabled = disabled;
299
+ }
300
+ const text = source.tagName === "STYLE" ? transformedText(source, manager, transformStyle) : source.textContent;
301
+ if (clone.textContent !== text) clone.textContent = text;
283
302
  };
284
- const createClone = (source, target, transformStyle) => {
303
+ const createClone = (source, target, manager, transformStyle) => {
285
304
  const clone = (isDocument(target) ? target : target.ownerDocument).createElement(source.tagName.toLowerCase());
286
305
  clone.setAttribute(SYNCED_STYLE_ATTR, "");
287
- copyAttributes(source, clone, transformStyle);
306
+ copyAttributes(source, clone, manager, transformStyle);
288
307
  return clone;
289
308
  };
290
309
  const targetContainer = (target) => isDocument(target) ? target.head : target;
@@ -314,9 +333,9 @@ const reconcileStyles = (sourceDocument, target, manager, enabled, transformStyl
314
333
  sources.forEach((source) => {
315
334
  let clone = manager.clones.get(source);
316
335
  if (!clone) {
317
- clone = createClone(source, target, transformStyle);
336
+ clone = createClone(source, target, manager, transformStyle);
318
337
  manager.clones.set(source, clone);
319
- } else copyAttributes(source, clone, transformStyle);
338
+ } else copyAttributes(source, clone, manager, transformStyle);
320
339
  const nextSibling = previous ? previous.nextSibling : Array.from(container.childNodes).find(isSyncedStyle) ?? (anchor?.parentNode === container ? anchor : null);
321
340
  if (clone !== nextSibling) container.insertBefore(clone, nextSibling);
322
341
  previous = clone;
@@ -361,13 +380,13 @@ const useHostStyleSync = (iframeRef, syncStyle) => {
361
380
  delay: 50,
362
381
  autoInvoke: false
363
382
  });
364
- useMutationObserver(document.head, debouncedApplyStyle, {
383
+ useMutationObserver(typeof document === "undefined" ? null : document.head, debouncedApplyStyle, {
365
384
  enabled: syncStyle,
366
385
  childList: true,
367
386
  subtree: true,
368
387
  attributes: true
369
388
  });
370
- useMutationObserver(document.documentElement, debouncedApplyStyle, {
389
+ useMutationObserver(typeof document === "undefined" ? null : document.documentElement, debouncedApplyStyle, {
371
390
  enabled: syncStyle,
372
391
  attributes: true
373
392
  });
@@ -388,9 +407,19 @@ const injectScripts = (doc, srcs) => {
388
407
  });
389
408
  };
390
409
  const useIframeDocument = (iframeRef, { scripts, onLoaded, applyStyle }) => {
410
+ const onLoadedRef = useLatest(onLoaded);
411
+ const scriptsRef = useLatest(scripts);
391
412
  const [mountNode, setMountNode] = useState(null);
392
413
  const loadedScriptsRef = useRef(/* @__PURE__ */ new Set());
393
414
  const loadedScriptsDocRef = useRef(null);
415
+ const loadedDocRef = useRef(null);
416
+ const injectPendingScripts = useCallback((doc) => {
417
+ const pendingScripts = scriptsRef.current.filter((src) => !loadedScriptsRef.current.has(src));
418
+ if (pendingScripts.length) {
419
+ pendingScripts.forEach((src) => loadedScriptsRef.current.add(src));
420
+ injectScripts(doc, pendingScripts);
421
+ }
422
+ }, [scriptsRef]);
394
423
  useEffect(() => {
395
424
  const $iframe = iframeRef.current;
396
425
  if (!$iframe) return;
@@ -411,23 +440,30 @@ const useIframeDocument = (iframeRef, { scripts, onLoaded, applyStyle }) => {
411
440
  }
412
441
  setMountNode(node);
413
442
  applyStyle();
414
- const pendingScripts = scripts.filter((src) => !loadedScriptsRef.current.has(src));
415
- if (pendingScripts.length) {
416
- pendingScripts.forEach((src) => loadedScriptsRef.current.add(src));
417
- injectScripts(doc, pendingScripts);
443
+ injectPendingScripts(doc);
444
+ if (loadedDocRef.current !== doc) {
445
+ loadedDocRef.current = doc;
446
+ onLoadedRef.current?.();
418
447
  }
419
- onLoaded?.();
420
448
  };
421
449
  $iframe.addEventListener("load", onLoad);
422
450
  if ($iframe.contentDocument?.readyState === "complete") onLoad();
423
451
  return () => {
424
452
  $iframe.removeEventListener("load", onLoad);
425
453
  };
454
+ }, [
455
+ iframeRef,
456
+ applyStyle,
457
+ injectPendingScripts,
458
+ onLoadedRef
459
+ ]);
460
+ useEffect(() => {
461
+ const doc = loadedScriptsDocRef.current;
462
+ if (doc && doc === iframeRef.current?.contentDocument) injectPendingScripts(doc);
426
463
  }, [
427
464
  iframeRef,
428
465
  scripts,
429
- onLoaded,
430
- applyStyle
466
+ injectPendingScripts
431
467
  ]);
432
468
  return mountNode;
433
469
  };
@@ -514,7 +550,7 @@ const Shadow = ({ syncStyle = false, children }) => {
514
550
  delay: 50,
515
551
  autoInvoke: false
516
552
  });
517
- useMutationObserver(document.head, debouncedApplyStyle, {
553
+ useMutationObserver(typeof document === "undefined" ? null : document.head, debouncedApplyStyle, {
518
554
  enabled: syncStyle,
519
555
  childList: true,
520
556
  subtree: true,
@@ -547,8 +583,13 @@ const Shadow = ({ syncStyle = false, children }) => {
547
583
  });
548
584
  };
549
585
  //#endregion
586
+ //#region src/components/frame/use-is-client.ts
587
+ const subscribe = () => () => {};
588
+ const useIsClient = () => useSyncExternalStore(subscribe, () => true, () => false);
589
+ //#endregion
550
590
  //#region src/components/frame/frame.tsx
551
591
  const Frame = ({ mode, children, ...restProps }) => {
592
+ if (!useIsClient()) return null;
552
593
  if (!mode) return children(document.body);
553
594
  if (mode === "shadow") return /* @__PURE__ */ jsx(Shadow, {
554
595
  syncStyle: restProps.syncStyle,
@@ -565,7 +606,48 @@ const HOOK_CALL = /\buse(?:[A-Z0-9_]\w*)?\s*\(/g;
565
606
  const hookSignature = (code) => (code.match(HOOK_CALL) ?? []).map((call) => call.replace(/\s*\($/, "")).join(",");
566
607
  const isFunctionComponent = (component) => typeof component === "function" && !component.prototype?.isReactComponent;
567
608
  const StableComponent = ({ render, props }) => render(props);
568
- const renderStableComponent = (Component, code, props) => isFunctionComponent(Component) ? createElement(StableComponent, {
609
+ var RemountOnRecompileError = class extends Component {
610
+ state = {
611
+ error: null,
612
+ attempt: 0
613
+ };
614
+ committedRender = null;
615
+ retriedRender = null;
616
+ static getDerivedStateFromError(error) {
617
+ return { error };
618
+ }
619
+ canRetry() {
620
+ const { render } = this.props;
621
+ return this.committedRender !== null && this.committedRender !== render && this.retriedRender !== render;
622
+ }
623
+ componentDidCatch() {
624
+ if (this.canRetry()) {
625
+ this.retriedRender = this.props.render;
626
+ this.setState(({ attempt }) => ({
627
+ error: null,
628
+ attempt: attempt + 1
629
+ }));
630
+ }
631
+ }
632
+ componentDidMount() {
633
+ this.committedRender = this.props.render;
634
+ }
635
+ componentDidUpdate() {
636
+ if (this.state.error === null) this.committedRender = this.props.render;
637
+ }
638
+ render() {
639
+ const { error, attempt } = this.state;
640
+ if (error !== null) {
641
+ if (!this.canRetry()) throw error;
642
+ return null;
643
+ }
644
+ return createElement(StableComponent, {
645
+ ...this.props,
646
+ key: attempt
647
+ });
648
+ }
649
+ };
650
+ const renderStableComponent = (Component, code, props) => isFunctionComponent(Component) ? createElement(RemountOnRecompileError, {
569
651
  key: hookSignature(code),
570
652
  render: Component,
571
653
  props
@@ -598,31 +680,24 @@ const useCompiledModule = (code, _modules) => {
598
680
  //#endregion
599
681
  //#region src/components/preview/use-dynamic-tailwind.ts
600
682
  const useDynamicTailwind = (code, enabled) => {
601
- const [css, setCss] = useState("");
602
683
  const [element, setElement] = useState(null);
603
684
  const ref = useCallback((node) => {
604
685
  setElement(node);
605
686
  }, []);
687
+ const { value: css = "", error } = useAsync(async () => {
688
+ const { generateTailwindCSSFromDOM } = await import("./utils/tailwind/index.js");
689
+ return generateTailwindCSSFromDOM(element);
690
+ }, [code, element], { enabled: enabled && !!code && !!element });
606
691
  useEffect(() => {
607
- if (!code || !enabled || !element) return;
608
- let cancelled = false;
609
- import("./utils/tailwind/index.js").then(({ generateTailwindCSSFromDOM }) => generateTailwindCSSFromDOM(element)).then((next) => {
610
- if (!cancelled) setCss(next);
611
- });
612
- return () => {
613
- cancelled = true;
614
- };
615
- }, [
616
- code,
617
- enabled,
618
- element
619
- ]);
692
+ if (error) console.error("Generating the preview Tailwind CSS failed", error);
693
+ }, [error]);
620
694
  return {
621
695
  ref,
622
- css
696
+ css,
697
+ error
623
698
  };
624
699
  };
625
700
  //#endregion
626
- export { renderStableComponent as a, NO_PROPS as i, useCompiledModule as n, Frame as o, NO_MODULES as r, useDynamicTailwind as t };
701
+ export { renderStableComponent as a, NO_PROPS as i, useCompiledModule as n, Frame as o, NO_MODULES as r, useIsClient as s, useDynamicTailwind as t };
627
702
 
628
- //# sourceMappingURL=use-dynamic-tailwind-B3l1qZRW.js.map
703
+ //# sourceMappingURL=use-dynamic-tailwind-CjXeHjsr.js.map