@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
@@ -10,19 +10,64 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
10
10
  import * as types from '@babel/types';
11
11
  import { parse } from '@babel/core';
12
12
  import ParsedASTNode from './parsed-ast';
13
- import { StringUtils } from '@teleporthq/teleport-shared';
13
+ import { JSIdentifiers, StringUtils, UIDLUtils } from '@teleporthq/teleport-shared';
14
14
  import babelPresetReact from '@babel/preset-react';
15
- import { ASTUtils } from '..';
15
+ import { balanceExpression, countUnclosedStaticParens } from './template-expression-balance';
16
16
  /**
17
- * Adds a class definition string to an existing string of classes
17
+ * Converts HTML attribute names to React/JSX camelCase format
18
+ * Preserves data-* and aria-* attributes as-is
19
+ */
20
+ /**
21
+ * React sets attributes on CUSTOM ELEMENTS (dash-named tags) verbatim, so
22
+ * camelCasing them is not just unnecessary — it breaks the element:
23
+ * `camera-controls` camelCased to `cameraControls` reaches the DOM as the
24
+ * meaningless `cameracontrols`. Web-component tags keep their attribute
25
+ * spelling untouched.
26
+ */
27
+ export var isCustomElementTagName = function (jsxNode) {
28
+ var name = jsxNode.openingElement.name;
29
+ return name.type === 'JSXIdentifier' && name.name.includes('-');
30
+ };
31
+ export var resolveAttributeNameForTag = function (jsxNode, attrName) {
32
+ return isCustomElementTagName(jsxNode) ? attrName : convertToReactAttributeName(attrName);
33
+ };
34
+ export var convertToReactAttributeName = function (attrName) {
35
+ if (attrName.startsWith('data-') || attrName.startsWith('aria-')) {
36
+ return attrName;
37
+ }
38
+ var htmlToReact = {
39
+ colspan: 'colSpan',
40
+ rowspan: 'rowSpan',
41
+ maxlength: 'maxLength',
42
+ minlength: 'minLength',
43
+ readonly: 'readOnly',
44
+ autocomplete: 'autoComplete',
45
+ autofocus: 'autoFocus',
46
+ tabindex: 'tabIndex',
47
+ contenteditable: 'contentEditable',
48
+ spellcheck: 'spellCheck',
49
+ };
50
+ if (htmlToReact[attrName]) {
51
+ return htmlToReact[attrName];
52
+ }
53
+ return attrName.replace(/-([a-z])/g, function (_, letter) { return letter.toUpperCase(); });
54
+ };
55
+ /**
56
+ * Adds a CSS class definition string to an existing string of classes
18
57
  */
19
58
  export var addClassStringOnJSXTag = function (jsxNode, classString, classAttributeName, dynamicValues) {
20
59
  if (dynamicValues === void 0) { dynamicValues = []; }
60
+ if (classString === '' && dynamicValues.length === 0) {
61
+ return;
62
+ }
21
63
  var classAttribute = getClassAttribute(jsxNode, { createIfNotFound: true, classAttributeName: classAttributeName });
22
64
  if (dynamicValues.length === 0) {
23
65
  if (classAttribute.value && classAttribute.value.type === 'StringLiteral') {
24
66
  var classArray = classAttribute.value.value.split(' ');
25
- classArray.push(classString);
67
+ if (classString) {
68
+ classArray.push(classString);
69
+ }
70
+ classArray.filter(function (item) { return item; });
26
71
  classAttribute.value.value = classArray.join(' ').trim();
27
72
  }
28
73
  else {
@@ -72,10 +117,16 @@ var getClassAttribute = function (jsxNode, _a, t) {
72
117
  export var addDynamicAttributeToJSXTag = function (jsxASTNode, name, value, prefix, t) {
73
118
  if (prefix === void 0) { prefix = ''; }
74
119
  if (t === void 0) { t = types; }
120
+ var reactName = resolveAttributeNameForTag(jsxASTNode, name);
121
+ // Same rule as `createDynamicValueExpression`: with no prefix the value IS the
122
+ // binding (React hooks state), so it must match the sanitised name
123
+ // `createStateHookAST` declared — `value={class}` does not parse. With a
124
+ // prefix it is `props.class` / `this.class`, where the UIDL spelling is legal
125
+ // AND load-bearing, so it is left alone.
75
126
  var content = prefix === ''
76
- ? t.identifier(value)
127
+ ? t.identifier(JSIdentifiers.createSafeJSIdentifierPath(value))
77
128
  : t.memberExpression(t.identifier(prefix), t.identifier(value));
78
- jsxASTNode.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier(name), t.jsxExpressionContainer(content)));
129
+ jsxASTNode.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier(reactName), t.jsxExpressionContainer(content)));
79
130
  };
80
131
  /**
81
132
  * Make code expressions happen in AST
@@ -83,13 +134,47 @@ export var addDynamicAttributeToJSXTag = function (jsxASTNode, name, value, pref
83
134
  * the corresponding value from the contexts for now
84
135
  * and in the future with other sources.
85
136
  */
137
+ /**
138
+ * UIDL `expr` values are opaque JavaScript expressions, but authoring tools
139
+ * (notably Teleport-GUI while the differentiator-navlink contract is mid-
140
+ * migration) occasionally emit malformed template literals with empty
141
+ * substitutions like `` `/profile/${}` ``. Babel rejects these and the whole
142
+ * generation run fails.
143
+ *
144
+ * We only repair a narrow set of known-safe patterns to avoid silently
145
+ * masking real UIDL bugs:
146
+ * 1. `/profile/${}` → `/profile/${currentUser?.id}` (My Profile navlink
147
+ * per the dual-mode profile page contract).
148
+ * 2. any remaining empty `${}` → `${''}` — at least the output parses and
149
+ * the placeholder is visibly empty at runtime.
150
+ * Each repair logs a warning so the upstream UIDL bug remains visible.
151
+ */
152
+ export var sanitizeExprContent = function (content, attrKey) {
153
+ if (typeof content !== 'string' || !content.includes('${}')) {
154
+ return content;
155
+ }
156
+ var repaired = content;
157
+ // My Profile navlink: the differentiator is always the session user's id.
158
+ repaired = repaired.replace(/`([^`]*\/profile\/)\$\{\}([^`]*)`/g, '`$1' + '$' + '{' + 'currentUser?.id}' + '$2`');
159
+ // Generic fallback: any other empty `${}` becomes an empty string literal so
160
+ // downstream Babel parsing succeeds. This is intentionally lossy — the goal
161
+ // is not to guess the original intent, just to keep the build from crashing.
162
+ if (repaired.includes('${}')) {
163
+ repaired = repaired.replace(/\$\{\}/g, '$' + '{' + "'" + "'" + '}');
164
+ }
165
+ if (repaired !== content) {
166
+ // tslint:disable-next-line:no-console
167
+ console.warn("[teleport] Repaired malformed empty template substitution in expr".concat(attrKey ? " attribute \"".concat(attrKey, "\"") : '', ": ").concat(content, " \u2192 ").concat(repaired));
168
+ }
169
+ return repaired;
170
+ };
86
171
  export var addDynamicExpressionAttributeToJSXTag = function (jsxASTNode, dynamicRef, attrKey, t) {
87
172
  if (t === void 0) { t = types; }
88
173
  var dynamicContent = dynamicRef.content;
89
174
  if (dynamicRef.type !== 'expr') {
90
175
  throw new Error("This method only works with dynamic nodes that have code expressions");
91
176
  }
92
- var code = dynamicContent;
177
+ var code = sanitizeExprContent(dynamicContent, attrKey);
93
178
  var options = {
94
179
  sourceType: 'module',
95
180
  };
@@ -101,7 +186,18 @@ export var addDynamicExpressionAttributeToJSXTag = function (jsxASTNode, dynamic
101
186
  if (theStatementOnlyWihtoutTheProgram.type !== 'ExpressionStatement') {
102
187
  throw new Error("Expr dynamic attribute only support expressions statements at the moment.");
103
188
  }
104
- jsxASTNode.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier(attrKey), t.jsxExpressionContainer(theStatementOnlyWihtoutTheProgram.expression)));
189
+ var expression = theStatementOnlyWihtoutTheProgram.expression;
190
+ // When an expression accesses `.value` on a simple identifier (e.g. `galleryImage?.value`),
191
+ // wrap it with a typeof check so that if the item is already a string we use it directly:
192
+ // `typeof galleryImage === 'string' ? galleryImage : galleryImage?.value`
193
+ if ((expression.type === 'OptionalMemberExpression' || expression.type === 'MemberExpression') &&
194
+ expression.object.type === 'Identifier' &&
195
+ expression.property.type === 'Identifier' &&
196
+ expression.property.name === 'value') {
197
+ var varName = expression.object.name;
198
+ expression = t.conditionalExpression(t.binaryExpression('===', t.unaryExpression('typeof', t.identifier(varName)), t.stringLiteral('string')), t.identifier(varName), expression);
199
+ }
200
+ jsxASTNode.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier(convertToReactAttributeName(attrKey)), t.jsxExpressionContainer(expression)));
105
201
  };
106
202
  /*
107
203
  Use, when we need to add a mix of dynamic and static values to
@@ -142,34 +238,248 @@ export var stringAsTemplateLiteral = function (str) {
142
238
  .children[0];
143
239
  return container.expression;
144
240
  };
241
+ /**
242
+ * Checks if a string contains {{ expression }} template patterns
243
+ */
244
+ export var containsTemplateExpression = function (str) {
245
+ return /\{\{.+?\}\}/.test(str);
246
+ };
247
+ /**
248
+ * Parses a JavaScript expression string into an AST Expression node.
249
+ * e.g. "item.type || 'coin'" → LogicalExpression AST
250
+ */
251
+ export var parseJSExpressionAsAST = function (expr) {
252
+ var ast = parse("(".concat(expr, ")"), {
253
+ sourceType: 'module',
254
+ });
255
+ if (!ast || !('program' in ast)) {
256
+ throw new Error("Failed to parse expression: ".concat(expr));
257
+ }
258
+ return ast.program.body[0].expression;
259
+ };
260
+ /**
261
+ * Parses a string containing {{ expr }} template patterns into a TemplateLiteral AST node.
262
+ * e.g. "translate({{ enemy.x || '0' }}px)" → `translate(${enemy.x || '0'}px)`
263
+ */
264
+ export var parseStringWithTemplateExpressions = function (str) {
265
+ // Step 1: Normalize state references: state.xxx → xxx
266
+ var normalized = str.replace(/state\.(\w+)/g, '$1');
267
+ // Step 2: Convert well-formed {{ expr }} to ${expr}
268
+ //
269
+ // The expression is BALANCED on the way in. A binding that lost a closing
270
+ // paren upstream (`-(cameraX || ''`) produces source Babel cannot parse, and
271
+ // no amount of patching the static text around it can help — the repair has
272
+ // to happen inside the interpolation, which is the only place the bracket is
273
+ // actually missing.
274
+ var templateStr = normalized.replace(/\{\{\s*(.+?)\s*\}\}/g, function (_, expr) { return '${' + balanceExpression(expr.trim()) + '}'; });
275
+ // Step 3: Handle unclosed {{ expr (no closing }})
276
+ // After step 2, any remaining {{ was not well-formed
277
+ if (/\{\{/.test(templateStr)) {
278
+ templateStr = templateStr.replace(/\{\{\s*(.+?)$/gm, function (_, expr) { return '${' + balanceExpression(expr.trim()) + '}'; });
279
+ }
280
+ // Step 4: Detect and fix incomplete CSS function calls
281
+ // If the original string contained a CSS function like translateX(...) or translate(...)
282
+ // but the template expression consumed the closing, we need to re-close it.
283
+ //
284
+ // Counted over the STATIC text only. Including the parentheses inside `${…}`
285
+ // made an imbalance in the expression look like an unclosed CSS function, so
286
+ // this step appended a unit and a `)` to the end of a string whose real fault
287
+ // was several characters earlier and inside the interpolation.
288
+ var missingStaticCloses = countUnclosedStaticParens(templateStr);
289
+ if (missingStaticCloses > 0) {
290
+ // Determine the CSS unit by:
291
+ // 1. Looking for existing units already in the string (e.g. "translate(${x}px, ${y" → px)
292
+ // 2. Inferring from the CSS function name
293
+ var existingUnit = templateStr.match(/(px|deg|em|rem|%|vh|vw)[),\s]/);
294
+ var unit = 'px'; // default
295
+ if (existingUnit) {
296
+ unit = existingUnit[1];
297
+ }
298
+ else {
299
+ // Infer unit from the CSS function name
300
+ var fnMatch = templateStr.match(/\b(rotate|skew|skewX|skewY)\s*\(/);
301
+ if (fnMatch) {
302
+ unit = 'deg';
303
+ }
304
+ var noUnitFns = /\b(scale|scaleX|scaleY|scale3d|opacity)\s*\(/;
305
+ if (noUnitFns.test(templateStr)) {
306
+ unit = '';
307
+ }
308
+ }
309
+ templateStr += unit + ')'.repeat(missingStaticCloses);
310
+ }
311
+ // Step 5: Parse — and NEVER let a single malformed binding abort the build.
312
+ //
313
+ // The inline-style caller has no error handling of its own, so an
314
+ // unparseable template used to escape as a raw Babel SyntaxError and take the
315
+ // whole project generation down with it. A UIDL can always carry a binding
316
+ // this module cannot rescue (hand-edited, produced by an older pipeline, or
317
+ // broken in a way `balanceExpression` refuses to guess at), and the right
318
+ // answer is to degrade that ONE value: emit the original text as a plain
319
+ // string so the property still renders and the other 99 pages still build.
320
+ try {
321
+ var ast = parse('const x = `' + templateStr + '`', {
322
+ sourceType: 'module',
323
+ });
324
+ if (ast && 'program' in ast) {
325
+ var decl = ast.program.body[0];
326
+ return decl.declarations[0].init;
327
+ }
328
+ }
329
+ catch (_a) {
330
+ // Fall through to the static fallback below.
331
+ }
332
+ return staticTemplateLiteral(stripTemplateExpressions(str));
333
+ };
334
+ /**
335
+ * Drop every `{{ … }}` binding from a string, keeping any `'literal'` fallback
336
+ * it declared. `translateX({{ -(x || 0) }}px)` → `translateX(px)` is useless as
337
+ * a style value, but `{{ name || 'Guest' }}` → `Guest` keeps the text the
338
+ * author intended. Used only when the expression could not be parsed at all.
339
+ */
340
+ var stripTemplateExpressions = function (value) {
341
+ return value.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, function (_, expr) {
342
+ var literalFallback = /\|\|\s*(['"])([\s\S]*?)\1\s*$/.exec(expr);
343
+ return literalFallback ? literalFallback[2] : '';
344
+ });
345
+ };
346
+ /** A TemplateLiteral with no interpolations, holding `value` verbatim. */
347
+ var staticTemplateLiteral = function (value) {
348
+ return types.templateLiteral([types.templateElement({ raw: value.replace(/[\\`]/g, '\\$&'), cooked: value }, true)], []);
349
+ };
350
+ var REACT_BOOLEAN_DOM_PROPS = new Set([
351
+ 'disabled',
352
+ 'required',
353
+ 'readOnly',
354
+ 'checked',
355
+ 'multiple',
356
+ 'hidden',
357
+ 'autoFocus',
358
+ 'muted',
359
+ 'loop',
360
+ 'playsInline',
361
+ 'autoPlay',
362
+ 'controls',
363
+ 'async',
364
+ 'defer',
365
+ 'inert',
366
+ 'scoped',
367
+ 'reversed',
368
+ 'allowFullScreen',
369
+ 'defaultChecked',
370
+ 'selected',
371
+ 'formNoValidate',
372
+ 'noValidate',
373
+ ]);
145
374
  export var addAttributeToJSXTag = function (jsxNode, attrName, attrValue, t) {
375
+ var _a, _b;
146
376
  if (t === void 0) { t = types; }
147
- var nameOfAttribute = t.jsxIdentifier(attrName);
377
+ var reactAttrName = resolveAttributeNameForTag(jsxNode, attrName);
378
+ var nameOfAttribute = t.jsxIdentifier(reactAttrName);
148
379
  var attributeDefinition;
149
- if (typeof attrValue === 'boolean') {
150
- attributeDefinition = t.jsxAttribute(nameOfAttribute, attrValue === true ? undefined : t.jsxExpressionContainer(t.booleanLiteral(attrValue)));
380
+ var normalizedValue = attrValue;
381
+ if (typeof attrValue === 'string' &&
382
+ (attrValue === 'true' || attrValue === 'false') &&
383
+ REACT_BOOLEAN_DOM_PROPS.has(reactAttrName)) {
384
+ normalizedValue = attrValue === 'true';
385
+ }
386
+ if (typeof normalizedValue === 'boolean') {
387
+ attributeDefinition = t.jsxAttribute(nameOfAttribute, normalizedValue === true
388
+ ? undefined
389
+ : t.jsxExpressionContainer(t.booleanLiteral(normalizedValue)));
390
+ }
391
+ else if (t.isNode(attrValue) && t.isJSXElement(attrValue)) {
392
+ attributeDefinition = t.jsxAttribute(nameOfAttribute, t.jsxExpressionContainer(attrValue));
151
393
  }
152
394
  else {
153
- attributeDefinition = t.jsxAttribute(nameOfAttribute, getProperAttributeValueAssignment(attrValue));
395
+ attributeDefinition = t.jsxAttribute(nameOfAttribute, getProperAttributeValueAssignment(normalizedValue));
396
+ }
397
+ var attribute = jsxNode.openingElement.attributes.find(function (attr) {
398
+ if (attr.type === 'JSXAttribute') {
399
+ return attr.name.name === reactAttrName;
400
+ }
401
+ });
402
+ if (attribute && attribute.value && attribute.value.type === 'StringLiteral') {
403
+ attribute.value.value = "".concat(attribute.value.value, " ").concat(attrValue);
404
+ return;
405
+ }
406
+ // An object-valued attribute (e.g. `style={{ ... }}`) can be contributed by
407
+ // more than one independent code path — e.g. a ctx-scoped dynamic style value
408
+ // resolved at JSX-build time, and a `dynamicStyleBindings` inline style added
409
+ // later by a style plugin. Pushing a second `style` JSXAttribute would silently
410
+ // drop one of the two (JS keeps only the last of duplicate object keys once
411
+ // transpiled), so merge into the existing ObjectExpression instead, replacing
412
+ // any property with a matching key so the newer value wins.
413
+ if (attribute &&
414
+ ((_a = attribute.value) === null || _a === void 0 ? void 0 : _a.type) === 'JSXExpressionContainer' &&
415
+ attribute.value.expression.type === 'ObjectExpression' &&
416
+ ((_b = attributeDefinition.value) === null || _b === void 0 ? void 0 : _b.type) === 'JSXExpressionContainer' &&
417
+ attributeDefinition.value.expression.type === 'ObjectExpression') {
418
+ var existingProps_1 = attribute.value.expression.properties;
419
+ attributeDefinition.value.expression.properties.forEach(function (newProp) {
420
+ if (newProp.type !== 'ObjectProperty' || newProp.key.type === 'PrivateName') {
421
+ existingProps_1.push(newProp);
422
+ return;
423
+ }
424
+ var newKeyName = newProp.key.type === 'Identifier' ? newProp.key.name : String(newProp.key.value);
425
+ var existingIndex = existingProps_1.findIndex(function (prop) {
426
+ if (prop.type !== 'ObjectProperty' || prop.key.type === 'PrivateName') {
427
+ return false;
428
+ }
429
+ var existingKeyName = prop.key.type === 'Identifier' ? prop.key.name : String(prop.key.value);
430
+ return existingKeyName === newKeyName;
431
+ });
432
+ if (existingIndex >= 0) {
433
+ existingProps_1[existingIndex] = newProp;
434
+ }
435
+ else {
436
+ existingProps_1.push(newProp);
437
+ }
438
+ });
439
+ return;
154
440
  }
155
441
  jsxNode.openingElement.attributes.push(attributeDefinition);
156
442
  };
157
443
  export var addRawAttributeToJSXTag = function (jsxNode, attrName, attrValue, t) {
158
444
  if (t === void 0) { t = types; }
159
- var attributeDefinition = t.jsxAttribute(t.jsxIdentifier(attrName), t.jsxExpressionContainer(types.templateLiteral([types.templateElement({ raw: attrValue.content })], [])));
445
+ // The content is expected to be pre-escaped for template literal context
446
+ // (e.g., \` for backticks, \${ for interpolations). Babel validates that
447
+ // the raw value is valid template literal content.
448
+ //
449
+ // We fix any unescaped backticks or ${ sequences that would make the
450
+ // template literal invalid. "Unescaped" means preceded by an even number
451
+ // of backslashes (0, 2, …), since pairs of backslashes form escape
452
+ // sequences for backslash itself, leaving the next character unescaped.
453
+ var content = attrValue.content
454
+ .replace(/\\*`/g, function (match) {
455
+ var bs = match.length - 1;
456
+ return bs % 2 === 0 ? match.slice(0, bs) + '\\`' : match;
457
+ })
458
+ .replace(/\\*\$\{/g, function (match) {
459
+ var bs = match.length - 2;
460
+ return bs % 2 === 0 ? match.slice(0, bs) + '\\${' : match;
461
+ });
462
+ var attributeDefinition = t.jsxAttribute(t.jsxIdentifier(attrName), t.jsxExpressionContainer(types.templateLiteral([types.templateElement({ raw: content })], [])));
160
463
  jsxNode.openingElement.attributes.push(attributeDefinition);
161
464
  };
465
+ // A JSX attribute string is raw text: nothing in it is unescaped, yet Babel
466
+ // prints a backslash or a line break in it escaped, so `pattern="\d"` would reach
467
+ // the page as `\\d`. Such a value goes in an expression container instead, where
468
+ // the escapes are JavaScript's and are read back.
469
+ var RAW_JSX_ATTRIBUTE_UNSAFE = /[\\\n\r\u2028\u2029]/;
162
470
  /**
163
471
  * node must be a AST node element of type JSXElement (babel-types) or
164
472
  * equivalent
165
473
  */
166
474
  var getProperAttributeValueAssignment = function (value, t) {
167
475
  if (t === void 0) { t = types; }
168
- if (!value) {
169
- return null;
170
- }
171
476
  if (typeof value === 'string') {
172
- return t.stringLiteral(StringUtils.encode(value));
477
+ return RAW_JSX_ATTRIBUTE_UNSAFE.test(value)
478
+ ? t.jsxExpressionContainer(t.stringLiteral(value))
479
+ : t.stringLiteral(StringUtils.encode(value));
480
+ }
481
+ if (!value && value !== 0 && value !== false) {
482
+ return null;
173
483
  }
174
484
  return t.jsxExpressionContainer(convertValueToLiteral(value));
175
485
  };
@@ -198,7 +508,18 @@ export var objectToObjectExpression = function (objectMap, t) {
198
508
  var keyIdentifier = t.stringLiteral(key);
199
509
  var value = objectMap[key];
200
510
  var computedLiteralValue = null;
201
- if (value instanceof ParsedASTNode || value.constructor.name === 'ParsedASTNode') {
511
+ if (value === undefined) {
512
+ return acc;
513
+ }
514
+ // Handle null values explicitly - they are valid in array mappers with different schemas
515
+ if (value === null) {
516
+ computedLiteralValue = t.nullLiteral();
517
+ }
518
+ // This is for function props that have successfully been parsed.
519
+ else if (typeof value === 'object' && 'functionExpressionParseResult' in value) {
520
+ computedLiteralValue = value.functionExpressionParseResult;
521
+ }
522
+ else if (value instanceof ParsedASTNode || value.constructor.name === 'ParsedASTNode') {
202
523
  computedLiteralValue = value.ast;
203
524
  }
204
525
  else if (typeof value === 'boolean') {
@@ -237,6 +558,83 @@ export var objectToObjectExpression = function (objectMap, t) {
237
558
  var objectExpression = t.objectExpression(props);
238
559
  return objectExpression;
239
560
  };
561
+ /**
562
+ * A value stored as text, read as the type it is declared with: a number prop
563
+ * or a condition comparing one meets "2" as the number 2, and a boolean one
564
+ * meets "true"/"false" as true/false, the way the editor's canvas compares
565
+ * them. A prop default and a condition's operand both arrive as text from
566
+ * writers that keep every input's value as typed.
567
+ */
568
+ export var coerceToDeclaredType = function (value, declaredType) {
569
+ if (typeof value !== 'string') {
570
+ return value;
571
+ }
572
+ if (declaredType === 'number' && value.trim() !== '' && !isNaN(Number(value))) {
573
+ return Number(value);
574
+ }
575
+ if (declaredType === 'boolean' && (value === 'true' || value === 'false')) {
576
+ return value === 'true';
577
+ }
578
+ return value;
579
+ };
580
+ var COLLECTION_OPERATIONS = [
581
+ 'isEmpty',
582
+ 'isNotEmpty',
583
+ 'lengthEquals',
584
+ 'lengthGreaterThan',
585
+ 'lengthLessThan',
586
+ 'contains',
587
+ 'notContains',
588
+ 'hasKey',
589
+ 'notHasKey',
590
+ ];
591
+ /** The operations that read a value as a collection rather than compare it. */
592
+ export var isCollectionOperation = function (operation) {
593
+ return COLLECTION_OPERATIONS.includes(operation);
594
+ };
595
+ /**
596
+ * A collection operation answered on a value known at build time, with the
597
+ * meaning `createBinaryExpression` (node-to-jsx) gives it at runtime: the
598
+ * length of `value || []` (its key count, `value || {}`, for an object),
599
+ * `.includes(operand)`, `.some((item) => item[field] === operand)`,
600
+ * `hasOwnProperty`.
601
+ */
602
+ export var passesCollectionTest = function (operation, value, operand, options) {
603
+ if (options === void 0) { options = {}; }
604
+ var containsField = options.containsField, valueType = options.valueType;
605
+ var collection = (value || (valueType === 'object' ? {} : []));
606
+ var length = valueType === 'object' ? Object.keys(collection).length : collection.length;
607
+ var contains = function () {
608
+ if (containsField) {
609
+ return (typeof collection.some === 'function' &&
610
+ collection.some(function (item) { return (item === null || item === void 0 ? void 0 : item[containsField]) === operand; }));
611
+ }
612
+ return typeof collection.includes === 'function' && collection.includes(operand);
613
+ };
614
+ var hasKey = function () {
615
+ return Object.prototype.hasOwnProperty.call(value || {}, operand);
616
+ };
617
+ switch (operation) {
618
+ case 'isEmpty':
619
+ return length === 0;
620
+ case 'isNotEmpty':
621
+ return length > 0;
622
+ case 'lengthEquals':
623
+ return length === operand;
624
+ case 'lengthGreaterThan':
625
+ return length > operand;
626
+ case 'lengthLessThan':
627
+ return length < operand;
628
+ case 'contains':
629
+ return contains();
630
+ case 'notContains':
631
+ return !contains();
632
+ case 'hasKey':
633
+ return hasKey();
634
+ default:
635
+ return !hasKey();
636
+ }
637
+ };
240
638
  export var convertValueToLiteral = function (
241
639
  // tslint:disable-next-line no-any
242
640
  value, explicitType, t) {
@@ -248,7 +646,23 @@ value, explicitType, t) {
248
646
  if (Array.isArray(value)) {
249
647
  return t.arrayExpression(value.map(function (val) { return convertValueToLiteral(val); }));
250
648
  }
251
- var typeToCompare = explicitType ? explicitType : typeof value;
649
+ if (explicitType === 'array' && typeof value === 'object' && value !== null) {
650
+ var arr = Object.keys(value)
651
+ .sort(function (a, b) { return Number(a) - Number(b); })
652
+ .map(function (key) { return convertValueToLiteral(value[key]); });
653
+ return t.arrayExpression(arr);
654
+ }
655
+ if ((explicitType === 'array' || explicitType === 'object') && typeof value === 'string') {
656
+ try {
657
+ var parsed = JSON.parse(value);
658
+ return convertValueToLiteral(parsed, explicitType, t);
659
+ }
660
+ catch (_a) {
661
+ // If parsing fails, fall through to treat as a regular string
662
+ }
663
+ }
664
+ var actualType = typeof value;
665
+ var typeToCompare = explicitType && explicitType === actualType ? explicitType : actualType;
252
666
  switch (typeToCompare) {
253
667
  case 'string':
254
668
  return t.stringLiteral(value);
@@ -279,7 +693,7 @@ export var getTSAnnotationForType = function (type, t) {
279
693
  case 'boolean':
280
694
  return t.tsBooleanKeyword();
281
695
  default:
282
- return t.tsUnknownKeyword();
696
+ return t.tsAnyKeyword();
283
697
  }
284
698
  };
285
699
  export var findAttributeByName = function (jsxTag, attrName) {
@@ -291,7 +705,7 @@ export var removeAttributeByName = function (jsxTag, attrName) {
291
705
  (attr.type === 'JSXAttribute' && attr.name.name !== attrName);
292
706
  });
293
707
  };
294
- export var createClassComponent = function (name, propDefinitions, stateDefinitions, jsxTagTree, t) {
708
+ export var createClassComponent = function (name, propDefinitions, stateDefinitions, jsxTagTree, dynamicReferencePrefixMap, t) {
295
709
  if (t === void 0) { t = types; }
296
710
  // TODO: Add event handlers as separate functions later
297
711
  var classMethodsAndProperties = [];
@@ -302,6 +716,11 @@ export var createClassComponent = function (name, propDefinitions, stateDefiniti
302
716
  if (Object.keys(stateDefinitions).length > 0) {
303
717
  var stateDeclarationsAST = Object.keys(stateDefinitions).map(function (stateKey) {
304
718
  var stateDefinition = stateDefinitions[stateKey];
719
+ if (stateDefinition.type === 'object' &&
720
+ dynamicReferencePrefixMap &&
721
+ isObjectStateWithEntries(stateDefinition)) {
722
+ return t.objectProperty(t.identifier(stateKey), convertObjectStateDefaultToExpression(stateDefinition.defaultValue, dynamicReferencePrefixMap, t));
723
+ }
305
724
  return t.objectProperty(t.identifier(stateKey), convertValueToLiteral(stateDefinition.defaultValue));
306
725
  });
307
726
  classMethodsAndProperties.push(t.classProperty(t.identifier('state'), t.objectExpression(stateDeclarationsAST)));
@@ -313,41 +732,269 @@ export var createClassComponent = function (name, propDefinitions, stateDefiniti
313
732
  var classDeclaration = t.classDeclaration(t.identifier(name), t.identifier('Component'), classBody, null);
314
733
  return classDeclaration;
315
734
  };
316
- export var createPureComponent = function (name, stateDefinitions, jsxTagTree, windowImports, t) {
735
+ export var createPureComponent = function (name, stateDefinitions, jsxTagTree, windowImports, dynamicReferencePrefixMap, t) {
317
736
  if (windowImports === void 0) { windowImports = {}; }
318
737
  if (t === void 0) { t = types; }
319
- var arrowFunctionBody = createReturnExpressionSyntax(stateDefinitions, jsxTagTree, windowImports);
738
+ var arrowFunctionBody = createReturnExpressionSyntax(stateDefinitions, jsxTagTree, windowImports, dynamicReferencePrefixMap);
320
739
  var arrowFunction = t.arrowFunctionExpression([t.identifier('props')], arrowFunctionBody);
321
740
  var declarator = t.variableDeclarator(t.identifier(name), arrowFunction);
322
741
  var component = t.variableDeclaration('const', [declarator]);
323
742
  return component;
324
743
  };
325
- export var createReturnExpressionSyntax = function (stateDefinitions, jsxTagTree, windowImports, t) {
744
+ export var createReturnExpressionSyntax = function (stateDefinitions, jsxTagTree, windowImports, dynamicReferencePrefixMap, t) {
326
745
  if (windowImports === void 0) { windowImports = {}; }
327
746
  if (t === void 0) { t = types; }
328
747
  var returnStatement = t.returnStatement(jsxTagTree);
329
748
  var stateHooks = Object.keys(stateDefinitions).map(function (stateKey) {
330
- return createStateHookAST(stateKey, stateDefinitions[stateKey]);
749
+ return createStateHookAST(stateKey, stateDefinitions[stateKey], dynamicReferencePrefixMap);
331
750
  });
332
- return t.blockStatement(__spreadArray(__spreadArray(__spreadArray([], stateHooks, true), Object.values(windowImports), true), [returnStatement], false) || []);
751
+ return t.blockStatement(__spreadArray(__spreadArray(__spreadArray([], stateHooks, true), Object.values(windowImports), true), [returnStatement], false));
333
752
  };
334
753
  /**
335
754
  * Creates an AST line for defining a single state hook
336
755
  */
337
- export var createStateHookAST = function (stateKey, stateDefinition, t) {
756
+ export var createStateHookAST = function (stateKey, stateDefinition, dynamicReferencePrefixMap, t) {
338
757
  if (t === void 0) { t = types; }
339
- var defaultValueArgument = convertValueToLiteral(stateDefinition.defaultValue, stateDefinition.type);
758
+ var defaultValueArgument;
759
+ if (stateDefinition.type === 'object' &&
760
+ dynamicReferencePrefixMap &&
761
+ isObjectStateWithEntries(stateDefinition)) {
762
+ defaultValueArgument = convertObjectStateDefaultToExpression(stateDefinition.defaultValue, dynamicReferencePrefixMap, t);
763
+ }
764
+ else {
765
+ defaultValueArgument = convertValueToLiteral(stateDefinition.defaultValue, stateDefinition.type);
766
+ }
767
+ // When the state has a dataSourceBinding, the initial value comes from props
768
+ // Generated: useState(props.stateKey !== undefined ? props.stateKey : defaultValue)
769
+ var useStateArgument = defaultValueArgument;
770
+ if (stateDefinition.dataSourceBinding) {
771
+ var propAccess = t.memberExpression(t.identifier('props'), t.identifier(stateKey));
772
+ useStateArgument = t.conditionalExpression(t.binaryExpression('!==', propAccess, t.identifier('undefined')), propAccess, defaultValueArgument);
773
+ }
774
+ else if (stateDefinition.urlSearchParamBinding &&
775
+ typeof stateDefinition.urlSearchParamBinding.key === 'string' &&
776
+ stateDefinition.urlSearchParamBinding.key !== '' &&
777
+ // `hydrateAfterMount`: the state keeps its static default on the client's
778
+ // first render too, and the router read-back effect adopts the URL value
779
+ // once `router.isReady` — a real update, so the elements it gates
780
+ // re-render. Needed where the server markup and a URL-seeded client value
781
+ // would differ only in ATTRIBUTES of same-tag siblings (a pressed toggle):
782
+ // React 17 does not patch those on hydration. See the type's docs.
783
+ stateDefinition.urlSearchParamBinding.hydrateAfterMount !== true) {
784
+ // URL-search-param binding: seed the initial state directly from
785
+ // `window.location.search`. We deliberately DO NOT use Next.js'
786
+ // `router.query` here because on statically-generated pages (getStaticProps
787
+ // / getStaticPaths) `router.query` is empty on the first render and only
788
+ // hydrates after `router.isReady` flips to true — by which point React's
789
+ // `useState` initializer has already captured the fallback default. That
790
+ // regression shipped as "detail panel does not auto-open on deep links to
791
+ // /admin/products?products_detail_panel_item_id=<id>". `window.location`
792
+ // is populated synchronously on both direct loads and client-side
793
+ // navigations, and the `typeof window` guard keeps SSR falling back to
794
+ // the declared static default cleanly.
795
+ //
796
+ // Emitted shape:
797
+ // useState(
798
+ // (typeof window !== "undefined"
799
+ // ? new URLSearchParams(window.location.search).get("<key>")
800
+ // : null) ?? <defaultValueLiteral>
801
+ // )
802
+ var paramKey = stateDefinition.urlSearchParamBinding.key;
803
+ var urlSearchParamsExpr = t.newExpression(t.identifier('URLSearchParams'), [
804
+ t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('location')), t.identifier('search')),
805
+ ]);
806
+ var readParamExpr = t.callExpression(t.memberExpression(urlSearchParamsExpr, t.identifier('get')), [t.stringLiteral(paramKey)]);
807
+ var browserGuard = t.binaryExpression('!==', t.unaryExpression('typeof', t.identifier('window')), t.stringLiteral('undefined'));
808
+ useStateArgument = t.logicalExpression('??', t.conditionalExpression(browserGuard, readParamExpr, t.nullLiteral()), defaultValueArgument);
809
+ }
340
810
  return t.variableDeclaration('const', [
341
811
  t.variableDeclarator(t.arrayPattern([
342
- t.identifier(stateKey),
812
+ // The state NAME comes from the UIDL and may be a reserved word (a
813
+ // character sheet has a column called `class`), which is fatal in
814
+ // binding position. Reads go through the same sanitiser, so the
815
+ // declaration and every reference stay in sync.
816
+ t.identifier(JSIdentifiers.createSafeJSIdentifier(stateKey)),
343
817
  t.identifier(StringUtils.createStateStoringFunction(stateKey)),
344
- ]), t.callExpression(t.identifier('useState'), [defaultValueArgument])),
818
+ ]), t.callExpression(t.identifier('useState'), [useStateArgument])),
345
819
  ]);
346
820
  };
821
+ export var isObjectStateWithEntries = function (stateDefinition) {
822
+ if (stateDefinition.type !== 'object') {
823
+ return false;
824
+ }
825
+ var defaultValue = stateDefinition.defaultValue;
826
+ if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
827
+ return false;
828
+ }
829
+ return Object.values(defaultValue).some(function (entry) {
830
+ if (typeof entry !== 'object' || entry === null) {
831
+ return false;
832
+ }
833
+ var typed = entry;
834
+ return (typed.type === 'static' || typed.type === 'dynamic') && 'content' in typed;
835
+ });
836
+ };
837
+ export var convertObjectStateDefaultToExpression = function (defaultValue, prefixMap, t) {
838
+ if (t === void 0) { t = types; }
839
+ var properties = Object.keys(defaultValue).map(function (key) {
840
+ var valueExpression = resolveObjectStateEntry(defaultValue[key], prefixMap, t);
841
+ return t.objectProperty(t.stringLiteral(key), valueExpression);
842
+ });
843
+ return t.objectExpression(properties);
844
+ };
845
+ var resolveObjectStateEntry = function (entry, prefixMap, t) {
846
+ if (t === void 0) { t = types; }
847
+ if (typeof entry !== 'object' || entry === null) {
848
+ return convertValueToLiteral(entry);
849
+ }
850
+ var typed = entry;
851
+ if (typed.type === 'static') {
852
+ return convertValueToLiteral(typed.content);
853
+ }
854
+ if (typed.type === 'dynamic') {
855
+ var content = typed.content;
856
+ var referenceType = content.referenceType, id = content.id, refPath = content.refPath;
857
+ if (referenceType === 'globalState') {
858
+ var gsRefPath = refPath || [];
859
+ var expr = t.identifier(id);
860
+ for (var _i = 0, gsRefPath_1 = gsRefPath; _i < gsRefPath_1.length; _i++) {
861
+ var segment = gsRefPath_1[_i];
862
+ expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true);
863
+ }
864
+ return expr;
865
+ }
866
+ if (referenceType === 'global') {
867
+ // Normalize Shape B ({ refPath: ['Current User', 'id'] }) to Shape A
868
+ // ({ id: 'currentUser', refPath: ['id'] }) so downstream access is uniform.
869
+ var resolvedId = resolveGlobalRefId(content);
870
+ if (resolvedId) {
871
+ var tail = !id && refPath && refPath.length > 0 ? refPath.slice(1) : refPath || [];
872
+ var expr = t.identifier(resolvedId);
873
+ for (var _a = 0, tail_1 = tail; _a < tail_1.length; _a++) {
874
+ var segment = tail_1[_a];
875
+ expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true);
876
+ }
877
+ return expr;
878
+ }
879
+ }
880
+ var idWithPath = UIDLUtils.generateIdWithRefPath(id, refPath);
881
+ var prefix = prefixMap[referenceType] || '';
882
+ return prefix === ''
883
+ ? t.identifier(idWithPath)
884
+ : t.memberExpression(t.identifier(prefix), t.identifier(idWithPath));
885
+ }
886
+ return convertValueToLiteral(entry);
887
+ };
888
+ // Mapping from the UIDL display name used in a global reference refPath
889
+ // to the runtime variable name that holds the value. Kept here so both the
890
+ // JSX emitter and the object-state global-reference collectors stay in sync.
891
+ export var GLOBAL_REF_ID_MAP = {
892
+ 'E-commerce': 'ecommerce',
893
+ Cart: 'cart',
894
+ 'Current User': 'currentUser',
895
+ Company: 'company',
896
+ };
897
+ export var resolveGlobalRefId = function (content) {
898
+ if (!content) {
899
+ return undefined;
900
+ }
901
+ if (content.id) {
902
+ return content.id;
903
+ }
904
+ if (!content.refPath || content.refPath.length === 0) {
905
+ return undefined;
906
+ }
907
+ return GLOBAL_REF_ID_MAP[content.refPath[0]];
908
+ };
909
+ export var collectGlobalReferencesFromObjectStates = function (stateDefinitions) {
910
+ var globalRefs = [];
911
+ Object.values(stateDefinitions).forEach(function (stateDef) {
912
+ if (stateDef.type !== 'object') {
913
+ return;
914
+ }
915
+ var defaultValue = stateDef.defaultValue;
916
+ if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
917
+ return;
918
+ }
919
+ Object.values(defaultValue).forEach(function (entry) {
920
+ if (typeof entry !== 'object' || entry === null) {
921
+ return;
922
+ }
923
+ var typed = entry;
924
+ if (typed.type === 'dynamic') {
925
+ var content = typed.content;
926
+ if (content.referenceType === 'global') {
927
+ var resolvedId = resolveGlobalRefId(content);
928
+ if (resolvedId) {
929
+ globalRefs.push(resolvedId);
930
+ }
931
+ }
932
+ }
933
+ });
934
+ });
935
+ return globalRefs;
936
+ };
937
+ export var collectGlobalStateReferencesFromObjectStates = function (stateDefinitions) {
938
+ var refs = [];
939
+ Object.values(stateDefinitions).forEach(function (stateDef) {
940
+ if (stateDef.type !== 'object') {
941
+ return;
942
+ }
943
+ var defaultValue = stateDef.defaultValue;
944
+ if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
945
+ return;
946
+ }
947
+ Object.values(defaultValue).forEach(function (entry) {
948
+ if (typeof entry !== 'object' || entry === null) {
949
+ return;
950
+ }
951
+ var typed = entry;
952
+ if (typed.type === 'dynamic') {
953
+ var content = typed.content;
954
+ if (content.referenceType === 'globalState' && content.id) {
955
+ refs.push({ id: content.id });
956
+ }
957
+ }
958
+ });
959
+ });
960
+ return refs;
961
+ };
962
+ /**
963
+ * The mount-time side-effect import for a package that cannot be imported at
964
+ * module scope because it touches `window` while it evaluates —
965
+ * self-registering web components such as `<lottie-player>` and
966
+ * `<model-viewer>`. Running it from an effect keeps it off the server render.
967
+ *
968
+ * useEffect(() => {
969
+ * import('@google/model-viewer').catch((error) => {
970
+ * console.warn('[teleport] Failed to load "@google/model-viewer"', error)
971
+ * })
972
+ * }, [])
973
+ *
974
+ * Two details of that shape are load-bearing:
975
+ *
976
+ * - The callback body is a BLOCK. A concise arrow body (`() => import(…)`)
977
+ * also RETURNS the import's Promise, and React stores an effect's return
978
+ * value as its cleanup function and calls it on unmount — so every mounted
979
+ * copy of the component turned navigating away into
980
+ * `TypeError: destroy is not a function`, thrown from React's commit phase
981
+ * with no frame naming the component. Nothing is returned here.
982
+ * - The rejection is handled. A chunk that fails to load (offline, a stale
983
+ * deploy, a blocked CDN) would otherwise surface as an unhandled promise
984
+ * rejection; the element simply stays unupgraded, which is a degraded page
985
+ * rather than a broken one, and the warning is what makes that visible.
986
+ */
347
987
  export var generateDynamicWindowImport = function (hookName, dependency) {
348
988
  if (hookName === void 0) { hookName = 'useEffect'; }
989
+ var failureIdentifier = types.identifier('error');
990
+ var importCall = types.callExpression(types.import(), [types.stringLiteral(dependency)]);
991
+ var guardedImport = types.callExpression(types.memberExpression(importCall, types.identifier('catch')), [
992
+ types.arrowFunctionExpression([failureIdentifier], types.blockStatement([
993
+ types.expressionStatement(types.callExpression(types.memberExpression(types.identifier('console'), types.identifier('warn')), [types.stringLiteral("[teleport] Failed to load \"".concat(dependency, "\"")), failureIdentifier])),
994
+ ])),
995
+ ]);
349
996
  return types.expressionStatement(types.callExpression(types.identifier(hookName), [
350
- types.arrowFunctionExpression([], types.callExpression(types.identifier('import'), [types.stringLiteral(dependency)])),
997
+ types.arrowFunctionExpression([], types.blockStatement([types.expressionStatement(guardedImport)])),
351
998
  types.arrayExpression([]),
352
999
  ]));
353
1000
  };
@@ -355,9 +1002,8 @@ export var wrapObjectPropertiesWithExpression = function (properties) {
355
1002
  return types.objectExpression(properties);
356
1003
  };
357
1004
  export var generateRemoteResourceASTs = function (resource) {
358
- var _a, _b;
1005
+ var _a, _b, _c, _d, _e;
359
1006
  var fetchUrl = computeFetchUrl(resource);
360
- var authHeaderAST = computeAuthorizationHeaderAST(resource === null || resource === void 0 ? void 0 : resource.headers);
361
1007
  var headersASTs = (resource === null || resource === void 0 ? void 0 : resource.headers) ? generateRESTHeadersAST(resource.headers) : [];
362
1008
  var queryParams = generateURLParamsAST(resource === null || resource === void 0 ? void 0 : resource.params);
363
1009
  var fetchUrlQuasis = fetchUrl.quasis;
@@ -369,43 +1015,61 @@ export var generateRemoteResourceASTs = function (resource) {
369
1015
  fetchUrlQuasis[fetchUrlQuasis.length - 1].value.cooked + '?';
370
1016
  queryParamsQuasis.pop();
371
1017
  }
372
- var paramsDeclerations = Object.keys((resource === null || resource === void 0 ? void 0 : resource.params) || {}).reduce(function (acc, item) {
373
- var prop = resource.params[item];
374
- if (prop.type === 'static') {
375
- acc.push(types.objectProperty(types.stringLiteral(item), ASTUtils.resolveObjectValue(prop)));
376
- }
377
- if (prop.type === 'expr') {
378
- acc.push(types.objectProperty(types.stringLiteral(item), ASTUtils.getExpressionFromUIDLExpressionNode(prop)));
379
- }
380
- if (prop.type === 'dynamic') {
381
- acc.push(types.spreadElement(types.logicalExpression('&&', types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false), types.objectExpression([
382
- types.objectProperty(types.stringLiteral(item), types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false)),
383
- ]))));
384
- }
385
- return acc;
386
- }, []);
387
- var paramsAST = types.variableDeclaration('const', [
388
- types.variableDeclarator(types.identifier('urlParams'), types.objectExpression(paramsDeclerations)),
389
- ]);
1018
+ var urlParamsDecleration = generateParamsAST(resource === null || resource === void 0 ? void 0 : resource.params);
1019
+ var bodyParamsDecleration = generateParamsAST(resource === null || resource === void 0 ? void 0 : resource.body);
390
1020
  var url = (queryParams === null || queryParams === void 0 ? void 0 : queryParams.quasis)
391
1021
  ? types.templateLiteral(__spreadArray(__spreadArray([], fetchUrlQuasis, true), queryParamsQuasis, true), __spreadArray([], fetchUrl.expressions.concat(queryParams.expressions), true))
392
1022
  : fetchUrl;
393
1023
  var method = types.objectProperty(types.identifier('method'), types.stringLiteral(resource.method));
394
1024
  var allHeaders = [];
395
- if (authHeaderAST) {
396
- allHeaders.push(authHeaderAST);
1025
+ if ((_a = resource === null || resource === void 0 ? void 0 : resource.headers) === null || _a === void 0 ? void 0 : _a.authToken) {
1026
+ allHeaders.push(computeAuthorizationHeaderAST(resource === null || resource === void 0 ? void 0 : resource.headers));
397
1027
  }
398
1028
  if (headersASTs.length) {
399
1029
  allHeaders = allHeaders.concat(headersASTs);
400
1030
  }
401
- var headers = types.objectProperty(types.identifier('headers'), types.objectExpression(allHeaders));
402
- var fetchAST = types.variableDeclaration('const', [
1031
+ var fetchAST = types.variableDeclaration('let', [
403
1032
  types.variableDeclarator(types.identifier('data'), types.awaitExpression(types.callExpression(types.identifier('fetch'), [
404
1033
  url,
405
- types.objectExpression([method, headers]),
1034
+ types.objectExpression(__spreadArray(__spreadArray([
1035
+ method
1036
+ ], (allHeaders.length > 0
1037
+ ? [
1038
+ types.objectProperty(types.identifier('headers'), types.objectExpression(allHeaders)),
1039
+ ]
1040
+ : []), true), (bodyParamsDecleration.length > 0 && (resource === null || resource === void 0 ? void 0 : resource.method) === 'POST'
1041
+ ? [
1042
+ types.objectProperty(types.identifier('body'), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [types.identifier('bodyParams')])),
1043
+ ]
1044
+ : []), true)),
406
1045
  ]))),
407
1046
  ]);
408
- var responseType = (_b = (_a = resource === null || resource === void 0 ? void 0 : resource.response) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : 'json';
1047
+ // Fallback in case i18n interferes with normal CMS flows
1048
+ // Only generate fallback if locale parameter exists
1049
+ var hasLocaleParam = ((_b = resource === null || resource === void 0 ? void 0 : resource.params) === null || _b === void 0 ? void 0 : _b.locale) !== undefined;
1050
+ var fallbackAST = null;
1051
+ if (hasLocaleParam) {
1052
+ var fallbackParams = JSON.parse(JSON.stringify(resource));
1053
+ (_c = fallbackParams === null || fallbackParams === void 0 ? void 0 : fallbackParams.params) === null || _c === void 0 ? true : delete _c.locale;
1054
+ var fallbackUrlParamsDeclaration = generateParamsAST(fallbackParams === null || fallbackParams === void 0 ? void 0 : fallbackParams.params);
1055
+ var assignmentOfNewUrlParams = types.expressionStatement(types.assignmentExpression('=', types.identifier('urlParams'), types.objectExpression(__spreadArray([], fallbackUrlParamsDeclaration, true))));
1056
+ var assignmentExpressionAST = types.expressionStatement(types.assignmentExpression('=', types.identifier('data'), types.awaitExpression(types.callExpression(types.identifier('fetch'), [
1057
+ url,
1058
+ types.objectExpression(__spreadArray(__spreadArray([
1059
+ method
1060
+ ], (allHeaders.length > 0
1061
+ ? [
1062
+ types.objectProperty(types.identifier('headers'), types.objectExpression(allHeaders)),
1063
+ ]
1064
+ : []), true), (bodyParamsDecleration.length > 0 && (resource === null || resource === void 0 ? void 0 : resource.method) === 'POST'
1065
+ ? [
1066
+ types.objectProperty(types.identifier('body'), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [types.identifier('bodyParams')])),
1067
+ ]
1068
+ : []), true)),
1069
+ ]))));
1070
+ fallbackAST = types.ifStatement(types.binaryExpression('!==', types.memberExpression(types.identifier('data'), types.identifier('status')), types.numericLiteral(200)), types.blockStatement([assignmentOfNewUrlParams, assignmentExpressionAST]));
1071
+ }
1072
+ var responseType = (_e = (_d = resource === null || resource === void 0 ? void 0 : resource.response) === null || _d === void 0 ? void 0 : _d.type) !== null && _e !== void 0 ? _e : 'json';
409
1073
  var responseJSONAST;
410
1074
  /**
411
1075
  * Responce types can be of json, text and we might be reading just headers
@@ -445,18 +1109,54 @@ export var generateRemoteResourceASTs = function (resource) {
445
1109
  ]);
446
1110
  }
447
1111
  }
448
- return [paramsAST, fetchAST, responseJSONAST];
1112
+ return __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], (urlParamsDecleration.length > 0
1113
+ ? [
1114
+ types.variableDeclaration('let', [
1115
+ types.variableDeclarator(types.identifier('urlParams'), types.objectExpression(urlParamsDecleration)),
1116
+ ]),
1117
+ ]
1118
+ : []), true), (bodyParamsDecleration.length > 0
1119
+ ? [
1120
+ types.variableDeclaration('const', [
1121
+ types.variableDeclarator(types.identifier('bodyParams'), types.objectExpression(bodyParamsDecleration)),
1122
+ ]),
1123
+ ]
1124
+ : []), true), [
1125
+ fetchAST
1126
+ ], false), (fallbackAST ? [fallbackAST] : []), true), [
1127
+ responseJSONAST,
1128
+ ], false).filter(Boolean);
1129
+ };
1130
+ var generateParamsAST = function (props) {
1131
+ return Object.keys(props || {}).reduce(function (acc, item) {
1132
+ var prop = props[item];
1133
+ if (prop.type === 'static') {
1134
+ acc.push(types.objectProperty(types.stringLiteral(item), resolveObjectValue(prop)));
1135
+ }
1136
+ if (prop.type === 'expr') {
1137
+ acc.push(types.objectProperty(types.stringLiteral(item), getExpressionFromUIDLExpressionNode(prop)));
1138
+ }
1139
+ if (prop.type === 'dynamic') {
1140
+ acc.push(types.spreadElement(types.logicalExpression('&&', types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false), types.objectExpression([
1141
+ types.objectProperty(types.stringLiteral(item), types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false)),
1142
+ ]))));
1143
+ }
1144
+ return acc;
1145
+ }, []);
449
1146
  };
450
1147
  var generateRESTHeadersAST = function (headers) {
451
- return Object.keys(headers)
452
- .filter(function (header) { return header !== 'authToken'; })
1148
+ return (Object.keys(headers)
1149
+ // `authToken` is rendered as the `Authorization` header; `authScheme` is a
1150
+ // generator-only directive for that header's prefix — neither is emitted as
1151
+ // its own literal HTTP header.
1152
+ .filter(function (header) { return header !== 'authToken' && header !== 'authScheme'; })
453
1153
  .map(function (header) {
454
1154
  var headerResolved = resolveResourceValue(headers[header]);
455
1155
  var value = headers[header].type === 'static'
456
1156
  ? types.stringLiteral(String(headerResolved))
457
1157
  : types.identifier(String(headerResolved));
458
1158
  return types.objectProperty(types.stringLiteral(header), value);
459
- });
1159
+ }));
460
1160
  };
461
1161
  export var generateMemberExpressionASTFromBase = function (base, path) {
462
1162
  if (path.length === 1) {
@@ -466,6 +1166,21 @@ export var generateMemberExpressionASTFromBase = function (base, path) {
466
1166
  pathClone.pop();
467
1167
  return types.optionalMemberExpression(generateMemberExpressionASTFromBase(base, pathClone), types.identifier(path[path.length - 1]), false, true);
468
1168
  };
1169
+ export var parseValuePath = function (valuePath) {
1170
+ return valuePath.map(function (segment) {
1171
+ if (typeof segment === 'string') {
1172
+ var bracketMatch = segment.match(/^\[(\d+)\]$/);
1173
+ if (bracketMatch) {
1174
+ return parseInt(bracketMatch[1], 10);
1175
+ }
1176
+ var numericMatch = segment.match(/^\d+$/);
1177
+ if (numericMatch) {
1178
+ return parseInt(segment, 10);
1179
+ }
1180
+ }
1181
+ return segment;
1182
+ });
1183
+ };
469
1184
  export var generateMemberExpressionASTFromPath = function (path) {
470
1185
  var pathClone = __spreadArray([], path, true);
471
1186
  if (path.length === 1) {
@@ -474,7 +1189,7 @@ export var generateMemberExpressionASTFromPath = function (path) {
474
1189
  pathClone.pop();
475
1190
  var currentPath = path[path.length - 1];
476
1191
  if (typeof currentPath === 'number') {
477
- return types.optionalMemberExpression(generateMemberExpressionASTFromPath(pathClone), types.numericLiteral(currentPath), false, true);
1192
+ return types.optionalMemberExpression(generateMemberExpressionASTFromPath(pathClone), types.numericLiteral(currentPath), true, true);
478
1193
  }
479
1194
  var containsSpecial = currentPath.indexOf('.') !== -1 || currentPath.indexOf('-') !== -1;
480
1195
  return types.optionalMemberExpression(generateMemberExpressionASTFromPath(pathClone), containsSpecial ? types.stringLiteral(currentPath) : types.identifier(currentPath), containsSpecial, true);
@@ -528,10 +1243,22 @@ var computeAuthorizationHeaderAST = function (headers) {
528
1243
  return null;
529
1244
  }
530
1245
  var authTokenType = (_a = headers.authToken) === null || _a === void 0 ? void 0 : _a.type;
1246
+ // The auth scheme prefix defaults to `Bearer ` (back-compatible with every CMS
1247
+ // and data-source that stores a bare bearer token). A resource may override it
1248
+ // via a `headers.authScheme` static value — e.g. WordPress Basic / Application
1249
+ // Password auth sets `Basic ` so the rendered header is `Basic <base64>`
1250
+ // instead of the wrong `Bearer <base64>`. `authScheme` is consumed here and
1251
+ // filtered out of the emitted REST headers (see generateRESTHeadersAST).
1252
+ var authSchemeValue = headers.authScheme;
1253
+ var schemePrefix = authSchemeValue &&
1254
+ authSchemeValue.type === 'static' &&
1255
+ typeof authSchemeValue.content === 'string'
1256
+ ? authSchemeValue.content
1257
+ : 'Bearer ';
531
1258
  return types.objectProperty(types.identifier('Authorization'), types.templateLiteral(__spreadArray([
532
1259
  types.templateElement({
533
- cooked: authTokenType === 'static' ? "Bearer ".concat(authToken) : 'Bearer ',
534
- raw: authTokenType === 'static' ? "Bearer ".concat(authToken) : 'Bearer ',
1260
+ cooked: authTokenType === 'static' ? "".concat(schemePrefix).concat(authToken) : schemePrefix,
1261
+ raw: authTokenType === 'static' ? "".concat(schemePrefix).concat(authToken) : schemePrefix,
535
1262
  }, false)
536
1263
  ], (authTokenType === 'static'
537
1264
  ? []
@@ -542,7 +1269,7 @@ var computeAuthorizationHeaderAST = function (headers) {
542
1269
  }, true),
543
1270
  ]), true), __spreadArray([], (authTokenType === 'static' ? [] : [types.identifier(String(authToken))]), true)), false, false);
544
1271
  };
545
- var computeFetchUrl = function (resource) {
1272
+ export var computeFetchUrl = function (resource) {
546
1273
  var _a, _b;
547
1274
  var path = resource.path;
548
1275
  var fetchBaseUrl = resolveResourceValue(path.baseUrl);
@@ -550,7 +1277,23 @@ var computeFetchUrl = function (resource) {
550
1277
  var baseUrlType = (_a = path.baseUrl) === null || _a === void 0 ? void 0 : _a.type;
551
1278
  var routeType = (_b = path.route) === null || _b === void 0 ? void 0 : _b.type;
552
1279
  if (baseUrlType === 'static' && routeType === 'static') {
553
- var stringsToJoin = [fetchBaseUrl, resourceRoute].filter(function (item) { return item; }).join('/');
1280
+ var baseUrlStr = typeof fetchBaseUrl === 'string' ? fetchBaseUrl : String(fetchBaseUrl || '');
1281
+ var routeStr = typeof resourceRoute === 'string' ? resourceRoute : String(resourceRoute || '');
1282
+ var cleanBaseUrl = baseUrlStr.endsWith('/') ? baseUrlStr.slice(0, -1) : baseUrlStr;
1283
+ var cleanRoute = routeStr.startsWith('/') ? routeStr.slice(1) : routeStr;
1284
+ var stringsToJoin = [cleanBaseUrl, cleanRoute].filter(function (item) { return item; }).join('/');
1285
+ // If the URL is relative (starts with /), add a runtime base URL prefix
1286
+ // so fetch() works in server-side contexts (getStaticProps/getServerSideProps).
1287
+ // Non-NEXT_PUBLIC_ env vars are only available server-side in Next.js,
1288
+ // so NEXTAUTH_URL naturally resolves to undefined on the client (making baseUrl '').
1289
+ if (stringsToJoin.startsWith('/')) {
1290
+ var processEnv = types.memberExpression(types.identifier('process'), types.identifier('env'));
1291
+ var serverBaseUrlExpr = types.logicalExpression('||', types.logicalExpression('||', types.memberExpression(processEnv, types.identifier('NEXT_PUBLIC_SITE_URL')), types.memberExpression(types.memberExpression(types.identifier('process'), types.identifier('env')), types.identifier('NEXTAUTH_URL'))), types.stringLiteral(''));
1292
+ return types.templateLiteral([
1293
+ types.templateElement({ cooked: '', raw: '' }, false),
1294
+ types.templateElement({ cooked: "".concat(stringsToJoin), raw: "".concat(stringsToJoin) }, true),
1295
+ ], [serverBaseUrlExpr]);
1296
+ }
554
1297
  return types.templateLiteral([types.templateElement({ cooked: "".concat(stringsToJoin), raw: "".concat(stringsToJoin) }, true)], []);
555
1298
  }
556
1299
  if (!routeType) {
@@ -604,26 +1347,197 @@ export var resolveObjectValue = function (prop) {
604
1347
  ? types.booleanLiteral(prop.content)
605
1348
  : typeof prop.content === 'number'
606
1349
  ? types.numericLiteral(prop.content)
607
- : typeof prop.content === 'object'
608
- ? objectToObjectExpression(prop.content)
609
- : types.identifier(String(prop.content));
1350
+ : Array.isArray(prop.content)
1351
+ ? types.arrayExpression(prop.content.map(function (element) { return convertValueToLiteral(element); }))
1352
+ : typeof prop.content === 'object'
1353
+ ? objectToObjectExpression(prop.content)
1354
+ : types.identifier(String(prop.content));
610
1355
  return value;
611
1356
  }
612
1357
  if (prop.type === 'expr') {
613
1358
  return getExpressionFromUIDLExpressionNode(prop);
614
1359
  }
615
1360
  };
1361
+ /**
1362
+ * Detects if a value is a UIDL dynamic reference (state or prop)
1363
+ */
1364
+ export var isUIDLDynamicReference = function (value) {
1365
+ return (typeof value === 'object' &&
1366
+ value !== null &&
1367
+ 'type' in value &&
1368
+ value.type === 'dynamic' &&
1369
+ 'content' in value &&
1370
+ typeof value.content === 'object' &&
1371
+ value.content !== null &&
1372
+ 'referenceType' in value.content &&
1373
+ 'id' in value.content);
1374
+ };
1375
+ /**
1376
+ * Converts a filter destination value to an AST expression.
1377
+ * Handles both static values and dynamic references (state/prop).
1378
+ */
1379
+ export var convertFilterDestinationToExpression = function (destination, options) {
1380
+ var _a;
1381
+ // Handle dynamic references (state or prop)
1382
+ if (isUIDLDynamicReference(destination)) {
1383
+ var content = destination.content;
1384
+ var referenceType = content.referenceType, id = content.id;
1385
+ if (referenceType === 'state') {
1386
+ return types.identifier(id);
1387
+ }
1388
+ if (referenceType === 'prop') {
1389
+ var prefix = ((_a = options === null || options === void 0 ? void 0 : options.dynamicReferencePrefixMap) === null || _a === void 0 ? void 0 : _a.prop) || 'props';
1390
+ return types.memberExpression(types.identifier(prefix), types.identifier(id));
1391
+ }
1392
+ // Fallback for other reference types
1393
+ return types.identifier(id);
1394
+ }
1395
+ // Handle static string values
1396
+ if (typeof destination === 'string') {
1397
+ return types.stringLiteral(destination);
1398
+ }
1399
+ // Handle other primitives
1400
+ if (typeof destination === 'number') {
1401
+ return types.numericLiteral(destination);
1402
+ }
1403
+ if (typeof destination === 'boolean') {
1404
+ return types.booleanLiteral(destination);
1405
+ }
1406
+ // Handle arrays
1407
+ if (Array.isArray(destination)) {
1408
+ return types.arrayExpression(destination.map(function (item) { return convertFilterDestinationToExpression(item, options); }));
1409
+ }
1410
+ // Fallback to empty string for undefined/null
1411
+ return types.stringLiteral('');
1412
+ };
616
1413
  export var getExpressionFromUIDLExpressionNode = function (node) {
617
- var ast = parse(node.content, {
618
- sourceType: 'module',
619
- });
620
- if (!('program' in ast)) {
1414
+ var ast;
1415
+ try {
1416
+ ast = parse(sanitizeExprContent(node.content), {
1417
+ sourceType: 'module',
1418
+ });
1419
+ }
1420
+ catch (err) {
1421
+ // Malformed expression content in the UIDL (e.g. `?.subtitle` missing its
1422
+ // left-hand identifier). Don't abort the whole generation — warn and fall
1423
+ // back to `undefined`, which renders as nothing in JSX.
1424
+ // tslint:disable-next-line:no-console
1425
+ console.warn("Failed to parse UIDL expression content ".concat(JSON.stringify(node.content), ": ").concat(err.message, ". Falling back to 'undefined'."));
1426
+ return types.identifier('undefined');
1427
+ }
1428
+ if (!ast || !('program' in ast)) {
621
1429
  throw new Error("The AST does not have a program node in the expression inside addDynamicExpressionAttributeToJSXTag");
622
1430
  }
623
1431
  var theStatementOnlyWihtoutTheProgram = ast.program.body[0];
624
- if (theStatementOnlyWihtoutTheProgram.type !== 'ExpressionStatement') {
1432
+ if (!theStatementOnlyWihtoutTheProgram ||
1433
+ theStatementOnlyWihtoutTheProgram.type !== 'ExpressionStatement') {
625
1434
  throw new Error("Expr dynamic attribute only support expressions statements at the moment.");
626
1435
  }
627
- return theStatementOnlyWihtoutTheProgram.expression;
1436
+ return makeMemberAccessOptional(theStatementOnlyWihtoutTheProgram.expression);
1437
+ };
1438
+ /**
1439
+ * Every member read in a UIDL expression becomes an optional-chain read:
1440
+ * `strengths[0].pillar` → `strengths?.[0]?.pillar`. A binding into a list
1441
+ * that is empty until a workflow fills it (the first render, a reset) must
1442
+ * read `undefined`, never throw — one such read took a whole page down at
1443
+ * server render ("Cannot read properties of undefined"). A call's callee
1444
+ * keeps its plain member (`JSON.stringify(x)`), and an assignment or update
1445
+ * target is left as written.
1446
+ */
1447
+ export var makeMemberAccessOptional = function (node) {
1448
+ var SKIP_KEYS = new Set([
1449
+ 'loc',
1450
+ 'start',
1451
+ 'end',
1452
+ 'leadingComments',
1453
+ 'trailingComments',
1454
+ 'innerComments',
1455
+ 'extra',
1456
+ ]);
1457
+ var isNode = function (value) {
1458
+ return Boolean(value) &&
1459
+ typeof value === 'object' &&
1460
+ typeof value.type === 'string';
1461
+ };
1462
+ var visit = function (current, asCallee, asTarget) {
1463
+ if (current.type === 'MemberExpression' && !asCallee && !asTarget) {
1464
+ var member = current;
1465
+ var object = visit(member.object, false, false);
1466
+ var property = member.computed
1467
+ ? visit(member.property, false, false)
1468
+ : member.property;
1469
+ return types.optionalMemberExpression(object, property, member.computed, true);
1470
+ }
1471
+ if (current.type === 'CallExpression' ||
1472
+ current.type === 'OptionalCallExpression' ||
1473
+ current.type === 'NewExpression') {
1474
+ var call = current;
1475
+ // The callee's own member stays plain; what it is read from is guarded.
1476
+ if (call.callee.type === 'MemberExpression') {
1477
+ var callee = call.callee;
1478
+ callee.object = visit(callee.object, false, false);
1479
+ if (callee.computed)
1480
+ callee.property = visit(callee.property, false, false);
1481
+ }
1482
+ else {
1483
+ call.callee = visit(call.callee, true, false);
1484
+ }
1485
+ call.arguments = call.arguments.map(function (argument) { return visit(argument, false, false); });
1486
+ return call;
1487
+ }
1488
+ if (current.type === 'AssignmentExpression') {
1489
+ var assignment = current;
1490
+ assignment.right = visit(assignment.right, false, false);
1491
+ return assignment;
1492
+ }
1493
+ if (current.type === 'UpdateExpression' ||
1494
+ (current.type === 'UnaryExpression' &&
1495
+ current.operator === 'delete')) {
1496
+ return current;
1497
+ }
1498
+ for (var _i = 0, _a = Object.keys(current); _i < _a.length; _i++) {
1499
+ var key = _a[_i];
1500
+ if (SKIP_KEYS.has(key))
1501
+ continue;
1502
+ var value = current[key];
1503
+ if (Array.isArray(value)) {
1504
+ ;
1505
+ current[key] = value.map(function (item) {
1506
+ return isNode(item) ? visit(item, false, false) : item;
1507
+ });
1508
+ }
1509
+ else if (isNode(value)) {
1510
+ ;
1511
+ current[key] = visit(value, false, false);
1512
+ }
1513
+ }
1514
+ return current;
1515
+ };
1516
+ return visit(node, false, false);
1517
+ };
1518
+ export var isJSXElement = function (value) {
1519
+ return value.type === 'JSXElement';
1520
+ };
1521
+ /**
1522
+ * Because of the restrictions of the AST Types we need to have a clear subset of binary operators we can use
1523
+ * @param operation - the operation defined in the UIDL for the current state branch
1524
+ */
1525
+ export var convertToBinaryOperator = function (operation) {
1526
+ var allowedOperations = ['===', '!==', '>=', '<=', '>', '<'];
1527
+ if (allowedOperations.includes(operation)) {
1528
+ return operation;
1529
+ }
1530
+ else {
1531
+ return '===';
1532
+ }
1533
+ };
1534
+ export var convertToUnaryOperator = function (operation) {
1535
+ var allowedOperations = ['!'];
1536
+ if (allowedOperations.includes(operation)) {
1537
+ return operation;
1538
+ }
1539
+ else {
1540
+ return '!';
1541
+ }
628
1542
  };
629
1543
  //# sourceMappingURL=ast-utils.js.map