@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.
- package/__tests__/builders/html-builders.ts +9 -2
- package/__tests__/builders/style-builders.ts +135 -1
- package/__tests__/node-handlers/node-to-html/index.ts +2 -0
- package/__tests__/node-handlers/node-to-jsx/attribute-value-mapper.ts +77 -0
- package/__tests__/node-handlers/node-to-jsx/calendar-events-reviver.ts +176 -0
- package/__tests__/node-handlers/node-to-jsx/chart-data-guard.ts +101 -0
- package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-ecommerce-source.ts +79 -0
- package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-loading.ts +122 -0
- package/__tests__/node-handlers/node-to-jsx/index.ts +719 -3
- package/__tests__/node-handlers/node-to-jsx/url-search-params-expression.ts +59 -0
- package/__tests__/node-handlers/node-to-jsx/utils.ts +635 -3
- package/__tests__/utils/ast-utils.ts +188 -0
- package/__tests__/utils/content-property-sanitiser.ts +156 -0
- package/__tests__/utils/page-seeds-state-from-data-source.ts +70 -0
- package/__tests__/utils/parse-string-with-template-expressions.ts +82 -0
- package/__tests__/utils/resource-auth-scheme.ts +55 -0
- package/__tests__/utils/route-utils.ts +118 -0
- package/__tests__/utils/style-utils.ts +59 -0
- package/__tests__/utils/template-expression-balance.ts +83 -0
- package/__tests__/utils/url-query-writer.ts +239 -0
- package/__tests__/utils/url-search-param-sync.ts +138 -0
- package/__tests__/utils/url-search-params.ts +48 -0
- package/dist/cjs/builders/ast-builders.d.ts +2 -0
- package/dist/cjs/builders/ast-builders.d.ts.map +1 -1
- package/dist/cjs/builders/ast-builders.js +41 -3
- package/dist/cjs/builders/ast-builders.js.map +1 -1
- package/dist/cjs/builders/hast-builders.d.ts +1 -0
- package/dist/cjs/builders/hast-builders.d.ts.map +1 -1
- package/dist/cjs/builders/hast-builders.js +11 -1
- package/dist/cjs/builders/hast-builders.js.map +1 -1
- package/dist/cjs/builders/style-builders.d.ts +8 -2
- package/dist/cjs/builders/style-builders.d.ts.map +1 -1
- package/dist/cjs/builders/style-builders.js +80 -33
- package/dist/cjs/builders/style-builders.js.map +1 -1
- package/dist/cjs/index.d.ts +5 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +10 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/constants.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/constants.js +2 -0
- package/dist/cjs/node-handlers/node-to-html/constants.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/index.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/index.js +69 -1
- package/dist/cjs/node-handlers/node-to-html/index.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/types.d.ts +5 -1
- package/dist/cjs/node-handlers/node-to-html/types.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/utils.d.ts +2 -1
- package/dist/cjs/node-handlers/node-to-html/utils.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/utils.js +174 -13
- package/dist/cjs/node-handlers/node-to-html/utils.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/index.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/index.js +1443 -45
- package/dist/cjs/node-handlers/node-to-jsx/index.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/types.d.ts +60 -6
- package/dist/cjs/node-handlers/node-to-jsx/types.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts +80 -7
- package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/utils.js +883 -72
- package/dist/cjs/node-handlers/node-to-jsx/utils.js.map +1 -1
- package/dist/cjs/tsconfig.tsbuildinfo +1 -1
- package/dist/cjs/utils/ast-utils.d.ts +163 -11
- package/dist/cjs/utils/ast-utils.d.ts.map +1 -1
- package/dist/cjs/utils/ast-utils.js +1013 -75
- package/dist/cjs/utils/ast-utils.js.map +1 -1
- package/dist/cjs/utils/hast-utils.d.ts +8 -6
- package/dist/cjs/utils/hast-utils.d.ts.map +1 -1
- package/dist/cjs/utils/hast-utils.js +28 -4
- package/dist/cjs/utils/hast-utils.js.map +1 -1
- package/dist/cjs/utils/nested-selector-commas.d.ts +2 -0
- package/dist/cjs/utils/nested-selector-commas.d.ts.map +1 -0
- package/dist/cjs/utils/nested-selector-commas.js +81 -0
- package/dist/cjs/utils/nested-selector-commas.js.map +1 -0
- package/dist/cjs/utils/route-utils.d.ts +117 -0
- package/dist/cjs/utils/route-utils.d.ts.map +1 -0
- package/dist/cjs/utils/route-utils.js +212 -0
- package/dist/cjs/utils/route-utils.js.map +1 -0
- package/dist/cjs/utils/style-utils.d.ts +1 -0
- package/dist/cjs/utils/style-utils.d.ts.map +1 -1
- package/dist/cjs/utils/style-utils.js +181 -2
- package/dist/cjs/utils/style-utils.js.map +1 -1
- package/dist/cjs/utils/template-expression-balance.d.ts +58 -0
- package/dist/cjs/utils/template-expression-balance.d.ts.map +1 -0
- package/dist/cjs/utils/template-expression-balance.js +181 -0
- package/dist/cjs/utils/template-expression-balance.js.map +1 -0
- package/dist/cjs/utils/types.d.ts +3 -0
- package/dist/cjs/utils/types.d.ts.map +1 -0
- package/dist/cjs/utils/types.js +3 -0
- package/dist/cjs/utils/types.js.map +1 -0
- package/dist/cjs/utils/url-query-writer.d.ts +123 -0
- package/dist/cjs/utils/url-query-writer.d.ts.map +1 -0
- package/dist/cjs/utils/url-query-writer.js +260 -0
- package/dist/cjs/utils/url-query-writer.js.map +1 -0
- package/dist/cjs/utils/url-search-param-sync.d.ts +4 -0
- package/dist/cjs/utils/url-search-param-sync.d.ts.map +1 -0
- package/dist/cjs/utils/url-search-param-sync.js +241 -0
- package/dist/cjs/utils/url-search-param-sync.js.map +1 -0
- package/dist/cjs/utils/url-search-params.d.ts +48 -0
- package/dist/cjs/utils/url-search-params.d.ts.map +1 -0
- package/dist/cjs/utils/url-search-params.js +109 -0
- package/dist/cjs/utils/url-search-params.js.map +1 -0
- package/dist/esm/builders/ast-builders.d.ts +2 -0
- package/dist/esm/builders/ast-builders.d.ts.map +1 -1
- package/dist/esm/builders/ast-builders.js +40 -4
- package/dist/esm/builders/ast-builders.js.map +1 -1
- package/dist/esm/builders/hast-builders.d.ts +1 -0
- package/dist/esm/builders/hast-builders.d.ts.map +1 -1
- package/dist/esm/builders/hast-builders.js +9 -0
- package/dist/esm/builders/hast-builders.js.map +1 -1
- package/dist/esm/builders/style-builders.d.ts +8 -2
- package/dist/esm/builders/style-builders.d.ts.map +1 -1
- package/dist/esm/builders/style-builders.js +78 -32
- package/dist/esm/builders/style-builders.js.map +1 -1
- package/dist/esm/index.d.ts +5 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +5 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node-handlers/node-to-html/constants.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/constants.js +2 -0
- package/dist/esm/node-handlers/node-to-html/constants.js.map +1 -1
- package/dist/esm/node-handlers/node-to-html/index.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/index.js +71 -3
- package/dist/esm/node-handlers/node-to-html/index.js.map +1 -1
- package/dist/esm/node-handlers/node-to-html/types.d.ts +5 -1
- package/dist/esm/node-handlers/node-to-html/types.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/utils.d.ts +2 -1
- package/dist/esm/node-handlers/node-to-html/utils.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/utils.js +170 -13
- package/dist/esm/node-handlers/node-to-html/utils.js.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/index.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/index.js +1442 -47
- package/dist/esm/node-handlers/node-to-jsx/index.js.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/types.d.ts +60 -6
- package/dist/esm/node-handlers/node-to-jsx/types.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/utils.d.ts +80 -7
- package/dist/esm/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/utils.js +875 -70
- package/dist/esm/node-handlers/node-to-jsx/utils.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/dist/esm/utils/ast-utils.d.ts +163 -11
- package/dist/esm/utils/ast-utils.d.ts.map +1 -1
- package/dist/esm/utils/ast-utils.js +989 -75
- package/dist/esm/utils/ast-utils.js.map +1 -1
- package/dist/esm/utils/hast-utils.d.ts +8 -6
- package/dist/esm/utils/hast-utils.d.ts.map +1 -1
- package/dist/esm/utils/hast-utils.js +26 -3
- package/dist/esm/utils/hast-utils.js.map +1 -1
- package/dist/esm/utils/nested-selector-commas.d.ts +2 -0
- package/dist/esm/utils/nested-selector-commas.d.ts.map +1 -0
- package/dist/esm/utils/nested-selector-commas.js +77 -0
- package/dist/esm/utils/nested-selector-commas.js.map +1 -0
- package/dist/esm/utils/route-utils.d.ts +117 -0
- package/dist/esm/utils/route-utils.d.ts.map +1 -0
- package/dist/esm/utils/route-utils.js +179 -0
- package/dist/esm/utils/route-utils.js.map +1 -0
- package/dist/esm/utils/style-utils.d.ts +1 -0
- package/dist/esm/utils/style-utils.d.ts.map +1 -1
- package/dist/esm/utils/style-utils.js +179 -1
- package/dist/esm/utils/style-utils.js.map +1 -1
- package/dist/esm/utils/template-expression-balance.d.ts +58 -0
- package/dist/esm/utils/template-expression-balance.d.ts.map +1 -0
- package/dist/esm/utils/template-expression-balance.js +174 -0
- package/dist/esm/utils/template-expression-balance.js.map +1 -0
- package/dist/esm/utils/types.d.ts +3 -0
- package/dist/esm/utils/types.d.ts.map +1 -0
- package/dist/esm/utils/types.js +2 -0
- package/dist/esm/utils/types.js.map +1 -0
- package/dist/esm/utils/url-query-writer.d.ts +123 -0
- package/dist/esm/utils/url-query-writer.d.ts.map +1 -0
- package/dist/esm/utils/url-query-writer.js +229 -0
- package/dist/esm/utils/url-query-writer.js.map +1 -0
- package/dist/esm/utils/url-search-param-sync.d.ts +4 -0
- package/dist/esm/utils/url-search-param-sync.d.ts.map +1 -0
- package/dist/esm/utils/url-search-param-sync.js +213 -0
- package/dist/esm/utils/url-search-param-sync.js.map +1 -0
- package/dist/esm/utils/url-search-params.d.ts +48 -0
- package/dist/esm/utils/url-search-params.d.ts.map +1 -0
- package/dist/esm/utils/url-search-params.js +81 -0
- package/dist/esm/utils/url-search-params.js.map +1 -0
- package/package.json +4 -4
- package/src/builders/ast-builders.ts +80 -3
- package/src/builders/hast-builders.ts +11 -0
- package/src/builders/style-builders.ts +121 -43
- package/src/index.ts +22 -1
- package/src/node-handlers/node-to-html/constants.ts +2 -0
- package/src/node-handlers/node-to-html/index.ts +126 -6
- package/src/node-handlers/node-to-html/types.ts +6 -0
- package/src/node-handlers/node-to-html/utils.ts +228 -14
- package/src/node-handlers/node-to-jsx/index.ts +2135 -62
- package/src/node-handlers/node-to-jsx/types.ts +75 -32
- package/src/node-handlers/node-to-jsx/utils.ts +1173 -84
- package/src/utils/ast-utils.ts +1316 -127
- package/src/utils/hast-utils.ts +37 -9
- package/src/utils/nested-selector-commas.ts +88 -0
- package/src/utils/route-utils.ts +214 -0
- package/src/utils/style-utils.ts +183 -1
- package/src/utils/template-expression-balance.ts +196 -0
- package/src/utils/types.ts +25 -0
- package/src/utils/url-query-writer.ts +318 -0
- package/src/utils/url-search-param-sync.ts +303 -0
- package/src/utils/url-search-params.ts +122 -0
package/src/utils/ast-utils.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as types from '@babel/types'
|
|
2
2
|
import { parse } from '@babel/core'
|
|
3
3
|
import ParsedASTNode from './parsed-ast'
|
|
4
|
-
import { StringUtils } from '@teleporthq/teleport-shared'
|
|
4
|
+
import { JSIdentifiers, StringUtils, UIDLUtils } from '@teleporthq/teleport-shared'
|
|
5
5
|
import {
|
|
6
6
|
UIDLStateDefinition,
|
|
7
7
|
UIDLPropDefinition,
|
|
@@ -12,25 +12,77 @@ import {
|
|
|
12
12
|
UIDLPropValue,
|
|
13
13
|
UIDLExpressionValue,
|
|
14
14
|
UIDLStateValue,
|
|
15
|
+
HastNode,
|
|
15
16
|
} from '@teleporthq/teleport-types'
|
|
16
17
|
import babelPresetReact from '@babel/preset-react'
|
|
17
|
-
import {
|
|
18
|
+
import { UnaryOperation, BinaryOperator } from './types'
|
|
19
|
+
import { balanceExpression, countUnclosedStaticParens } from './template-expression-balance'
|
|
18
20
|
|
|
19
21
|
/**
|
|
20
|
-
*
|
|
22
|
+
* Converts HTML attribute names to React/JSX camelCase format
|
|
23
|
+
* Preserves data-* and aria-* attributes as-is
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* React sets attributes on CUSTOM ELEMENTS (dash-named tags) verbatim, so
|
|
27
|
+
* camelCasing them is not just unnecessary — it breaks the element:
|
|
28
|
+
* `camera-controls` camelCased to `cameraControls` reaches the DOM as the
|
|
29
|
+
* meaningless `cameracontrols`. Web-component tags keep their attribute
|
|
30
|
+
* spelling untouched.
|
|
31
|
+
*/
|
|
32
|
+
export const isCustomElementTagName = (jsxNode: types.JSXElement): boolean => {
|
|
33
|
+
const name = jsxNode.openingElement.name
|
|
34
|
+
return name.type === 'JSXIdentifier' && name.name.includes('-')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const resolveAttributeNameForTag = (jsxNode: types.JSXElement, attrName: string): string => {
|
|
38
|
+
return isCustomElementTagName(jsxNode) ? attrName : convertToReactAttributeName(attrName)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const convertToReactAttributeName = (attrName: string): string => {
|
|
42
|
+
if (attrName.startsWith('data-') || attrName.startsWith('aria-')) {
|
|
43
|
+
return attrName
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const htmlToReact: Record<string, string> = {
|
|
47
|
+
colspan: 'colSpan',
|
|
48
|
+
rowspan: 'rowSpan',
|
|
49
|
+
maxlength: 'maxLength',
|
|
50
|
+
minlength: 'minLength',
|
|
51
|
+
readonly: 'readOnly',
|
|
52
|
+
autocomplete: 'autoComplete',
|
|
53
|
+
autofocus: 'autoFocus',
|
|
54
|
+
tabindex: 'tabIndex',
|
|
55
|
+
contenteditable: 'contentEditable',
|
|
56
|
+
spellcheck: 'spellCheck',
|
|
57
|
+
}
|
|
58
|
+
if (htmlToReact[attrName]) {
|
|
59
|
+
return htmlToReact[attrName]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return attrName.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Adds a CSS class definition string to an existing string of classes
|
|
21
67
|
*/
|
|
22
68
|
export const addClassStringOnJSXTag = (
|
|
23
69
|
jsxNode: types.JSXElement,
|
|
24
70
|
classString: string,
|
|
25
71
|
classAttributeName?: string,
|
|
26
|
-
dynamicValues: Array<types.MemberExpression | types.Identifier> = []
|
|
72
|
+
dynamicValues: Array<types.MemberExpression | types.Identifier | types.ConditionalExpression> = []
|
|
27
73
|
) => {
|
|
28
|
-
|
|
74
|
+
if (classString === '' && dynamicValues.length === 0) {
|
|
75
|
+
return
|
|
76
|
+
}
|
|
29
77
|
|
|
78
|
+
const classAttribute = getClassAttribute(jsxNode, { createIfNotFound: true, classAttributeName })
|
|
30
79
|
if (dynamicValues.length === 0) {
|
|
31
80
|
if (classAttribute.value && classAttribute.value.type === 'StringLiteral') {
|
|
32
81
|
const classArray = classAttribute.value.value.split(' ')
|
|
33
|
-
|
|
82
|
+
if (classString) {
|
|
83
|
+
classArray.push(classString)
|
|
84
|
+
}
|
|
85
|
+
classArray.filter((item) => item)
|
|
34
86
|
classAttribute.value.value = classArray.join(' ').trim()
|
|
35
87
|
} else {
|
|
36
88
|
throw new Error(
|
|
@@ -43,7 +95,9 @@ export const addClassStringOnJSXTag = (
|
|
|
43
95
|
if (classAttribute.value && classAttribute.value.type === 'StringLiteral') {
|
|
44
96
|
const classArray = classAttribute.value.value.split(' ')
|
|
45
97
|
const quasis: types.TemplateElement[] = []
|
|
46
|
-
const expression: Array<
|
|
98
|
+
const expression: Array<
|
|
99
|
+
types.MemberExpression | types.Identifier | types.ConditionalExpression
|
|
100
|
+
> = []
|
|
47
101
|
|
|
48
102
|
quasis.push(
|
|
49
103
|
types.templateElement({
|
|
@@ -102,13 +156,19 @@ export const addDynamicAttributeToJSXTag = (
|
|
|
102
156
|
prefix: string = '',
|
|
103
157
|
t = types
|
|
104
158
|
) => {
|
|
159
|
+
const reactName = resolveAttributeNameForTag(jsxASTNode, name)
|
|
160
|
+
// Same rule as `createDynamicValueExpression`: with no prefix the value IS the
|
|
161
|
+
// binding (React hooks state), so it must match the sanitised name
|
|
162
|
+
// `createStateHookAST` declared — `value={class}` does not parse. With a
|
|
163
|
+
// prefix it is `props.class` / `this.class`, where the UIDL spelling is legal
|
|
164
|
+
// AND load-bearing, so it is left alone.
|
|
105
165
|
const content =
|
|
106
166
|
prefix === ''
|
|
107
|
-
? t.identifier(value)
|
|
167
|
+
? t.identifier(JSIdentifiers.createSafeJSIdentifierPath(value))
|
|
108
168
|
: t.memberExpression(t.identifier(prefix), t.identifier(value))
|
|
109
169
|
|
|
110
170
|
jsxASTNode.openingElement.attributes.push(
|
|
111
|
-
t.jsxAttribute(t.jsxIdentifier(
|
|
171
|
+
t.jsxAttribute(t.jsxIdentifier(reactName), t.jsxExpressionContainer(content))
|
|
112
172
|
)
|
|
113
173
|
}
|
|
114
174
|
|
|
@@ -118,6 +178,53 @@ export const addDynamicAttributeToJSXTag = (
|
|
|
118
178
|
* the corresponding value from the contexts for now
|
|
119
179
|
* and in the future with other sources.
|
|
120
180
|
*/
|
|
181
|
+
/**
|
|
182
|
+
* UIDL `expr` values are opaque JavaScript expressions, but authoring tools
|
|
183
|
+
* (notably Teleport-GUI while the differentiator-navlink contract is mid-
|
|
184
|
+
* migration) occasionally emit malformed template literals with empty
|
|
185
|
+
* substitutions like `` `/profile/${}` ``. Babel rejects these and the whole
|
|
186
|
+
* generation run fails.
|
|
187
|
+
*
|
|
188
|
+
* We only repair a narrow set of known-safe patterns to avoid silently
|
|
189
|
+
* masking real UIDL bugs:
|
|
190
|
+
* 1. `/profile/${}` → `/profile/${currentUser?.id}` (My Profile navlink
|
|
191
|
+
* per the dual-mode profile page contract).
|
|
192
|
+
* 2. any remaining empty `${}` → `${''}` — at least the output parses and
|
|
193
|
+
* the placeholder is visibly empty at runtime.
|
|
194
|
+
* Each repair logs a warning so the upstream UIDL bug remains visible.
|
|
195
|
+
*/
|
|
196
|
+
export const sanitizeExprContent = (content: string, attrKey?: string): string => {
|
|
197
|
+
if (typeof content !== 'string' || !content.includes('${}')) {
|
|
198
|
+
return content
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let repaired = content
|
|
202
|
+
|
|
203
|
+
// My Profile navlink: the differentiator is always the session user's id.
|
|
204
|
+
repaired = repaired.replace(
|
|
205
|
+
/`([^`]*\/profile\/)\$\{\}([^`]*)`/g,
|
|
206
|
+
'`$1' + '$' + '{' + 'currentUser?.id}' + '$2`'
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
// Generic fallback: any other empty `${}` becomes an empty string literal so
|
|
210
|
+
// downstream Babel parsing succeeds. This is intentionally lossy — the goal
|
|
211
|
+
// is not to guess the original intent, just to keep the build from crashing.
|
|
212
|
+
if (repaired.includes('${}')) {
|
|
213
|
+
repaired = repaired.replace(/\$\{\}/g, '$' + '{' + "'" + "'" + '}')
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (repaired !== content) {
|
|
217
|
+
// tslint:disable-next-line:no-console
|
|
218
|
+
console.warn(
|
|
219
|
+
`[teleport] Repaired malformed empty template substitution in expr${
|
|
220
|
+
attrKey ? ` attribute "${attrKey}"` : ''
|
|
221
|
+
}: ${content} → ${repaired}`
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return repaired
|
|
226
|
+
}
|
|
227
|
+
|
|
121
228
|
export const addDynamicExpressionAttributeToJSXTag = (
|
|
122
229
|
jsxASTNode: types.JSXElement,
|
|
123
230
|
dynamicRef: UIDLExpressionValue,
|
|
@@ -129,7 +236,7 @@ export const addDynamicExpressionAttributeToJSXTag = (
|
|
|
129
236
|
throw new Error(`This method only works with dynamic nodes that have code expressions`)
|
|
130
237
|
}
|
|
131
238
|
|
|
132
|
-
const code = dynamicContent
|
|
239
|
+
const code = sanitizeExprContent(dynamicContent, attrKey)
|
|
133
240
|
const options = {
|
|
134
241
|
sourceType: 'module' as const,
|
|
135
242
|
}
|
|
@@ -148,10 +255,33 @@ export const addDynamicExpressionAttributeToJSXTag = (
|
|
|
148
255
|
throw new Error(`Expr dynamic attribute only support expressions statements at the moment.`)
|
|
149
256
|
}
|
|
150
257
|
|
|
258
|
+
let expression = theStatementOnlyWihtoutTheProgram.expression
|
|
259
|
+
|
|
260
|
+
// When an expression accesses `.value` on a simple identifier (e.g. `galleryImage?.value`),
|
|
261
|
+
// wrap it with a typeof check so that if the item is already a string we use it directly:
|
|
262
|
+
// `typeof galleryImage === 'string' ? galleryImage : galleryImage?.value`
|
|
263
|
+
if (
|
|
264
|
+
(expression.type === 'OptionalMemberExpression' || expression.type === 'MemberExpression') &&
|
|
265
|
+
expression.object.type === 'Identifier' &&
|
|
266
|
+
expression.property.type === 'Identifier' &&
|
|
267
|
+
expression.property.name === 'value'
|
|
268
|
+
) {
|
|
269
|
+
const varName = expression.object.name
|
|
270
|
+
expression = t.conditionalExpression(
|
|
271
|
+
t.binaryExpression(
|
|
272
|
+
'===',
|
|
273
|
+
t.unaryExpression('typeof', t.identifier(varName)),
|
|
274
|
+
t.stringLiteral('string')
|
|
275
|
+
),
|
|
276
|
+
t.identifier(varName),
|
|
277
|
+
expression
|
|
278
|
+
)
|
|
279
|
+
}
|
|
280
|
+
|
|
151
281
|
jsxASTNode.openingElement.attributes.push(
|
|
152
282
|
t.jsxAttribute(
|
|
153
|
-
t.jsxIdentifier(attrKey),
|
|
154
|
-
t.jsxExpressionContainer(
|
|
283
|
+
t.jsxIdentifier(convertToReactAttributeName(attrKey)),
|
|
284
|
+
t.jsxExpressionContainer(expression)
|
|
155
285
|
)
|
|
156
286
|
)
|
|
157
287
|
}
|
|
@@ -164,17 +294,21 @@ export const addDynamicExpressionAttributeToJSXTag = (
|
|
|
164
294
|
export const addMultipleDynamicAttributesToJSXTag = (
|
|
165
295
|
jsxASTNode: types.JSXElement,
|
|
166
296
|
name: string,
|
|
167
|
-
attrValues: Array<types.MemberExpression | types.Identifier> = [],
|
|
297
|
+
attrValues: Array<types.MemberExpression | types.Identifier | types.StringLiteral> = [],
|
|
168
298
|
t = types
|
|
169
299
|
) => {
|
|
170
|
-
const memberExpressions: Array<types.Identifier | types.MemberExpression> =
|
|
300
|
+
const memberExpressions: Array<types.Identifier | types.MemberExpression | types.StringLiteral> =
|
|
301
|
+
[]
|
|
171
302
|
const templateElements: types.TemplateElement[] = []
|
|
172
|
-
|
|
173
303
|
if (attrValues.length === 0) {
|
|
174
304
|
return
|
|
175
305
|
}
|
|
176
306
|
|
|
177
|
-
let content:
|
|
307
|
+
let content:
|
|
308
|
+
| types.TemplateLiteral
|
|
309
|
+
| types.MemberExpression
|
|
310
|
+
| types.Identifier
|
|
311
|
+
| types.StringLiteral
|
|
178
312
|
if (attrValues.length === 1) {
|
|
179
313
|
content = attrValues[0]
|
|
180
314
|
} else {
|
|
@@ -210,26 +344,242 @@ export const stringAsTemplateLiteral = (str: string): types.TemplateLiteral => {
|
|
|
210
344
|
return container.expression as types.TemplateLiteral
|
|
211
345
|
}
|
|
212
346
|
|
|
347
|
+
/**
|
|
348
|
+
* Checks if a string contains {{ expression }} template patterns
|
|
349
|
+
*/
|
|
350
|
+
export const containsTemplateExpression = (str: string): boolean => {
|
|
351
|
+
return /\{\{.+?\}\}/.test(str)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Parses a JavaScript expression string into an AST Expression node.
|
|
356
|
+
* e.g. "item.type || 'coin'" → LogicalExpression AST
|
|
357
|
+
*/
|
|
358
|
+
export const parseJSExpressionAsAST = (expr: string): types.Expression => {
|
|
359
|
+
const ast = parse(`(${expr})`, {
|
|
360
|
+
sourceType: 'module',
|
|
361
|
+
})
|
|
362
|
+
|
|
363
|
+
if (!ast || !('program' in ast)) {
|
|
364
|
+
throw new Error(`Failed to parse expression: ${expr}`)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
return (ast.program.body[0] as types.ExpressionStatement).expression
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Parses a string containing {{ expr }} template patterns into a TemplateLiteral AST node.
|
|
372
|
+
* e.g. "translate({{ enemy.x || '0' }}px)" → `translate(${enemy.x || '0'}px)`
|
|
373
|
+
*/
|
|
374
|
+
export const parseStringWithTemplateExpressions = (str: string): types.TemplateLiteral => {
|
|
375
|
+
// Step 1: Normalize state references: state.xxx → xxx
|
|
376
|
+
const normalized = str.replace(/state\.(\w+)/g, '$1')
|
|
377
|
+
|
|
378
|
+
// Step 2: Convert well-formed {{ expr }} to ${expr}
|
|
379
|
+
//
|
|
380
|
+
// The expression is BALANCED on the way in. A binding that lost a closing
|
|
381
|
+
// paren upstream (`-(cameraX || ''`) produces source Babel cannot parse, and
|
|
382
|
+
// no amount of patching the static text around it can help — the repair has
|
|
383
|
+
// to happen inside the interpolation, which is the only place the bracket is
|
|
384
|
+
// actually missing.
|
|
385
|
+
let templateStr = normalized.replace(
|
|
386
|
+
/\{\{\s*(.+?)\s*\}\}/g,
|
|
387
|
+
(_, expr: string) => '${' + balanceExpression(expr.trim()) + '}'
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
// Step 3: Handle unclosed {{ expr (no closing }})
|
|
391
|
+
// After step 2, any remaining {{ was not well-formed
|
|
392
|
+
if (/\{\{/.test(templateStr)) {
|
|
393
|
+
templateStr = templateStr.replace(
|
|
394
|
+
/\{\{\s*(.+?)$/gm,
|
|
395
|
+
(_, expr: string) => '${' + balanceExpression(expr.trim()) + '}'
|
|
396
|
+
)
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// Step 4: Detect and fix incomplete CSS function calls
|
|
400
|
+
// If the original string contained a CSS function like translateX(...) or translate(...)
|
|
401
|
+
// but the template expression consumed the closing, we need to re-close it.
|
|
402
|
+
//
|
|
403
|
+
// Counted over the STATIC text only. Including the parentheses inside `${…}`
|
|
404
|
+
// made an imbalance in the expression look like an unclosed CSS function, so
|
|
405
|
+
// this step appended a unit and a `)` to the end of a string whose real fault
|
|
406
|
+
// was several characters earlier and inside the interpolation.
|
|
407
|
+
const missingStaticCloses = countUnclosedStaticParens(templateStr)
|
|
408
|
+
if (missingStaticCloses > 0) {
|
|
409
|
+
// Determine the CSS unit by:
|
|
410
|
+
// 1. Looking for existing units already in the string (e.g. "translate(${x}px, ${y" → px)
|
|
411
|
+
// 2. Inferring from the CSS function name
|
|
412
|
+
const existingUnit = templateStr.match(/(px|deg|em|rem|%|vh|vw)[),\s]/)
|
|
413
|
+
let unit = 'px' // default
|
|
414
|
+
if (existingUnit) {
|
|
415
|
+
unit = existingUnit[1]
|
|
416
|
+
} else {
|
|
417
|
+
// Infer unit from the CSS function name
|
|
418
|
+
const fnMatch = templateStr.match(/\b(rotate|skew|skewX|skewY)\s*\(/)
|
|
419
|
+
if (fnMatch) {
|
|
420
|
+
unit = 'deg'
|
|
421
|
+
}
|
|
422
|
+
const noUnitFns = /\b(scale|scaleX|scaleY|scale3d|opacity)\s*\(/
|
|
423
|
+
if (noUnitFns.test(templateStr)) {
|
|
424
|
+
unit = ''
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
templateStr += unit + ')'.repeat(missingStaticCloses)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Step 5: Parse — and NEVER let a single malformed binding abort the build.
|
|
432
|
+
//
|
|
433
|
+
// The inline-style caller has no error handling of its own, so an
|
|
434
|
+
// unparseable template used to escape as a raw Babel SyntaxError and take the
|
|
435
|
+
// whole project generation down with it. A UIDL can always carry a binding
|
|
436
|
+
// this module cannot rescue (hand-edited, produced by an older pipeline, or
|
|
437
|
+
// broken in a way `balanceExpression` refuses to guess at), and the right
|
|
438
|
+
// answer is to degrade that ONE value: emit the original text as a plain
|
|
439
|
+
// string so the property still renders and the other 99 pages still build.
|
|
440
|
+
try {
|
|
441
|
+
const ast = parse('const x = `' + templateStr + '`', {
|
|
442
|
+
sourceType: 'module',
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
if (ast && 'program' in ast) {
|
|
446
|
+
const decl = ast.program.body[0] as types.VariableDeclaration
|
|
447
|
+
return decl.declarations[0].init as types.TemplateLiteral
|
|
448
|
+
}
|
|
449
|
+
} catch {
|
|
450
|
+
// Fall through to the static fallback below.
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
return staticTemplateLiteral(stripTemplateExpressions(str))
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Drop every `{{ … }}` binding from a string, keeping any `'literal'` fallback
|
|
458
|
+
* it declared. `translateX({{ -(x || 0) }}px)` → `translateX(px)` is useless as
|
|
459
|
+
* a style value, but `{{ name || 'Guest' }}` → `Guest` keeps the text the
|
|
460
|
+
* author intended. Used only when the expression could not be parsed at all.
|
|
461
|
+
*/
|
|
462
|
+
const stripTemplateExpressions = (value: string): string =>
|
|
463
|
+
value.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_, expr: string) => {
|
|
464
|
+
const literalFallback = /\|\|\s*(['"])([\s\S]*?)\1\s*$/.exec(expr)
|
|
465
|
+
return literalFallback ? literalFallback[2] : ''
|
|
466
|
+
})
|
|
467
|
+
|
|
468
|
+
/** A TemplateLiteral with no interpolations, holding `value` verbatim. */
|
|
469
|
+
const staticTemplateLiteral = (value: string): types.TemplateLiteral =>
|
|
470
|
+
types.templateLiteral(
|
|
471
|
+
[types.templateElement({ raw: value.replace(/[\\`]/g, '\\$&'), cooked: value }, true)],
|
|
472
|
+
[]
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
const REACT_BOOLEAN_DOM_PROPS = new Set([
|
|
476
|
+
'disabled',
|
|
477
|
+
'required',
|
|
478
|
+
'readOnly',
|
|
479
|
+
'checked',
|
|
480
|
+
'multiple',
|
|
481
|
+
'hidden',
|
|
482
|
+
'autoFocus',
|
|
483
|
+
'muted',
|
|
484
|
+
'loop',
|
|
485
|
+
'playsInline',
|
|
486
|
+
'autoPlay',
|
|
487
|
+
'controls',
|
|
488
|
+
'async',
|
|
489
|
+
'defer',
|
|
490
|
+
'inert',
|
|
491
|
+
'scoped',
|
|
492
|
+
'reversed',
|
|
493
|
+
'allowFullScreen',
|
|
494
|
+
'defaultChecked',
|
|
495
|
+
'selected',
|
|
496
|
+
'formNoValidate',
|
|
497
|
+
'noValidate',
|
|
498
|
+
])
|
|
499
|
+
|
|
213
500
|
export const addAttributeToJSXTag = (
|
|
214
501
|
jsxNode: types.JSXElement,
|
|
215
502
|
attrName: string,
|
|
216
503
|
attrValue?: boolean | unknown,
|
|
217
504
|
t = types
|
|
218
505
|
) => {
|
|
219
|
-
const
|
|
506
|
+
const reactAttrName = resolveAttributeNameForTag(jsxNode, attrName)
|
|
507
|
+
const nameOfAttribute = t.jsxIdentifier(reactAttrName)
|
|
220
508
|
let attributeDefinition
|
|
221
|
-
|
|
509
|
+
let normalizedValue: boolean | unknown = attrValue
|
|
510
|
+
if (
|
|
511
|
+
typeof attrValue === 'string' &&
|
|
512
|
+
(attrValue === 'true' || attrValue === 'false') &&
|
|
513
|
+
REACT_BOOLEAN_DOM_PROPS.has(reactAttrName)
|
|
514
|
+
) {
|
|
515
|
+
normalizedValue = attrValue === 'true'
|
|
516
|
+
}
|
|
517
|
+
if (typeof normalizedValue === 'boolean') {
|
|
222
518
|
attributeDefinition = t.jsxAttribute(
|
|
223
519
|
nameOfAttribute,
|
|
224
|
-
|
|
520
|
+
normalizedValue === true
|
|
521
|
+
? undefined
|
|
522
|
+
: t.jsxExpressionContainer(t.booleanLiteral(normalizedValue))
|
|
225
523
|
)
|
|
524
|
+
} else if (t.isNode(attrValue) && t.isJSXElement(attrValue)) {
|
|
525
|
+
attributeDefinition = t.jsxAttribute(nameOfAttribute, t.jsxExpressionContainer(attrValue))
|
|
226
526
|
} else {
|
|
227
527
|
attributeDefinition = t.jsxAttribute(
|
|
228
528
|
nameOfAttribute,
|
|
229
|
-
getProperAttributeValueAssignment(
|
|
529
|
+
getProperAttributeValueAssignment(normalizedValue)
|
|
230
530
|
)
|
|
231
531
|
}
|
|
232
532
|
|
|
533
|
+
const attribute: types.JSXAttribute = jsxNode.openingElement.attributes.find((attr) => {
|
|
534
|
+
if (attr.type === 'JSXAttribute') {
|
|
535
|
+
return attr.name.name === reactAttrName
|
|
536
|
+
}
|
|
537
|
+
}) as types.JSXAttribute
|
|
538
|
+
|
|
539
|
+
if (attribute && attribute.value && attribute.value.type === 'StringLiteral') {
|
|
540
|
+
attribute.value.value = `${attribute.value.value} ${attrValue}`
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// An object-valued attribute (e.g. `style={{ ... }}`) can be contributed by
|
|
545
|
+
// more than one independent code path — e.g. a ctx-scoped dynamic style value
|
|
546
|
+
// resolved at JSX-build time, and a `dynamicStyleBindings` inline style added
|
|
547
|
+
// later by a style plugin. Pushing a second `style` JSXAttribute would silently
|
|
548
|
+
// drop one of the two (JS keeps only the last of duplicate object keys once
|
|
549
|
+
// transpiled), so merge into the existing ObjectExpression instead, replacing
|
|
550
|
+
// any property with a matching key so the newer value wins.
|
|
551
|
+
if (
|
|
552
|
+
attribute &&
|
|
553
|
+
attribute.value?.type === 'JSXExpressionContainer' &&
|
|
554
|
+
attribute.value.expression.type === 'ObjectExpression' &&
|
|
555
|
+
attributeDefinition.value?.type === 'JSXExpressionContainer' &&
|
|
556
|
+
attributeDefinition.value.expression.type === 'ObjectExpression'
|
|
557
|
+
) {
|
|
558
|
+
const existingProps = attribute.value.expression.properties
|
|
559
|
+
attributeDefinition.value.expression.properties.forEach((newProp) => {
|
|
560
|
+
if (newProp.type !== 'ObjectProperty' || newProp.key.type === 'PrivateName') {
|
|
561
|
+
existingProps.push(newProp)
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
const newKeyName =
|
|
565
|
+
newProp.key.type === 'Identifier' ? newProp.key.name : String((newProp.key as any).value)
|
|
566
|
+
const existingIndex = existingProps.findIndex((prop) => {
|
|
567
|
+
if (prop.type !== 'ObjectProperty' || prop.key.type === 'PrivateName') {
|
|
568
|
+
return false
|
|
569
|
+
}
|
|
570
|
+
const existingKeyName =
|
|
571
|
+
prop.key.type === 'Identifier' ? prop.key.name : String((prop.key as any).value)
|
|
572
|
+
return existingKeyName === newKeyName
|
|
573
|
+
})
|
|
574
|
+
if (existingIndex >= 0) {
|
|
575
|
+
existingProps[existingIndex] = newProp
|
|
576
|
+
} else {
|
|
577
|
+
existingProps.push(newProp)
|
|
578
|
+
}
|
|
579
|
+
})
|
|
580
|
+
return
|
|
581
|
+
}
|
|
582
|
+
|
|
233
583
|
jsxNode.openingElement.attributes.push(attributeDefinition)
|
|
234
584
|
}
|
|
235
585
|
|
|
@@ -239,26 +589,50 @@ export const addRawAttributeToJSXTag = (
|
|
|
239
589
|
attrValue: UIDLRawValue,
|
|
240
590
|
t = types
|
|
241
591
|
) => {
|
|
592
|
+
// The content is expected to be pre-escaped for template literal context
|
|
593
|
+
// (e.g., \` for backticks, \${ for interpolations). Babel validates that
|
|
594
|
+
// the raw value is valid template literal content.
|
|
595
|
+
//
|
|
596
|
+
// We fix any unescaped backticks or ${ sequences that would make the
|
|
597
|
+
// template literal invalid. "Unescaped" means preceded by an even number
|
|
598
|
+
// of backslashes (0, 2, …), since pairs of backslashes form escape
|
|
599
|
+
// sequences for backslash itself, leaving the next character unescaped.
|
|
600
|
+
const content = attrValue.content
|
|
601
|
+
.replace(/\\*`/g, (match) => {
|
|
602
|
+
const bs = match.length - 1
|
|
603
|
+
return bs % 2 === 0 ? match.slice(0, bs) + '\\`' : match
|
|
604
|
+
})
|
|
605
|
+
.replace(/\\*\$\{/g, (match) => {
|
|
606
|
+
const bs = match.length - 2
|
|
607
|
+
return bs % 2 === 0 ? match.slice(0, bs) + '\\${' : match
|
|
608
|
+
})
|
|
609
|
+
|
|
242
610
|
const attributeDefinition = t.jsxAttribute(
|
|
243
611
|
t.jsxIdentifier(attrName),
|
|
244
|
-
t.jsxExpressionContainer(
|
|
245
|
-
types.templateLiteral([types.templateElement({ raw: attrValue.content })], [])
|
|
246
|
-
)
|
|
612
|
+
t.jsxExpressionContainer(types.templateLiteral([types.templateElement({ raw: content })], []))
|
|
247
613
|
)
|
|
248
614
|
jsxNode.openingElement.attributes.push(attributeDefinition)
|
|
249
615
|
}
|
|
250
616
|
|
|
617
|
+
// A JSX attribute string is raw text: nothing in it is unescaped, yet Babel
|
|
618
|
+
// prints a backslash or a line break in it escaped, so `pattern="\d"` would reach
|
|
619
|
+
// the page as `\\d`. Such a value goes in an expression container instead, where
|
|
620
|
+
// the escapes are JavaScript's and are read back.
|
|
621
|
+
const RAW_JSX_ATTRIBUTE_UNSAFE = /[\\\n\r\u2028\u2029]/
|
|
622
|
+
|
|
251
623
|
/**
|
|
252
624
|
* node must be a AST node element of type JSXElement (babel-types) or
|
|
253
625
|
* equivalent
|
|
254
626
|
*/
|
|
255
627
|
const getProperAttributeValueAssignment = (value: string | unknown, t = types) => {
|
|
256
|
-
if (
|
|
257
|
-
return
|
|
628
|
+
if (typeof value === 'string') {
|
|
629
|
+
return RAW_JSX_ATTRIBUTE_UNSAFE.test(value)
|
|
630
|
+
? t.jsxExpressionContainer(t.stringLiteral(value))
|
|
631
|
+
: t.stringLiteral(StringUtils.encode(value))
|
|
258
632
|
}
|
|
259
633
|
|
|
260
|
-
if (
|
|
261
|
-
return
|
|
634
|
+
if (!value && value !== 0 && value !== false) {
|
|
635
|
+
return null
|
|
262
636
|
}
|
|
263
637
|
|
|
264
638
|
return t.jsxExpressionContainer(convertValueToLiteral(value))
|
|
@@ -300,7 +674,18 @@ export const objectToObjectExpression = (
|
|
|
300
674
|
const value = objectMap[key]
|
|
301
675
|
let computedLiteralValue = null
|
|
302
676
|
|
|
303
|
-
if (value
|
|
677
|
+
if (value === undefined) {
|
|
678
|
+
return acc
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// Handle null values explicitly - they are valid in array mappers with different schemas
|
|
682
|
+
if (value === null) {
|
|
683
|
+
computedLiteralValue = t.nullLiteral()
|
|
684
|
+
}
|
|
685
|
+
// This is for function props that have successfully been parsed.
|
|
686
|
+
else if (typeof value === 'object' && 'functionExpressionParseResult' in value) {
|
|
687
|
+
computedLiteralValue = value.functionExpressionParseResult
|
|
688
|
+
} else if (value instanceof ParsedASTNode || value.constructor.name === 'ParsedASTNode') {
|
|
304
689
|
computedLiteralValue = (value as ParsedASTNode).ast
|
|
305
690
|
} else if (typeof value === 'boolean') {
|
|
306
691
|
computedLiteralValue = t.booleanLiteral(value)
|
|
@@ -347,6 +732,98 @@ type ExpressionLiteral =
|
|
|
347
732
|
| types.ObjectExpression
|
|
348
733
|
| types.NullLiteral
|
|
349
734
|
|
|
735
|
+
/**
|
|
736
|
+
* A value stored as text, read as the type it is declared with: a number prop
|
|
737
|
+
* or a condition comparing one meets "2" as the number 2, and a boolean one
|
|
738
|
+
* meets "true"/"false" as true/false, the way the editor's canvas compares
|
|
739
|
+
* them. A prop default and a condition's operand both arrive as text from
|
|
740
|
+
* writers that keep every input's value as typed.
|
|
741
|
+
*/
|
|
742
|
+
export const coerceToDeclaredType = <T>(value: T, declaredType?: string): T | number | boolean => {
|
|
743
|
+
if (typeof value !== 'string') {
|
|
744
|
+
return value
|
|
745
|
+
}
|
|
746
|
+
if (declaredType === 'number' && value.trim() !== '' && !isNaN(Number(value))) {
|
|
747
|
+
return Number(value)
|
|
748
|
+
}
|
|
749
|
+
if (declaredType === 'boolean' && (value === 'true' || value === 'false')) {
|
|
750
|
+
return value === 'true'
|
|
751
|
+
}
|
|
752
|
+
return value
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const COLLECTION_OPERATIONS = [
|
|
756
|
+
'isEmpty',
|
|
757
|
+
'isNotEmpty',
|
|
758
|
+
'lengthEquals',
|
|
759
|
+
'lengthGreaterThan',
|
|
760
|
+
'lengthLessThan',
|
|
761
|
+
'contains',
|
|
762
|
+
'notContains',
|
|
763
|
+
'hasKey',
|
|
764
|
+
'notHasKey',
|
|
765
|
+
]
|
|
766
|
+
|
|
767
|
+
/** The operations that read a value as a collection rather than compare it. */
|
|
768
|
+
export const isCollectionOperation = (operation?: string): boolean =>
|
|
769
|
+
COLLECTION_OPERATIONS.includes(operation)
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* A collection operation answered on a value known at build time, with the
|
|
773
|
+
* meaning `createBinaryExpression` (node-to-jsx) gives it at runtime: the
|
|
774
|
+
* length of `value || []` (its key count, `value || {}`, for an object),
|
|
775
|
+
* `.includes(operand)`, `.some((item) => item[field] === operand)`,
|
|
776
|
+
* `hasOwnProperty`.
|
|
777
|
+
*/
|
|
778
|
+
export const passesCollectionTest = (
|
|
779
|
+
operation: string,
|
|
780
|
+
value: unknown,
|
|
781
|
+
operand: unknown,
|
|
782
|
+
options: { containsField?: string; valueType?: string } = {}
|
|
783
|
+
): boolean => {
|
|
784
|
+
const { containsField, valueType } = options
|
|
785
|
+
const collection = (value || (valueType === 'object' ? {} : [])) as {
|
|
786
|
+
length?: number
|
|
787
|
+
includes?: (item: unknown) => boolean
|
|
788
|
+
some?: (test: (item: unknown) => boolean) => boolean
|
|
789
|
+
}
|
|
790
|
+
const length = valueType === 'object' ? Object.keys(collection).length : collection.length
|
|
791
|
+
const contains = (): boolean => {
|
|
792
|
+
if (containsField) {
|
|
793
|
+
return (
|
|
794
|
+
typeof collection.some === 'function' &&
|
|
795
|
+
collection.some(
|
|
796
|
+
(item) => (item as Record<string, unknown> | null)?.[containsField] === operand
|
|
797
|
+
)
|
|
798
|
+
)
|
|
799
|
+
}
|
|
800
|
+
return typeof collection.includes === 'function' && collection.includes(operand)
|
|
801
|
+
}
|
|
802
|
+
const hasKey = (): boolean =>
|
|
803
|
+
Object.prototype.hasOwnProperty.call(value || {}, operand as PropertyKey)
|
|
804
|
+
|
|
805
|
+
switch (operation) {
|
|
806
|
+
case 'isEmpty':
|
|
807
|
+
return length === 0
|
|
808
|
+
case 'isNotEmpty':
|
|
809
|
+
return length > 0
|
|
810
|
+
case 'lengthEquals':
|
|
811
|
+
return length === operand
|
|
812
|
+
case 'lengthGreaterThan':
|
|
813
|
+
return length > (operand as number)
|
|
814
|
+
case 'lengthLessThan':
|
|
815
|
+
return length < (operand as number)
|
|
816
|
+
case 'contains':
|
|
817
|
+
return contains()
|
|
818
|
+
case 'notContains':
|
|
819
|
+
return !contains()
|
|
820
|
+
case 'hasKey':
|
|
821
|
+
return hasKey()
|
|
822
|
+
default:
|
|
823
|
+
return !hasKey()
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
350
827
|
export const convertValueToLiteral = (
|
|
351
828
|
// tslint:disable-next-line no-any
|
|
352
829
|
value: any,
|
|
@@ -361,7 +838,24 @@ export const convertValueToLiteral = (
|
|
|
361
838
|
return t.arrayExpression(value.map((val) => convertValueToLiteral(val)))
|
|
362
839
|
}
|
|
363
840
|
|
|
364
|
-
|
|
841
|
+
if (explicitType === 'array' && typeof value === 'object' && value !== null) {
|
|
842
|
+
const arr = Object.keys(value)
|
|
843
|
+
.sort((a, b) => Number(a) - Number(b))
|
|
844
|
+
.map((key) => convertValueToLiteral(value[key]))
|
|
845
|
+
return t.arrayExpression(arr)
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
if ((explicitType === 'array' || explicitType === 'object') && typeof value === 'string') {
|
|
849
|
+
try {
|
|
850
|
+
const parsed = JSON.parse(value)
|
|
851
|
+
return convertValueToLiteral(parsed, explicitType, t)
|
|
852
|
+
} catch {
|
|
853
|
+
// If parsing fails, fall through to treat as a regular string
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
const actualType = typeof value
|
|
858
|
+
const typeToCompare = explicitType && explicitType === actualType ? explicitType : actualType
|
|
365
859
|
switch (typeToCompare) {
|
|
366
860
|
case 'string':
|
|
367
861
|
return t.stringLiteral(value)
|
|
@@ -396,7 +890,7 @@ export const getTSAnnotationForType = (type: any, t = types) => {
|
|
|
396
890
|
case 'boolean':
|
|
397
891
|
return t.tsBooleanKeyword()
|
|
398
892
|
default:
|
|
399
|
-
return t.
|
|
893
|
+
return t.tsAnyKeyword()
|
|
400
894
|
}
|
|
401
895
|
}
|
|
402
896
|
|
|
@@ -419,6 +913,7 @@ export const createClassComponent = (
|
|
|
419
913
|
propDefinitions: Record<string, UIDLPropDefinition>,
|
|
420
914
|
stateDefinitions: Record<string, UIDLStateDefinition>,
|
|
421
915
|
jsxTagTree: types.JSXElement,
|
|
916
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
422
917
|
t = types
|
|
423
918
|
) => {
|
|
424
919
|
// TODO: Add event handlers as separate functions later
|
|
@@ -432,6 +927,20 @@ export const createClassComponent = (
|
|
|
432
927
|
if (Object.keys(stateDefinitions).length > 0) {
|
|
433
928
|
const stateDeclarationsAST = Object.keys(stateDefinitions).map((stateKey) => {
|
|
434
929
|
const stateDefinition = stateDefinitions[stateKey]
|
|
930
|
+
if (
|
|
931
|
+
stateDefinition.type === 'object' &&
|
|
932
|
+
dynamicReferencePrefixMap &&
|
|
933
|
+
isObjectStateWithEntries(stateDefinition)
|
|
934
|
+
) {
|
|
935
|
+
return t.objectProperty(
|
|
936
|
+
t.identifier(stateKey),
|
|
937
|
+
convertObjectStateDefaultToExpression(
|
|
938
|
+
stateDefinition.defaultValue as Record<string, unknown>,
|
|
939
|
+
dynamicReferencePrefixMap,
|
|
940
|
+
t
|
|
941
|
+
)
|
|
942
|
+
)
|
|
943
|
+
}
|
|
435
944
|
return t.objectProperty(
|
|
436
945
|
t.identifier(stateKey),
|
|
437
946
|
convertValueToLiteral(stateDefinition.defaultValue)
|
|
@@ -469,12 +978,14 @@ export const createPureComponent = (
|
|
|
469
978
|
stateDefinitions: Record<string, UIDLStateDefinition>,
|
|
470
979
|
jsxTagTree: types.JSXElement,
|
|
471
980
|
windowImports: Record<string, types.ExpressionStatement> = {},
|
|
981
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
472
982
|
t = types
|
|
473
983
|
): types.VariableDeclaration => {
|
|
474
984
|
const arrowFunctionBody = createReturnExpressionSyntax(
|
|
475
985
|
stateDefinitions,
|
|
476
986
|
jsxTagTree,
|
|
477
|
-
windowImports
|
|
987
|
+
windowImports,
|
|
988
|
+
dynamicReferencePrefixMap
|
|
478
989
|
)
|
|
479
990
|
const arrowFunction = t.arrowFunctionExpression([t.identifier('props')], arrowFunctionBody)
|
|
480
991
|
|
|
@@ -488,15 +999,16 @@ export const createReturnExpressionSyntax = (
|
|
|
488
999
|
stateDefinitions: Record<string, UIDLStateDefinition>,
|
|
489
1000
|
jsxTagTree: types.JSXElement,
|
|
490
1001
|
windowImports: Record<string, types.ExpressionStatement> = {},
|
|
1002
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
491
1003
|
t = types
|
|
492
1004
|
) => {
|
|
493
1005
|
const returnStatement = t.returnStatement(jsxTagTree)
|
|
494
1006
|
|
|
495
1007
|
const stateHooks = Object.keys(stateDefinitions).map((stateKey) =>
|
|
496
|
-
createStateHookAST(stateKey, stateDefinitions[stateKey])
|
|
1008
|
+
createStateHookAST(stateKey, stateDefinitions[stateKey], dynamicReferencePrefixMap)
|
|
497
1009
|
)
|
|
498
1010
|
|
|
499
|
-
return t.blockStatement([...stateHooks, ...Object.values(windowImports), returnStatement]
|
|
1011
|
+
return t.blockStatement([...stateHooks, ...Object.values(windowImports), returnStatement])
|
|
500
1012
|
}
|
|
501
1013
|
|
|
502
1014
|
/**
|
|
@@ -505,33 +1017,337 @@ export const createReturnExpressionSyntax = (
|
|
|
505
1017
|
export const createStateHookAST = (
|
|
506
1018
|
stateKey: string,
|
|
507
1019
|
stateDefinition: UIDLStateDefinition,
|
|
1020
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
508
1021
|
t = types
|
|
509
1022
|
) => {
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
1023
|
+
let defaultValueArgument: types.Expression
|
|
1024
|
+
|
|
1025
|
+
if (
|
|
1026
|
+
stateDefinition.type === 'object' &&
|
|
1027
|
+
dynamicReferencePrefixMap &&
|
|
1028
|
+
isObjectStateWithEntries(stateDefinition)
|
|
1029
|
+
) {
|
|
1030
|
+
defaultValueArgument = convertObjectStateDefaultToExpression(
|
|
1031
|
+
stateDefinition.defaultValue as Record<string, unknown>,
|
|
1032
|
+
dynamicReferencePrefixMap,
|
|
1033
|
+
t
|
|
1034
|
+
)
|
|
1035
|
+
} else {
|
|
1036
|
+
defaultValueArgument = convertValueToLiteral(stateDefinition.defaultValue, stateDefinition.type)
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// When the state has a dataSourceBinding, the initial value comes from props
|
|
1040
|
+
// Generated: useState(props.stateKey !== undefined ? props.stateKey : defaultValue)
|
|
1041
|
+
let useStateArgument: types.Expression = defaultValueArgument
|
|
1042
|
+
if (stateDefinition.dataSourceBinding) {
|
|
1043
|
+
const propAccess = t.memberExpression(t.identifier('props'), t.identifier(stateKey))
|
|
1044
|
+
useStateArgument = t.conditionalExpression(
|
|
1045
|
+
t.binaryExpression('!==', propAccess, t.identifier('undefined')),
|
|
1046
|
+
propAccess,
|
|
1047
|
+
defaultValueArgument
|
|
1048
|
+
)
|
|
1049
|
+
} else if (
|
|
1050
|
+
stateDefinition.urlSearchParamBinding &&
|
|
1051
|
+
typeof stateDefinition.urlSearchParamBinding.key === 'string' &&
|
|
1052
|
+
stateDefinition.urlSearchParamBinding.key !== '' &&
|
|
1053
|
+
// `hydrateAfterMount`: the state keeps its static default on the client's
|
|
1054
|
+
// first render too, and the router read-back effect adopts the URL value
|
|
1055
|
+
// once `router.isReady` — a real update, so the elements it gates
|
|
1056
|
+
// re-render. Needed where the server markup and a URL-seeded client value
|
|
1057
|
+
// would differ only in ATTRIBUTES of same-tag siblings (a pressed toggle):
|
|
1058
|
+
// React 17 does not patch those on hydration. See the type's docs.
|
|
1059
|
+
stateDefinition.urlSearchParamBinding.hydrateAfterMount !== true
|
|
1060
|
+
) {
|
|
1061
|
+
// URL-search-param binding: seed the initial state directly from
|
|
1062
|
+
// `window.location.search`. We deliberately DO NOT use Next.js'
|
|
1063
|
+
// `router.query` here because on statically-generated pages (getStaticProps
|
|
1064
|
+
// / getStaticPaths) `router.query` is empty on the first render and only
|
|
1065
|
+
// hydrates after `router.isReady` flips to true — by which point React's
|
|
1066
|
+
// `useState` initializer has already captured the fallback default. That
|
|
1067
|
+
// regression shipped as "detail panel does not auto-open on deep links to
|
|
1068
|
+
// /admin/products?products_detail_panel_item_id=<id>". `window.location`
|
|
1069
|
+
// is populated synchronously on both direct loads and client-side
|
|
1070
|
+
// navigations, and the `typeof window` guard keeps SSR falling back to
|
|
1071
|
+
// the declared static default cleanly.
|
|
1072
|
+
//
|
|
1073
|
+
// Emitted shape:
|
|
1074
|
+
// useState(
|
|
1075
|
+
// (typeof window !== "undefined"
|
|
1076
|
+
// ? new URLSearchParams(window.location.search).get("<key>")
|
|
1077
|
+
// : null) ?? <defaultValueLiteral>
|
|
1078
|
+
// )
|
|
1079
|
+
const paramKey = stateDefinition.urlSearchParamBinding.key
|
|
1080
|
+
const urlSearchParamsExpr = t.newExpression(t.identifier('URLSearchParams'), [
|
|
1081
|
+
t.memberExpression(
|
|
1082
|
+
t.memberExpression(t.identifier('window'), t.identifier('location')),
|
|
1083
|
+
t.identifier('search')
|
|
1084
|
+
),
|
|
1085
|
+
])
|
|
1086
|
+
const readParamExpr = t.callExpression(
|
|
1087
|
+
t.memberExpression(urlSearchParamsExpr, t.identifier('get')),
|
|
1088
|
+
[t.stringLiteral(paramKey)]
|
|
1089
|
+
)
|
|
1090
|
+
const browserGuard = t.binaryExpression(
|
|
1091
|
+
'!==',
|
|
1092
|
+
t.unaryExpression('typeof', t.identifier('window')),
|
|
1093
|
+
t.stringLiteral('undefined')
|
|
1094
|
+
)
|
|
1095
|
+
useStateArgument = t.logicalExpression(
|
|
1096
|
+
'??',
|
|
1097
|
+
t.conditionalExpression(browserGuard, readParamExpr, t.nullLiteral()),
|
|
1098
|
+
defaultValueArgument
|
|
1099
|
+
)
|
|
1100
|
+
}
|
|
514
1101
|
|
|
515
1102
|
return t.variableDeclaration('const', [
|
|
516
1103
|
t.variableDeclarator(
|
|
517
1104
|
t.arrayPattern([
|
|
518
|
-
|
|
1105
|
+
// The state NAME comes from the UIDL and may be a reserved word (a
|
|
1106
|
+
// character sheet has a column called `class`), which is fatal in
|
|
1107
|
+
// binding position. Reads go through the same sanitiser, so the
|
|
1108
|
+
// declaration and every reference stay in sync.
|
|
1109
|
+
t.identifier(JSIdentifiers.createSafeJSIdentifier(stateKey)),
|
|
519
1110
|
t.identifier(StringUtils.createStateStoringFunction(stateKey)),
|
|
520
1111
|
]),
|
|
521
|
-
t.callExpression(t.identifier('useState'), [
|
|
1112
|
+
t.callExpression(t.identifier('useState'), [useStateArgument])
|
|
522
1113
|
),
|
|
523
1114
|
])
|
|
524
1115
|
}
|
|
525
1116
|
|
|
1117
|
+
export const isObjectStateWithEntries = (stateDefinition: UIDLStateDefinition): boolean => {
|
|
1118
|
+
if (stateDefinition.type !== 'object') {
|
|
1119
|
+
return false
|
|
1120
|
+
}
|
|
1121
|
+
const defaultValue = stateDefinition.defaultValue
|
|
1122
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
1123
|
+
return false
|
|
1124
|
+
}
|
|
1125
|
+
return Object.values(defaultValue).some((entry) => {
|
|
1126
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1127
|
+
return false
|
|
1128
|
+
}
|
|
1129
|
+
const typed = entry as Record<string, unknown>
|
|
1130
|
+
return (typed.type === 'static' || typed.type === 'dynamic') && 'content' in typed
|
|
1131
|
+
})
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
export const convertObjectStateDefaultToExpression = (
|
|
1135
|
+
defaultValue: Record<string, unknown>,
|
|
1136
|
+
prefixMap: { prop: string; state: string; local: string },
|
|
1137
|
+
t = types
|
|
1138
|
+
): types.ObjectExpression => {
|
|
1139
|
+
const properties = Object.keys(defaultValue).map((key) => {
|
|
1140
|
+
const valueExpression = resolveObjectStateEntry(defaultValue[key], prefixMap, t)
|
|
1141
|
+
return t.objectProperty(t.stringLiteral(key), valueExpression)
|
|
1142
|
+
})
|
|
1143
|
+
|
|
1144
|
+
return t.objectExpression(properties)
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
const resolveObjectStateEntry = (
|
|
1148
|
+
entry: unknown,
|
|
1149
|
+
prefixMap: { prop: string; state: string; local: string },
|
|
1150
|
+
t = types
|
|
1151
|
+
): types.Expression => {
|
|
1152
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1153
|
+
return convertValueToLiteral(entry) as types.Expression
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
const typed = entry as { type?: string; content?: unknown }
|
|
1157
|
+
|
|
1158
|
+
if (typed.type === 'static') {
|
|
1159
|
+
return convertValueToLiteral(typed.content) as types.Expression
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
if (typed.type === 'dynamic') {
|
|
1163
|
+
const content = typed.content as {
|
|
1164
|
+
referenceType: string
|
|
1165
|
+
id: string
|
|
1166
|
+
refPath?: string[]
|
|
1167
|
+
}
|
|
1168
|
+
const { referenceType, id, refPath } = content
|
|
1169
|
+
|
|
1170
|
+
if (referenceType === 'globalState') {
|
|
1171
|
+
const gsRefPath = refPath || []
|
|
1172
|
+
let expr: types.Identifier | types.OptionalMemberExpression = t.identifier(id)
|
|
1173
|
+
for (const segment of gsRefPath) {
|
|
1174
|
+
expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true)
|
|
1175
|
+
}
|
|
1176
|
+
return expr
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
if (referenceType === 'global') {
|
|
1180
|
+
// Normalize Shape B ({ refPath: ['Current User', 'id'] }) to Shape A
|
|
1181
|
+
// ({ id: 'currentUser', refPath: ['id'] }) so downstream access is uniform.
|
|
1182
|
+
const resolvedId = resolveGlobalRefId(content)
|
|
1183
|
+
if (resolvedId) {
|
|
1184
|
+
const tail = !id && refPath && refPath.length > 0 ? refPath.slice(1) : refPath || []
|
|
1185
|
+
let expr: types.Identifier | types.OptionalMemberExpression = t.identifier(resolvedId)
|
|
1186
|
+
for (const segment of tail) {
|
|
1187
|
+
expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true)
|
|
1188
|
+
}
|
|
1189
|
+
return expr
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
const idWithPath = UIDLUtils.generateIdWithRefPath(id, refPath)
|
|
1194
|
+
const prefix = prefixMap[referenceType as 'prop' | 'state' | 'local'] || ''
|
|
1195
|
+
|
|
1196
|
+
return prefix === ''
|
|
1197
|
+
? t.identifier(idWithPath)
|
|
1198
|
+
: t.memberExpression(t.identifier(prefix), t.identifier(idWithPath))
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
return convertValueToLiteral(entry) as types.Expression
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// Mapping from the UIDL display name used in a global reference refPath
|
|
1205
|
+
// to the runtime variable name that holds the value. Kept here so both the
|
|
1206
|
+
// JSX emitter and the object-state global-reference collectors stay in sync.
|
|
1207
|
+
export const GLOBAL_REF_ID_MAP: Record<string, string> = {
|
|
1208
|
+
'E-commerce': 'ecommerce',
|
|
1209
|
+
Cart: 'cart',
|
|
1210
|
+
'Current User': 'currentUser',
|
|
1211
|
+
Company: 'company',
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
export const resolveGlobalRefId = (
|
|
1215
|
+
content: { id?: string; refPath?: string[] } | undefined
|
|
1216
|
+
): string | undefined => {
|
|
1217
|
+
if (!content) {
|
|
1218
|
+
return undefined
|
|
1219
|
+
}
|
|
1220
|
+
if (content.id) {
|
|
1221
|
+
return content.id
|
|
1222
|
+
}
|
|
1223
|
+
if (!content.refPath || content.refPath.length === 0) {
|
|
1224
|
+
return undefined
|
|
1225
|
+
}
|
|
1226
|
+
return GLOBAL_REF_ID_MAP[content.refPath[0]]
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
export const collectGlobalReferencesFromObjectStates = (
|
|
1230
|
+
stateDefinitions: Record<string, UIDLStateDefinition>
|
|
1231
|
+
): string[] => {
|
|
1232
|
+
const globalRefs: string[] = []
|
|
1233
|
+
|
|
1234
|
+
Object.values(stateDefinitions).forEach((stateDef) => {
|
|
1235
|
+
if (stateDef.type !== 'object') {
|
|
1236
|
+
return
|
|
1237
|
+
}
|
|
1238
|
+
const defaultValue = stateDef.defaultValue
|
|
1239
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
1240
|
+
return
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
Object.values(defaultValue as Record<string, unknown>).forEach((entry) => {
|
|
1244
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1245
|
+
return
|
|
1246
|
+
}
|
|
1247
|
+
const typed = entry as { type?: string; content?: unknown }
|
|
1248
|
+
if (typed.type === 'dynamic') {
|
|
1249
|
+
const content = typed.content as {
|
|
1250
|
+
referenceType?: string
|
|
1251
|
+
id?: string
|
|
1252
|
+
refPath?: string[]
|
|
1253
|
+
}
|
|
1254
|
+
if (content.referenceType === 'global') {
|
|
1255
|
+
const resolvedId = resolveGlobalRefId(content)
|
|
1256
|
+
if (resolvedId) {
|
|
1257
|
+
globalRefs.push(resolvedId)
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
})
|
|
1262
|
+
})
|
|
1263
|
+
|
|
1264
|
+
return globalRefs
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
export const collectGlobalStateReferencesFromObjectStates = (
|
|
1268
|
+
stateDefinitions: Record<string, UIDLStateDefinition>
|
|
1269
|
+
): Array<{ id: string }> => {
|
|
1270
|
+
const refs: Array<{ id: string }> = []
|
|
1271
|
+
|
|
1272
|
+
Object.values(stateDefinitions).forEach((stateDef) => {
|
|
1273
|
+
if (stateDef.type !== 'object') {
|
|
1274
|
+
return
|
|
1275
|
+
}
|
|
1276
|
+
const defaultValue = stateDef.defaultValue
|
|
1277
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
1278
|
+
return
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
Object.values(defaultValue as Record<string, unknown>).forEach((entry) => {
|
|
1282
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1283
|
+
return
|
|
1284
|
+
}
|
|
1285
|
+
const typed = entry as { type?: string; content?: unknown }
|
|
1286
|
+
if (typed.type === 'dynamic') {
|
|
1287
|
+
const content = typed.content as { referenceType?: string; id?: string }
|
|
1288
|
+
if (content.referenceType === 'globalState' && content.id) {
|
|
1289
|
+
refs.push({ id: content.id })
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
})
|
|
1293
|
+
})
|
|
1294
|
+
|
|
1295
|
+
return refs
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
/**
|
|
1299
|
+
* The mount-time side-effect import for a package that cannot be imported at
|
|
1300
|
+
* module scope because it touches `window` while it evaluates —
|
|
1301
|
+
* self-registering web components such as `<lottie-player>` and
|
|
1302
|
+
* `<model-viewer>`. Running it from an effect keeps it off the server render.
|
|
1303
|
+
*
|
|
1304
|
+
* useEffect(() => {
|
|
1305
|
+
* import('@google/model-viewer').catch((error) => {
|
|
1306
|
+
* console.warn('[teleport] Failed to load "@google/model-viewer"', error)
|
|
1307
|
+
* })
|
|
1308
|
+
* }, [])
|
|
1309
|
+
*
|
|
1310
|
+
* Two details of that shape are load-bearing:
|
|
1311
|
+
*
|
|
1312
|
+
* - The callback body is a BLOCK. A concise arrow body (`() => import(…)`)
|
|
1313
|
+
* also RETURNS the import's Promise, and React stores an effect's return
|
|
1314
|
+
* value as its cleanup function and calls it on unmount — so every mounted
|
|
1315
|
+
* copy of the component turned navigating away into
|
|
1316
|
+
* `TypeError: destroy is not a function`, thrown from React's commit phase
|
|
1317
|
+
* with no frame naming the component. Nothing is returned here.
|
|
1318
|
+
* - The rejection is handled. A chunk that fails to load (offline, a stale
|
|
1319
|
+
* deploy, a blocked CDN) would otherwise surface as an unhandled promise
|
|
1320
|
+
* rejection; the element simply stays unupgraded, which is a degraded page
|
|
1321
|
+
* rather than a broken one, and the warning is what makes that visible.
|
|
1322
|
+
*/
|
|
526
1323
|
export const generateDynamicWindowImport = (
|
|
527
1324
|
hookName = 'useEffect',
|
|
528
1325
|
dependency: string
|
|
529
1326
|
): types.ExpressionStatement => {
|
|
1327
|
+
const failureIdentifier = types.identifier('error')
|
|
1328
|
+
const importCall = types.callExpression(types.import(), [types.stringLiteral(dependency)])
|
|
1329
|
+
const guardedImport = types.callExpression(
|
|
1330
|
+
types.memberExpression(importCall, types.identifier('catch')),
|
|
1331
|
+
[
|
|
1332
|
+
types.arrowFunctionExpression(
|
|
1333
|
+
[failureIdentifier],
|
|
1334
|
+
types.blockStatement([
|
|
1335
|
+
types.expressionStatement(
|
|
1336
|
+
types.callExpression(
|
|
1337
|
+
types.memberExpression(types.identifier('console'), types.identifier('warn')),
|
|
1338
|
+
[types.stringLiteral(`[teleport] Failed to load "${dependency}"`), failureIdentifier]
|
|
1339
|
+
)
|
|
1340
|
+
),
|
|
1341
|
+
])
|
|
1342
|
+
),
|
|
1343
|
+
]
|
|
1344
|
+
)
|
|
1345
|
+
|
|
530
1346
|
return types.expressionStatement(
|
|
531
1347
|
types.callExpression(types.identifier(hookName), [
|
|
532
1348
|
types.arrowFunctionExpression(
|
|
533
1349
|
[],
|
|
534
|
-
types.
|
|
1350
|
+
types.blockStatement([types.expressionStatement(guardedImport)])
|
|
535
1351
|
),
|
|
536
1352
|
types.arrayExpression([]),
|
|
537
1353
|
])
|
|
@@ -543,9 +1359,7 @@ export const wrapObjectPropertiesWithExpression = (properties: types.ObjectPrope
|
|
|
543
1359
|
|
|
544
1360
|
export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
545
1361
|
const fetchUrl = computeFetchUrl(resource)
|
|
546
|
-
const authHeaderAST = computeAuthorizationHeaderAST(resource?.headers)
|
|
547
1362
|
const headersASTs = resource?.headers ? generateRESTHeadersAST(resource.headers) : []
|
|
548
|
-
|
|
549
1363
|
const queryParams = generateURLParamsAST(resource?.params)
|
|
550
1364
|
const fetchUrlQuasis = fetchUrl.quasis
|
|
551
1365
|
const queryParamsQuasis = queryParams?.quasis || [types.templateElement({ raw: '', cooked: '' })]
|
|
@@ -560,60 +1374,8 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
|
560
1374
|
queryParamsQuasis.pop()
|
|
561
1375
|
}
|
|
562
1376
|
|
|
563
|
-
const
|
|
564
|
-
|
|
565
|
-
).reduce((acc: Array<types.ObjectProperty | types.SpreadElement>, item) => {
|
|
566
|
-
const prop = resource.params[item]
|
|
567
|
-
if (prop.type === 'static') {
|
|
568
|
-
acc.push(types.objectProperty(types.stringLiteral(item), ASTUtils.resolveObjectValue(prop)))
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
if (prop.type === 'expr') {
|
|
572
|
-
acc.push(
|
|
573
|
-
types.objectProperty(
|
|
574
|
-
types.stringLiteral(item),
|
|
575
|
-
ASTUtils.getExpressionFromUIDLExpressionNode(prop)
|
|
576
|
-
)
|
|
577
|
-
)
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
if (prop.type === 'dynamic') {
|
|
581
|
-
acc.push(
|
|
582
|
-
types.spreadElement(
|
|
583
|
-
types.logicalExpression(
|
|
584
|
-
'&&',
|
|
585
|
-
types.memberExpression(
|
|
586
|
-
types.identifier('params'),
|
|
587
|
-
types.stringLiteral(prop.content.id),
|
|
588
|
-
true,
|
|
589
|
-
false
|
|
590
|
-
),
|
|
591
|
-
types.objectExpression([
|
|
592
|
-
types.objectProperty(
|
|
593
|
-
types.stringLiteral(item),
|
|
594
|
-
types.memberExpression(
|
|
595
|
-
types.identifier('params'),
|
|
596
|
-
types.stringLiteral(prop.content.id),
|
|
597
|
-
true,
|
|
598
|
-
false
|
|
599
|
-
)
|
|
600
|
-
),
|
|
601
|
-
])
|
|
602
|
-
)
|
|
603
|
-
)
|
|
604
|
-
)
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
return acc
|
|
608
|
-
}, [])
|
|
609
|
-
|
|
610
|
-
const paramsAST = types.variableDeclaration('const', [
|
|
611
|
-
types.variableDeclarator(
|
|
612
|
-
types.identifier('urlParams'),
|
|
613
|
-
types.objectExpression(paramsDeclerations)
|
|
614
|
-
),
|
|
615
|
-
])
|
|
616
|
-
|
|
1377
|
+
const urlParamsDecleration = generateParamsAST(resource?.params)
|
|
1378
|
+
const bodyParamsDecleration = generateParamsAST(resource?.body)
|
|
617
1379
|
const url = queryParams?.quasis
|
|
618
1380
|
? types.templateLiteral(
|
|
619
1381
|
[...fetchUrlQuasis, ...queryParamsQuasis],
|
|
@@ -628,31 +1390,113 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
|
628
1390
|
|
|
629
1391
|
let allHeaders: types.ObjectProperty[] = []
|
|
630
1392
|
|
|
631
|
-
if (
|
|
632
|
-
allHeaders.push(
|
|
1393
|
+
if (resource?.headers?.authToken) {
|
|
1394
|
+
allHeaders.push(computeAuthorizationHeaderAST(resource?.headers))
|
|
633
1395
|
}
|
|
634
1396
|
|
|
635
1397
|
if (headersASTs.length) {
|
|
636
1398
|
allHeaders = allHeaders.concat(headersASTs)
|
|
637
1399
|
}
|
|
638
1400
|
|
|
639
|
-
const
|
|
640
|
-
types.identifier('headers'),
|
|
641
|
-
types.objectExpression(allHeaders)
|
|
642
|
-
)
|
|
643
|
-
|
|
644
|
-
const fetchAST = types.variableDeclaration('const', [
|
|
1401
|
+
const fetchAST = types.variableDeclaration('let', [
|
|
645
1402
|
types.variableDeclarator(
|
|
646
1403
|
types.identifier('data'),
|
|
647
1404
|
types.awaitExpression(
|
|
648
1405
|
types.callExpression(types.identifier('fetch'), [
|
|
649
1406
|
url,
|
|
650
|
-
types.objectExpression([
|
|
1407
|
+
types.objectExpression([
|
|
1408
|
+
method,
|
|
1409
|
+
...(allHeaders.length > 0
|
|
1410
|
+
? [
|
|
1411
|
+
types.objectProperty(
|
|
1412
|
+
types.identifier('headers'),
|
|
1413
|
+
types.objectExpression(allHeaders)
|
|
1414
|
+
),
|
|
1415
|
+
]
|
|
1416
|
+
: []),
|
|
1417
|
+
...(bodyParamsDecleration.length > 0 && resource?.method === 'POST'
|
|
1418
|
+
? [
|
|
1419
|
+
types.objectProperty(
|
|
1420
|
+
types.identifier('body'),
|
|
1421
|
+
types.callExpression(
|
|
1422
|
+
types.memberExpression(
|
|
1423
|
+
types.identifier('JSON'),
|
|
1424
|
+
types.identifier('stringify')
|
|
1425
|
+
),
|
|
1426
|
+
[types.identifier('bodyParams')]
|
|
1427
|
+
)
|
|
1428
|
+
),
|
|
1429
|
+
]
|
|
1430
|
+
: []),
|
|
1431
|
+
]),
|
|
651
1432
|
])
|
|
652
1433
|
)
|
|
653
1434
|
),
|
|
654
1435
|
])
|
|
655
1436
|
|
|
1437
|
+
// Fallback in case i18n interferes with normal CMS flows
|
|
1438
|
+
// Only generate fallback if locale parameter exists
|
|
1439
|
+
const hasLocaleParam = resource?.params?.locale !== undefined
|
|
1440
|
+
let fallbackAST = null
|
|
1441
|
+
|
|
1442
|
+
if (hasLocaleParam) {
|
|
1443
|
+
const fallbackParams = JSON.parse(JSON.stringify(resource))
|
|
1444
|
+
delete fallbackParams?.params?.locale
|
|
1445
|
+
const fallbackUrlParamsDeclaration = generateParamsAST(fallbackParams?.params)
|
|
1446
|
+
const assignmentOfNewUrlParams = types.expressionStatement(
|
|
1447
|
+
types.assignmentExpression(
|
|
1448
|
+
'=',
|
|
1449
|
+
types.identifier('urlParams'),
|
|
1450
|
+
types.objectExpression([...fallbackUrlParamsDeclaration])
|
|
1451
|
+
)
|
|
1452
|
+
)
|
|
1453
|
+
|
|
1454
|
+
const assignmentExpressionAST = types.expressionStatement(
|
|
1455
|
+
types.assignmentExpression(
|
|
1456
|
+
'=',
|
|
1457
|
+
types.identifier('data'),
|
|
1458
|
+
types.awaitExpression(
|
|
1459
|
+
types.callExpression(types.identifier('fetch'), [
|
|
1460
|
+
url,
|
|
1461
|
+
types.objectExpression([
|
|
1462
|
+
method,
|
|
1463
|
+
...(allHeaders.length > 0
|
|
1464
|
+
? [
|
|
1465
|
+
types.objectProperty(
|
|
1466
|
+
types.identifier('headers'),
|
|
1467
|
+
types.objectExpression(allHeaders)
|
|
1468
|
+
),
|
|
1469
|
+
]
|
|
1470
|
+
: []),
|
|
1471
|
+
...(bodyParamsDecleration.length > 0 && resource?.method === 'POST'
|
|
1472
|
+
? [
|
|
1473
|
+
types.objectProperty(
|
|
1474
|
+
types.identifier('body'),
|
|
1475
|
+
types.callExpression(
|
|
1476
|
+
types.memberExpression(
|
|
1477
|
+
types.identifier('JSON'),
|
|
1478
|
+
types.identifier('stringify')
|
|
1479
|
+
),
|
|
1480
|
+
[types.identifier('bodyParams')]
|
|
1481
|
+
)
|
|
1482
|
+
),
|
|
1483
|
+
]
|
|
1484
|
+
: []),
|
|
1485
|
+
]),
|
|
1486
|
+
])
|
|
1487
|
+
)
|
|
1488
|
+
)
|
|
1489
|
+
)
|
|
1490
|
+
|
|
1491
|
+
fallbackAST = types.ifStatement(
|
|
1492
|
+
types.binaryExpression(
|
|
1493
|
+
'!==',
|
|
1494
|
+
types.memberExpression(types.identifier('data'), types.identifier('status')),
|
|
1495
|
+
types.numericLiteral(200)
|
|
1496
|
+
),
|
|
1497
|
+
types.blockStatement([assignmentOfNewUrlParams, assignmentExpressionAST])
|
|
1498
|
+
)
|
|
1499
|
+
}
|
|
656
1500
|
const responseType = resource?.response?.type ?? 'json'
|
|
657
1501
|
let responseJSONAST
|
|
658
1502
|
|
|
@@ -719,20 +1563,98 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
|
719
1563
|
}
|
|
720
1564
|
}
|
|
721
1565
|
|
|
722
|
-
return [
|
|
1566
|
+
return [
|
|
1567
|
+
...(urlParamsDecleration.length > 0
|
|
1568
|
+
? [
|
|
1569
|
+
types.variableDeclaration('let', [
|
|
1570
|
+
types.variableDeclarator(
|
|
1571
|
+
types.identifier('urlParams'),
|
|
1572
|
+
types.objectExpression(urlParamsDecleration)
|
|
1573
|
+
),
|
|
1574
|
+
]),
|
|
1575
|
+
]
|
|
1576
|
+
: []),
|
|
1577
|
+
...(bodyParamsDecleration.length > 0
|
|
1578
|
+
? [
|
|
1579
|
+
types.variableDeclaration('const', [
|
|
1580
|
+
types.variableDeclarator(
|
|
1581
|
+
types.identifier('bodyParams'),
|
|
1582
|
+
types.objectExpression(bodyParamsDecleration)
|
|
1583
|
+
),
|
|
1584
|
+
]),
|
|
1585
|
+
]
|
|
1586
|
+
: []),
|
|
1587
|
+
fetchAST,
|
|
1588
|
+
...(fallbackAST ? [fallbackAST] : []),
|
|
1589
|
+
responseJSONAST,
|
|
1590
|
+
].filter(Boolean)
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
const generateParamsAST = (
|
|
1594
|
+
props: Record<string, UIDLStaticValue | UIDLPropValue | UIDLStateValue | UIDLExpressionValue>
|
|
1595
|
+
): Array<types.ObjectProperty | types.SpreadElement> => {
|
|
1596
|
+
return Object.keys(props || {}).reduce(
|
|
1597
|
+
(acc: Array<types.ObjectProperty | types.SpreadElement>, item) => {
|
|
1598
|
+
const prop = props[item]
|
|
1599
|
+
if (prop.type === 'static') {
|
|
1600
|
+
acc.push(types.objectProperty(types.stringLiteral(item), resolveObjectValue(prop)))
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
if (prop.type === 'expr') {
|
|
1604
|
+
acc.push(
|
|
1605
|
+
types.objectProperty(types.stringLiteral(item), getExpressionFromUIDLExpressionNode(prop))
|
|
1606
|
+
)
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
if (prop.type === 'dynamic') {
|
|
1610
|
+
acc.push(
|
|
1611
|
+
types.spreadElement(
|
|
1612
|
+
types.logicalExpression(
|
|
1613
|
+
'&&',
|
|
1614
|
+
types.memberExpression(
|
|
1615
|
+
types.identifier('params'),
|
|
1616
|
+
types.stringLiteral(prop.content.id),
|
|
1617
|
+
true,
|
|
1618
|
+
false
|
|
1619
|
+
),
|
|
1620
|
+
types.objectExpression([
|
|
1621
|
+
types.objectProperty(
|
|
1622
|
+
types.stringLiteral(item),
|
|
1623
|
+
types.memberExpression(
|
|
1624
|
+
types.identifier('params'),
|
|
1625
|
+
types.stringLiteral(prop.content.id),
|
|
1626
|
+
true,
|
|
1627
|
+
false
|
|
1628
|
+
)
|
|
1629
|
+
),
|
|
1630
|
+
])
|
|
1631
|
+
)
|
|
1632
|
+
)
|
|
1633
|
+
)
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
return acc
|
|
1637
|
+
},
|
|
1638
|
+
[]
|
|
1639
|
+
)
|
|
723
1640
|
}
|
|
724
1641
|
|
|
725
1642
|
const generateRESTHeadersAST = (headers: UIDLResourceItem['headers']): types.ObjectProperty[] => {
|
|
726
|
-
return
|
|
727
|
-
.
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
1643
|
+
return (
|
|
1644
|
+
Object.keys(headers)
|
|
1645
|
+
// `authToken` is rendered as the `Authorization` header; `authScheme` is a
|
|
1646
|
+
// generator-only directive for that header's prefix — neither is emitted as
|
|
1647
|
+
// its own literal HTTP header.
|
|
1648
|
+
.filter((header) => header !== 'authToken' && header !== 'authScheme')
|
|
1649
|
+
.map((header) => {
|
|
1650
|
+
const headerResolved = resolveResourceValue(headers[header])
|
|
1651
|
+
const value =
|
|
1652
|
+
headers[header].type === 'static'
|
|
1653
|
+
? types.stringLiteral(String(headerResolved))
|
|
1654
|
+
: types.identifier(String(headerResolved))
|
|
1655
|
+
return types.objectProperty(types.stringLiteral(header), value)
|
|
1656
|
+
})
|
|
1657
|
+
)
|
|
736
1658
|
}
|
|
737
1659
|
|
|
738
1660
|
export const generateMemberExpressionASTFromBase = (
|
|
@@ -754,6 +1676,22 @@ export const generateMemberExpressionASTFromBase = (
|
|
|
754
1676
|
)
|
|
755
1677
|
}
|
|
756
1678
|
|
|
1679
|
+
export const parseValuePath = (valuePath: Array<string | number>): Array<string | number> => {
|
|
1680
|
+
return valuePath.map((segment) => {
|
|
1681
|
+
if (typeof segment === 'string') {
|
|
1682
|
+
const bracketMatch = segment.match(/^\[(\d+)\]$/)
|
|
1683
|
+
if (bracketMatch) {
|
|
1684
|
+
return parseInt(bracketMatch[1], 10)
|
|
1685
|
+
}
|
|
1686
|
+
const numericMatch = segment.match(/^\d+$/)
|
|
1687
|
+
if (numericMatch) {
|
|
1688
|
+
return parseInt(segment, 10)
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
return segment
|
|
1692
|
+
})
|
|
1693
|
+
}
|
|
1694
|
+
|
|
757
1695
|
export const generateMemberExpressionASTFromPath = (
|
|
758
1696
|
path: Array<string | number>
|
|
759
1697
|
): types.OptionalMemberExpression | types.Identifier => {
|
|
@@ -769,7 +1707,7 @@ export const generateMemberExpressionASTFromPath = (
|
|
|
769
1707
|
return types.optionalMemberExpression(
|
|
770
1708
|
generateMemberExpressionASTFromPath(pathClone),
|
|
771
1709
|
types.numericLiteral(currentPath),
|
|
772
|
-
|
|
1710
|
+
true,
|
|
773
1711
|
true
|
|
774
1712
|
)
|
|
775
1713
|
}
|
|
@@ -855,14 +1793,28 @@ const computeAuthorizationHeaderAST = (headers: UIDLResourceItem['headers']) =>
|
|
|
855
1793
|
|
|
856
1794
|
const authTokenType = headers.authToken?.type
|
|
857
1795
|
|
|
1796
|
+
// The auth scheme prefix defaults to `Bearer ` (back-compatible with every CMS
|
|
1797
|
+
// and data-source that stores a bare bearer token). A resource may override it
|
|
1798
|
+
// via a `headers.authScheme` static value — e.g. WordPress Basic / Application
|
|
1799
|
+
// Password auth sets `Basic ` so the rendered header is `Basic <base64>`
|
|
1800
|
+
// instead of the wrong `Bearer <base64>`. `authScheme` is consumed here and
|
|
1801
|
+
// filtered out of the emitted REST headers (see generateRESTHeadersAST).
|
|
1802
|
+
const authSchemeValue = headers.authScheme
|
|
1803
|
+
const schemePrefix =
|
|
1804
|
+
authSchemeValue &&
|
|
1805
|
+
authSchemeValue.type === 'static' &&
|
|
1806
|
+
typeof authSchemeValue.content === 'string'
|
|
1807
|
+
? authSchemeValue.content
|
|
1808
|
+
: 'Bearer '
|
|
1809
|
+
|
|
858
1810
|
return types.objectProperty(
|
|
859
1811
|
types.identifier('Authorization'),
|
|
860
1812
|
types.templateLiteral(
|
|
861
1813
|
[
|
|
862
1814
|
types.templateElement(
|
|
863
1815
|
{
|
|
864
|
-
cooked: authTokenType === 'static' ?
|
|
865
|
-
raw: authTokenType === 'static' ?
|
|
1816
|
+
cooked: authTokenType === 'static' ? `${schemePrefix}${authToken}` : schemePrefix,
|
|
1817
|
+
raw: authTokenType === 'static' ? `${schemePrefix}${authToken}` : schemePrefix,
|
|
866
1818
|
},
|
|
867
1819
|
false
|
|
868
1820
|
),
|
|
@@ -885,7 +1837,7 @@ const computeAuthorizationHeaderAST = (headers: UIDLResourceItem['headers']) =>
|
|
|
885
1837
|
)
|
|
886
1838
|
}
|
|
887
1839
|
|
|
888
|
-
const computeFetchUrl = (resource: UIDLResourceItem) => {
|
|
1840
|
+
export const computeFetchUrl = (resource: UIDLResourceItem) => {
|
|
889
1841
|
const { path } = resource
|
|
890
1842
|
const fetchBaseUrl = resolveResourceValue(path.baseUrl)
|
|
891
1843
|
const resourceRoute = resolveResourceValue(path.route)
|
|
@@ -894,7 +1846,42 @@ const computeFetchUrl = (resource: UIDLResourceItem) => {
|
|
|
894
1846
|
const routeType = path.route?.type
|
|
895
1847
|
|
|
896
1848
|
if (baseUrlType === 'static' && routeType === 'static') {
|
|
897
|
-
const
|
|
1849
|
+
const baseUrlStr = typeof fetchBaseUrl === 'string' ? fetchBaseUrl : String(fetchBaseUrl || '')
|
|
1850
|
+
const routeStr = typeof resourceRoute === 'string' ? resourceRoute : String(resourceRoute || '')
|
|
1851
|
+
const cleanBaseUrl = baseUrlStr.endsWith('/') ? baseUrlStr.slice(0, -1) : baseUrlStr
|
|
1852
|
+
const cleanRoute = routeStr.startsWith('/') ? routeStr.slice(1) : routeStr
|
|
1853
|
+
const stringsToJoin = [cleanBaseUrl, cleanRoute].filter((item) => item).join('/')
|
|
1854
|
+
|
|
1855
|
+
// If the URL is relative (starts with /), add a runtime base URL prefix
|
|
1856
|
+
// so fetch() works in server-side contexts (getStaticProps/getServerSideProps).
|
|
1857
|
+
// Non-NEXT_PUBLIC_ env vars are only available server-side in Next.js,
|
|
1858
|
+
// so NEXTAUTH_URL naturally resolves to undefined on the client (making baseUrl '').
|
|
1859
|
+
if (stringsToJoin.startsWith('/')) {
|
|
1860
|
+
const processEnv = types.memberExpression(
|
|
1861
|
+
types.identifier('process'),
|
|
1862
|
+
types.identifier('env')
|
|
1863
|
+
)
|
|
1864
|
+
const serverBaseUrlExpr = types.logicalExpression(
|
|
1865
|
+
'||',
|
|
1866
|
+
types.logicalExpression(
|
|
1867
|
+
'||',
|
|
1868
|
+
types.memberExpression(processEnv, types.identifier('NEXT_PUBLIC_SITE_URL')),
|
|
1869
|
+
types.memberExpression(
|
|
1870
|
+
types.memberExpression(types.identifier('process'), types.identifier('env')),
|
|
1871
|
+
types.identifier('NEXTAUTH_URL')
|
|
1872
|
+
)
|
|
1873
|
+
),
|
|
1874
|
+
types.stringLiteral('')
|
|
1875
|
+
)
|
|
1876
|
+
return types.templateLiteral(
|
|
1877
|
+
[
|
|
1878
|
+
types.templateElement({ cooked: '', raw: '' }, false),
|
|
1879
|
+
types.templateElement({ cooked: `${stringsToJoin}`, raw: `${stringsToJoin}` }, true),
|
|
1880
|
+
],
|
|
1881
|
+
[serverBaseUrlExpr]
|
|
1882
|
+
)
|
|
1883
|
+
}
|
|
1884
|
+
|
|
898
1885
|
return types.templateLiteral(
|
|
899
1886
|
[types.templateElement({ cooked: `${stringsToJoin}`, raw: `${stringsToJoin}` }, true)],
|
|
900
1887
|
[]
|
|
@@ -983,6 +1970,7 @@ export const resolveObjectValue = (
|
|
|
983
1970
|
| types.NumericLiteral
|
|
984
1971
|
| types.BooleanLiteral
|
|
985
1972
|
| types.ObjectExpression
|
|
1973
|
+
| types.ArrayExpression
|
|
986
1974
|
| types.Expression => {
|
|
987
1975
|
if (prop.type === 'static') {
|
|
988
1976
|
const value =
|
|
@@ -992,6 +1980,8 @@ export const resolveObjectValue = (
|
|
|
992
1980
|
? types.booleanLiteral(prop.content)
|
|
993
1981
|
: typeof prop.content === 'number'
|
|
994
1982
|
? types.numericLiteral(prop.content)
|
|
1983
|
+
: Array.isArray(prop.content)
|
|
1984
|
+
? types.arrayExpression(prop.content.map((element) => convertValueToLiteral(element)))
|
|
995
1985
|
: typeof prop.content === 'object'
|
|
996
1986
|
? objectToObjectExpression(prop.content as unknown as Record<string, unknown>)
|
|
997
1987
|
: types.identifier(String(prop.content))
|
|
@@ -1004,14 +1994,99 @@ export const resolveObjectValue = (
|
|
|
1004
1994
|
}
|
|
1005
1995
|
}
|
|
1006
1996
|
|
|
1997
|
+
/**
|
|
1998
|
+
* Detects if a value is a UIDL dynamic reference (state or prop)
|
|
1999
|
+
*/
|
|
2000
|
+
export const isUIDLDynamicReference = (value: unknown): boolean => {
|
|
2001
|
+
return (
|
|
2002
|
+
typeof value === 'object' &&
|
|
2003
|
+
value !== null &&
|
|
2004
|
+
'type' in value &&
|
|
2005
|
+
(value as Record<string, unknown>).type === 'dynamic' &&
|
|
2006
|
+
'content' in value &&
|
|
2007
|
+
typeof (value as Record<string, unknown>).content === 'object' &&
|
|
2008
|
+
(value as Record<string, unknown>).content !== null &&
|
|
2009
|
+
'referenceType' in ((value as Record<string, unknown>).content as Record<string, unknown>) &&
|
|
2010
|
+
'id' in ((value as Record<string, unknown>).content as Record<string, unknown>)
|
|
2011
|
+
)
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
/**
|
|
2015
|
+
* Converts a filter destination value to an AST expression.
|
|
2016
|
+
* Handles both static values and dynamic references (state/prop).
|
|
2017
|
+
*/
|
|
2018
|
+
export const convertFilterDestinationToExpression = (
|
|
2019
|
+
destination: unknown,
|
|
2020
|
+
options?: { dynamicReferencePrefixMap?: Record<string, string> }
|
|
2021
|
+
): types.Expression => {
|
|
2022
|
+
// Handle dynamic references (state or prop)
|
|
2023
|
+
if (isUIDLDynamicReference(destination)) {
|
|
2024
|
+
const content = (destination as Record<string, unknown>).content as {
|
|
2025
|
+
referenceType: string
|
|
2026
|
+
id: string
|
|
2027
|
+
}
|
|
2028
|
+
const { referenceType, id } = content
|
|
2029
|
+
|
|
2030
|
+
if (referenceType === 'state') {
|
|
2031
|
+
return types.identifier(id)
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
if (referenceType === 'prop') {
|
|
2035
|
+
const prefix = options?.dynamicReferencePrefixMap?.prop || 'props'
|
|
2036
|
+
return types.memberExpression(types.identifier(prefix), types.identifier(id))
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
// Fallback for other reference types
|
|
2040
|
+
return types.identifier(id)
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
// Handle static string values
|
|
2044
|
+
if (typeof destination === 'string') {
|
|
2045
|
+
return types.stringLiteral(destination)
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
// Handle other primitives
|
|
2049
|
+
if (typeof destination === 'number') {
|
|
2050
|
+
return types.numericLiteral(destination)
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
if (typeof destination === 'boolean') {
|
|
2054
|
+
return types.booleanLiteral(destination)
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
// Handle arrays
|
|
2058
|
+
if (Array.isArray(destination)) {
|
|
2059
|
+
return types.arrayExpression(
|
|
2060
|
+
destination.map((item) => convertFilterDestinationToExpression(item, options))
|
|
2061
|
+
)
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
// Fallback to empty string for undefined/null
|
|
2065
|
+
return types.stringLiteral('')
|
|
2066
|
+
}
|
|
2067
|
+
|
|
1007
2068
|
export const getExpressionFromUIDLExpressionNode = (
|
|
1008
2069
|
node: UIDLExpressionValue
|
|
1009
2070
|
): types.Expression => {
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
2071
|
+
let ast
|
|
2072
|
+
try {
|
|
2073
|
+
ast = parse(sanitizeExprContent(node.content), {
|
|
2074
|
+
sourceType: 'module' as const,
|
|
2075
|
+
})
|
|
2076
|
+
} catch (err) {
|
|
2077
|
+
// Malformed expression content in the UIDL (e.g. `?.subtitle` missing its
|
|
2078
|
+
// left-hand identifier). Don't abort the whole generation — warn and fall
|
|
2079
|
+
// back to `undefined`, which renders as nothing in JSX.
|
|
2080
|
+
// tslint:disable-next-line:no-console
|
|
2081
|
+
console.warn(
|
|
2082
|
+
`Failed to parse UIDL expression content ${JSON.stringify(node.content)}: ${
|
|
2083
|
+
(err as Error).message
|
|
2084
|
+
}. Falling back to 'undefined'.`
|
|
2085
|
+
)
|
|
2086
|
+
return types.identifier('undefined')
|
|
2087
|
+
}
|
|
1013
2088
|
|
|
1014
|
-
if (!('program' in ast)) {
|
|
2089
|
+
if (!ast || !('program' in ast)) {
|
|
1015
2090
|
throw new Error(
|
|
1016
2091
|
`The AST does not have a program node in the expression inside addDynamicExpressionAttributeToJSXTag`
|
|
1017
2092
|
)
|
|
@@ -1019,9 +2094,123 @@ export const getExpressionFromUIDLExpressionNode = (
|
|
|
1019
2094
|
|
|
1020
2095
|
const theStatementOnlyWihtoutTheProgram = ast.program.body[0]
|
|
1021
2096
|
|
|
1022
|
-
if (
|
|
2097
|
+
if (
|
|
2098
|
+
!theStatementOnlyWihtoutTheProgram ||
|
|
2099
|
+
theStatementOnlyWihtoutTheProgram.type !== 'ExpressionStatement'
|
|
2100
|
+
) {
|
|
1023
2101
|
throw new Error(`Expr dynamic attribute only support expressions statements at the moment.`)
|
|
1024
2102
|
}
|
|
1025
2103
|
|
|
1026
|
-
return theStatementOnlyWihtoutTheProgram.expression
|
|
2104
|
+
return makeMemberAccessOptional(theStatementOnlyWihtoutTheProgram.expression)
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
/**
|
|
2108
|
+
* Every member read in a UIDL expression becomes an optional-chain read:
|
|
2109
|
+
* `strengths[0].pillar` → `strengths?.[0]?.pillar`. A binding into a list
|
|
2110
|
+
* that is empty until a workflow fills it (the first render, a reset) must
|
|
2111
|
+
* read `undefined`, never throw — one such read took a whole page down at
|
|
2112
|
+
* server render ("Cannot read properties of undefined"). A call's callee
|
|
2113
|
+
* keeps its plain member (`JSON.stringify(x)`), and an assignment or update
|
|
2114
|
+
* target is left as written.
|
|
2115
|
+
*/
|
|
2116
|
+
export const makeMemberAccessOptional = <T extends types.Node>(node: T): T => {
|
|
2117
|
+
const SKIP_KEYS = new Set([
|
|
2118
|
+
'loc',
|
|
2119
|
+
'start',
|
|
2120
|
+
'end',
|
|
2121
|
+
'leadingComments',
|
|
2122
|
+
'trailingComments',
|
|
2123
|
+
'innerComments',
|
|
2124
|
+
'extra',
|
|
2125
|
+
])
|
|
2126
|
+
const isNode = (value: unknown): value is types.Node =>
|
|
2127
|
+
Boolean(value) &&
|
|
2128
|
+
typeof value === 'object' &&
|
|
2129
|
+
typeof (value as { type?: unknown }).type === 'string'
|
|
2130
|
+
|
|
2131
|
+
const visit = (current: types.Node, asCallee: boolean, asTarget: boolean): types.Node => {
|
|
2132
|
+
if (current.type === 'MemberExpression' && !asCallee && !asTarget) {
|
|
2133
|
+
const member = current as types.MemberExpression
|
|
2134
|
+
const object = visit(member.object, false, false) as types.Expression
|
|
2135
|
+
const property = member.computed
|
|
2136
|
+
? (visit(member.property, false, false) as types.Expression)
|
|
2137
|
+
: member.property
|
|
2138
|
+
return types.optionalMemberExpression(
|
|
2139
|
+
object,
|
|
2140
|
+
property as types.Expression,
|
|
2141
|
+
member.computed,
|
|
2142
|
+
true
|
|
2143
|
+
)
|
|
2144
|
+
}
|
|
2145
|
+
if (
|
|
2146
|
+
current.type === 'CallExpression' ||
|
|
2147
|
+
current.type === 'OptionalCallExpression' ||
|
|
2148
|
+
current.type === 'NewExpression'
|
|
2149
|
+
) {
|
|
2150
|
+
const call = current as types.CallExpression
|
|
2151
|
+
// The callee's own member stays plain; what it is read from is guarded.
|
|
2152
|
+
if (call.callee.type === 'MemberExpression') {
|
|
2153
|
+
const callee = call.callee as types.MemberExpression
|
|
2154
|
+
callee.object = visit(callee.object, false, false) as types.Expression
|
|
2155
|
+
if (callee.computed)
|
|
2156
|
+
callee.property = visit(callee.property, false, false) as types.Expression
|
|
2157
|
+
} else {
|
|
2158
|
+
call.callee = visit(call.callee, true, false) as types.Expression
|
|
2159
|
+
}
|
|
2160
|
+
call.arguments = call.arguments.map(
|
|
2161
|
+
(argument) => visit(argument, false, false) as typeof argument
|
|
2162
|
+
)
|
|
2163
|
+
return call
|
|
2164
|
+
}
|
|
2165
|
+
if (current.type === 'AssignmentExpression') {
|
|
2166
|
+
const assignment = current as types.AssignmentExpression
|
|
2167
|
+
assignment.right = visit(assignment.right, false, false) as types.Expression
|
|
2168
|
+
return assignment
|
|
2169
|
+
}
|
|
2170
|
+
if (
|
|
2171
|
+
current.type === 'UpdateExpression' ||
|
|
2172
|
+
(current.type === 'UnaryExpression' &&
|
|
2173
|
+
(current as types.UnaryExpression).operator === 'delete')
|
|
2174
|
+
) {
|
|
2175
|
+
return current
|
|
2176
|
+
}
|
|
2177
|
+
for (const key of Object.keys(current)) {
|
|
2178
|
+
if (SKIP_KEYS.has(key)) continue
|
|
2179
|
+
const value = (current as unknown as Record<string, unknown>)[key]
|
|
2180
|
+
if (Array.isArray(value)) {
|
|
2181
|
+
;(current as unknown as Record<string, unknown>)[key] = value.map((item) =>
|
|
2182
|
+
isNode(item) ? visit(item, false, false) : item
|
|
2183
|
+
)
|
|
2184
|
+
} else if (isNode(value)) {
|
|
2185
|
+
;(current as unknown as Record<string, unknown>)[key] = visit(value, false, false)
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
return current
|
|
2189
|
+
}
|
|
2190
|
+
return visit(node, false, false) as T
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
export const isJSXElement = (value: types.JSXElement | HastNode): value is types.JSXElement =>
|
|
2194
|
+
value.type === 'JSXElement'
|
|
2195
|
+
|
|
2196
|
+
/**
|
|
2197
|
+
* Because of the restrictions of the AST Types we need to have a clear subset of binary operators we can use
|
|
2198
|
+
* @param operation - the operation defined in the UIDL for the current state branch
|
|
2199
|
+
*/
|
|
2200
|
+
export const convertToBinaryOperator = (operation: string): BinaryOperator => {
|
|
2201
|
+
const allowedOperations = ['===', '!==', '>=', '<=', '>', '<']
|
|
2202
|
+
if (allowedOperations.includes(operation)) {
|
|
2203
|
+
return operation as BinaryOperator
|
|
2204
|
+
} else {
|
|
2205
|
+
return '==='
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
|
|
2209
|
+
export const convertToUnaryOperator = (operation: string): UnaryOperation => {
|
|
2210
|
+
const allowedOperations = ['!']
|
|
2211
|
+
if (allowedOperations.includes(operation)) {
|
|
2212
|
+
return operation as UnaryOperation
|
|
2213
|
+
} else {
|
|
2214
|
+
return '!'
|
|
2215
|
+
}
|
|
1027
2216
|
}
|