@teleporthq/teleport-plugin-common 0.45.3-alpha.0 → 0.45.13

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 (200) hide show
  1. package/__tests__/builders/html-builders.ts +9 -2
  2. package/__tests__/builders/style-builders.ts +135 -1
  3. package/__tests__/node-handlers/node-to-html/index.ts +2 -0
  4. package/__tests__/node-handlers/node-to-jsx/attribute-value-mapper.ts +77 -0
  5. package/__tests__/node-handlers/node-to-jsx/calendar-events-reviver.ts +176 -0
  6. package/__tests__/node-handlers/node-to-jsx/chart-data-guard.ts +101 -0
  7. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-ecommerce-source.ts +79 -0
  8. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-loading.ts +122 -0
  9. package/__tests__/node-handlers/node-to-jsx/index.ts +719 -3
  10. package/__tests__/node-handlers/node-to-jsx/url-search-params-expression.ts +59 -0
  11. package/__tests__/node-handlers/node-to-jsx/utils.ts +635 -3
  12. package/__tests__/utils/ast-utils.ts +188 -0
  13. package/__tests__/utils/content-property-sanitiser.ts +156 -0
  14. package/__tests__/utils/page-seeds-state-from-data-source.ts +70 -0
  15. package/__tests__/utils/parse-string-with-template-expressions.ts +82 -0
  16. package/__tests__/utils/resource-auth-scheme.ts +55 -0
  17. package/__tests__/utils/route-utils.ts +118 -0
  18. package/__tests__/utils/style-utils.ts +59 -0
  19. package/__tests__/utils/template-expression-balance.ts +83 -0
  20. package/__tests__/utils/url-query-writer.ts +239 -0
  21. package/__tests__/utils/url-search-param-sync.ts +138 -0
  22. package/__tests__/utils/url-search-params.ts +48 -0
  23. package/dist/cjs/builders/ast-builders.d.ts +2 -0
  24. package/dist/cjs/builders/ast-builders.d.ts.map +1 -1
  25. package/dist/cjs/builders/ast-builders.js +41 -3
  26. package/dist/cjs/builders/ast-builders.js.map +1 -1
  27. package/dist/cjs/builders/hast-builders.d.ts +1 -0
  28. package/dist/cjs/builders/hast-builders.d.ts.map +1 -1
  29. package/dist/cjs/builders/hast-builders.js +11 -1
  30. package/dist/cjs/builders/hast-builders.js.map +1 -1
  31. package/dist/cjs/builders/style-builders.d.ts +8 -2
  32. package/dist/cjs/builders/style-builders.d.ts.map +1 -1
  33. package/dist/cjs/builders/style-builders.js +80 -33
  34. package/dist/cjs/builders/style-builders.js.map +1 -1
  35. package/dist/cjs/index.d.ts +5 -1
  36. package/dist/cjs/index.d.ts.map +1 -1
  37. package/dist/cjs/index.js +10 -1
  38. package/dist/cjs/index.js.map +1 -1
  39. package/dist/cjs/node-handlers/node-to-html/constants.d.ts.map +1 -1
  40. package/dist/cjs/node-handlers/node-to-html/constants.js +2 -0
  41. package/dist/cjs/node-handlers/node-to-html/constants.js.map +1 -1
  42. package/dist/cjs/node-handlers/node-to-html/index.d.ts.map +1 -1
  43. package/dist/cjs/node-handlers/node-to-html/index.js +69 -1
  44. package/dist/cjs/node-handlers/node-to-html/index.js.map +1 -1
  45. package/dist/cjs/node-handlers/node-to-html/types.d.ts +5 -1
  46. package/dist/cjs/node-handlers/node-to-html/types.d.ts.map +1 -1
  47. package/dist/cjs/node-handlers/node-to-html/utils.d.ts +2 -1
  48. package/dist/cjs/node-handlers/node-to-html/utils.d.ts.map +1 -1
  49. package/dist/cjs/node-handlers/node-to-html/utils.js +174 -13
  50. package/dist/cjs/node-handlers/node-to-html/utils.js.map +1 -1
  51. package/dist/cjs/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  52. package/dist/cjs/node-handlers/node-to-jsx/index.js +1443 -45
  53. package/dist/cjs/node-handlers/node-to-jsx/index.js.map +1 -1
  54. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts +60 -6
  55. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  56. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts +80 -7
  57. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  58. package/dist/cjs/node-handlers/node-to-jsx/utils.js +883 -72
  59. package/dist/cjs/node-handlers/node-to-jsx/utils.js.map +1 -1
  60. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  61. package/dist/cjs/utils/ast-utils.d.ts +163 -11
  62. package/dist/cjs/utils/ast-utils.d.ts.map +1 -1
  63. package/dist/cjs/utils/ast-utils.js +1013 -75
  64. package/dist/cjs/utils/ast-utils.js.map +1 -1
  65. package/dist/cjs/utils/hast-utils.d.ts +8 -6
  66. package/dist/cjs/utils/hast-utils.d.ts.map +1 -1
  67. package/dist/cjs/utils/hast-utils.js +28 -4
  68. package/dist/cjs/utils/hast-utils.js.map +1 -1
  69. package/dist/cjs/utils/nested-selector-commas.d.ts +2 -0
  70. package/dist/cjs/utils/nested-selector-commas.d.ts.map +1 -0
  71. package/dist/cjs/utils/nested-selector-commas.js +81 -0
  72. package/dist/cjs/utils/nested-selector-commas.js.map +1 -0
  73. package/dist/cjs/utils/route-utils.d.ts +117 -0
  74. package/dist/cjs/utils/route-utils.d.ts.map +1 -0
  75. package/dist/cjs/utils/route-utils.js +212 -0
  76. package/dist/cjs/utils/route-utils.js.map +1 -0
  77. package/dist/cjs/utils/style-utils.d.ts +1 -0
  78. package/dist/cjs/utils/style-utils.d.ts.map +1 -1
  79. package/dist/cjs/utils/style-utils.js +181 -2
  80. package/dist/cjs/utils/style-utils.js.map +1 -1
  81. package/dist/cjs/utils/template-expression-balance.d.ts +58 -0
  82. package/dist/cjs/utils/template-expression-balance.d.ts.map +1 -0
  83. package/dist/cjs/utils/template-expression-balance.js +181 -0
  84. package/dist/cjs/utils/template-expression-balance.js.map +1 -0
  85. package/dist/cjs/utils/types.d.ts +3 -0
  86. package/dist/cjs/utils/types.d.ts.map +1 -0
  87. package/dist/cjs/utils/types.js +3 -0
  88. package/dist/cjs/utils/types.js.map +1 -0
  89. package/dist/cjs/utils/url-query-writer.d.ts +123 -0
  90. package/dist/cjs/utils/url-query-writer.d.ts.map +1 -0
  91. package/dist/cjs/utils/url-query-writer.js +260 -0
  92. package/dist/cjs/utils/url-query-writer.js.map +1 -0
  93. package/dist/cjs/utils/url-search-param-sync.d.ts +4 -0
  94. package/dist/cjs/utils/url-search-param-sync.d.ts.map +1 -0
  95. package/dist/cjs/utils/url-search-param-sync.js +241 -0
  96. package/dist/cjs/utils/url-search-param-sync.js.map +1 -0
  97. package/dist/cjs/utils/url-search-params.d.ts +48 -0
  98. package/dist/cjs/utils/url-search-params.d.ts.map +1 -0
  99. package/dist/cjs/utils/url-search-params.js +109 -0
  100. package/dist/cjs/utils/url-search-params.js.map +1 -0
  101. package/dist/esm/builders/ast-builders.d.ts +2 -0
  102. package/dist/esm/builders/ast-builders.d.ts.map +1 -1
  103. package/dist/esm/builders/ast-builders.js +40 -4
  104. package/dist/esm/builders/ast-builders.js.map +1 -1
  105. package/dist/esm/builders/hast-builders.d.ts +1 -0
  106. package/dist/esm/builders/hast-builders.d.ts.map +1 -1
  107. package/dist/esm/builders/hast-builders.js +9 -0
  108. package/dist/esm/builders/hast-builders.js.map +1 -1
  109. package/dist/esm/builders/style-builders.d.ts +8 -2
  110. package/dist/esm/builders/style-builders.d.ts.map +1 -1
  111. package/dist/esm/builders/style-builders.js +78 -32
  112. package/dist/esm/builders/style-builders.js.map +1 -1
  113. package/dist/esm/index.d.ts +5 -1
  114. package/dist/esm/index.d.ts.map +1 -1
  115. package/dist/esm/index.js +5 -1
  116. package/dist/esm/index.js.map +1 -1
  117. package/dist/esm/node-handlers/node-to-html/constants.d.ts.map +1 -1
  118. package/dist/esm/node-handlers/node-to-html/constants.js +2 -0
  119. package/dist/esm/node-handlers/node-to-html/constants.js.map +1 -1
  120. package/dist/esm/node-handlers/node-to-html/index.d.ts.map +1 -1
  121. package/dist/esm/node-handlers/node-to-html/index.js +71 -3
  122. package/dist/esm/node-handlers/node-to-html/index.js.map +1 -1
  123. package/dist/esm/node-handlers/node-to-html/types.d.ts +5 -1
  124. package/dist/esm/node-handlers/node-to-html/types.d.ts.map +1 -1
  125. package/dist/esm/node-handlers/node-to-html/utils.d.ts +2 -1
  126. package/dist/esm/node-handlers/node-to-html/utils.d.ts.map +1 -1
  127. package/dist/esm/node-handlers/node-to-html/utils.js +170 -13
  128. package/dist/esm/node-handlers/node-to-html/utils.js.map +1 -1
  129. package/dist/esm/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  130. package/dist/esm/node-handlers/node-to-jsx/index.js +1442 -47
  131. package/dist/esm/node-handlers/node-to-jsx/index.js.map +1 -1
  132. package/dist/esm/node-handlers/node-to-jsx/types.d.ts +60 -6
  133. package/dist/esm/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  134. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts +80 -7
  135. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  136. package/dist/esm/node-handlers/node-to-jsx/utils.js +875 -70
  137. package/dist/esm/node-handlers/node-to-jsx/utils.js.map +1 -1
  138. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  139. package/dist/esm/utils/ast-utils.d.ts +163 -11
  140. package/dist/esm/utils/ast-utils.d.ts.map +1 -1
  141. package/dist/esm/utils/ast-utils.js +989 -75
  142. package/dist/esm/utils/ast-utils.js.map +1 -1
  143. package/dist/esm/utils/hast-utils.d.ts +8 -6
  144. package/dist/esm/utils/hast-utils.d.ts.map +1 -1
  145. package/dist/esm/utils/hast-utils.js +26 -3
  146. package/dist/esm/utils/hast-utils.js.map +1 -1
  147. package/dist/esm/utils/nested-selector-commas.d.ts +2 -0
  148. package/dist/esm/utils/nested-selector-commas.d.ts.map +1 -0
  149. package/dist/esm/utils/nested-selector-commas.js +77 -0
  150. package/dist/esm/utils/nested-selector-commas.js.map +1 -0
  151. package/dist/esm/utils/route-utils.d.ts +117 -0
  152. package/dist/esm/utils/route-utils.d.ts.map +1 -0
  153. package/dist/esm/utils/route-utils.js +179 -0
  154. package/dist/esm/utils/route-utils.js.map +1 -0
  155. package/dist/esm/utils/style-utils.d.ts +1 -0
  156. package/dist/esm/utils/style-utils.d.ts.map +1 -1
  157. package/dist/esm/utils/style-utils.js +179 -1
  158. package/dist/esm/utils/style-utils.js.map +1 -1
  159. package/dist/esm/utils/template-expression-balance.d.ts +58 -0
  160. package/dist/esm/utils/template-expression-balance.d.ts.map +1 -0
  161. package/dist/esm/utils/template-expression-balance.js +174 -0
  162. package/dist/esm/utils/template-expression-balance.js.map +1 -0
  163. package/dist/esm/utils/types.d.ts +3 -0
  164. package/dist/esm/utils/types.d.ts.map +1 -0
  165. package/dist/esm/utils/types.js +2 -0
  166. package/dist/esm/utils/types.js.map +1 -0
  167. package/dist/esm/utils/url-query-writer.d.ts +123 -0
  168. package/dist/esm/utils/url-query-writer.d.ts.map +1 -0
  169. package/dist/esm/utils/url-query-writer.js +229 -0
  170. package/dist/esm/utils/url-query-writer.js.map +1 -0
  171. package/dist/esm/utils/url-search-param-sync.d.ts +4 -0
  172. package/dist/esm/utils/url-search-param-sync.d.ts.map +1 -0
  173. package/dist/esm/utils/url-search-param-sync.js +213 -0
  174. package/dist/esm/utils/url-search-param-sync.js.map +1 -0
  175. package/dist/esm/utils/url-search-params.d.ts +48 -0
  176. package/dist/esm/utils/url-search-params.d.ts.map +1 -0
  177. package/dist/esm/utils/url-search-params.js +81 -0
  178. package/dist/esm/utils/url-search-params.js.map +1 -0
  179. package/package.json +4 -4
  180. package/src/builders/ast-builders.ts +80 -3
  181. package/src/builders/hast-builders.ts +11 -0
  182. package/src/builders/style-builders.ts +121 -43
  183. package/src/index.ts +22 -1
  184. package/src/node-handlers/node-to-html/constants.ts +2 -0
  185. package/src/node-handlers/node-to-html/index.ts +126 -6
  186. package/src/node-handlers/node-to-html/types.ts +6 -0
  187. package/src/node-handlers/node-to-html/utils.ts +228 -14
  188. package/src/node-handlers/node-to-jsx/index.ts +2135 -62
  189. package/src/node-handlers/node-to-jsx/types.ts +75 -32
  190. package/src/node-handlers/node-to-jsx/utils.ts +1173 -84
  191. package/src/utils/ast-utils.ts +1316 -127
  192. package/src/utils/hast-utils.ts +37 -9
  193. package/src/utils/nested-selector-commas.ts +88 -0
  194. package/src/utils/route-utils.ts +214 -0
  195. package/src/utils/style-utils.ts +183 -1
  196. package/src/utils/template-expression-balance.ts +196 -0
  197. package/src/utils/types.ts +25 -0
  198. package/src/utils/url-query-writer.ts +318 -0
  199. package/src/utils/url-search-param-sync.ts +303 -0
  200. package/src/utils/url-search-params.ts +122 -0
@@ -1,29 +1,194 @@
1
1
  import * as types from '@babel/types'
2
2
 
3
- import { convertValueToLiteral } from '../../utils/ast-utils'
4
- import { StringUtils } from '@teleporthq/teleport-shared'
3
+ import {
4
+ coerceToDeclaredType,
5
+ convertToBinaryOperator,
6
+ convertToUnaryOperator,
7
+ convertValueToLiteral,
8
+ getExpressionFromUIDLExpressionNode,
9
+ } from '../../utils/ast-utils'
10
+ import { JSIdentifiers, StringUtils, UIDLUtils } from '@teleporthq/teleport-shared'
5
11
  import {
6
12
  UIDLPropDefinition,
7
13
  UIDLAttributeValue,
14
+ UIDLDynamicCondition,
8
15
  UIDLDynamicReference,
9
16
  UIDLStateDefinition,
10
17
  UIDLEventHandlerStatement,
11
18
  UIDLConditionalExpression,
19
+ UIDLConditionExpressionEntry,
20
+ UIDLConditionExpressionGroup,
12
21
  UIDLPropCallEvent,
13
22
  UIDLStateModifierEvent,
23
+ UIDLExpressionValue,
24
+ UIDLGlobalReference,
25
+ UIDLGlobalStateDefinition,
26
+ UIDLGlobalStateReference,
14
27
  } from '@teleporthq/teleport-types'
15
28
 
16
29
  import {
17
- BinaryOperator,
18
- UnaryOperation,
19
30
  JSXASTReturnType,
20
31
  ConditionalIdentifier,
21
32
  JSXGenerationParams,
22
33
  JSXGenerationOptions,
23
34
  } from './types'
35
+ import { generateIdWithRefPath } from '@teleporthq/teleport-shared/dist/cjs/utils/uidl-utils'
24
36
 
25
37
  // Adds all the event handlers and all the instructions for each event handler
26
38
  // in case there is more than one specified in the UIDL
39
+ /** HTML form controls that React treats as "controlled" when given a value/checked prop. */
40
+ const CONTROLLED_FORM_CONTROL_TAGS = new Set(['input', 'textarea', 'select'])
41
+
42
+ /**
43
+ * `<input type=...>` values the browser accepts ONLY in a narrow string format,
44
+ * mapped to the number of leading ISO-8601 characters that format requires:
45
+ * datetime-local → `YYYY-MM-DDTHH:mm` (16) date → `YYYY-MM-DD` (10)
46
+ * month → `YYYY-MM` (7)
47
+ * A stored timestamp such as `2026-07-21T20:00:00.000Z` (with seconds/ms and a
48
+ * `Z`) does NOT conform, so the input renders EMPTY — and when it is `required`
49
+ * the whole form fails HTML5 validation and can never submit (edit pages could
50
+ * not be saved). `time` is handled separately because its digits are not a
51
+ * simple prefix. Slicing the ISO STRING (not `new Date(...)`) keeps the nominal
52
+ * wall-clock value and avoids server/browser timezone shifts.
53
+ */
54
+ const DATE_TIME_INPUT_PREFIX_LENGTH: Record<string, number> = {
55
+ 'datetime-local': 16,
56
+ date: 10,
57
+ month: 7,
58
+ }
59
+
60
+ /** Reads a static `type="..."` off a JSX opening tag, lowercased; null if absent/dynamic. */
61
+ const getStaticInputType = (tag: types.JSXElement): string | null => {
62
+ const typeAttr = tag.openingElement.attributes.find(
63
+ (attr) =>
64
+ attr.type === 'JSXAttribute' &&
65
+ attr.name.type === 'JSXIdentifier' &&
66
+ attr.name.name === 'type'
67
+ ) as types.JSXAttribute | undefined
68
+ if (!typeAttr || !typeAttr.value || typeAttr.value.type !== 'StringLiteral') {
69
+ return null
70
+ }
71
+ return typeAttr.value.value.toLowerCase()
72
+ }
73
+
74
+ /**
75
+ * Wrap a bound `<input>` value expression so it renders in the format the input
76
+ * `type` requires. Returns the original expression untouched for non date/time
77
+ * types. `E` → `String(E || '').slice(0, N)` (date/datetime-local/month) or, for
78
+ * `time`, strip an optional leading `YYYY-MM-DD[T| ]` date then take `HH:mm`.
79
+ */
80
+ const buildDateTimeInputValueExpression = (
81
+ expression: types.Expression,
82
+ inputType: string,
83
+ t = types
84
+ ): types.Expression => {
85
+ const stringified = t.callExpression(t.identifier('String'), [
86
+ t.logicalExpression('||', expression, t.stringLiteral('')),
87
+ ])
88
+
89
+ if (inputType === 'time') {
90
+ const dateStripped = t.callExpression(
91
+ t.memberExpression(stringified, t.identifier('replace')),
92
+ [t.regExpLiteral('^\\d{4}-\\d{2}-\\d{2}[T ]', ''), t.stringLiteral('')]
93
+ )
94
+ return t.callExpression(t.memberExpression(dateStripped, t.identifier('slice')), [
95
+ t.numericLiteral(0),
96
+ t.numericLiteral(5),
97
+ ])
98
+ }
99
+
100
+ const prefixLength = DATE_TIME_INPUT_PREFIX_LENGTH[inputType]
101
+ return t.callExpression(t.memberExpression(stringified, t.identifier('slice')), [
102
+ t.numericLiteral(0),
103
+ t.numericLiteral(prefixLength),
104
+ ])
105
+ }
106
+
107
+ /**
108
+ * React FREEZES a controlled form control (`value`/`checked` set) that has no
109
+ * `onChange` — the user cannot type and a console warning is logged. This is the
110
+ * classic edit-form failure: entity-bound fields rendered `value={props.item?.x}`
111
+ * with no state mirror (the worker intentionally does not mirror entity columns
112
+ * into state). When an `<input>`/`<textarea>`/`<select>` has a `value` (or a
113
+ * checkbox/radio `checked`) attribute but NO `onChange` handler was attached, and
114
+ * it is not `readOnly`/`disabled`, convert it to UNCONTROLLED — `value`→
115
+ * `defaultValue`, `checked`→`defaultChecked`. The control then pre-fills, stays
116
+ * editable, and its live DOM value is what form-submit workflows read via
117
+ * `document.getElementById(id).value`. Controls that ARE controlled (an onChange
118
+ * was already attached — via UIDL events, the form-store binding, or a workflow
119
+ * trigger) and read-only/disabled display fields are left untouched.
120
+ *
121
+ * Must run AFTER all attributes and event handlers have been added to the tag.
122
+ * Mutates the tag in place; idempotent.
123
+ */
124
+ export const makeControlUncontrolledWhenNoChangeHandler = (
125
+ tag: types.JSXElement,
126
+ elementName: string,
127
+ t = types
128
+ ): void => {
129
+ if (!CONTROLLED_FORM_CONTROL_TAGS.has(elementName.toLowerCase())) {
130
+ return
131
+ }
132
+ const attributes = tag.openingElement.attributes
133
+ const hasNamedAttribute = (name: string): boolean =>
134
+ attributes.some(
135
+ (attr) =>
136
+ attr.type === 'JSXAttribute' &&
137
+ attr.name.type === 'JSXIdentifier' &&
138
+ attr.name.name === name
139
+ )
140
+
141
+ // An onChange means it is legitimately controlled; readOnly/disabled inputs are
142
+ // intentionally non-editable display fields (React does not warn on those).
143
+ if (
144
+ hasNamedAttribute('onChange') ||
145
+ hasNamedAttribute('readOnly') ||
146
+ hasNamedAttribute('disabled')
147
+ ) {
148
+ return
149
+ }
150
+
151
+ // A date/time `<input>` whose value is a dynamic binding (an entity-prefilled
152
+ // edit field) must have its ISO value reformatted to the input's required
153
+ // string shape, or the browser drops it and a `required` field blocks submit.
154
+ const inputType = elementName.toLowerCase() === 'input' ? getStaticInputType(tag) : null
155
+ const needsDateTimeFormat =
156
+ inputType !== null && (inputType === 'time' || inputType in DATE_TIME_INPUT_PREFIX_LENGTH)
157
+
158
+ const controlledToUncontrolled: Array<[string, string]> = [
159
+ ['value', 'defaultValue'],
160
+ ['checked', 'defaultChecked'],
161
+ ]
162
+ for (const [controlled, uncontrolled] of controlledToUncontrolled) {
163
+ const index = attributes.findIndex(
164
+ (attr) =>
165
+ attr.type === 'JSXAttribute' &&
166
+ attr.name.type === 'JSXIdentifier' &&
167
+ attr.name.name === controlled
168
+ )
169
+ if (index !== -1) {
170
+ const attr = attributes[index] as types.JSXAttribute
171
+ let attrValue = attr.value
172
+ if (
173
+ controlled === 'value' &&
174
+ needsDateTimeFormat &&
175
+ attrValue &&
176
+ attrValue.type === 'JSXExpressionContainer' &&
177
+ attrValue.expression.type !== 'JSXEmptyExpression'
178
+ ) {
179
+ attrValue = t.jsxExpressionContainer(
180
+ buildDateTimeInputValueExpression(
181
+ attrValue.expression as types.Expression,
182
+ inputType as string,
183
+ t
184
+ )
185
+ )
186
+ }
187
+ attributes.splice(index, 1, t.jsxAttribute(t.jsxIdentifier(uncontrolled), attrValue))
188
+ }
189
+ }
190
+ }
191
+
27
192
  export const addEventHandlerToTag = (
28
193
  tag: types.JSXElement,
29
194
  eventKey: string,
@@ -52,15 +217,24 @@ export const addEventHandlerToTag = (
52
217
  })
53
218
 
54
219
  let expressionContent: types.ArrowFunctionExpression | types.Expression
220
+ const functionParams = eventHandlerStatements.some(
221
+ (eventHandler) => eventHandler.includeEventObject
222
+ )
223
+ ? [t.identifier('event')]
224
+ : []
225
+
55
226
  if (eventHandlerASTStatements.length === 1) {
56
227
  const expression = eventHandlerASTStatements[0].expression
57
228
 
58
229
  expressionContent =
59
230
  expression.type === 'CallExpression' && expression.arguments.length === 0
60
231
  ? (expression.callee as types.ArrowFunctionExpression | types.Expression)
61
- : t.arrowFunctionExpression([], expression)
232
+ : t.arrowFunctionExpression(functionParams, expression)
62
233
  } else {
63
- expressionContent = t.arrowFunctionExpression([], t.blockStatement(eventHandlerASTStatements))
234
+ expressionContent = t.arrowFunctionExpression(
235
+ functionParams,
236
+ t.blockStatement(eventHandlerASTStatements)
237
+ )
64
238
  }
65
239
 
66
240
  tag.openingElement.attributes.push(
@@ -91,14 +265,37 @@ const createPropCallStatement = (
91
265
  const prefix = options.dynamicReferencePrefixMap.prop
92
266
  ? options.dynamicReferencePrefixMap.prop + '.'
93
267
  : ''
268
+ // Un-prefixed the prop name is called as a bare binding, so it must be
269
+ // identifier-safe; prefixed it is `props.<name>`, where the UIDL spelling is
270
+ // both legal and load-bearing.
271
+ const calleeName = prefix
272
+ ? prefix + propFunctionKey
273
+ : JSIdentifiers.createSafeJSIdentifier(propFunctionKey)
94
274
  return t.expressionStatement(
95
- t.callExpression(t.identifier(prefix + propFunctionKey), [
96
- ...args.map((arg) => convertValueToLiteral(arg)),
97
- ])
275
+ t.callExpression(t.identifier(calleeName), [...args.map((arg) => convertValueToLiteral(arg))])
98
276
  )
99
277
  }
100
278
 
101
- const createStateChangeStatement = (
279
+ /**
280
+ * Plan v14 — Type-aware state setter emitter.
281
+ *
282
+ * The old emitter unconditionally produced `setX(!x)` for `$toggle` and
283
+ * `setX(<literal>)` for primitives, regardless of the declared state
284
+ * type. That broke every multi-step form: `$toggle` on a numeric step
285
+ * state turned `1` into `false`, hiding every `state === N` panel; a
286
+ * primitive written to an object state replaced the whole object.
287
+ *
288
+ * The codegen here is now the safety net for what server-side Layers 1-3
289
+ * could not catch (legacy projects, AI bypass). When a combination is
290
+ * incoherent (e.g. `$toggle` on a number, or a bare string targeting an
291
+ * object), we skip the statement and warn — the workflow runtime handler
292
+ * remains the source of truth. Coherent combinations emit the same code
293
+ * as before, plus four new modifier shapes (`$increment` / `$decrement` /
294
+ * `$patch` / `$append`) that produce React functional setters.
295
+ *
296
+ * Returns `null` when the emitter declines (caller already handles null).
297
+ */
298
+ export const createStateChangeStatement = (
102
299
  eventHandlerStatement: UIDLStateModifierEvent,
103
300
  stateDefinitions: Record<string, UIDLStateDefinition>,
104
301
  options: JSXGenerationOptions,
@@ -111,86 +308,638 @@ const createStateChangeStatement = (
111
308
 
112
309
  const stateKey = eventHandlerStatement.modifies
113
310
  const stateDefinition = stateDefinitions[stateKey]
311
+ if (!stateDefinition) {
312
+ console.warn(
313
+ `State change references an undeclared state "${stateKey}" — skipping setter emission.`
314
+ )
315
+ return null
316
+ }
114
317
 
115
318
  const statePrefix = options.dynamicReferencePrefixMap.state
116
319
  ? options.dynamicReferencePrefixMap.state + '.'
117
320
  : ''
321
+ // Reading/writing the state through a prefix (`this.class`) is a member
322
+ // access and keeps the UIDL spelling; without one the name IS the binding
323
+ // and has to match what `createStateHookAST` declared.
324
+ const stateReadName = statePrefix
325
+ ? statePrefix + stateKey
326
+ : JSIdentifiers.createSafeJSIdentifier(stateKey)
118
327
 
119
- const newStateValue =
120
- eventHandlerStatement.newState === '$toggle'
121
- ? t.unaryExpression('!', t.identifier(statePrefix + stateKey))
122
- : convertValueToLiteral(eventHandlerStatement.newState, stateDefinition.type)
328
+ const declaredType = stateDefinition.type
329
+ const newState = eventHandlerStatement.newState
330
+ let newStateValue: types.Expression | undefined
331
+ let useFunctionalSetter = false
332
+ let functionalSetterBuilder: ((prevId: types.Identifier) => types.Expression) | undefined
123
333
 
124
- switch (options.stateHandling) {
125
- case 'hooks':
126
- return t.expressionStatement(
127
- t.callExpression(t.identifier(StringUtils.createStateStoringFunction(stateKey)), [
128
- newStateValue,
334
+ if (newState === '$toggle') {
335
+ // Boolean-only. Reject for number / object / array — emitting `!x`
336
+ // on those types is the v13/v14 regression we are fixing.
337
+ if (declaredType !== 'boolean') {
338
+ console.warn(
339
+ `[createStateChangeStatement] '$toggle' is only valid for boolean state; state "${stateKey}" is declared as ${declaredType}. Skipping setter to avoid corrupting state.`
340
+ )
341
+ return null
342
+ }
343
+ newStateValue = t.unaryExpression('!', t.identifier(stateReadName))
344
+ } else if (typeof newState === 'object' && newState !== null) {
345
+ const obj = newState as
346
+ | UIDLDynamicReference
347
+ | UIDLExpressionValue
348
+ | { type: '$increment' | '$decrement'; delta?: number }
349
+ | { type: '$patch'; path: string; value: unknown }
350
+ | { type: '$append'; value: unknown }
351
+ const objType = (obj as { type?: string }).type
352
+ if (objType === 'expr') {
353
+ newStateValue = getExpressionFromUIDLExpressionNode(newState as UIDLExpressionValue)
354
+ } else if (objType === 'dynamic') {
355
+ newStateValue = createDynamicValueExpression(newState as UIDLDynamicReference, options)
356
+ } else if (objType === '$increment' || objType === '$decrement') {
357
+ if (declaredType !== 'number') {
358
+ console.warn(
359
+ `[createStateChangeStatement] '${objType}' requires a numeric state; "${stateKey}" is declared as ${declaredType}. Skipping setter.`
360
+ )
361
+ return null
362
+ }
363
+ // Honor the sign of `delta`: an $increment with delta -2 is a
364
+ // deliberate decrement by 2 (the type doc documents this). The
365
+ // builder emits `prev + delta` for $increment and `prev - delta`
366
+ // for $decrement, then the absolute value of |delta| is the
367
+ // numeric literal we feed in. Math.abs prevents the rare double-
368
+ // negative case where someone writes `{ type: '$decrement', delta: -1 }`
369
+ // (intended +1) from emitting `prev - -1` (which would be `+1`
370
+ // via JS coercion but is unreadable).
371
+ const rawDelta = (obj as { delta?: number }).delta ?? 1
372
+ const operator: '+' | '-' =
373
+ objType === '$increment' ? (rawDelta < 0 ? '-' : '+') : rawDelta < 0 ? '+' : '-'
374
+ const magnitude = Math.abs(rawDelta)
375
+ useFunctionalSetter = true
376
+ functionalSetterBuilder = (prevId) =>
377
+ t.binaryExpression(operator, prevId, t.numericLiteral(magnitude))
378
+ } else if (objType === '$patch') {
379
+ if (declaredType !== 'object') {
380
+ console.warn(
381
+ `[createStateChangeStatement] '$patch' requires an object state; "${stateKey}" is declared as ${declaredType}. Skipping setter.`
382
+ )
383
+ return null
384
+ }
385
+ const patch = obj as { type: '$patch'; path: string; value: unknown }
386
+ if (!patch.path || typeof patch.path !== 'string') {
387
+ console.warn(
388
+ `[createStateChangeStatement] '$patch' requires a string "path"; received "${String(
389
+ patch.path
390
+ )}" for state "${stateKey}". Skipping setter.`
391
+ )
392
+ return null
393
+ }
394
+ const patchValueAst = convertValueToLiteral(
395
+ patch.value as string | number | boolean,
396
+ 'string'
397
+ )
398
+ useFunctionalSetter = true
399
+ functionalSetterBuilder = (prevId) =>
400
+ t.objectExpression([
401
+ t.spreadElement(prevId),
402
+ t.objectProperty(t.identifier(patch.path), patchValueAst, false, false),
129
403
  ])
404
+ } else if (objType === '$append') {
405
+ if (declaredType !== 'array') {
406
+ console.warn(
407
+ `[createStateChangeStatement] '$append' requires an array state; "${stateKey}" is declared as ${declaredType}. Skipping setter.`
408
+ )
409
+ return null
410
+ }
411
+ const appended = obj as { type: '$append'; value: unknown }
412
+ const appendedValueAst = convertValueToLiteral(
413
+ appended.value as string | number | boolean,
414
+ 'string'
130
415
  )
131
- case 'function':
416
+ useFunctionalSetter = true
417
+ functionalSetterBuilder = (prevId) =>
418
+ t.arrayExpression([t.spreadElement(prevId), appendedValueAst])
419
+ } else {
420
+ // Unknown object shape — fall back to literal conversion only when
421
+ // the declared type accepts a primitive write.
422
+ if (declaredType === 'object' || declaredType === 'array') {
423
+ console.warn(
424
+ `[createStateChangeStatement] Unrecognised modifier shape on a ${declaredType} state "${stateKey}"; skipping setter to avoid corrupting state.`
425
+ )
426
+ return null
427
+ }
428
+ newStateValue = convertValueToLiteral(newState as unknown as string, declaredType)
429
+ }
430
+ } else {
431
+ // Bare primitive (`'oily'`, `2`, `true`). Coerce against the declared type.
432
+ // For object/array state, writing a primitive REPLACES the structure.
433
+ // That is the bug — fail safe.
434
+ if (declaredType === 'object' || declaredType === 'array') {
435
+ console.warn(
436
+ `[createStateChangeStatement] Refusing to overwrite ${declaredType} state "${stateKey}" with a primitive value (${JSON.stringify(
437
+ newState
438
+ )}). Use '$patch' / '$append' modifiers instead. Skipping setter.`
439
+ )
440
+ return null
441
+ }
442
+ newStateValue = convertValueToLiteral(newState as string | number | boolean, declaredType)
443
+ }
444
+
445
+ switch (options.stateHandling) {
446
+ case 'hooks': {
447
+ const setterId = t.identifier(StringUtils.createStateStoringFunction(stateKey))
448
+ if (useFunctionalSetter && functionalSetterBuilder) {
449
+ const prevId = t.identifier('prev')
450
+ const arrow = t.arrowFunctionExpression([prevId], functionalSetterBuilder(prevId))
451
+ return t.expressionStatement(t.callExpression(setterId, [arrow]))
452
+ }
453
+ if (!newStateValue) {
454
+ return null
455
+ }
456
+ return t.expressionStatement(t.callExpression(setterId, [newStateValue]))
457
+ }
458
+ case 'function': {
459
+ // Class-component setState path is legacy; functional setters aren't
460
+ // supported via `this.setState(prev => …)` here, so for the new
461
+ // modifiers we fall back to skipping. The hooks path is the path the
462
+ // multi-step form actually exercises.
463
+ if (useFunctionalSetter) {
464
+ console.warn(
465
+ `[createStateChangeStatement] Functional-setter modifiers are only supported under stateHandling="hooks". Skipping setter for "${stateKey}".`
466
+ )
467
+ return null
468
+ }
469
+ if (!newStateValue) {
470
+ return null
471
+ }
132
472
  return t.expressionStatement(
133
473
  t.callExpression(t.identifier('this.setState'), [
134
474
  t.objectExpression([t.objectProperty(t.identifier(stateKey), newStateValue)]),
135
475
  ])
136
476
  )
477
+ }
137
478
  case 'mutation':
138
- default:
479
+ default: {
480
+ if (useFunctionalSetter) {
481
+ console.warn(
482
+ `[createStateChangeStatement] Functional-setter modifiers are only supported under stateHandling="hooks". Skipping setter for "${stateKey}".`
483
+ )
484
+ return null
485
+ }
486
+ if (!newStateValue) {
487
+ return null
488
+ }
139
489
  return t.expressionStatement(
140
- t.assignmentExpression('=', t.identifier(statePrefix + stateKey), newStateValue)
490
+ t.assignmentExpression('=', t.identifier(stateReadName), newStateValue)
141
491
  )
492
+ }
142
493
  }
143
494
  }
144
495
 
496
+ export const resolveGlobalStateName = (
497
+ id: string,
498
+ definitions?: Record<string, UIDLGlobalStateDefinition>
499
+ ): string => {
500
+ if (!definitions) {
501
+ return id
502
+ }
503
+ for (const def of Object.values(definitions)) {
504
+ if (def.id === id) {
505
+ return def.name
506
+ }
507
+ }
508
+ return id
509
+ }
510
+
511
+ // Matches the leading JS identifier of an expression, e.g. `foo` from
512
+ // `foo?.['bar'] || []`. Used to recognise when a string-encoded UIDL source
513
+ // (cms-list-repeater `source`) is rooted at a global-state name so the
514
+ // generator can register the reference for `useGlobalState()` destructuring.
515
+ const LEADING_IDENTIFIER_RE = /^([A-Za-z_$][A-Za-z0-9_$]*)/
516
+
517
+ // Older versions of the UIDL emitter encoded a global-state reference as the
518
+ // magic literal `globalState_<defId>` instead of the declared variable name.
519
+ // Detect that prefix so we can rewrite it to the proper identifier and fix
520
+ // already-published UIDL documents without forcing them to be regenerated.
521
+ const LEGACY_GLOBAL_STATE_RE = /^globalState_([A-Za-z0-9_-]+)/
522
+
523
+ /**
524
+ * Given a string-encoded UIDL `source` expression, resolve any global-state
525
+ * reference into the proper JS identifier for the generator and ensure the
526
+ * reference is registered for `useGlobalState()` destructuring.
527
+ *
528
+ * Two upstream encodings are accepted:
529
+ * 1. Modern shape — leading identifier is the declared state name
530
+ * (e.g. `countriesWithDescriptions || []`). We just register it.
531
+ * 2. Legacy shape — leading identifier is the magic placeholder
532
+ * `globalState_<defId>` (e.g. `globalState_TQ_96vaRH5pdf['key']`). We
533
+ * rewrite the placeholder to the declared name AND register it.
534
+ *
535
+ * Returns the (possibly rewritten) source string. The caller should embed
536
+ * the returned string instead of the input.
537
+ */
538
+ export const resolveAndRegisterGlobalStateSource = (
539
+ source: string | undefined,
540
+ params: JSXGenerationParams
541
+ ): string => {
542
+ const original = source ?? ''
543
+ if (!original) {
544
+ return original
545
+ }
546
+ const definitions = params.globalStateDefinitions
547
+ if (!definitions || Object.keys(definitions).length === 0) {
548
+ return original
549
+ }
550
+
551
+ const legacyMatch = original.match(LEGACY_GLOBAL_STATE_RE)
552
+ if (legacyMatch) {
553
+ const id = legacyMatch[1]
554
+ for (const def of Object.values(definitions)) {
555
+ if (def.id === id) {
556
+ params.globalStateReferences.push({ id: def.id, name: def.name })
557
+ // The rewritten source is embedded as code, so the placeholder becomes
558
+ // the LOCAL binding — the sanitised name the destructuring declares.
559
+ return original.replace(
560
+ LEGACY_GLOBAL_STATE_RE,
561
+ JSIdentifiers.createSafeJSIdentifier(def.name)
562
+ )
563
+ }
564
+ }
565
+ // Legacy prefix found but no matching definition (orphaned reference).
566
+ // Leave the source untouched; the downstream identifier creation will
567
+ // still emit something, and a separate sanity pass can flag it.
568
+ return original
569
+ }
570
+
571
+ const leadingMatch = original.match(LEADING_IDENTIFIER_RE)
572
+ if (leadingMatch) {
573
+ const leadingName = leadingMatch[1]
574
+ for (const def of Object.values(definitions)) {
575
+ if (def.name === leadingName) {
576
+ params.globalStateReferences.push({ id: def.id, name: def.name })
577
+ return original
578
+ }
579
+ }
580
+ }
581
+
582
+ return original
583
+ }
584
+
585
+ export const createGlobalStateExpression = (
586
+ ref: UIDLGlobalStateReference,
587
+ definitions?: Record<string, UIDLGlobalStateDefinition>,
588
+ t = types
589
+ ): types.Identifier | types.OptionalMemberExpression => {
590
+ // The global-state name is destructured out of `useGlobalState()` as a local
591
+ // binding, so it goes through the same sanitiser the destructuring site uses.
592
+ const name = JSIdentifiers.createSafeJSIdentifier(
593
+ resolveGlobalStateName(ref.content.id, definitions)
594
+ )
595
+ const refPath = ref.content.refPath || []
596
+
597
+ if (refPath.length === 0) {
598
+ return t.identifier(name)
599
+ }
600
+
601
+ let expr: types.Identifier | types.OptionalMemberExpression = t.identifier(name)
602
+ for (const segment of refPath) {
603
+ expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true)
604
+ }
605
+ return expr
606
+ }
607
+
145
608
  export const createDynamicValueExpression = (
146
- identifier: UIDLDynamicReference,
609
+ identifier: UIDLDynamicReference | UIDLGlobalReference,
610
+ options: JSXGenerationOptions,
611
+ t = types
612
+ ) => {
613
+ const inner = createDynamicValueExpressionRaw(identifier, options, t)
614
+
615
+ // When the UIDL content carries a `valueMapper`, wrap the resolved
616
+ // expression in a sandboxed IIFE that runs the user's `mapValue(value)`
617
+ // and falls back to the raw value on error. This mirrors the state
618
+ // definition `wrapWithMappingFunction` pattern and lets any framework
619
+ // that re-uses `createDynamicValueExpression` inherit the behaviour.
620
+ const valueMapper = (identifier.content as { valueMapper?: string }).valueMapper?.trim() || ''
621
+ if (!valueMapper) {
622
+ return inner
623
+ }
624
+ return wrapExpressionWithValueMapperAst(inner, valueMapper, t)
625
+ }
626
+
627
+ const wrapExpressionWithValueMapperAst = (
628
+ innerExpression: types.Expression,
629
+ valueMapper: string,
630
+ t = types
631
+ ): types.Expression => {
632
+ // Build: ((v) => { try { return (new Function('value', '"use strict"; <mapper>; return mapValue(value);')).call(null, v) } catch (_e) { return v } })(<inner>)
633
+ //
634
+ // We deliberately use `new Function(...)` at runtime rather than parsing
635
+ // the mapper body into AST statements here. That keeps this plugin free
636
+ // of a parser dependency, matches the sandboxing used by state-definition
637
+ // `wrapWithMappingFunction`, and ensures the generated code is framework
638
+ // agnostic — only stringify semantics + `toString()` on primitives are
639
+ // required for the output to render correctly.
640
+ const tryBlock = t.tryStatement(
641
+ t.blockStatement([
642
+ t.returnStatement(
643
+ t.callExpression(
644
+ t.memberExpression(
645
+ t.newExpression(t.identifier('Function'), [
646
+ t.stringLiteral('value'),
647
+ t.stringLiteral(`"use strict"; ${valueMapper}; return mapValue(value);`),
648
+ ]),
649
+ t.identifier('call')
650
+ ),
651
+ [t.nullLiteral(), t.identifier('v')]
652
+ )
653
+ ),
654
+ ]),
655
+ t.catchClause(t.identifier('_e'), t.blockStatement([t.returnStatement(t.identifier('v'))]))
656
+ )
657
+ const arrow = t.arrowFunctionExpression([t.identifier('v')], t.blockStatement([tryBlock]))
658
+ return t.callExpression(arrow, [innerExpression])
659
+ }
660
+
661
+ const createDynamicValueExpressionRaw = (
662
+ identifier: UIDLDynamicReference | UIDLGlobalReference,
147
663
  options: JSXGenerationOptions,
148
664
  t = types
149
665
  ) => {
150
666
  const identifierContent = identifier.content
667
+ const refPath = identifier.content.refPath || []
151
668
  const { referenceType, id } = identifierContent
152
669
 
153
670
  if (referenceType === 'attr' || referenceType === 'children' || referenceType === 'token') {
154
671
  throw new Error(`Dynamic reference type "${referenceType}" is not supported yet`)
155
672
  }
156
673
 
674
+ // 'ctx' references resolve to the data source context render prop identifier
675
+ // using only the refPath to build property access
676
+ if (referenceType === 'ctx') {
677
+ const ctxPrefix = (options.dynamicReferencePrefixMap as Record<string, string>).ctx || ''
678
+ if (ctxPrefix && refPath.length > 0) {
679
+ let expr: types.Expression = t.identifier(ctxPrefix)
680
+ for (const path of refPath) {
681
+ expr = t.optionalMemberExpression(expr, t.identifier(path), false, true)
682
+ }
683
+ return expr
684
+ }
685
+ // Details-page fallback: an unresolvable `ctx` reference on a details page
686
+ // (its ctxId points at no known render-prop context — e.g. a synthetic
687
+ // `details-page-generic-*` id produced for a widget's `target`) is still a
688
+ // column on the fetched row exposed as a prop. Resolve it exactly like the
689
+ // `local` branch below → `props.<exposeAs>.<refPath>` (e.g.
690
+ // `props.webinar?.scheduled_at`), so the widget binds the real value.
691
+ if (options.detailsPageExposeAsName && refPath.length > 0) {
692
+ const propPrefix =
693
+ (options.dynamicReferencePrefixMap as Record<string, string>).prop || 'props'
694
+ let expr: types.Expression = t.memberExpression(
695
+ t.identifier(propPrefix),
696
+ t.identifier(options.detailsPageExposeAsName)
697
+ )
698
+ for (const path of refPath) {
699
+ expr = t.optionalMemberExpression(expr, t.identifier(path), false, true)
700
+ }
701
+ return expr
702
+ }
703
+ // Last resort: NEVER emit a bare identifier for an unresolved ctx reference —
704
+ // `generateIdWithRefPath(id, …)` yields an UNDECLARED variable (e.g.
705
+ // `tQQGFGA6h4I`), which throws `ReferenceError` during SSR and crashes the
706
+ // Vercel `next build` export (run 1b6eb5ba: `/webinar-detail/[id]`). Emit the
707
+ // reference's declared `fallbackValue` literal, or `undefined`.
708
+ const ctxFallbackValue = (identifierContent as { fallbackValue?: unknown }).fallbackValue
709
+ if (
710
+ typeof ctxFallbackValue === 'string' ||
711
+ typeof ctxFallbackValue === 'number' ||
712
+ typeof ctxFallbackValue === 'boolean'
713
+ ) {
714
+ return convertValueToLiteral(ctxFallbackValue)
715
+ }
716
+ return t.identifier('undefined')
717
+ }
718
+
719
+ // `urlSearchParams` references read a declared key from the URL query string.
720
+ // Next.js generators typically set `dynamicReferencePrefixMap.urlSearchParams`
721
+ // to `'router.query'` so we emit `router.query.<key>`. Static / HTML
722
+ // generators set it to `'__urlSearchParams'` and inject a `const
723
+ // __urlSearchParams = new URLSearchParams(location.search)` prelude.
724
+ //
725
+ // `options.urlSearchParamsRegistry` (set by the plugin based on the page
726
+ // UIDL's `searchParams` definition) supplies per-key defaults so we emit
727
+ // `(router.query.category ?? 'food')` with the declared fallback.
728
+ if (referenceType === 'urlSearchParams') {
729
+ const paramKey = refPath[0] || id
730
+ const urlParamsPrefix =
731
+ (options.dynamicReferencePrefixMap as Record<string, string | undefined>).urlSearchParams ||
732
+ 'router.query'
733
+ const [rootPrefix, ...restPath] = urlParamsPrefix.split('.')
734
+ let expr: types.Expression = t.identifier(rootPrefix)
735
+ for (const segment of restPath) {
736
+ expr = t.memberExpression(expr, t.identifier(segment))
737
+ }
738
+ expr = t.optionalMemberExpression(expr, t.identifier(paramKey), false, true)
739
+ const registry = (options as Record<string, unknown>).urlSearchParamsRegistry as
740
+ | Record<string, { defaultValue?: string }>
741
+ | undefined
742
+ const declaredDefault = registry?.[paramKey]?.defaultValue
743
+ if (declaredDefault !== undefined && declaredDefault !== '') {
744
+ expr = t.logicalExpression('??', expr, t.stringLiteral(declaredDefault))
745
+ }
746
+ return expr
747
+ }
748
+
749
+ // 'local' references resolve to the iteration variable of the enclosing repeater.
750
+ // The reference id in UIDL is a node id (e.g. "TQ_xxxxxx") and carries no meaning
751
+ // at runtime — the only load-bearing pieces are the refPath and the current
752
+ // localIdentifier (set when walking into a repeater/data-provider's children).
753
+ if (referenceType === 'local') {
754
+ const localPrefix =
755
+ options.localIdentifier ||
756
+ (options.dynamicReferencePrefixMap as Record<string, string>).local ||
757
+ ''
758
+ if (localPrefix) {
759
+ if (refPath.length === 0) {
760
+ return t.identifier(localPrefix)
761
+ }
762
+ let expr: types.Expression = t.identifier(localPrefix)
763
+ for (const path of refPath) {
764
+ expr = t.optionalMemberExpression(expr, t.identifier(path), false, true)
765
+ }
766
+ return expr
767
+ }
768
+
769
+ // Details-page fallback: a page-root `local` reference (no enclosing
770
+ // repeater) means "a column on the fetched row" exposed as a prop under
771
+ // `initialPropsData.exposeAs.name`. Resolve to `props.<name>.<refPath>`.
772
+ if (options.detailsPageExposeAsName && refPath.length > 0) {
773
+ const propPrefix =
774
+ (options.dynamicReferencePrefixMap as Record<string, string>).prop || 'props'
775
+ let expr: types.Expression = t.memberExpression(
776
+ t.identifier(propPrefix),
777
+ t.identifier(options.detailsPageExposeAsName)
778
+ )
779
+ for (const path of refPath) {
780
+ expr = t.optionalMemberExpression(expr, t.identifier(path), false, true)
781
+ }
782
+ return expr
783
+ }
784
+ }
785
+
786
+ const idWithPath = generateIdWithRefPath(id, refPath)
787
+
157
788
  const prefix =
158
789
  options.dynamicReferencePrefixMap[referenceType as 'prop' | 'state' | 'local'] || ''
790
+
791
+ // With no prefix the id IS the binding (React hooks: `class`), so it has to
792
+ // be sanitised exactly the way the declaration was. With a prefix it is a
793
+ // MEMBER (`props.class`, `this.class`), where a reserved word is perfectly
794
+ // legal and renaming it would point at a property that does not exist.
159
795
  return prefix === ''
160
- ? t.identifier(id)
161
- : t.memberExpression(t.identifier(prefix), t.identifier(id))
796
+ ? t.identifier(JSIdentifiers.createSafeJSIdentifierPath(idWithPath))
797
+ : t.memberExpression(t.identifier(prefix), t.identifier(idWithPath))
162
798
  }
163
799
 
164
800
  // Prepares an identifier (from props or state or an expr) to be used as a conditional rendering identifier
165
801
  // Assumes the type from the corresponding props/state definitions if not expr. Expressions are expected to have a boolean return here
166
802
  export const createConditionIdentifier = (
167
- dynamicReference: UIDLDynamicReference,
803
+ dynamicReference: UIDLDynamicReference | UIDLExpressionValue,
168
804
  params: JSXGenerationParams,
169
805
  options: JSXGenerationOptions
170
806
  ): ConditionalIdentifier => {
171
- const { id, referenceType } = dynamicReference.content
807
+ if (dynamicReference.type === 'expr') {
808
+ return {
809
+ key: dynamicReference.content,
810
+ type: 'boolean',
811
+ isExpression: true,
812
+ }
813
+ }
814
+
815
+ const { id, referenceType, refPath } = dynamicReference.content
816
+
817
+ // Handle local references (from repeaters/loops) - they don't have an id
818
+ if (referenceType === 'local') {
819
+ // For local references, the identifier comes from the refPath
820
+ const refPathKey = refPath && refPath.length > 0 ? refPath.join('.') : ''
821
+ const prefix = options.localIdentifier || ''
822
+
823
+ // Details-page fallback: at the page root there is no enclosing repeater,
824
+ // so a `local` reference means "a column on the fetched row" exposed as a
825
+ // prop under `initialPropsData.exposeAs.name`.
826
+ if (!prefix && options.detailsPageExposeAsName && refPathKey) {
827
+ const propPrefix =
828
+ (options.dynamicReferencePrefixMap as Record<string, string> | undefined)?.prop || 'props'
829
+ return {
830
+ key: `${options.detailsPageExposeAsName}.${refPathKey}`,
831
+ type: 'string',
832
+ prefix: propPrefix,
833
+ }
834
+ }
835
+
836
+ return {
837
+ key: refPathKey,
838
+ type: 'string', // Default to string, actual type will be determined at runtime
839
+ prefix,
840
+ }
841
+ }
842
+
843
+ if (referenceType === 'global') {
844
+ return {
845
+ key: UIDLUtils.generateIdWithRefPath(id, refPath),
846
+ type: 'string',
847
+ prefix: '',
848
+ referenceType: 'global',
849
+ }
850
+ }
851
+
852
+ if ((referenceType as string) === 'globalState') {
853
+ const resolvedName = resolveGlobalStateName(id, params.globalStateDefinitions)
854
+ const refPathSegments = refPath || []
855
+ const key =
856
+ refPathSegments.length > 0
857
+ ? refPathSegments.reduce((acc, seg) => `${acc}?.${seg}`, resolvedName)
858
+ : resolvedName
859
+
860
+ return {
861
+ key,
862
+ type: 'string',
863
+ prefix: '',
864
+ referenceType: 'globalState',
865
+ }
866
+ }
867
+
868
+ // A value of the page address's query string, read the way the value path
869
+ // above reads it (`router.query.<key>` in Next, the prelude's object in a
870
+ // static generator) — e.g. a categories overview that steps aside while a
871
+ // search narrows the list.
872
+ if (referenceType === 'urlSearchParams') {
873
+ return {
874
+ key: refPath?.[0] || id,
875
+ type: 'string',
876
+ prefix:
877
+ (options.dynamicReferencePrefixMap as Record<string, string | undefined>).urlSearchParams ||
878
+ 'router.query',
879
+ }
880
+ }
172
881
 
173
882
  // in case the id is a member expression: eg: fields.name
174
883
  const referenceRoot = id.split('.')[0]
884
+ const currentType =
885
+ referenceType === 'prop'
886
+ ? params.propDefinitions[referenceRoot]?.type
887
+ : params.stateDefinitions[referenceRoot]?.type
888
+
889
+ let type = currentType
890
+ if (refPath?.length) {
891
+ if (referenceType === 'prop' && params.propDefinitions[referenceRoot]?.defaultValue) {
892
+ let currentValue = params.propDefinitions[referenceRoot].defaultValue as Record<
893
+ string,
894
+ unknown
895
+ >
896
+ for (const path of refPath) {
897
+ currentValue = currentValue?.[path] as Record<string, unknown>
898
+ type = currentValue ? typeof currentValue : currentType
899
+ }
900
+ } else if (referenceType === 'state' && currentType === 'object') {
901
+ const stateDef = params.stateDefinitions[referenceRoot]
902
+ if (
903
+ stateDef &&
904
+ typeof stateDef.defaultValue === 'object' &&
905
+ stateDef.defaultValue !== null &&
906
+ !Array.isArray(stateDef.defaultValue)
907
+ ) {
908
+ const objectDefault = stateDef.defaultValue as Record<
909
+ string,
910
+ { type?: string; content?: unknown }
911
+ >
912
+ const entry = objectDefault[refPath[0]]
913
+ if (entry?.type === 'static' && entry.content !== undefined) {
914
+ type = typeof entry.content
915
+ } else {
916
+ type = 'string'
917
+ }
918
+ }
919
+ }
920
+ }
175
921
 
176
922
  switch (referenceType) {
177
923
  case 'prop':
178
924
  return {
179
- key: id,
180
- type: params.propDefinitions[referenceRoot].type,
925
+ key: UIDLUtils.generateIdWithRefPath(id, refPath),
926
+ type,
181
927
  prefix: options.dynamicReferencePrefixMap.prop,
182
928
  }
183
929
  case 'state':
184
930
  return {
185
- key: id,
186
- type: params.stateDefinitions[referenceRoot].type,
931
+ key: UIDLUtils.generateIdWithRefPath(id, refPath),
932
+ type,
187
933
  prefix: options.dynamicReferencePrefixMap.state,
188
934
  }
935
+
189
936
  case 'expr':
190
937
  return {
191
938
  key: id,
192
939
  type: 'boolean',
940
+ isExpression: true,
193
941
  }
942
+
194
943
  default:
195
944
  throw new Error(
196
945
  `createConditionIdentifier encountered an invalid reference type: ${JSON.stringify(
@@ -202,10 +951,22 @@ export const createConditionIdentifier = (
202
951
  }
203
952
  }
204
953
 
954
+ interface ConditionalJSXExpressionOptions {
955
+ localIdentifier?: string
956
+ detailsPageExposeAsName?: string
957
+ // Resolves the identifier for a leaf entry carrying its own `reference`;
958
+ // returning undefined (or omitting the hook) inherits the chain's
959
+ // top-level identifier.
960
+ resolveEntryIdentifier?: (
961
+ entry: UIDLConditionExpressionEntry
962
+ ) => ConditionalIdentifier | undefined
963
+ }
964
+
205
965
  export const createConditionalJSXExpression = (
206
966
  content: JSXASTReturnType,
207
967
  conditionalExpression: UIDLConditionalExpression,
208
968
  conditionalIdentifier: ConditionalIdentifier,
969
+ options: ConditionalJSXExpressionOptions = {},
209
970
  t = types
210
971
  ) => {
211
972
  let contentNode: types.Expression
@@ -218,54 +979,363 @@ export const createConditionalJSXExpression = (
218
979
  contentNode = content
219
980
  }
220
981
 
221
- let binaryExpression:
222
- | types.LogicalExpression
223
- | types.BinaryExpression
224
- | types.UnaryExpression
225
- | types.Identifier
226
- | types.MemberExpression
982
+ const binaryExpression = createConditionChainExpression(
983
+ conditionalExpression,
984
+ conditionalIdentifier,
985
+ options,
986
+ t
987
+ )
988
+
989
+ return t.logicalExpression('&&', binaryExpression, contentNode)
990
+ }
227
991
 
228
- // When the stateValue is an object we will compute a logical/binary expression on the left side
229
- const { conditions, matchingCriteria } = conditionalExpression
230
- const binaryExpressions = conditions.map((condition) =>
231
- createBinaryExpression(condition, conditionalIdentifier)
992
+ // Folds a (possibly nested) conditions chain into one expression. Group
993
+ // entries recurse with their own matchingCriteria — the AST nesting is what
994
+ // the printer emits as parentheses.
995
+ const createConditionChainExpression = (
996
+ chain: UIDLConditionalExpression | UIDLConditionExpressionGroup,
997
+ conditionalIdentifier: ConditionalIdentifier,
998
+ options: ConditionalJSXExpressionOptions,
999
+ t = types
1000
+ ): types.Expression => {
1001
+ const { conditions, matchingCriteria } = chain
1002
+ const entryExpressions = conditions.map((entry) =>
1003
+ UIDLUtils.isUIDLConditionGroup(entry)
1004
+ ? createConditionChainExpression(entry, conditionalIdentifier, options, t)
1005
+ : createBinaryExpression(
1006
+ entry,
1007
+ options.resolveEntryIdentifier?.(entry) ?? conditionalIdentifier,
1008
+ options
1009
+ )
232
1010
  )
233
1011
 
234
- if (binaryExpressions.length === 1) {
235
- binaryExpression = binaryExpressions[0]
236
- } else {
237
- // the first two binary expressions are put together as a logical expression
238
- const [firstExp, secondExp] = binaryExpressions
239
- const operation = matchingCriteria === 'all' ? '&&' : '||'
240
- let expression: types.LogicalExpression = t.logicalExpression(operation, firstExp, secondExp)
1012
+ if (entryExpressions.length === 0) {
1013
+ // An empty group cannot gate anything; degrade to a pass-through.
1014
+ return t.booleanLiteral(true)
1015
+ }
241
1016
 
242
- // accumulate the rest of the expressions to the logical expression
243
- for (let index = 2; index < binaryExpressions.length; index++) {
244
- expression = t.logicalExpression(operation, expression, binaryExpressions[index])
245
- }
1017
+ if (entryExpressions.length === 1) {
1018
+ return entryExpressions[0]
1019
+ }
1020
+
1021
+ // the first two expressions are put together as a logical expression
1022
+ const operation = matchingCriteria === 'all' ? '&&' : '||'
1023
+ let expression: types.LogicalExpression = t.logicalExpression(
1024
+ operation,
1025
+ entryExpressions[0],
1026
+ entryExpressions[1]
1027
+ )
246
1028
 
247
- binaryExpression = expression
1029
+ // accumulate the rest of the expressions to the logical expression
1030
+ for (let index = 2; index < entryExpressions.length; index++) {
1031
+ expression = t.logicalExpression(operation, expression, entryExpressions[index])
248
1032
  }
249
1033
 
250
- return t.logicalExpression('&&', binaryExpression, contentNode)
1034
+ return expression
1035
+ }
1036
+
1037
+ /**
1038
+ * The test a conditionally-bound class applies under: every rule of its chain,
1039
+ * joined by the chain's matchingCriteria, or the single `value` it equals. A
1040
+ * condition with neither can never hold, so there is no test and the caller
1041
+ * leaves the class off.
1042
+ */
1043
+ export const createClassConditionExpression = (
1044
+ condition: UIDLDynamicCondition,
1045
+ conditionalIdentifier: ConditionalIdentifier
1046
+ ): types.Expression | null => {
1047
+ if (condition.expression?.conditions?.length) {
1048
+ return createConditionChainExpression(condition.expression, conditionalIdentifier, {})
1049
+ }
1050
+ if (condition.value !== undefined) {
1051
+ return createBinaryExpression(
1052
+ { operation: '===', operand: condition.value },
1053
+ conditionalIdentifier
1054
+ )
1055
+ }
1056
+ return null
1057
+ }
1058
+
1059
+ /**
1060
+ * Resolves an operand value to an AST expression, handling dynamic refs, expressions, and static values.
1061
+ */
1062
+ const resolveOperandExpression = (
1063
+ operand: string | number | boolean | UIDLDynamicReference | UIDLExpressionValue,
1064
+ conditionalIdentifier: ConditionalIdentifier,
1065
+ options: { localIdentifier?: string; detailsPageExposeAsName?: string }
1066
+ ): types.Expression => {
1067
+ if (typeof operand === 'object' && 'type' in operand && operand.type === 'expr') {
1068
+ return getExpressionFromUIDLExpressionNode(operand)
1069
+ }
1070
+
1071
+ if (typeof operand === 'object' && 'type' in operand && operand.type === 'dynamic') {
1072
+ return createDynamicValueExpression(operand, {
1073
+ dynamicReferencePrefixMap: {
1074
+ prop: 'props',
1075
+ state: '',
1076
+ local: '',
1077
+ },
1078
+ localIdentifier: options.localIdentifier,
1079
+ detailsPageExposeAsName: options.detailsPageExposeAsName,
1080
+ })
1081
+ }
1082
+
1083
+ return convertValueToLiteral(operand, conditionalIdentifier.type)
1084
+ }
1085
+
1086
+ /**
1087
+ * `resolveOperandExpression` for an operand that is ONE ELEMENT of the bound
1088
+ * collection (`contains` / `notContains`), not a value of the collection's own
1089
+ * type.
1090
+ *
1091
+ * The typed resolver parses a static operand as the identifier's type, which
1092
+ * for an array-typed state means `JSON.parse`: the string `"5"` came out as the
1093
+ * number `5`, `"true"` as `true`. The rows an array state actually holds are
1094
+ * whatever a workflow pushed — strings, read off `data-*` attributes — so
1095
+ * `selectedRatings.includes(5)` never matched `["5"]` and a ticked rating
1096
+ * checkbox stayed empty. The literal keeps the type it was authored with, which
1097
+ * is also how the editor's canvas evaluates the same condition.
1098
+ */
1099
+ const resolveElementOperandExpression = (
1100
+ operand: string | number | boolean | UIDLDynamicReference | UIDLExpressionValue,
1101
+ conditionalIdentifier: ConditionalIdentifier,
1102
+ options: { localIdentifier?: string; detailsPageExposeAsName?: string }
1103
+ ): types.Expression =>
1104
+ resolveOperandExpression(operand, { ...conditionalIdentifier, type: '' }, options)
1105
+
1106
+ /**
1107
+ * Coerce a conditional identifier to an empty collection when it is null or
1108
+ * undefined, so the collection operators below can dereference it safely.
1109
+ *
1110
+ * The bound value is absent far more often than it looks: an optional CMS
1111
+ * column, a category without an image, a state that has not hydrated yet. A
1112
+ * bare `x.length` / `x.includes(...)` then throws `Cannot read properties of
1113
+ * null` during render and takes the whole page down with an unhandled runtime
1114
+ * error — a condition whose entire job is to HIDE a node must never be able to
1115
+ * do that. `x || []` keeps string semantics intact (a non-empty string is
1116
+ * truthy and carries both `.length` and `.includes`) while turning nullish
1117
+ * values into a harmless empty collection; objects get `{}` for `Object.keys`
1118
+ * / `hasOwnProperty`, which reject `null` outright.
1119
+ */
1120
+ const createNullSafeCollection = (
1121
+ identifier: types.Expression,
1122
+ conditionalIdentifier: ConditionalIdentifier,
1123
+ t = types
1124
+ ): types.Expression =>
1125
+ t.logicalExpression(
1126
+ '||',
1127
+ identifier,
1128
+ conditionalIdentifier.type === 'object' ? t.objectExpression([]) : t.arrayExpression([])
1129
+ )
1130
+
1131
+ /** `x.length` — via `Object.keys(x).length` for objects — on a nullish-safe target. */
1132
+ const createLengthExpression = (
1133
+ identifier: types.Expression,
1134
+ conditionalIdentifier: ConditionalIdentifier,
1135
+ t = types
1136
+ ): types.Expression => {
1137
+ const target = createNullSafeCollection(identifier, conditionalIdentifier, t)
1138
+ return conditionalIdentifier.type === 'object'
1139
+ ? t.memberExpression(
1140
+ t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('keys')), [
1141
+ target,
1142
+ ]),
1143
+ t.identifier('length')
1144
+ )
1145
+ : t.memberExpression(target, t.identifier('length'))
1146
+ }
1147
+
1148
+ /**
1149
+ * A UIDL `expr` reference whose whole body is a JavaScript LITERAL.
1150
+ *
1151
+ * `expr` content is source, not a name, so it must never reach the reserved
1152
+ * word sanitiser: the domain-to-UIDL mapper emits the literal `false` as its
1153
+ * "this condition could not be resolved" fallback (an orphaned state/prop
1154
+ * reference), and `t.identifier(createSafeJSIdentifierPath('false'))` prints
1155
+ * `false_` — an undefined binding that throws
1156
+ * `ReferenceError: false_ is not defined` while the page is rendering, taking
1157
+ * the whole page down instead of quietly rendering nothing.
1158
+ *
1159
+ * Only complete literals are matched. Anything else (`chatMessage?.sender`,
1160
+ * `props.product?.slug`) keeps the historical verbatim-identifier printing,
1161
+ * including the sanitiser pass that a state genuinely named `class` relies on.
1162
+ */
1163
+ const NUMERIC_LITERAL_RE = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/
1164
+
1165
+ const createJSLiteralExpression = (source: string, t = types): types.Expression | null => {
1166
+ switch (source) {
1167
+ case 'true':
1168
+ return t.booleanLiteral(true)
1169
+ case 'false':
1170
+ return t.booleanLiteral(false)
1171
+ case 'null':
1172
+ return t.nullLiteral()
1173
+ case 'undefined':
1174
+ return t.identifier('undefined')
1175
+ default:
1176
+ return NUMERIC_LITERAL_RE.test(source) ? t.numericLiteral(Number(source)) : null
1177
+ }
1178
+ }
1179
+
1180
+ /** The left-hand side of one condition, as an AST node. */
1181
+ const createConditionalIdentifierExpression = (
1182
+ conditionalIdentifier: ConditionalIdentifier,
1183
+ t = types
1184
+ ): types.Expression => {
1185
+ // Same rule as `createDynamicValueExpression`: an un-prefixed key is the
1186
+ // binding itself and must be identifier-safe; a prefixed one is a member
1187
+ // access that has to keep the UIDL's original spelling.
1188
+ if (conditionalIdentifier.prefix) {
1189
+ return t.memberExpression(
1190
+ t.identifier(conditionalIdentifier.prefix),
1191
+ t.identifier(conditionalIdentifier.key)
1192
+ )
1193
+ }
1194
+
1195
+ if (conditionalIdentifier.isExpression) {
1196
+ const literal = createJSLiteralExpression(conditionalIdentifier.key, t)
1197
+ if (literal) {
1198
+ return literal
1199
+ }
1200
+ }
1201
+
1202
+ return t.identifier(JSIdentifiers.createSafeJSIdentifierPath(conditionalIdentifier.key))
251
1203
  }
252
1204
 
253
1205
  export const createBinaryExpression = (
254
1206
  condition: {
255
1207
  operation: string
256
- operand?: string | number | boolean
1208
+ operand?: string | number | boolean | UIDLDynamicReference | UIDLExpressionValue
1209
+ containsField?: string
257
1210
  },
258
1211
  conditionalIdentifier: ConditionalIdentifier,
1212
+ options: { localIdentifier?: string; detailsPageExposeAsName?: string } = {},
259
1213
  t = types
260
1214
  ) => {
261
- const { operand, operation } = condition
262
- const identifier = conditionalIdentifier.prefix
263
- ? t.memberExpression(
264
- t.identifier(conditionalIdentifier.prefix),
265
- t.identifier(conditionalIdentifier.key)
1215
+ const { operand, operation, containsField } = condition
1216
+ const identifier = createConditionalIdentifierExpression(conditionalIdentifier, t)
1217
+
1218
+ // Array/Object operators
1219
+ if (operation === 'isEmpty') {
1220
+ return t.binaryExpression(
1221
+ '===',
1222
+ createLengthExpression(identifier, conditionalIdentifier, t),
1223
+ t.numericLiteral(0)
1224
+ )
1225
+ }
1226
+
1227
+ if (operation === 'isNotEmpty') {
1228
+ return t.binaryExpression(
1229
+ '>',
1230
+ createLengthExpression(identifier, conditionalIdentifier, t),
1231
+ t.numericLiteral(0)
1232
+ )
1233
+ }
1234
+
1235
+ if (operation === 'lengthEquals' && operand !== undefined) {
1236
+ return t.binaryExpression(
1237
+ '===',
1238
+ createLengthExpression(identifier, conditionalIdentifier, t),
1239
+ resolveOperandExpression(operand, conditionalIdentifier, options)
1240
+ )
1241
+ }
1242
+
1243
+ if (operation === 'lengthGreaterThan' && operand !== undefined) {
1244
+ return t.binaryExpression(
1245
+ '>',
1246
+ createLengthExpression(identifier, conditionalIdentifier, t),
1247
+ resolveOperandExpression(operand, conditionalIdentifier, options)
1248
+ )
1249
+ }
1250
+
1251
+ if (operation === 'lengthLessThan' && operand !== undefined) {
1252
+ return t.binaryExpression(
1253
+ '<',
1254
+ createLengthExpression(identifier, conditionalIdentifier, t),
1255
+ resolveOperandExpression(operand, conditionalIdentifier, options)
1256
+ )
1257
+ }
1258
+
1259
+ if (operation === 'contains' && operand !== undefined) {
1260
+ const operandExpr = resolveElementOperandExpression(operand, conditionalIdentifier, options)
1261
+ const target = createNullSafeCollection(identifier, conditionalIdentifier, t)
1262
+
1263
+ if (containsField) {
1264
+ const itemParam = t.identifier('__item')
1265
+ return t.callExpression(t.memberExpression(target, t.identifier('some')), [
1266
+ t.arrowFunctionExpression(
1267
+ [itemParam],
1268
+ t.binaryExpression(
1269
+ '===',
1270
+ t.memberExpression(itemParam, t.identifier(containsField)),
1271
+ operandExpr
1272
+ )
1273
+ ),
1274
+ ])
1275
+ }
1276
+
1277
+ return t.callExpression(t.memberExpression(target, t.identifier('includes')), [operandExpr])
1278
+ }
1279
+
1280
+ if (operation === 'notContains' && operand !== undefined) {
1281
+ const operandExpr = resolveElementOperandExpression(operand, conditionalIdentifier, options)
1282
+ const target = createNullSafeCollection(identifier, conditionalIdentifier, t)
1283
+
1284
+ if (containsField) {
1285
+ const itemParam = t.identifier('__item')
1286
+ return t.unaryExpression(
1287
+ '!',
1288
+ t.callExpression(t.memberExpression(target, t.identifier('some')), [
1289
+ t.arrowFunctionExpression(
1290
+ [itemParam],
1291
+ t.binaryExpression(
1292
+ '===',
1293
+ t.memberExpression(itemParam, t.identifier(containsField)),
1294
+ operandExpr
1295
+ )
1296
+ ),
1297
+ ])
266
1298
  )
267
- : t.identifier(conditionalIdentifier.key)
1299
+ }
1300
+
1301
+ return t.unaryExpression(
1302
+ '!',
1303
+ t.callExpression(t.memberExpression(target, t.identifier('includes')), [operandExpr])
1304
+ )
1305
+ }
1306
+
1307
+ if (operation === 'hasKey' && operand !== undefined) {
1308
+ const operandExpr = resolveOperandExpression(operand, conditionalIdentifier, options)
1309
+ return t.callExpression(
1310
+ t.memberExpression(
1311
+ t.memberExpression(
1312
+ t.memberExpression(t.identifier('Object'), t.identifier('prototype')),
1313
+ t.identifier('hasOwnProperty')
1314
+ ),
1315
+ t.identifier('call')
1316
+ ),
1317
+ [createNullSafeCollection(identifier, conditionalIdentifier, t), operandExpr]
1318
+ )
1319
+ }
1320
+
1321
+ if (operation === 'notHasKey' && operand !== undefined) {
1322
+ const operandExpr = resolveOperandExpression(operand, conditionalIdentifier, options)
1323
+ return t.unaryExpression(
1324
+ '!',
1325
+ t.callExpression(
1326
+ t.memberExpression(
1327
+ t.memberExpression(
1328
+ t.memberExpression(t.identifier('Object'), t.identifier('prototype')),
1329
+ t.identifier('hasOwnProperty')
1330
+ ),
1331
+ t.identifier('call')
1332
+ ),
1333
+ [createNullSafeCollection(identifier, conditionalIdentifier, t), operandExpr]
1334
+ )
1335
+ )
1336
+ }
268
1337
 
1338
+ // Standard binary operators
269
1339
  if (operation === '===') {
270
1340
  if (operand === true) {
271
1341
  return identifier
@@ -277,33 +1347,52 @@ export const createBinaryExpression = (
277
1347
  }
278
1348
 
279
1349
  if (operand !== undefined) {
280
- const stateValueIdentifier = convertValueToLiteral(operand, conditionalIdentifier.type)
1350
+ if (typeof operand === 'object' && 'type' in operand && operand.type === 'expr') {
1351
+ const exprIdentifier = getExpressionFromUIDLExpressionNode(operand)
281
1352
 
282
- return t.binaryExpression(convertToBinaryOperator(operation), identifier, stateValueIdentifier)
283
- } else {
284
- return operation ? t.unaryExpression(convertToUnaryOperator(operation), identifier) : identifier
285
- }
286
- }
1353
+ return t.binaryExpression(convertToBinaryOperator(operation), identifier, exprIdentifier)
1354
+ }
287
1355
 
288
- /**
289
- * Because of the restrictions of the AST Types we need to have a clear subset of binary operators we can use
290
- * @param operation - the operation defined in the UIDL for the current state branch
291
- */
292
- const convertToBinaryOperator = (operation: string): BinaryOperator => {
293
- const allowedOperations = ['===', '!==', '>=', '<=', '>', '<']
294
- if (allowedOperations.includes(operation)) {
295
- return operation as BinaryOperator
296
- } else {
297
- return '==='
298
- }
299
- }
1356
+ if (typeof operand === 'object' && 'type' in operand && operand.type === 'dynamic') {
1357
+ const dynamicValueIdentifier = createDynamicValueExpression(operand, {
1358
+ dynamicReferencePrefixMap: {
1359
+ prop: 'props',
1360
+ state: '',
1361
+ local: '',
1362
+ },
1363
+ localIdentifier: options.localIdentifier,
1364
+ })
1365
+
1366
+ return t.binaryExpression(
1367
+ convertToBinaryOperator(operation),
1368
+ identifier,
1369
+ dynamicValueIdentifier
1370
+ )
1371
+ }
1372
+
1373
+ // An expression's type is a placeholder, not the type of its value.
1374
+ const stateValueIdentifier = convertValueToLiteral(
1375
+ coerceToDeclaredType(
1376
+ operand,
1377
+ conditionalIdentifier.isExpression ? undefined : conditionalIdentifier.type
1378
+ ),
1379
+ conditionalIdentifier.type
1380
+ )
300
1381
 
301
- const convertToUnaryOperator = (operation: string): UnaryOperation => {
302
- const allowedOperations = ['!']
303
- if (allowedOperations.includes(operation)) {
304
- return operation as UnaryOperation
1382
+ const lhs =
1383
+ (conditionalIdentifier.referenceType === 'global' ||
1384
+ conditionalIdentifier.referenceType === 'globalState') &&
1385
+ typeof operand === 'string'
1386
+ ? t.optionalCallExpression(
1387
+ t.optionalMemberExpression(identifier, t.identifier('toString'), false, true),
1388
+ [],
1389
+ false
1390
+ )
1391
+ : identifier
1392
+
1393
+ return t.binaryExpression(convertToBinaryOperator(operation), lhs, stateValueIdentifier)
305
1394
  } else {
306
- return '!'
1395
+ return operation ? t.unaryExpression(convertToUnaryOperator(operation), identifier) : identifier
307
1396
  }
308
1397
  }
309
1398