@builder.io/sdk-svelte 5.2.15 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +4 -0
  2. package/lib/browser/components/block/block.helpers.d.ts +1 -3
  3. package/lib/browser/components/block/block.helpers.js +31 -4
  4. package/lib/browser/components/block/block.svelte +14 -1
  5. package/lib/browser/components/content/components/styles.helpers.d.ts +1 -1
  6. package/lib/browser/components/content/components/styles.helpers.js +1 -1
  7. package/lib/browser/components/content/content.helpers.d.ts +5 -1
  8. package/lib/browser/components/content/content.helpers.js +39 -2
  9. package/lib/browser/components/content/content.svelte +4 -17
  10. package/lib/browser/constants/builder-registered-components.d.ts +1 -0
  11. package/lib/browser/constants/builder-registered-components.js +40 -33
  12. package/lib/browser/constants/device-sizes.js +14 -2
  13. package/lib/browser/constants/sdk-version.d.ts +1 -1
  14. package/lib/browser/constants/sdk-version.js +1 -1
  15. package/lib/browser/functions/evaluate/browser-runtime/browser.js +13 -1
  16. package/lib/browser/functions/evaluate/evaluate.js +21 -5
  17. package/lib/browser/functions/evaluate/node-runtime/node-runtime.js +114 -23
  18. package/lib/browser/functions/evaluate/safe-state-expression.d.ts +33 -0
  19. package/lib/browser/functions/evaluate/safe-state-expression.js +236 -0
  20. package/lib/browser/functions/evaluate/should-force-browser-runtime-in-node.js +3 -1
  21. package/lib/browser/functions/extract-localized-values.d.ts +4 -0
  22. package/lib/browser/functions/extract-localized-values.js +65 -26
  23. package/lib/browser/functions/get-block-properties.js +2 -1
  24. package/lib/browser/functions/get-processed-block.d.ts +0 -1
  25. package/lib/browser/functions/get-processed-block.js +45 -57
  26. package/lib/browser/functions/is-editing-or-previewing.d.ts +1 -0
  27. package/lib/browser/functions/is-editing-or-previewing.js +3 -0
  28. package/lib/browser/functions/set.d.ts +29 -1
  29. package/lib/browser/functions/set.js +87 -3
  30. package/lib/browser/helpers/bounded-cache.d.ts +4 -0
  31. package/lib/browser/helpers/bounded-cache.js +12 -0
  32. package/lib/browser/helpers/copy-plain-data.d.ts +6 -0
  33. package/lib/browser/helpers/copy-plain-data.js +40 -0
  34. package/lib/edge/components/block/block.helpers.d.ts +1 -3
  35. package/lib/edge/components/block/block.helpers.js +31 -4
  36. package/lib/edge/components/block/block.svelte +14 -1
  37. package/lib/edge/components/content/components/styles.helpers.d.ts +1 -1
  38. package/lib/edge/components/content/components/styles.helpers.js +1 -1
  39. package/lib/edge/components/content/content.helpers.d.ts +5 -1
  40. package/lib/edge/components/content/content.helpers.js +39 -2
  41. package/lib/edge/components/content/content.svelte +4 -17
  42. package/lib/edge/constants/builder-registered-components.d.ts +1 -0
  43. package/lib/edge/constants/builder-registered-components.js +40 -33
  44. package/lib/edge/constants/device-sizes.js +14 -2
  45. package/lib/edge/constants/sdk-version.d.ts +1 -1
  46. package/lib/edge/constants/sdk-version.js +1 -1
  47. package/lib/edge/functions/evaluate/browser-runtime/browser.js +13 -1
  48. package/lib/edge/functions/evaluate/evaluate.js +21 -5
  49. package/lib/edge/functions/evaluate/node-runtime/node-runtime.js +114 -23
  50. package/lib/edge/functions/evaluate/safe-state-expression.d.ts +33 -0
  51. package/lib/edge/functions/evaluate/safe-state-expression.js +236 -0
  52. package/lib/edge/functions/evaluate/should-force-browser-runtime-in-node.js +3 -1
  53. package/lib/edge/functions/extract-localized-values.d.ts +4 -0
  54. package/lib/edge/functions/extract-localized-values.js +65 -26
  55. package/lib/edge/functions/get-block-properties.js +2 -1
  56. package/lib/edge/functions/get-processed-block.d.ts +0 -1
  57. package/lib/edge/functions/get-processed-block.js +45 -57
  58. package/lib/edge/functions/is-editing-or-previewing.d.ts +1 -0
  59. package/lib/edge/functions/is-editing-or-previewing.js +3 -0
  60. package/lib/edge/functions/set.d.ts +29 -1
  61. package/lib/edge/functions/set.js +87 -3
  62. package/lib/edge/helpers/bounded-cache.d.ts +4 -0
  63. package/lib/edge/helpers/bounded-cache.js +12 -0
  64. package/lib/edge/helpers/copy-plain-data.d.ts +6 -0
  65. package/lib/edge/helpers/copy-plain-data.js +40 -0
  66. package/lib/node/components/block/block.helpers.d.ts +1 -3
  67. package/lib/node/components/block/block.helpers.js +31 -4
  68. package/lib/node/components/block/block.svelte +14 -1
  69. package/lib/node/components/content/components/styles.helpers.d.ts +1 -1
  70. package/lib/node/components/content/components/styles.helpers.js +1 -1
  71. package/lib/node/components/content/content.helpers.d.ts +5 -1
  72. package/lib/node/components/content/content.helpers.js +39 -2
  73. package/lib/node/components/content/content.svelte +4 -17
  74. package/lib/node/constants/builder-registered-components.d.ts +1 -0
  75. package/lib/node/constants/builder-registered-components.js +40 -33
  76. package/lib/node/constants/device-sizes.js +14 -2
  77. package/lib/node/constants/sdk-version.d.ts +1 -1
  78. package/lib/node/constants/sdk-version.js +1 -1
  79. package/lib/node/functions/evaluate/browser-runtime/browser.js +13 -1
  80. package/lib/node/functions/evaluate/evaluate.js +21 -5
  81. package/lib/node/functions/evaluate/node-runtime/node-runtime.js +114 -23
  82. package/lib/node/functions/evaluate/safe-state-expression.d.ts +33 -0
  83. package/lib/node/functions/evaluate/safe-state-expression.js +236 -0
  84. package/lib/node/functions/evaluate/should-force-browser-runtime-in-node.js +3 -1
  85. package/lib/node/functions/extract-localized-values.d.ts +4 -0
  86. package/lib/node/functions/extract-localized-values.js +65 -26
  87. package/lib/node/functions/get-block-properties.js +2 -1
  88. package/lib/node/functions/get-processed-block.d.ts +0 -1
  89. package/lib/node/functions/get-processed-block.js +45 -57
  90. package/lib/node/functions/is-editing-or-previewing.d.ts +1 -0
  91. package/lib/node/functions/is-editing-or-previewing.js +3 -0
  92. package/lib/node/functions/set.d.ts +29 -1
  93. package/lib/node/functions/set.js +87 -3
  94. package/lib/node/helpers/bounded-cache.d.ts +4 -0
  95. package/lib/node/helpers/bounded-cache.js +12 -0
  96. package/lib/node/helpers/copy-plain-data.d.ts +6 -0
  97. package/lib/node/helpers/copy-plain-data.js +40 -0
  98. package/package.json +1 -1
  99. package/src/components/block/block.helpers.ts +38 -5
  100. package/src/components/block/block.svelte +14 -1
  101. package/src/components/content/components/styles.helpers.ts +1 -1
  102. package/src/components/content/content.helpers.ts +45 -4
  103. package/src/components/content/content.svelte +7 -24
  104. package/src/constants/builder-registered-components.ts +40 -34
  105. package/src/constants/device-sizes.ts +14 -3
  106. package/src/constants/sdk-version.ts +1 -1
  107. package/src/functions/evaluate/browser-runtime/browser.ts +14 -1
  108. package/src/functions/evaluate/evaluate.ts +22 -5
  109. package/src/functions/evaluate/node-runtime/node-runtime.ts +116 -25
  110. package/src/functions/evaluate/safe-state-expression.ts +224 -0
  111. package/src/functions/evaluate/should-force-browser-runtime-in-node.ts +3 -1
  112. package/src/functions/extract-localized-values.ts +61 -27
  113. package/src/functions/get-block-properties.ts +5 -1
  114. package/src/functions/get-processed-block.ts +46 -57
  115. package/src/functions/is-editing-or-previewing.ts +3 -0
  116. package/src/functions/set.ts +91 -3
  117. package/src/helpers/bounded-cache.ts +12 -0
  118. package/src/helpers/copy-plain-data.ts +36 -0
@@ -1,19 +1,22 @@
1
- import type { IsolateOptions } from 'isolated-vm';
1
+ import type { Isolate, IsolateOptions, Reference, Script } from 'isolated-vm';
2
2
  import { SDK_NAME } from '../../../constants/sdk-name';
3
3
  import { MSG_PREFIX, logger } from '../../../helpers/logger';
4
4
  import { fastClone } from '../../fast-clone';
5
- import { set } from '../../set';
5
+ import { set, unset } from '../../set';
6
6
  import type { BuilderGlobals, ExecutorArgs, FunctionArguments } from '../helpers';
7
7
  import { getFunctionArguments } from '../helpers';
8
+ import { NOT_EVALUATED, evaluateSafeStateExpression } from '../safe-state-expression';
8
9
  import { safeDynamicRequire } from './safeDynamicRequire';
9
10
  const getSyncValName = (key: string) => `bldr_${key}_sync`;
10
11
  const BUILDER_SET_STATE_NAME = 'BUILDER_SET_STATE';
12
+ const BUILDER_DELETE_STATE_NAME = 'BUILDER_DELETE_STATE';
11
13
  const INJECTED_IVM_GLOBAL = 'BUILDER_IVM';
12
14
 
13
15
  // Convert all argument references to proxies, and pass `copySync` method to target object, to return a copy of the original JS object
16
+ // Only the `state` proxy carries a `path`, so only writes and deletes on `state` reach the host's root state.
14
17
  // https://github.com/laverdet/isolated-vm#referencecopysync
15
18
  const REF_TO_PROXY_FN = `
16
- var refToProxy = (obj) => {
19
+ var refToProxy = (obj, path) => {
17
20
  if (typeof obj !== 'object' || obj === null) {
18
21
  return obj;
19
22
  }
@@ -24,17 +27,24 @@ var refToProxy = (obj) => {
24
27
  }
25
28
  const val = obj.getSync(key);
26
29
  if (typeof val?.getSync === 'function') {
27
- return refToProxy(val);
30
+ return refToProxy(val, path && path.concat(key));
28
31
  }
29
32
  return val;
30
33
  },
31
34
  set(target, key, value) {
35
+ // Functions cannot cross the isolate boundary, and server renders never call them.
36
+ if (typeof value === 'function') {
37
+ return true;
38
+ }
32
39
  const v = typeof value === 'object' ? new ${INJECTED_IVM_GLOBAL}.Reference(value) : value;
33
40
  obj.setSync(key, v);
34
- ${BUILDER_SET_STATE_NAME}(key, value)
41
+ if (path) ${BUILDER_SET_STATE_NAME}(path.concat(key), value);
42
+ return true;
35
43
  },
36
44
  deleteProperty(target, key) {
37
45
  obj.deleteSync(key);
46
+ if (path) ${BUILDER_DELETE_STATE_NAME}(path.concat(key));
47
+ return true;
38
48
  }
39
49
  })
40
50
  }
@@ -46,10 +56,11 @@ const processCode = ({
46
56
  code: string;
47
57
  args: FunctionArguments;
48
58
  }) => {
49
- const fnArgs = args.map(([name]) => `var ${name} = refToProxy(${getSyncValName(name)}); `).join('');
59
+ const fnArgs = args.map(([name]) => `var ${name} = refToProxy(${getSyncValName(name)}${name === 'state' ? ', []' : ''}); `).join('');
50
60
 
51
61
  // the output is stringified and parsed back to the parent isolate if needed (when it's an `object`)
52
- return `
62
+ // Wrapped in an IIFE so it compiles as a reusable script whose completion value is the result.
63
+ return `(function () {
53
64
  ${REF_TO_PROXY_FN}
54
65
  ${fnArgs}
55
66
  function theFunction() {
@@ -63,15 +74,63 @@ if (typeof output === 'object' && output !== null) {
63
74
  } else {
64
75
  return output;
65
76
  }
66
- `;
77
+ })()`;
67
78
  };
68
79
  type IsolatedVMImport = typeof import('isolated-vm');
69
80
  let IVM_INSTANCE: IsolatedVMImport | null = null;
70
- // Create fresh isolates per request to prevent memory leaks
71
81
  let IVM_OPTIONS: IsolateOptions = {
72
82
  memoryLimit: 128
73
83
  };
74
84
 
85
+ /**
86
+ * Evaluations share one isolate, each in a fresh context. The isolate is disposed at the end of the
87
+ * current task (or after a fixed number of evaluations), so a render's bindings share it without it
88
+ * outliving that work: a single long-lived isolate leaked memory (#4210), and one still alive at
89
+ * worker-thread teardown crashes `isolated-vm` on Linux.
90
+ */
91
+ const MAX_EVALUATIONS_PER_ISOLATE = 1000;
92
+ let POOLED: {
93
+ isolate: Isolate;
94
+ evaluations: number;
95
+ scripts: Map<string, Script>;
96
+ } | null = null;
97
+ let DISPOSE_TIMER: ReturnType<typeof setTimeout> | null = null;
98
+ let IS_EXIT_HANDLER_REGISTERED = false;
99
+ const disposePooledIsolate = () => {
100
+ if (DISPOSE_TIMER) {
101
+ clearTimeout(DISPOSE_TIMER);
102
+ DISPOSE_TIMER = null;
103
+ }
104
+ if (POOLED && !POOLED.isolate.isDisposed) {
105
+ try {
106
+ POOLED.isolate.dispose();
107
+ } catch (e) {
108
+ // Ignore disposal errors
109
+ }
110
+ }
111
+ POOLED = null;
112
+ };
113
+ const getPooledIsolate = (ivm: IsolatedVMImport) => {
114
+ if (!POOLED || POOLED.isolate.isDisposed || POOLED.evaluations >= MAX_EVALUATIONS_PER_ISOLATE) {
115
+ disposePooledIsolate();
116
+ POOLED = {
117
+ isolate: new ivm.Isolate(IVM_OPTIONS),
118
+ evaluations: 0,
119
+ scripts: new Map()
120
+ };
121
+ }
122
+ if (!DISPOSE_TIMER) {
123
+ DISPOSE_TIMER = setTimeout(disposePooledIsolate, 0);
124
+ DISPOSE_TIMER.unref?.();
125
+ }
126
+ if (!IS_EXIT_HANDLER_REGISTERED && typeof process !== 'undefined' && typeof process.once === 'function') {
127
+ IS_EXIT_HANDLER_REGISTERED = true;
128
+ process.once('exit', disposePooledIsolate);
129
+ }
130
+ POOLED.evaluations++;
131
+ return POOLED;
132
+ };
133
+
75
134
  /**
76
135
  * Set the `isolated-vm` instance to be used by the node runtime.
77
136
  * This is useful for environments that are not able to rely on our
@@ -106,6 +165,22 @@ const getIvm = (): IsolatedVMImport => {
106
165
  For more information, visit https://builder.io/c/docs/integration-tips#enabling-data-bindings-in-node-environments`;
107
166
  throw new Error(ERROR_MESSAGE);
108
167
  };
168
+ let IS_PROXY: ((value: unknown) => boolean) | null | undefined;
169
+
170
+ /**
171
+ * Node's `util.types.isProxy`, which detects a Proxy without running its traps.
172
+ * `null` when unavailable, in which case the pure-expression fast path is skipped.
173
+ */
174
+ const getIsProxy = () => {
175
+ if (IS_PROXY === undefined) {
176
+ try {
177
+ IS_PROXY = safeDynamicRequire('node:util')?.types?.isProxy ?? null;
178
+ } catch {
179
+ IS_PROXY = null;
180
+ }
181
+ }
182
+ return IS_PROXY;
183
+ };
109
184
  export const runInNode = ({
110
185
  code,
111
186
  builder,
@@ -115,13 +190,16 @@ export const runInNode = ({
115
190
  rootSetState,
116
191
  rootState
117
192
  }: ExecutorArgs) => {
193
+ const isProxy = getIsProxy();
194
+ if (isProxy) {
195
+ const safeValue = evaluateSafeStateExpression(code, rootState, localState, isProxy);
196
+ if (safeValue !== NOT_EVALUATED) return safeValue;
197
+ }
118
198
  const ivm = getIvm();
119
-
120
- // Use stored options from setIvm, or default to { memoryLimit: 128 }
121
- let isolate;
199
+ const pooled = getPooledIsolate(ivm);
200
+ const isolateContext = pooled.isolate.createContextSync();
201
+ const references: Reference[] = [];
122
202
  try {
123
- isolate = new ivm.Isolate(IVM_OPTIONS);
124
- const isolateContext = isolate.createContextSync();
125
203
  const jail = isolateContext.global;
126
204
 
127
205
  // Setup the isolate
@@ -144,13 +222,17 @@ export const runInNode = ({
144
222
  /**
145
223
  * Propagate state changes back to the reactive root state.
146
224
  */
147
- jail.setSync(BUILDER_SET_STATE_NAME, function (key: string, value: any) {
225
+ jail.setSync(BUILDER_SET_STATE_NAME, function (path: string[], value: any) {
148
226
  // mutate the `rootState` object itself. Important for cases where we do not have `rootSetState`
149
227
  // like Qwik.
150
- set(rootState, key, value);
228
+ set(rootState, path, value);
151
229
  // call the `rootSetState` function if it exists
152
230
  rootSetState?.(rootState);
153
231
  });
232
+ jail.setSync(BUILDER_DELETE_STATE_NAME, function (path: string[]) {
233
+ unset(rootState, path);
234
+ rootSetState?.(rootState);
235
+ });
154
236
  args.forEach(([key, arg]) => {
155
237
  const val = typeof arg === 'object' ? new ivm.Reference(
156
238
  // workaround: methods with default values for arguments is not being cloned over
@@ -158,13 +240,18 @@ export const runInNode = ({
158
240
  ...arg,
159
241
  getUserAttributes: () => (arg as BuilderGlobals).getUserAttributes()
160
242
  } : arg) : null;
243
+ if (val) references.push(val);
161
244
  jail.setSync(getSyncValName(key), val);
162
245
  });
163
- const evalStr = processCode({
164
- code,
165
- args
166
- });
167
- const resultStr = isolateContext.evalClosureSync(evalStr);
246
+ let script = pooled.scripts.get(code);
247
+ if (!script) {
248
+ script = pooled.isolate.compileScriptSync(processCode({
249
+ code,
250
+ args
251
+ }));
252
+ pooled.scripts.set(code, script);
253
+ }
254
+ const resultStr = script.runSync(isolateContext);
168
255
  try {
169
256
  // returning objects throw errors in isolated vm, so we stringify it and parse it back
170
257
  const res = JSON.parse(resultStr);
@@ -173,13 +260,17 @@ export const runInNode = ({
173
260
  return resultStr;
174
261
  }
175
262
  } finally {
176
- // Destroy the entire VM, this frees ALL memory at the C++ level.
177
- if (isolate) {
263
+ references.forEach(reference => {
178
264
  try {
179
- isolate.dispose();
265
+ reference.release();
180
266
  } catch (e) {
181
- // Ignore disposal errors
267
+ // Ignore release errors
182
268
  }
269
+ });
270
+ try {
271
+ isolateContext.release();
272
+ } catch (e) {
273
+ // Ignore release errors (e.g. the isolate was disposed after hitting its memory limit)
183
274
  }
184
275
  }
185
276
  }
@@ -0,0 +1,224 @@
1
+ import { createBoundedCache } from '../../helpers/bounded-cache';
2
+
3
+ /**
4
+ * Recognizes binding expressions that only read `state` and combine the values
5
+ * with operators and literals, e.g. `!state.open`, `state.$index + 1` or
6
+ * `state.plan === "pro" ? "Upgrade" : "Manage"`. Such an expression cannot call
7
+ * functions, assign, loop or reach any global, so it can run as a plain function
8
+ * instead of in a sandbox. Anything else returns `null` and is sandboxed as usual.
9
+ */
10
+
11
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*/;
12
+ const NUMBER = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/;
13
+
14
+ /**
15
+ * The length of a single- or double-quoted string literal at the start of `code`
16
+ * (no escapes or line breaks), or 0 when there is none.
17
+ */
18
+ const getStringLiteralLength = (code: string) => {
19
+ const quote = code[0];
20
+ if (quote !== '"' && quote !== "'") return 0;
21
+ for (let i = 1; i < code.length; i++) {
22
+ const char = code[i];
23
+ if (char === quote) return i + 1;
24
+ if (char === '\\' || char === '\n' || char === '\r') return 0;
25
+ }
26
+ return 0;
27
+ };
28
+ const OPERATORS = ['===', '!==', '==', '!=', '<=', '>=', '&&', '||', '??', '<', '>', '!', '+', '-', '*', '/', '%', '?', ':'];
29
+ const LITERAL_KEYWORDS = new Set(['true', 'false', 'null', 'undefined']);
30
+ // Reading these is harmless on data, but they lead to functions and prototypes.
31
+ const BLOCKED_PROPERTIES = new Set(['constructor', '__proto__', 'prototype', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__']);
32
+ const MAX_EXPRESSION_LENGTH = 500;
33
+
34
+ /**
35
+ * Returns `expression` when it only uses the allowed grammar, otherwise `null`.
36
+ */
37
+ export const getSafeStateExpression = (expression: string): string | null => {
38
+ if (expression.length > MAX_EXPRESSION_LENGTH) return null;
39
+ let rest = expression.trim();
40
+ if (!rest) return null;
41
+ let depth = 0;
42
+ // A value (state path, literal or closing paren) was just read: `(` here would be a call.
43
+ let afterValue = false;
44
+ let readsState = false;
45
+ while (rest) {
46
+ const whitespace = /^\s+/.exec(rest);
47
+ if (whitespace) {
48
+ rest = rest.slice(whitespace[0].length);
49
+ continue;
50
+ }
51
+ const identifier = IDENTIFIER.exec(rest);
52
+ if (identifier) {
53
+ if (afterValue) return null;
54
+ const word = identifier[0];
55
+ rest = rest.slice(word.length);
56
+ if (LITERAL_KEYWORDS.has(word)) {
57
+ afterValue = true;
58
+ continue;
59
+ }
60
+ if (word !== 'state') return null;
61
+ let hasProperty = false;
62
+ let property = /^\s*\.\s*([A-Za-z_$][\w$]*)/.exec(rest);
63
+ while (property) {
64
+ if (BLOCKED_PROPERTIES.has(property[1])) return null;
65
+ hasProperty = true;
66
+ rest = rest.slice(property[0].length);
67
+ property = /^\s*\.\s*([A-Za-z_$][\w$]*)/.exec(rest);
68
+ }
69
+ if (!hasProperty) return null;
70
+ readsState = true;
71
+ afterValue = true;
72
+ continue;
73
+ }
74
+ const literalLength = NUMBER.exec(rest)?.[0].length || getStringLiteralLength(rest);
75
+ if (literalLength) {
76
+ if (afterValue) return null;
77
+ rest = rest.slice(literalLength);
78
+ afterValue = true;
79
+ continue;
80
+ }
81
+ if (rest[0] === '(') {
82
+ if (afterValue) return null;
83
+ depth++;
84
+ rest = rest.slice(1);
85
+ continue;
86
+ }
87
+ if (rest[0] === ')') {
88
+ if (depth === 0) return null;
89
+ depth--;
90
+ rest = rest.slice(1);
91
+ afterValue = true;
92
+ continue;
93
+ }
94
+ const operator = OPERATORS.find(op => rest.startsWith(op));
95
+ if (!operator) return null;
96
+ // `?.` is optional chaining (a property access we do not handle)
97
+ if (operator === '?' && rest[1] === '.') return null;
98
+ // `++` / `--` would write to state
99
+ if ((operator === '+' || operator === '-') && rest[1] === operator) {
100
+ return null;
101
+ }
102
+ rest = rest.slice(operator.length);
103
+ afterValue = false;
104
+ }
105
+ if (depth !== 0 || !readsState || !afterValue) return null;
106
+ return expression.trim();
107
+ };
108
+ const RETURN_EXPRESSION = /^\s*return\s*\(([\s\S]*)\);\s*$/;
109
+ const VIRTUAL_INDEX_EXPRESSION = /^\s*var\s+_virtual_index\s*=\s*([\s\S]*?);?\s*return\s+_virtual_index\s*;?\s*$/;
110
+
111
+ /**
112
+ * Extracts the expression from code produced by `parseCode` (`return (expr);`) or
113
+ * from the editor's transpiled form (`var _virtual_index=expr;` followed by a return of it).
114
+ * (Mitosis treats any file containing a literal "return" + " _virtual_index" as a function body.)
115
+ */
116
+ export const getSafeStateExpressionFromCode = (code: string) => {
117
+ const match = RETURN_EXPRESSION.exec(code) || VIRTUAL_INDEX_EXPRESSION.exec(code);
118
+ return match ? getSafeStateExpression(match[1]) : null;
119
+ };
120
+ const isPrimitiveValue = (value: unknown) => value === null || typeof value !== 'object' && typeof value !== 'function';
121
+ type SafeExpressionFn = (state: Record<string, any>) => unknown;
122
+ const MAX_CACHED_EXPRESSIONS = 5000;
123
+ const COMPILED_EXPRESSIONS = createBoundedCache<SafeExpressionFn | null>(MAX_CACHED_EXPRESSIONS);
124
+
125
+ /**
126
+ * The compiled expression for `code`, or `null` when `code` is not a safe state expression.
127
+ */
128
+ export const getSafeStateExpressionFn = (code: string): SafeExpressionFn | null => {
129
+ let fn = COMPILED_EXPRESSIONS.get(code);
130
+ if (fn === undefined) {
131
+ const expression = getSafeStateExpressionFromCode(code);
132
+ fn = null;
133
+ if (expression) {
134
+ try {
135
+ fn = (new Function('state', `return (${expression});`) as SafeExpressionFn);
136
+ } catch (e) {
137
+ fn = null;
138
+ }
139
+ }
140
+ COMPILED_EXPRESSIONS.set(code, fn);
141
+ }
142
+ return fn;
143
+ };
144
+ const UNSAFE_STATE_READ = Symbol('unsafe state read');
145
+ const isPlainContainer = (value: object) => {
146
+ const prototype = Object.getPrototypeOf(value);
147
+ return prototype === Object.prototype || prototype === Array.prototype || prototype === null;
148
+ };
149
+ const READ_ONLY_TRAPS = {
150
+ set: () => false,
151
+ deleteProperty: () => false
152
+ };
153
+ const findDescriptor = (target: object, prop: string | symbol) => {
154
+ for (let o: object | null = target; o; o = Object.getPrototypeOf(o)) {
155
+ const descriptor = Object.getOwnPropertyDescriptor(o, prop);
156
+ if (descriptor) return descriptor;
157
+ }
158
+ return undefined;
159
+ };
160
+
161
+ /**
162
+ * A read-only view of local state over root state, without copying either.
163
+ *
164
+ * Plain objects and arrays are wrapped so every nested read is checked: accessors
165
+ * anywhere on the prototype chain, class instances and functions (which could run
166
+ * getters or custom `valueOf`/`toString`) abort the read. Each source object maps to
167
+ * one wrapper for the life of the view, so `===` still compares the underlying objects.
168
+ * Wrappers target a fresh empty container rather than the object itself, because proxy
169
+ * invariants forbid returning a wrapper for a frozen (non-configurable) property.
170
+ */
171
+ export const getReadOnlyStateView = (rootState: Record<string | symbol, any>, localState: Record<string | symbol, any> | undefined, isProxy: (value: unknown) => boolean) => {
172
+ // Reflecting on a Proxy (even `Object.getPrototypeOf`) runs its traps.
173
+ const isInspectable = (value: object) => !isProxy(value) && isPlainContainer(value);
174
+ if (!isInspectable(rootState) || localState && isProxy(localState)) {
175
+ throw UNSAFE_STATE_READ;
176
+ }
177
+ const wrappers = new WeakMap<object, object>();
178
+ const guardStateValue = (value: unknown): unknown => {
179
+ if (value === null || typeof value !== 'object') {
180
+ if (typeof value === 'function') throw UNSAFE_STATE_READ;
181
+ return value;
182
+ }
183
+ if (!isInspectable(value)) throw UNSAFE_STATE_READ;
184
+ let wrapper = wrappers.get(value);
185
+ if (!wrapper) {
186
+ wrapper = new Proxy(Array.isArray(value) ? [] : {}, {
187
+ get: (_, prop) => readDataProperty(value, prop),
188
+ ...READ_ONLY_TRAPS
189
+ });
190
+ wrappers.set(value, wrapper);
191
+ }
192
+ return wrapper;
193
+ };
194
+ const readDataProperty = (target: object, prop: string | symbol): unknown => {
195
+ const descriptor = findDescriptor(target, prop);
196
+ if (descriptor && (descriptor.get || descriptor.set)) {
197
+ throw UNSAFE_STATE_READ;
198
+ }
199
+ return guardStateValue(descriptor?.value);
200
+ };
201
+ return new Proxy({}, {
202
+ get: (_, prop) => localState && Object.prototype.hasOwnProperty.call(localState, prop) ? readDataProperty(localState, prop) : readDataProperty(rootState, prop),
203
+ ...READ_ONLY_TRAPS
204
+ });
205
+ };
206
+ export const NOT_EVALUATED = Symbol('not evaluated');
207
+
208
+ /**
209
+ * Evaluates `code` outside the sandbox when it is a safe state expression over plain
210
+ * data and produces a primitive. Returns `NOT_EVALUATED` when the sandbox must run it.
211
+ */
212
+ export const evaluateSafeStateExpression = (code: string, rootState: Record<string | symbol, any>, localState: Record<string | symbol, any> | undefined, isProxy: (value: unknown) => boolean): unknown => {
213
+ const fn = getSafeStateExpressionFn(code);
214
+ if (!fn) return NOT_EVALUATED;
215
+ let value: unknown;
216
+ try {
217
+ value = fn(getReadOnlyStateView(rootState, localState, isProxy));
218
+ } catch {
219
+ // Unsafe reads and ordinary errors (e.g. a null-prototype object in `+`) both
220
+ // go to the regular evaluator, so behavior matches evaluation without the fast path.
221
+ return NOT_EVALUATED;
222
+ }
223
+ return isPrimitiveValue(value) ? value : NOT_EVALUATED;
224
+ }
@@ -1,5 +1,6 @@
1
1
  import { logger } from '../../helpers/logger';
2
2
  import { isNodeRuntime } from '../is-node-runtime';
3
+ let hasLoggedWarning = false;
3
4
  export const shouldForceBrowserRuntimeInNode = ({
4
5
  shouldLogWarning
5
6
  }: {
@@ -10,7 +11,8 @@ export const shouldForceBrowserRuntimeInNode = ({
10
11
  const isNode20 = process.version.startsWith('v20');
11
12
  const hasNoNodeSnapshotNodeOption = process.env.NODE_OPTIONS?.includes('--no-node-snapshot');
12
13
  if (isArm64 && isNode20 && !hasNoNodeSnapshotNodeOption) {
13
- if (shouldLogWarning) {
14
+ if (shouldLogWarning && !hasLoggedWarning) {
15
+ hasLoggedWarning = true;
14
16
  logger.log(`Skipping usage of \`isolated-vm\` to avoid crashes in Node v20 on an arm64 machine.
15
17
  If you would like to use the \`isolated-vm\` package on this machine, please provide the \`NODE_OPTIONS=--no-node-snapshot\` config to your Node process.
16
18
  See https://github.com/BuilderIO/builder/blob/main/packages/sdks/README.md#node-v20--m1-macs-apple-silicon-support for more information.
@@ -1,38 +1,72 @@
1
1
  import type { BuilderBlock } from '../types/builder-block';
2
- import { traverse } from './traverse';
3
2
  function isLocalizedField(value: any) {
4
3
  return value && typeof value === 'object' && value['@type'] === '@builder.io/core:LocalizedValue';
5
4
  }
6
- function containsLocalizedValues(data: Record<string, any>) {
7
- if (!data || !Object.getOwnPropertyNames(data).length) {
8
- return false;
5
+ const isPlainObjectOrArray = (value: object) => {
6
+ if (Array.isArray(value)) return true;
7
+ const proto = Object.getPrototypeOf(value);
8
+ return proto === Object.prototype || proto === null;
9
+ };
10
+
11
+ /**
12
+ * Returns `value` with every localized value replaced by its `locale` entry.
13
+ * Only the objects and arrays on the way to a replaced value are copied: the
14
+ * input is never mutated, and a value with nothing localized is returned as-is.
15
+ */
16
+ function resolveLocalized(value: any, locale: string, seen: WeakMap<object, any>): any {
17
+ if (value === null || typeof value !== 'object') return value;
18
+ if (isLocalizedField(value)) {
19
+ return resolveLocalized(value[locale] ?? undefined, locale, seen);
9
20
  }
10
- let hasLocalizedValues = false;
11
- traverse(data, value => {
12
- if (isLocalizedField(value)) {
13
- hasLocalizedValues = true;
14
- return;
21
+ if (!isPlainObjectOrArray(value)) return value;
22
+ if (seen.has(value)) return seen.get(value);
23
+ seen.set(value, value);
24
+ let copy: any = null;
25
+ if (Array.isArray(value)) {
26
+ for (let i = 0; i < value.length; i++) {
27
+ const next = resolveLocalized(value[i], locale, seen);
28
+ if (next !== value[i]) {
29
+ if (!copy) copy = value.slice();
30
+ copy[i] = next;
31
+ }
15
32
  }
16
- });
17
- return hasLocalizedValues;
18
- }
19
- function extractLocalizedValues(data: Record<string, any>, locale: string) {
20
- if (!data || !Object.getOwnPropertyNames(data).length) {
21
- return {};
22
- }
23
- traverse(data, (value, update) => {
24
- if (isLocalizedField(value)) {
25
- update(value[locale] ?? undefined);
33
+ } else {
34
+ for (const key of Object.keys(value)) {
35
+ const next = resolveLocalized(value[key], locale, seen);
36
+ if (next !== value[key]) {
37
+ if (!copy) copy = {
38
+ ...value
39
+ };
40
+ copy[key] = next;
41
+ }
26
42
  }
27
- });
28
- return data;
43
+ }
44
+ const result = copy ?? value;
45
+ seen.set(value, result);
46
+ return result;
29
47
  }
48
+
49
+ /**
50
+ * Returns the block with localized values in `component.options` resolved.
51
+ * The block is returned unchanged (same object) when it has none.
52
+ */
30
53
  export function resolveLocalizedValues(block: BuilderBlock, locale: string | undefined) {
31
- if (block.component?.options && containsLocalizedValues(block.component?.options)) {
32
- if (!locale) {
33
- console.warn('[Builder.io] In order to use localized fields in Builder, you must pass a locale prop to the BuilderComponent or to options object while fetching the content to resolve localized fields. Learn more: https://www.builder.io/c/docs/localization-inline#targeting-and-inline-localization');
34
- }
35
- block.component.options = extractLocalizedValues(block.component.options, locale ?? 'Default');
54
+ const options = block.component?.options;
55
+ if (!options || typeof options !== 'object' || isLocalizedField(options)) {
56
+ return block;
36
57
  }
37
- return block;
58
+ const resolvedOptions = resolveLocalized(options, locale ?? 'Default', new WeakMap());
59
+ if (resolvedOptions === options) {
60
+ return block;
61
+ }
62
+ if (!locale) {
63
+ console.warn('[Builder.io] In order to use localized fields in Builder, you must pass a locale prop to the BuilderComponent or to options object while fetching the content to resolve localized fields. Learn more: https://www.builder.io/c/docs/localization-inline#targeting-and-inline-localization');
64
+ }
65
+ return {
66
+ ...block,
67
+ component: {
68
+ ...block.component!,
69
+ options: resolvedOptions
70
+ }
71
+ };
38
72
  }
@@ -44,9 +44,13 @@ export function getBlockProperties({
44
44
  block: BuilderBlock;
45
45
  context: BuilderContextInterface;
46
46
  }) {
47
+ const {
48
+ _newProperty,
49
+ ...blockProperties
50
+ } = block.properties || {};
47
51
  const properties = {
48
52
  ...extractRelevantRootBlockProperties(block),
49
- ...block.properties,
53
+ ...blockProperties,
50
54
  'builder-id': block.id,
51
55
  style: getStyle({
52
56
  block,