@builder.io/sdk-solid 5.0.1 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/edge/index.js CHANGED
@@ -219,141 +219,429 @@ var getUserAttributes = () => {
219
219
  };
220
220
  };
221
221
 
222
- // src/functions/evaluate/helpers.ts
223
- var getFunctionArguments = ({
224
- builder,
225
- context,
226
- event,
227
- state
222
+ // src/constants/sdk-version.ts
223
+ var SDK_VERSION = "5.1.1";
224
+
225
+ // src/helpers/sdk-headers.ts
226
+ var getSdkHeaders = () => ({
227
+ "X-Builder-SDK": TARGET,
228
+ "X-Builder-SDK-GEN": "2",
229
+ "X-Builder-SDK-Version": SDK_VERSION
230
+ });
231
+
232
+ // src/helpers/nullable.ts
233
+ var checkIsDefined = (maybeT) => maybeT !== null && maybeT !== void 0;
234
+
235
+ // src/helpers/url.ts
236
+ var getTopLevelDomain = (host) => {
237
+ if (host === "localhost" || host === "127.0.0.1") {
238
+ return host;
239
+ }
240
+ const parts = host.split(".");
241
+ if (parts.length > 2) {
242
+ return parts.slice(1).join(".");
243
+ }
244
+ return host;
245
+ };
246
+
247
+ // src/helpers/cookie.ts
248
+ var getCookieSync = ({
249
+ name,
250
+ canTrack
228
251
  }) => {
229
- return Object.entries({
230
- state,
231
- Builder: builder,
232
- // legacy
233
- builder,
234
- context,
235
- event
236
- });
252
+ try {
253
+ if (!canTrack) {
254
+ return void 0;
255
+ }
256
+ return document.cookie.split("; ").find((row) => row.startsWith(`${name}=`))?.split("=")[1];
257
+ } catch (err) {
258
+ logger.warn("[COOKIE] GET error: ", err?.message || err);
259
+ return void 0;
260
+ }
237
261
  };
238
- var getBuilderGlobals = () => ({
239
- isEditing: isEditing(),
240
- isBrowser: isBrowser(),
241
- isServer: !isBrowser(),
242
- getUserAttributes: () => getUserAttributes()
243
- });
244
- var parseCode = (code, {
245
- isExpression = true
262
+ var getCookie = async (args) => getCookieSync(args);
263
+ var stringifyCookie = (cookie) => cookie.map(([key, value]) => value ? `${key}=${value}` : key).filter(checkIsDefined).join("; ");
264
+ var SECURE_CONFIG = [["secure", ""], ["SameSite", "None"]];
265
+ var createCookieString = ({
266
+ name,
267
+ value,
268
+ expires
246
269
  }) => {
247
- const useReturn = (
248
- // we disable this for cases where we definitely don't want a return
249
- isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "))
250
- );
251
- const useCode = useReturn ? `return (${code});` : code;
252
- return useCode;
270
+ const secure = isBrowser() ? location.protocol === "https:" : true;
271
+ const secureObj = secure ? SECURE_CONFIG : [[]];
272
+ const expiresObj = expires ? [["expires", expires.toUTCString()]] : [[]];
273
+ const cookieValue = [[name, value], ...expiresObj, ["path", "/"], ["domain", getTopLevelDomain(window.location.hostname)], ...secureObj];
274
+ const cookie = stringifyCookie(cookieValue);
275
+ return cookie;
253
276
  };
254
- function flattenState({
255
- rootState,
256
- localState,
257
- rootSetState
258
- }) {
259
- return new Proxy(rootState, {
260
- get: (target, prop) => {
261
- if (localState && prop in localState) {
262
- return localState[prop];
263
- }
264
- const val = target[prop];
265
- if (typeof val === "object" && val !== null) {
266
- return flattenState({
267
- rootState: val,
268
- localState: void 0,
269
- rootSetState: rootSetState ? (subState) => {
270
- target[prop] = subState;
271
- rootSetState(target);
272
- } : void 0
273
- });
274
- }
275
- return val;
276
- },
277
- set: (target, prop, value) => {
278
- if (localState && prop in localState) {
279
- throw new Error("Writing to local state is not allowed as it is read-only.");
280
- }
281
- target[prop] = value;
282
- rootSetState?.(target);
283
- return true;
277
+ var setCookie = async ({
278
+ name,
279
+ value,
280
+ expires,
281
+ canTrack
282
+ }) => {
283
+ try {
284
+ if (!canTrack) {
285
+ return;
284
286
  }
287
+ const cookie = createCookieString({
288
+ name,
289
+ value,
290
+ expires
291
+ });
292
+ document.cookie = cookie;
293
+ } catch (err) {
294
+ logger.warn("[COOKIE] SET error: ", err?.message || err);
295
+ }
296
+ };
297
+
298
+ // src/helpers/uuid.ts
299
+ function uuidv4() {
300
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
301
+ const r = Math.random() * 16 | 0, v2 = c == "x" ? r : r & 3 | 8;
302
+ return v2.toString(16);
285
303
  });
286
304
  }
305
+ function uuid() {
306
+ return uuidv4().replace(/-/g, "");
307
+ }
287
308
 
288
- // src/functions/evaluate/browser-runtime/browser.ts
289
- var runInBrowser = ({
290
- code,
291
- builder,
292
- context,
293
- event,
294
- localState,
295
- rootSetState,
296
- rootState
309
+ // src/helpers/sessionId.ts
310
+ var SESSION_LOCAL_STORAGE_KEY = "builderSessionId";
311
+ var getSessionId = async ({
312
+ canTrack
297
313
  }) => {
298
- const functionArgs = getFunctionArguments({
299
- builder,
300
- context,
301
- event,
302
- state: flattenState({
303
- rootState,
304
- localState,
305
- rootSetState
306
- })
314
+ if (!canTrack) {
315
+ return void 0;
316
+ }
317
+ const sessionId = await getCookie({
318
+ name: SESSION_LOCAL_STORAGE_KEY,
319
+ canTrack
307
320
  });
308
- return new Function(...functionArgs.map(([name]) => name), code)(...functionArgs.map(([, value]) => value));
321
+ if (checkIsDefined(sessionId)) {
322
+ return sessionId;
323
+ } else {
324
+ const newSessionId = createSessionId();
325
+ setSessionId({
326
+ id: newSessionId,
327
+ canTrack
328
+ });
329
+ return newSessionId;
330
+ }
309
331
  };
332
+ var createSessionId = () => uuid();
333
+ var setSessionId = ({
334
+ id: id2,
335
+ canTrack
336
+ }) => setCookie({
337
+ name: SESSION_LOCAL_STORAGE_KEY,
338
+ value: id2,
339
+ canTrack
340
+ });
310
341
 
311
- // src/functions/evaluate/edge-runtime/acorn-interpreter.ts
312
- var p;
313
- var ca = function(a) {
314
- function b(f) {
315
- return 48 > f ? 36 === f : 58 > f ? true : 65 > f ? false : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Jc.test(String.fromCharCode(f));
316
- }
317
- function d(f) {
318
- return 65 > f ? 36 === f : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Pb.test(String.fromCharCode(f));
319
- }
320
- function c(f, g) {
321
- var l = r;
322
- for (var n = 1, w = 0; ; ) {
323
- Sa.lastIndex = w;
324
- var J = Sa.exec(l);
325
- if (J && J.index < f)
326
- ++n, w = J.index + J[0].length;
327
- else
328
- break;
342
+ // src/helpers/localStorage.ts
343
+ var getLocalStorage = () => isBrowser() && typeof localStorage !== "undefined" ? localStorage : void 0;
344
+ var getLocalStorageItem = ({
345
+ key,
346
+ canTrack
347
+ }) => {
348
+ try {
349
+ if (canTrack) {
350
+ return getLocalStorage()?.getItem(key);
329
351
  }
330
- l = {
331
- line: n,
332
- ab: f - w
333
- };
334
- g += " (" + l.line + ":" + l.ab + ")";
335
- g = new SyntaxError(g);
336
- g.j = f;
337
- g.X = l;
338
- g.o = m;
339
- throw g;
352
+ return void 0;
353
+ } catch (err) {
354
+ return void 0;
340
355
  }
341
- function e(f) {
342
- f = f.split(" ");
343
- for (var g = /* @__PURE__ */ Object.create(null), l = 0; l < f.length; l++)
344
- g[f[l]] = true;
345
- return function(n) {
346
- return g[n] || false;
347
- };
356
+ };
357
+ var setLocalStorageItem = ({
358
+ key,
359
+ canTrack,
360
+ value
361
+ }) => {
362
+ try {
363
+ if (canTrack) {
364
+ getLocalStorage()?.setItem(key, value);
365
+ }
366
+ } catch (err) {
348
367
  }
349
- function h() {
350
- this.line = la;
351
- this.ab = m - X;
368
+ };
369
+
370
+ // src/helpers/visitorId.ts
371
+ var VISITOR_LOCAL_STORAGE_KEY = "builderVisitorId";
372
+ var getVisitorId = ({
373
+ canTrack
374
+ }) => {
375
+ if (!canTrack) {
376
+ return void 0;
352
377
  }
353
- function k(f, g) {
354
- oa = m;
355
- z.C && (cb = new h());
356
- x = f;
378
+ const visitorId = getLocalStorageItem({
379
+ key: VISITOR_LOCAL_STORAGE_KEY,
380
+ canTrack
381
+ });
382
+ if (checkIsDefined(visitorId)) {
383
+ return visitorId;
384
+ } else {
385
+ const newVisitorId = createVisitorId();
386
+ setVisitorId({
387
+ id: newVisitorId,
388
+ canTrack
389
+ });
390
+ return newVisitorId;
391
+ }
392
+ };
393
+ var createVisitorId = () => uuid();
394
+ var setVisitorId = ({
395
+ id: id2,
396
+ canTrack
397
+ }) => setLocalStorageItem({
398
+ key: VISITOR_LOCAL_STORAGE_KEY,
399
+ value: id2,
400
+ canTrack
401
+ });
402
+
403
+ // src/functions/log-fetch.ts
404
+ function logFetch(url) {
405
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
406
+ if (String(process.env.DEBUG) == "true") {
407
+ logger.log(url);
408
+ }
409
+ }
410
+ }
411
+
412
+ // src/functions/track/index.ts
413
+ var getTrackingEventData = async ({
414
+ canTrack
415
+ }) => {
416
+ if (!canTrack) {
417
+ return {
418
+ visitorId: void 0,
419
+ sessionId: void 0
420
+ };
421
+ }
422
+ const sessionId = await getSessionId({
423
+ canTrack
424
+ });
425
+ const visitorId = getVisitorId({
426
+ canTrack
427
+ });
428
+ return {
429
+ sessionId,
430
+ visitorId
431
+ };
432
+ };
433
+ var createEvent = async ({
434
+ type: eventType,
435
+ canTrack,
436
+ apiKey,
437
+ metadata,
438
+ ...properties
439
+ }) => ({
440
+ type: eventType,
441
+ data: {
442
+ ...properties,
443
+ metadata: {
444
+ url: location.href,
445
+ ...metadata
446
+ },
447
+ ...await getTrackingEventData({
448
+ canTrack
449
+ }),
450
+ userAttributes: getUserAttributes(),
451
+ ownerId: apiKey
452
+ }
453
+ });
454
+ async function _track({
455
+ apiHost,
456
+ ...eventProps
457
+ }) {
458
+ if (!eventProps.apiKey) {
459
+ logger.error("Missing API key for track call. Please provide your API key.");
460
+ return;
461
+ }
462
+ if (!eventProps.canTrack) {
463
+ return;
464
+ }
465
+ if (isEditing()) {
466
+ return;
467
+ }
468
+ if (!(isBrowser() || TARGET === "reactNative")) {
469
+ return;
470
+ }
471
+ const baseUrl = apiHost || "https://cdn.builder.io";
472
+ const url = `${baseUrl}/api/v1/track`;
473
+ logFetch(url);
474
+ return fetch(url, {
475
+ method: "POST",
476
+ body: JSON.stringify({
477
+ events: [await createEvent(eventProps)]
478
+ }),
479
+ headers: {
480
+ "content-type": "application/json",
481
+ ...getSdkHeaders()
482
+ },
483
+ mode: "cors"
484
+ }).catch((err) => {
485
+ });
486
+ }
487
+ var track = (args) => _track({
488
+ ...args,
489
+ canTrack: true
490
+ });
491
+
492
+ // src/functions/evaluate/helpers.ts
493
+ var getFunctionArguments = ({
494
+ builder,
495
+ context,
496
+ event,
497
+ state
498
+ }) => {
499
+ return Object.entries({
500
+ state,
501
+ Builder: builder,
502
+ // legacy
503
+ builder,
504
+ context,
505
+ event
506
+ });
507
+ };
508
+ var getBuilderGlobals = (trackingContext) => ({
509
+ isEditing: isEditing(),
510
+ isBrowser: isBrowser(),
511
+ isServer: !isBrowser(),
512
+ getUserAttributes: () => getUserAttributes(),
513
+ trackConversion: (amount, customProperties) => {
514
+ if (!trackingContext?.apiKey || trackingContext?.canTrack === false) {
515
+ return;
516
+ }
517
+ _track({
518
+ type: "conversion",
519
+ apiKey: trackingContext.apiKey,
520
+ canTrack: trackingContext.canTrack ?? true,
521
+ contentId: trackingContext.contentId,
522
+ variationId: trackingContext.variationId !== trackingContext.contentId ? trackingContext.variationId : void 0,
523
+ metadata: {
524
+ ...customProperties || {},
525
+ ...amount !== void 0 ? {
526
+ amount
527
+ } : {}
528
+ }
529
+ });
530
+ }
531
+ });
532
+ var parseCode = (code, {
533
+ isExpression = true
534
+ }) => {
535
+ const useReturn = (
536
+ // we disable this for cases where we definitely don't want a return
537
+ isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "))
538
+ );
539
+ const useCode = useReturn ? `return (${code});` : code;
540
+ return useCode;
541
+ };
542
+ function flattenState({
543
+ rootState,
544
+ localState,
545
+ rootSetState
546
+ }) {
547
+ return new Proxy(rootState, {
548
+ get: (target, prop) => {
549
+ if (localState && prop in localState) {
550
+ return localState[prop];
551
+ }
552
+ const val = target[prop];
553
+ if (typeof val === "object" && val !== null) {
554
+ return flattenState({
555
+ rootState: val,
556
+ localState: void 0,
557
+ rootSetState: rootSetState ? (subState) => {
558
+ target[prop] = subState;
559
+ rootSetState(target);
560
+ } : void 0
561
+ });
562
+ }
563
+ return val;
564
+ },
565
+ set: (target, prop, value) => {
566
+ if (localState && prop in localState) {
567
+ throw new Error("Writing to local state is not allowed as it is read-only.");
568
+ }
569
+ target[prop] = value;
570
+ rootSetState?.(target);
571
+ return true;
572
+ }
573
+ });
574
+ }
575
+
576
+ // src/functions/evaluate/browser-runtime/browser.ts
577
+ var runInBrowser = ({
578
+ code,
579
+ builder,
580
+ context,
581
+ event,
582
+ localState,
583
+ rootSetState,
584
+ rootState
585
+ }) => {
586
+ const functionArgs = getFunctionArguments({
587
+ builder,
588
+ context,
589
+ event,
590
+ state: flattenState({
591
+ rootState,
592
+ localState,
593
+ rootSetState
594
+ })
595
+ });
596
+ return new Function(...functionArgs.map(([name]) => name), code)(...functionArgs.map(([, value]) => value));
597
+ };
598
+
599
+ // src/functions/evaluate/edge-runtime/acorn-interpreter.ts
600
+ var p;
601
+ var ca = function(a) {
602
+ function b(f) {
603
+ return 48 > f ? 36 === f : 58 > f ? true : 65 > f ? false : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Jc.test(String.fromCharCode(f));
604
+ }
605
+ function d(f) {
606
+ return 65 > f ? 36 === f : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Pb.test(String.fromCharCode(f));
607
+ }
608
+ function c(f, g) {
609
+ var l = r;
610
+ for (var n = 1, w = 0; ; ) {
611
+ Sa.lastIndex = w;
612
+ var J = Sa.exec(l);
613
+ if (J && J.index < f)
614
+ ++n, w = J.index + J[0].length;
615
+ else
616
+ break;
617
+ }
618
+ l = {
619
+ line: n,
620
+ ab: f - w
621
+ };
622
+ g += " (" + l.line + ":" + l.ab + ")";
623
+ g = new SyntaxError(g);
624
+ g.j = f;
625
+ g.X = l;
626
+ g.o = m;
627
+ throw g;
628
+ }
629
+ function e(f) {
630
+ f = f.split(" ");
631
+ for (var g = /* @__PURE__ */ Object.create(null), l = 0; l < f.length; l++)
632
+ g[f[l]] = true;
633
+ return function(n) {
634
+ return g[n] || false;
635
+ };
636
+ }
637
+ function h() {
638
+ this.line = la;
639
+ this.ab = m - X;
640
+ }
641
+ function k(f, g) {
642
+ oa = m;
643
+ z.C && (cb = new h());
644
+ x = f;
357
645
  C();
358
646
  T = g;
359
647
  ya = f.m;
@@ -3483,1116 +3771,854 @@ theFunction();
3483
3771
  return output;
3484
3772
  };
3485
3773
 
3486
- // src/helpers/nullable.ts
3487
- var checkIsDefined = (maybeT) => maybeT !== null && maybeT !== void 0;
3488
-
3489
3774
  // src/functions/is-node-runtime.ts
3490
3775
  function isNodeRuntime() {
3491
3776
  return typeof process !== "undefined" && checkIsDefined(process?.versions?.node);
3492
3777
  }
3493
-
3494
- // src/functions/evaluate/should-force-browser-runtime-in-node.ts
3495
- var shouldForceBrowserRuntimeInNode = ({
3496
- shouldLogWarning
3497
- }) => {
3498
- if (!isNodeRuntime())
3499
- return false;
3500
- const isArm64 = process.arch === "arm64";
3501
- const isNode20 = process.version.startsWith("v20");
3502
- const hasNoNodeSnapshotNodeOption = process.env.NODE_OPTIONS?.includes("--no-node-snapshot");
3503
- if (isArm64 && isNode20 && !hasNoNodeSnapshotNodeOption) {
3504
- if (shouldLogWarning) {
3505
- logger.log(`Skipping usage of \`isolated-vm\` to avoid crashes in Node v20 on an arm64 machine.
3506
- 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.
3507
- See https://github.com/BuilderIO/builder/blob/main/packages/sdks/README.md#node-v20--m1-macs-apple-silicon-support for more information.
3508
- `);
3509
- }
3510
- return true;
3511
- }
3512
- return false;
3513
- };
3514
-
3515
- // src/functions/evaluate/choose-eval.ts
3516
- var chooseBrowserOrServerEval = (args) => isBrowser() || shouldForceBrowserRuntimeInNode({
3517
- shouldLogWarning: true
3518
- }) ? runInBrowser(args) : runInEdge(args);
3519
-
3520
- // src/functions/evaluate/evaluate.ts
3521
- var STATE_GETTER_REGEX = /^(return )?(\s*)?state(?<getPath>(\.\w+)+)(\s*);?$/;
3522
- var VIRTUAL_INDEX_REGEX = /(\s)*var(\s)+_virtual_index(\s)*=(\s)*state(?<getPath>(\.\w+)+)(\s*);?(\s)*return(\s)*_virtual_index(\s)*/;
3523
- var getSimpleExpressionGetPath = (code) => {
3524
- return STATE_GETTER_REGEX.exec(code.trim())?.groups?.getPath?.slice(1) || VIRTUAL_INDEX_REGEX.exec(code.trim())?.groups?.getPath?.slice(1);
3525
- };
3526
- function evaluate({
3527
- code,
3528
- context,
3529
- localState,
3530
- rootState,
3531
- rootSetState,
3532
- event,
3533
- isExpression = true
3534
- }) {
3535
- if (code.trim() === "") {
3536
- return void 0;
3537
- }
3538
- const getPath = getSimpleExpressionGetPath(code.trim());
3539
- if (getPath) {
3540
- return get({
3541
- ...rootState,
3542
- ...localState
3543
- }, getPath);
3544
- }
3545
- const args = {
3546
- code: parseCode(code, {
3547
- isExpression
3548
- }),
3549
- builder: getBuilderGlobals(),
3550
- context,
3551
- event,
3552
- rootSetState,
3553
- rootState,
3554
- localState
3555
- };
3556
- try {
3557
- const newEval = chooseBrowserOrServerEval(args);
3558
- return newEval;
3559
- } catch (e) {
3560
- logger.error("Failed code evaluation: " + e.message, {
3561
- code
3562
- });
3563
- return void 0;
3564
- }
3565
- }
3566
-
3567
- // src/functions/get-block-component-options.ts
3568
- function getBlockComponentOptions(block, context) {
3569
- return {
3570
- ...block.component?.options,
3571
- ...block.options,
3572
- ...evaluateTextComponentTextOption(block, context)
3573
- };
3574
- }
3575
- var evaluateTextComponentTextOption = (block, context) => {
3576
- if (block.component?.name === "Text" && block.component.options?.text && typeof block.component.options.text === "string") {
3577
- return {
3578
- ...block.component.options,
3579
- text: block.component.options.text.replace(/{{([^}]+)}}/g, (_match, group) => evaluate({
3580
- code: group,
3581
- context,
3582
- localState: context.localState,
3583
- rootState: context.rootState,
3584
- rootSetState: context.rootSetState
3585
- }))
3586
- };
3587
- }
3588
- };
3589
-
3590
- // src/helpers/omit.ts
3591
- function omit(obj, ...values) {
3592
- const newObject = Object.assign({}, obj);
3593
- for (const key of values) {
3594
- delete newObject[key];
3595
- }
3596
- return newObject;
3597
- }
3598
-
3599
- // src/functions/traverse.ts
3600
- function traverse(obj, callback, parent2 = null, key = null, visited = /* @__PURE__ */ new WeakSet()) {
3601
- if (obj == null || typeof obj !== "object") {
3602
- callback(obj, (newValue) => {
3603
- if (parent2 !== null && key !== null) {
3604
- parent2[key] = newValue;
3605
- }
3606
- });
3607
- return;
3608
- }
3609
- if (visited.has(obj)) {
3610
- return;
3611
- }
3612
- visited.add(obj);
3613
- if (Array.isArray(obj)) {
3614
- obj.forEach((item, index) => {
3615
- const update = (newValue) => {
3616
- obj[index] = newValue;
3617
- };
3618
- callback(item, update);
3619
- traverse(item, callback, obj, index, visited);
3620
- });
3621
- } else {
3622
- Object.entries(obj).forEach(([key2, value]) => {
3623
- const update = (newValue) => {
3624
- obj[key2] = newValue;
3625
- };
3626
- callback(value, update);
3627
- traverse(value, callback, obj, key2, visited);
3628
- });
3629
- }
3630
- }
3631
-
3632
- // src/functions/extract-localized-values.ts
3633
- function isLocalizedField(value) {
3634
- return value && typeof value === "object" && value["@type"] === "@builder.io/core:LocalizedValue";
3635
- }
3636
- function containsLocalizedValues(data) {
3637
- if (!data || !Object.getOwnPropertyNames(data).length) {
3638
- return false;
3639
- }
3640
- let hasLocalizedValues = false;
3641
- traverse(data, (value) => {
3642
- if (isLocalizedField(value)) {
3643
- hasLocalizedValues = true;
3644
- return;
3645
- }
3646
- });
3647
- return hasLocalizedValues;
3648
- }
3649
- function extractLocalizedValues(data, locale) {
3650
- if (!data || !Object.getOwnPropertyNames(data).length) {
3651
- return {};
3652
- }
3653
- traverse(data, (value, update) => {
3654
- if (isLocalizedField(value)) {
3655
- update(value[locale] ?? void 0);
3656
- }
3657
- });
3658
- return data;
3659
- }
3660
- function resolveLocalizedValues(block, locale) {
3661
- if (block.component?.options && containsLocalizedValues(block.component?.options)) {
3662
- block.component.options = extractLocalizedValues(block.component.options, locale ?? "Default");
3663
- }
3664
- return block;
3665
- }
3666
-
3667
- // src/functions/fast-clone.ts
3668
- var fastClone = (obj) => JSON.parse(JSON.stringify(obj));
3669
-
3670
- // src/functions/set.ts
3671
- var set = (obj, _path, value) => {
3672
- if (Object(obj) !== obj) {
3673
- return obj;
3674
- }
3675
- const path = Array.isArray(_path) ? _path : _path.toString().match(/[^.[\]]+/g);
3676
- path.slice(0, -1).reduce((a, c, i) => Object(a[c]) === a[c] ? a[c] : a[c] = Math.abs(Number(path[i + 1])) >> 0 === +path[i + 1] ? [] : {}, obj)[path[path.length - 1]] = value;
3677
- return obj;
3678
- };
3679
-
3680
- // src/functions/transform-block.ts
3681
- function transformBlock(block) {
3682
- return block;
3683
- }
3684
-
3685
- // src/functions/get-processed-block.ts
3686
- function deepCloneWithConditions(obj) {
3687
- if (obj === null || typeof obj !== "object") {
3688
- return obj;
3689
- }
3690
- if (Array.isArray(obj)) {
3691
- return obj.map((item) => deepCloneWithConditions(item));
3692
- }
3693
- if (obj["@type"] === "@builder.io/sdk:Element") {
3694
- return obj;
3695
- }
3696
- const clonedObj = {};
3697
- for (const key in obj) {
3698
- if (key !== "meta" && Object.prototype.hasOwnProperty.call(obj, key)) {
3699
- clonedObj[key] = deepCloneWithConditions(obj[key]);
3700
- }
3701
- }
3702
- return clonedObj;
3703
- }
3704
- var IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK = ["svelte", "vue", "angular", "qwik", "solid"].includes(TARGET);
3705
- var getCopy = (block) => {
3706
- if (IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK) {
3707
- const copy = fastClone(block);
3708
- const copied = {
3709
- ...copy,
3710
- properties: {
3711
- ...copy.properties
3712
- },
3713
- actions: {
3714
- ...copy.actions
3715
- }
3716
- };
3717
- return copied;
3718
- } else {
3719
- const copy = deepCloneWithConditions(omit(block, "children", "meta"));
3720
- return {
3721
- ...copy,
3722
- properties: {
3723
- ...copy.properties
3724
- },
3725
- actions: {
3726
- ...copy.actions
3727
- },
3728
- children: block.children,
3729
- meta: block.meta
3730
- };
3731
- }
3732
- };
3733
- var evaluateBindings = ({
3734
- block,
3735
- context,
3736
- localState,
3737
- rootState,
3738
- rootSetState
3739
- }) => {
3740
- if (!block.bindings) {
3741
- return block;
3742
- }
3743
- const copied = getCopy(block);
3744
- for (const binding in block.bindings) {
3745
- const expression = block.bindings[binding];
3746
- const value = evaluate({
3747
- code: expression,
3748
- localState,
3749
- rootState,
3750
- rootSetState,
3751
- context
3752
- });
3753
- set(copied, binding, value);
3754
- }
3755
- return copied;
3756
- };
3757
- function getProcessedBlock({
3758
- block,
3759
- context,
3760
- localState,
3761
- rootState,
3762
- rootSetState
3763
- }) {
3764
- let transformedBlock = transformBlock(block);
3765
- transformedBlock = evaluateBindings({
3766
- block: transformedBlock,
3767
- localState,
3768
- rootState,
3769
- rootSetState,
3770
- context
3771
- });
3772
- transformedBlock = resolveLocalizedValues(transformedBlock, rootState.locale);
3773
- return transformedBlock;
3774
- }
3775
-
3776
- // src/functions/camel-to-kebab-case.ts
3777
- var camelToKebabCase = (str) => str ? str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase() : "";
3778
-
3779
- // src/components/block/animator.ts
3780
- function throttle(func, wait, options = {}) {
3781
- let context;
3782
- let args;
3783
- let result;
3784
- let timeout = null;
3785
- let previous = 0;
3786
- const later = function() {
3787
- previous = options.leading === false ? 0 : Date.now();
3788
- timeout = null;
3789
- result = func.apply(context, args);
3790
- if (!timeout)
3791
- context = args = null;
3792
- };
3793
- return function() {
3794
- const now = Date.now();
3795
- if (!previous && options.leading === false)
3796
- previous = now;
3797
- const remaining = wait - (now - previous);
3798
- context = this;
3799
- args = arguments;
3800
- if (remaining <= 0 || remaining > wait) {
3801
- if (timeout) {
3802
- clearTimeout(timeout);
3803
- timeout = null;
3804
- }
3805
- previous = now;
3806
- result = func.apply(context, args);
3807
- if (!timeout)
3808
- context = args = null;
3809
- } else if (!timeout && options.trailing !== false) {
3810
- timeout = setTimeout(later, remaining);
3811
- }
3812
- return result;
3813
- };
3814
- }
3815
- function assign(target, ..._args) {
3816
- const to = Object(target);
3817
- for (let index = 1; index < arguments.length; index++) {
3818
- const nextSource = arguments[index];
3819
- if (nextSource != null) {
3820
- for (const nextKey in nextSource) {
3821
- if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
3822
- to[nextKey] = nextSource[nextKey];
3823
- }
3824
- }
3825
- }
3826
- }
3827
- return to;
3828
- }
3829
- function bindAnimations(animations) {
3830
- if (TARGET === "reactNative") {
3831
- return;
3832
- }
3833
- for (const animation of animations) {
3834
- switch (animation.trigger) {
3835
- case "pageLoad":
3836
- triggerAnimation(animation);
3837
- break;
3838
- case "scrollInView":
3839
- bindScrollInViewAnimation(animation);
3840
- break;
3841
- }
3842
- }
3843
- }
3844
- function warnElementNotPresent(id2) {
3845
- }
3846
- function augmentAnimation(animation, element) {
3847
- const stylesUsed = getAllStylesUsed(animation);
3848
- const computedStyle = getComputedStyle(element);
3849
- const firstStyles = animation.steps[0].styles;
3850
- const lastStyles = animation.steps[animation.steps.length - 1].styles;
3851
- const bothStyles = [firstStyles, lastStyles];
3852
- for (const styles of bothStyles) {
3853
- for (const style of stylesUsed) {
3854
- if (!(style in styles)) {
3855
- styles[style] = computedStyle[style];
3856
- }
3857
- }
3858
- }
3859
- }
3860
- function getAllStylesUsed(animation) {
3861
- const properties = [];
3862
- for (const step of animation.steps) {
3863
- for (const key in step.styles) {
3864
- if (properties.indexOf(key) === -1) {
3865
- properties.push(key);
3866
- }
3867
- }
3868
- }
3869
- return properties;
3870
- }
3871
- function triggerAnimation(animation) {
3872
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
3873
- if (!elements.length) {
3874
- warnElementNotPresent(animation.elementId || animation.id || "");
3875
- return;
3876
- }
3877
- Array.from(elements).forEach((element) => {
3878
- augmentAnimation(animation, element);
3879
- element.style.transition = "none";
3880
- element.style.transitionDelay = "0";
3881
- assign(element.style, animation.steps[0].styles);
3882
- setTimeout(() => {
3883
- element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
3884
- if (animation.delay) {
3885
- element.style.transitionDelay = animation.delay + "s";
3886
- }
3887
- assign(element.style, animation.steps[1].styles);
3888
- setTimeout(() => {
3889
- element.style.transition = "";
3890
- element.style.transitionDelay = "";
3891
- }, (animation.delay || 0) * 1e3 + animation.duration * 1e3 + 100);
3892
- });
3893
- });
3894
- }
3895
- function bindScrollInViewAnimation(animation) {
3896
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
3897
- if (!elements.length) {
3898
- warnElementNotPresent(animation.elementId || animation.id || "");
3899
- return;
3900
- }
3901
- Array.from(elements).forEach((element) => {
3902
- augmentAnimation(animation, element);
3903
- let triggered = false;
3904
- let pendingAnimation = false;
3905
- function immediateOnScroll() {
3906
- if (!triggered && isScrolledIntoView(element)) {
3907
- triggered = true;
3908
- pendingAnimation = true;
3909
- setTimeout(() => {
3910
- assign(element.style, animation.steps[1].styles);
3911
- if (!animation.repeat) {
3912
- document.removeEventListener("scroll", onScroll);
3913
- }
3914
- setTimeout(() => {
3915
- pendingAnimation = false;
3916
- if (!animation.repeat) {
3917
- element.style.transition = "";
3918
- element.style.transitionDelay = "";
3919
- }
3920
- }, (animation.duration + (animation.delay || 0)) * 1e3 + 100);
3921
- });
3922
- } else if (animation.repeat && triggered && !pendingAnimation && !isScrolledIntoView(element)) {
3923
- triggered = false;
3924
- assign(element.style, animation.steps[0].styles);
3925
- }
3926
- }
3927
- const onScroll = throttle(immediateOnScroll, 200, {
3928
- leading: false
3929
- });
3930
- function isScrolledIntoView(elem) {
3931
- const rect = elem.getBoundingClientRect();
3932
- const windowHeight = window.innerHeight;
3933
- const thresholdPercent = (animation.thresholdPercent || 0) / 100;
3934
- const threshold = thresholdPercent * windowHeight;
3935
- return rect.bottom > threshold && rect.top < windowHeight - threshold;
3936
- }
3937
- const defaultState = animation.steps[0].styles;
3938
- function attachDefaultState() {
3939
- assign(element.style, defaultState);
3940
- }
3941
- attachDefaultState();
3942
- setTimeout(() => {
3943
- element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
3944
- if (animation.delay) {
3945
- element.style.transitionDelay = animation.delay + "s";
3946
- }
3947
- });
3948
- document.addEventListener("scroll", onScroll, {
3949
- capture: true,
3950
- passive: true
3951
- });
3952
- immediateOnScroll();
3953
- });
3954
- }
3955
-
3956
- // src/helpers/css.ts
3957
- var convertStyleMapToCSSArray = (style) => {
3958
- const cssProps = Object.entries(style).map(([key, value]) => {
3959
- if (typeof value === "string") {
3960
- return `${camelToKebabCase(key)}: ${value};`;
3961
- } else {
3962
- return void 0;
3963
- }
3964
- });
3965
- return cssProps.filter(checkIsDefined);
3966
- };
3967
- var convertStyleMapToCSS = (style) => convertStyleMapToCSSArray(style).join("\n");
3968
- var createCssClass = ({
3969
- mediaQuery,
3970
- className,
3971
- styles
3778
+
3779
+ // src/functions/evaluate/should-force-browser-runtime-in-node.ts
3780
+ var shouldForceBrowserRuntimeInNode = ({
3781
+ shouldLogWarning
3972
3782
  }) => {
3973
- const cssClass = `.${className} {
3974
- ${convertStyleMapToCSS(styles)}
3975
- }`;
3976
- if (mediaQuery) {
3977
- return `${mediaQuery} {
3978
- ${cssClass}
3979
- }`;
3980
- } else {
3981
- return cssClass;
3783
+ if (!isNodeRuntime())
3784
+ return false;
3785
+ const isArm64 = process.arch === "arm64";
3786
+ const isNode20 = process.version.startsWith("v20");
3787
+ const hasNoNodeSnapshotNodeOption = process.env.NODE_OPTIONS?.includes("--no-node-snapshot");
3788
+ if (isArm64 && isNode20 && !hasNoNodeSnapshotNodeOption) {
3789
+ if (shouldLogWarning) {
3790
+ logger.log(`Skipping usage of \`isolated-vm\` to avoid crashes in Node v20 on an arm64 machine.
3791
+ 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.
3792
+ See https://github.com/BuilderIO/builder/blob/main/packages/sdks/README.md#node-v20--m1-macs-apple-silicon-support for more information.
3793
+ `);
3794
+ }
3795
+ return true;
3982
3796
  }
3797
+ return false;
3983
3798
  };
3984
3799
 
3985
- // src/functions/transform-style-property.ts
3986
- function transformStyleProperty({
3987
- style
3800
+ // src/functions/evaluate/choose-eval.ts
3801
+ var chooseBrowserOrServerEval = (args) => isBrowser() || shouldForceBrowserRuntimeInNode({
3802
+ shouldLogWarning: true
3803
+ }) ? runInBrowser(args) : runInEdge(args);
3804
+
3805
+ // src/functions/evaluate/evaluate.ts
3806
+ var STATE_GETTER_REGEX = /^(return )?(\s*)?state(?<getPath>(\.\w+)+)(\s*);?$/;
3807
+ var VIRTUAL_INDEX_REGEX = /(\s)*var(\s)+_virtual_index(\s)*=(\s)*state(?<getPath>(\.\w+)+)(\s*);?(\s)*return(\s)*_virtual_index(\s)*/;
3808
+ var getSimpleExpressionGetPath = (code) => {
3809
+ return STATE_GETTER_REGEX.exec(code.trim())?.groups?.getPath?.slice(1) || VIRTUAL_INDEX_REGEX.exec(code.trim())?.groups?.getPath?.slice(1);
3810
+ };
3811
+ function evaluate({
3812
+ code,
3813
+ context,
3814
+ localState,
3815
+ rootState,
3816
+ rootSetState,
3817
+ event,
3818
+ isExpression = true,
3819
+ trackingContext
3988
3820
  }) {
3989
- return style;
3821
+ if (code.trim() === "") {
3822
+ return void 0;
3823
+ }
3824
+ const getPath = getSimpleExpressionGetPath(code.trim());
3825
+ if (getPath) {
3826
+ return get({
3827
+ ...rootState,
3828
+ ...localState
3829
+ }, getPath);
3830
+ }
3831
+ const args = {
3832
+ code: parseCode(code, {
3833
+ isExpression
3834
+ }),
3835
+ builder: getBuilderGlobals(trackingContext),
3836
+ context,
3837
+ event,
3838
+ rootSetState,
3839
+ rootState,
3840
+ localState
3841
+ };
3842
+ try {
3843
+ const newEval = chooseBrowserOrServerEval(args);
3844
+ return newEval;
3845
+ } catch (e) {
3846
+ logger.error("Failed code evaluation: " + e.message, {
3847
+ code
3848
+ });
3849
+ return void 0;
3850
+ }
3990
3851
  }
3991
3852
 
3992
- // src/functions/get-style.ts
3993
- var getStyle = ({
3994
- block,
3995
- context
3996
- }) => {
3997
- return mapStyleObjToStrIfNeeded(transformStyleProperty({
3998
- style: block.style || {},
3999
- context,
4000
- block
4001
- }));
3853
+ // src/functions/get-block-component-options.ts
3854
+ function getBlockComponentOptions(block, context) {
3855
+ return {
3856
+ ...block.component?.options,
3857
+ ...block.options,
3858
+ ...evaluateTextComponentTextOption(block, context)
3859
+ };
3860
+ }
3861
+ var evaluateTextComponentTextOption = (block, context) => {
3862
+ if (block.component?.name === "Text" && block.component.options?.text && typeof block.component.options.text === "string") {
3863
+ return {
3864
+ ...block.component.options,
3865
+ text: block.component.options.text.replace(/{{([^}]+)}}/g, (_match, group) => evaluate({
3866
+ code: group,
3867
+ context,
3868
+ localState: context.localState,
3869
+ rootState: context.rootState,
3870
+ rootSetState: context.rootSetState
3871
+ }))
3872
+ };
3873
+ }
4002
3874
  };
4003
- function mapStyleObjToStrIfNeeded(style) {
4004
- switch (TARGET) {
4005
- case "svelte":
4006
- case "vue":
4007
- case "solid":
4008
- case "angular":
4009
- return convertStyleMapToCSSArray(style).join(" ");
4010
- case "qwik":
4011
- case "reactNative":
4012
- case "react":
4013
- case "rsc":
4014
- return style;
3875
+
3876
+ // src/helpers/omit.ts
3877
+ function omit(obj, ...values) {
3878
+ const newObject = Object.assign({}, obj);
3879
+ for (const key of values) {
3880
+ delete newObject[key];
4015
3881
  }
3882
+ return newObject;
4016
3883
  }
4017
3884
 
4018
- // src/components/block/block.helpers.ts
4019
- var checkIsComponentRestricted = (component, model) => {
4020
- if (!component)
4021
- return true;
4022
- if (!model)
4023
- return false;
4024
- return component.models && component.models.length > 0 && !component.models.includes(model);
4025
- };
4026
- var getComponent = ({
4027
- block,
4028
- registeredComponents,
4029
- model
4030
- }) => {
4031
- const componentName = block.component?.name;
4032
- if (!componentName) {
4033
- return null;
3885
+ // src/functions/traverse.ts
3886
+ function traverse(obj, callback, parent2 = null, key = null, visited = /* @__PURE__ */ new WeakSet()) {
3887
+ if (obj == null || typeof obj !== "object") {
3888
+ callback(obj, (newValue) => {
3889
+ if (parent2 !== null && key !== null) {
3890
+ parent2[key] = newValue;
3891
+ }
3892
+ });
3893
+ return;
4034
3894
  }
4035
- const ref = registeredComponents[componentName];
4036
- if (!ref || checkIsComponentRestricted(ref, model)) {
4037
- return void 0;
3895
+ if (visited.has(obj)) {
3896
+ return;
3897
+ }
3898
+ visited.add(obj);
3899
+ if (Array.isArray(obj)) {
3900
+ obj.forEach((item, index) => {
3901
+ const update = (newValue) => {
3902
+ obj[index] = newValue;
3903
+ };
3904
+ callback(item, update);
3905
+ traverse(item, callback, obj, index, visited);
3906
+ });
4038
3907
  } else {
4039
- return ref;
3908
+ Object.entries(obj).forEach(([key2, value]) => {
3909
+ const update = (newValue) => {
3910
+ obj[key2] = newValue;
3911
+ };
3912
+ callback(value, update);
3913
+ traverse(value, callback, obj, key2, visited);
3914
+ });
4040
3915
  }
4041
- };
4042
- var getRepeatItemData = ({
4043
- block,
4044
- context
4045
- }) => {
4046
- const {
4047
- repeat,
4048
- ...blockWithoutRepeat
4049
- } = block;
4050
- if (!repeat?.collection) {
4051
- return void 0;
3916
+ }
3917
+
3918
+ // src/functions/extract-localized-values.ts
3919
+ function isLocalizedField(value) {
3920
+ return value && typeof value === "object" && value["@type"] === "@builder.io/core:LocalizedValue";
3921
+ }
3922
+ function containsLocalizedValues(data) {
3923
+ if (!data || !Object.getOwnPropertyNames(data).length) {
3924
+ return false;
4052
3925
  }
4053
- const itemsArray = evaluate({
4054
- code: repeat.collection,
4055
- localState: context.localState,
4056
- rootState: context.rootState,
4057
- rootSetState: context.rootSetState,
4058
- context: context.context
3926
+ let hasLocalizedValues = false;
3927
+ traverse(data, (value) => {
3928
+ if (isLocalizedField(value)) {
3929
+ hasLocalizedValues = true;
3930
+ return;
3931
+ }
4059
3932
  });
4060
- if (!Array.isArray(itemsArray)) {
4061
- return void 0;
3933
+ return hasLocalizedValues;
3934
+ }
3935
+ function extractLocalizedValues(data, locale) {
3936
+ if (!data || !Object.getOwnPropertyNames(data).length) {
3937
+ return {};
4062
3938
  }
4063
- const collectionName = repeat.collection.split(".").pop();
4064
- const itemNameToUse = repeat.itemName || (collectionName ? collectionName + "Item" : "item");
4065
- const repeatArray = itemsArray.map((item, index) => ({
4066
- context: {
4067
- ...context,
4068
- localState: {
4069
- ...context.localState,
4070
- $index: index,
4071
- $item: item,
4072
- [itemNameToUse]: item,
4073
- [`$${itemNameToUse}Index`]: index
4074
- }
4075
- },
4076
- block: blockWithoutRepeat
4077
- }));
4078
- return repeatArray;
4079
- };
4080
- var provideLinkComponent = (block, linkComponent) => {
4081
- if (block?.shouldReceiveBuilderProps?.builderLinkComponent)
4082
- return {
4083
- builderLinkComponent: linkComponent
4084
- };
4085
- return {};
4086
- };
4087
- var provideRegisteredComponents = (block, registeredComponents, model) => {
4088
- if (block?.shouldReceiveBuilderProps?.builderComponents) {
4089
- const filteredRegisteredComponents = Object.fromEntries(Object.entries(registeredComponents).filter(([_, component]) => {
4090
- return !checkIsComponentRestricted(component, model);
4091
- }));
4092
- return {
4093
- builderComponents: filteredRegisteredComponents
4094
- };
3939
+ traverse(data, (value, update) => {
3940
+ if (isLocalizedField(value)) {
3941
+ update(value[locale] ?? void 0);
3942
+ }
3943
+ });
3944
+ return data;
3945
+ }
3946
+ function resolveLocalizedValues(block, locale) {
3947
+ if (block.component?.options && containsLocalizedValues(block.component?.options)) {
3948
+ block.component.options = extractLocalizedValues(block.component.options, locale ?? "Default");
4095
3949
  }
4096
- return {};
4097
- };
4098
- var provideBuilderBlock = (block, builderBlock) => {
4099
- if (block?.shouldReceiveBuilderProps?.builderBlock)
4100
- return {
4101
- builderBlock
4102
- };
4103
- return {};
4104
- };
4105
- var provideBuilderContext = (block, context) => {
4106
- if (block?.shouldReceiveBuilderProps?.builderContext)
4107
- return {
4108
- builderContext: context
4109
- };
4110
- return {};
4111
- };
4112
- var generateKey = (index) => {
4113
- return index.toString();
4114
- };
4115
-
4116
- // src/functions/event-handler-name.ts
4117
- function capitalizeFirstLetter(string) {
4118
- return string.charAt(0).toUpperCase() + string.slice(1);
3950
+ return block;
4119
3951
  }
4120
- var getEventHandlerName = (key) => `on${capitalizeFirstLetter(key)}`;
4121
3952
 
4122
- // src/functions/get-block-actions-handler.ts
4123
- var createEventHandler = (value, options) => (event) => evaluate({
4124
- code: value,
4125
- context: options.context,
4126
- localState: options.localState,
4127
- rootState: options.rootState,
4128
- rootSetState: options.rootSetState,
4129
- event,
4130
- isExpression: false
4131
- });
3953
+ // src/functions/fast-clone.ts
3954
+ var fastClone = (obj) => JSON.parse(JSON.stringify(obj));
4132
3955
 
4133
- // src/functions/get-block-actions.ts
4134
- function getBlockActions(options) {
4135
- const obj = {};
4136
- const optionActions = options.block.actions ?? {};
4137
- for (const key in optionActions) {
4138
- if (!optionActions.hasOwnProperty(key)) {
4139
- continue;
4140
- }
4141
- const value = optionActions[key];
4142
- let eventHandlerName = getEventHandlerName(key);
4143
- if (options.stripPrefix) {
4144
- switch (TARGET) {
4145
- case "vue":
4146
- eventHandlerName = eventHandlerName.replace("v-on:", "");
4147
- break;
4148
- case "svelte":
4149
- eventHandlerName = eventHandlerName.replace("on:", "");
4150
- break;
4151
- }
4152
- }
4153
- obj[eventHandlerName] = createEventHandler(value, options);
3956
+ // src/functions/set.ts
3957
+ var set = (obj, _path, value) => {
3958
+ if (Object(obj) !== obj) {
3959
+ return obj;
4154
3960
  }
3961
+ const path = Array.isArray(_path) ? _path : _path.toString().match(/[^.[\]]+/g);
3962
+ path.slice(0, -1).reduce((a, c, i) => Object(a[c]) === a[c] ? a[c] : a[c] = Math.abs(Number(path[i + 1])) >> 0 === +path[i + 1] ? [] : {}, obj)[path[path.length - 1]] = value;
4155
3963
  return obj;
4156
- }
3964
+ };
4157
3965
 
4158
- // src/functions/transform-block-properties.ts
4159
- function transformBlockProperties({
4160
- properties
4161
- }) {
4162
- return properties;
3966
+ // src/functions/transform-block.ts
3967
+ function transformBlock(block) {
3968
+ return block;
4163
3969
  }
4164
3970
 
4165
- // src/functions/get-block-properties.ts
4166
- var extractRelevantRootBlockProperties = (block) => {
4167
- return {
4168
- href: block.href
4169
- };
3971
+ // src/functions/get-processed-block.ts
3972
+ function deepCloneWithConditions(obj) {
3973
+ if (obj === null || typeof obj !== "object") {
3974
+ return obj;
3975
+ }
3976
+ if (Array.isArray(obj)) {
3977
+ return obj.map((item) => deepCloneWithConditions(item));
3978
+ }
3979
+ if (obj["@type"] === "@builder.io/sdk:Element") {
3980
+ return obj;
3981
+ }
3982
+ const clonedObj = {};
3983
+ for (const key in obj) {
3984
+ if (key !== "meta" && Object.prototype.hasOwnProperty.call(obj, key)) {
3985
+ clonedObj[key] = deepCloneWithConditions(obj[key]);
3986
+ }
3987
+ }
3988
+ return clonedObj;
3989
+ }
3990
+ var IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK = ["svelte", "vue", "angular", "qwik", "solid"].includes(TARGET);
3991
+ var getCopy = (block) => {
3992
+ if (IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK) {
3993
+ const copy = fastClone(block);
3994
+ const copied = {
3995
+ ...copy,
3996
+ properties: {
3997
+ ...copy.properties
3998
+ },
3999
+ actions: {
4000
+ ...copy.actions
4001
+ }
4002
+ };
4003
+ return copied;
4004
+ } else {
4005
+ const copy = deepCloneWithConditions(omit(block, "children", "meta"));
4006
+ return {
4007
+ ...copy,
4008
+ properties: {
4009
+ ...copy.properties
4010
+ },
4011
+ actions: {
4012
+ ...copy.actions
4013
+ },
4014
+ children: block.children,
4015
+ meta: block.meta
4016
+ };
4017
+ }
4170
4018
  };
4171
- function getBlockProperties({
4019
+ var evaluateBindings = ({
4172
4020
  block,
4173
- context
4174
- }) {
4175
- const properties = {
4176
- ...extractRelevantRootBlockProperties(block),
4177
- ...block.properties,
4178
- "builder-id": block.id,
4179
- style: getStyle({
4180
- block,
4021
+ context,
4022
+ localState,
4023
+ rootState,
4024
+ rootSetState
4025
+ }) => {
4026
+ if (!block.bindings) {
4027
+ return block;
4028
+ }
4029
+ const copied = getCopy(block);
4030
+ for (const binding in block.bindings) {
4031
+ const expression = block.bindings[binding];
4032
+ const value = evaluate({
4033
+ code: expression,
4034
+ localState,
4035
+ rootState,
4036
+ rootSetState,
4181
4037
  context
4182
- }),
4183
- [getClassPropName()]: [block.id, "builder-block", block.class, block.properties?.class].filter(Boolean).join(" ")
4184
- };
4185
- return transformBlockProperties({
4186
- properties,
4187
- context,
4188
- block
4189
- });
4190
- }
4191
-
4192
- // src/components/block/components/block-wrapper.tsx
4193
- function BlockWrapper(props) {
4194
- return createComponent(dynamic_renderer_default, {
4195
- get TagName() {
4196
- return props.Wrapper;
4197
- },
4198
- get attributes() {
4199
- return getBlockProperties({
4200
- block: props.block,
4201
- context: props.context
4202
- });
4203
- },
4204
- get actionAttributes() {
4205
- return getBlockActions({
4206
- block: props.block,
4207
- rootState: props.context.rootState,
4208
- rootSetState: props.context.rootSetState,
4209
- localState: props.context.localState,
4210
- context: props.context.context,
4211
- stripPrefix: true
4212
- });
4213
- },
4214
- get children() {
4215
- return props.children;
4216
- }
4038
+ });
4039
+ set(copied, binding, value);
4040
+ }
4041
+ return copied;
4042
+ };
4043
+ function getProcessedBlock({
4044
+ block,
4045
+ context,
4046
+ localState,
4047
+ rootState,
4048
+ rootSetState
4049
+ }) {
4050
+ let transformedBlock = transformBlock(block);
4051
+ transformedBlock = evaluateBindings({
4052
+ block: transformedBlock,
4053
+ localState,
4054
+ rootState,
4055
+ rootSetState,
4056
+ context
4217
4057
  });
4058
+ transformedBlock = resolveLocalizedValues(transformedBlock, rootState.locale);
4059
+ return transformedBlock;
4218
4060
  }
4219
- var block_wrapper_default = BlockWrapper;
4220
4061
 
4221
- // src/functions/is-previewing.ts
4222
- function isPreviewing(search) {
4223
- const searchToUse = search || (isBrowser() ? window.location.search : void 0);
4224
- if (!searchToUse) {
4225
- return false;
4226
- }
4227
- const normalizedSearch = getSearchString(searchToUse);
4228
- return Boolean(normalizedSearch.indexOf("builder.preview=") !== -1);
4229
- }
4062
+ // src/functions/camel-to-kebab-case.ts
4063
+ var camelToKebabCase = (str) => str ? str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase() : "";
4230
4064
 
4231
- // src/functions/register-component.ts
4232
- var createRegisterComponentMessage = (info) => ({
4233
- type: "builder.registerComponent",
4234
- data: serializeIncludingFunctions(info)
4235
- });
4236
- var serializeFn = (fnValue) => {
4237
- const fnStr = fnValue.toString().trim();
4238
- const isArrowWithoutParens = /^[a-zA-Z0-9_]+\s*=>/i.test(fnStr);
4239
- const appendFunction = !fnStr.startsWith("function") && !fnStr.startsWith("async") && !fnStr.startsWith("(") && !isArrowWithoutParens;
4240
- return `return (${appendFunction ? "function " : ""}${fnStr}).apply(this, arguments)`;
4241
- };
4242
- function serializeIncludingFunctions(info) {
4243
- return JSON.parse(JSON.stringify(info, (key, value) => {
4244
- if (typeof value === "function") {
4245
- return serializeFn(value);
4065
+ // src/components/block/animator.ts
4066
+ function throttle(func, wait, options = {}) {
4067
+ let context;
4068
+ let args;
4069
+ let result;
4070
+ let timeout = null;
4071
+ let previous = 0;
4072
+ const later = function() {
4073
+ previous = options.leading === false ? 0 : Date.now();
4074
+ timeout = null;
4075
+ result = func.apply(context, args);
4076
+ if (!timeout)
4077
+ context = args = null;
4078
+ };
4079
+ return function() {
4080
+ const now = Date.now();
4081
+ if (!previous && options.leading === false)
4082
+ previous = now;
4083
+ const remaining = wait - (now - previous);
4084
+ context = this;
4085
+ args = arguments;
4086
+ if (remaining <= 0 || remaining > wait) {
4087
+ if (timeout) {
4088
+ clearTimeout(timeout);
4089
+ timeout = null;
4090
+ }
4091
+ previous = now;
4092
+ result = func.apply(context, args);
4093
+ if (!timeout)
4094
+ context = args = null;
4095
+ } else if (!timeout && options.trailing !== false) {
4096
+ timeout = setTimeout(later, remaining);
4246
4097
  }
4247
- return value;
4248
- }));
4098
+ return result;
4099
+ };
4249
4100
  }
4250
-
4251
- // src/functions/register.ts
4252
- var registry = {};
4253
- function register(type, info) {
4254
- if (type === "plugin") {
4255
- info = serializeIncludingFunctions(info);
4256
- }
4257
- let typeList = registry[type];
4258
- if (!typeList) {
4259
- typeList = registry[type] = [];
4260
- }
4261
- typeList.push(info);
4262
- if (isBrowser()) {
4263
- const message = {
4264
- type: "builder.register",
4265
- data: {
4266
- type,
4267
- info
4268
- }
4269
- };
4270
- try {
4271
- parent.postMessage(message, "*");
4272
- if (parent !== window) {
4273
- window.postMessage(message, "*");
4101
+ function assign(target, ..._args) {
4102
+ const to = Object(target);
4103
+ for (let index = 1; index < arguments.length; index++) {
4104
+ const nextSource = arguments[index];
4105
+ if (nextSource != null) {
4106
+ for (const nextKey in nextSource) {
4107
+ if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
4108
+ to[nextKey] = nextSource[nextKey];
4109
+ }
4274
4110
  }
4275
- } catch (err) {
4276
4111
  }
4277
4112
  }
4113
+ return to;
4278
4114
  }
4279
- function registerAction(action) {
4280
- if (isBrowser()) {
4281
- const actionClone = JSON.parse(JSON.stringify(action));
4282
- if (action.action) {
4283
- actionClone.action = action.action.toString();
4115
+ function bindAnimations(animations) {
4116
+ if (TARGET === "reactNative") {
4117
+ return;
4118
+ }
4119
+ for (const animation of animations) {
4120
+ switch (animation.trigger) {
4121
+ case "pageLoad":
4122
+ triggerAnimation(animation);
4123
+ break;
4124
+ case "scrollInView":
4125
+ bindScrollInViewAnimation(animation);
4126
+ break;
4284
4127
  }
4285
- window.parent?.postMessage({
4286
- type: "builder.registerAction",
4287
- data: actionClone
4288
- }, "*");
4289
4128
  }
4290
4129
  }
4291
-
4292
- // src/functions/set-editor-settings.ts
4293
- var settings = {};
4294
- function setEditorSettings(newSettings) {
4295
- if (isBrowser()) {
4296
- Object.assign(settings, newSettings);
4297
- const message = {
4298
- type: "builder.settingsChange",
4299
- data: settings
4300
- };
4301
- parent.postMessage(message, "*");
4302
- }
4130
+ function warnElementNotPresent(id2) {
4303
4131
  }
4304
-
4305
- // src/functions/get-builder-search-params/index.ts
4306
- var BUILDER_SEARCHPARAMS_PREFIX = "builder.";
4307
- var BUILDER_OPTIONS_PREFIX = "options.";
4308
- var getBuilderSearchParams = (_options) => {
4309
- if (!_options) {
4310
- return {};
4132
+ function augmentAnimation(animation, element) {
4133
+ const stylesUsed = getAllStylesUsed(animation);
4134
+ const computedStyle = getComputedStyle(element);
4135
+ const firstStyles = animation.steps[0].styles;
4136
+ const lastStyles = animation.steps[animation.steps.length - 1].styles;
4137
+ const bothStyles = [firstStyles, lastStyles];
4138
+ for (const styles of bothStyles) {
4139
+ for (const style of stylesUsed) {
4140
+ if (!(style in styles)) {
4141
+ styles[style] = computedStyle[style];
4142
+ }
4143
+ }
4311
4144
  }
4312
- const options = normalizeSearchParams(_options);
4313
- const newOptions = {};
4314
- Object.keys(options).forEach((key) => {
4315
- if (key.startsWith(BUILDER_SEARCHPARAMS_PREFIX)) {
4316
- const trimmedKey = key.replace(BUILDER_SEARCHPARAMS_PREFIX, "").replace(BUILDER_OPTIONS_PREFIX, "");
4317
- newOptions[trimmedKey] = options[key];
4145
+ }
4146
+ function getAllStylesUsed(animation) {
4147
+ const properties = [];
4148
+ for (const step of animation.steps) {
4149
+ for (const key in step.styles) {
4150
+ if (properties.indexOf(key) === -1) {
4151
+ properties.push(key);
4152
+ }
4318
4153
  }
4319
- });
4320
- return newOptions;
4321
- };
4322
- var getBuilderSearchParamsFromWindow = () => {
4323
- if (!isBrowser()) {
4324
- return {};
4325
4154
  }
4326
- const searchParams = new URLSearchParams(window.location.search);
4327
- return getBuilderSearchParams(searchParams);
4328
- };
4329
-
4330
- // src/constants/sdk-version.ts
4331
- var SDK_VERSION = "5.0.1";
4332
-
4333
- // src/helpers/sdk-headers.ts
4334
- var getSdkHeaders = () => ({
4335
- "X-Builder-SDK": TARGET,
4336
- "X-Builder-SDK-GEN": "2",
4337
- "X-Builder-SDK-Version": SDK_VERSION
4338
- });
4339
-
4340
- // src/helpers/url.ts
4341
- var getTopLevelDomain = (host) => {
4342
- if (host === "localhost" || host === "127.0.0.1") {
4343
- return host;
4155
+ return properties;
4156
+ }
4157
+ function triggerAnimation(animation) {
4158
+ const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
4159
+ if (!elements.length) {
4160
+ warnElementNotPresent(animation.elementId || animation.id || "");
4161
+ return;
4344
4162
  }
4345
- const parts = host.split(".");
4346
- if (parts.length > 2) {
4347
- return parts.slice(1).join(".");
4163
+ Array.from(elements).forEach((element) => {
4164
+ augmentAnimation(animation, element);
4165
+ element.style.transition = "none";
4166
+ element.style.transitionDelay = "0";
4167
+ assign(element.style, animation.steps[0].styles);
4168
+ setTimeout(() => {
4169
+ element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
4170
+ if (animation.delay) {
4171
+ element.style.transitionDelay = animation.delay + "s";
4172
+ }
4173
+ assign(element.style, animation.steps[1].styles);
4174
+ setTimeout(() => {
4175
+ element.style.transition = "";
4176
+ element.style.transitionDelay = "";
4177
+ }, (animation.delay || 0) * 1e3 + animation.duration * 1e3 + 100);
4178
+ });
4179
+ });
4180
+ }
4181
+ function bindScrollInViewAnimation(animation) {
4182
+ const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
4183
+ if (!elements.length) {
4184
+ warnElementNotPresent(animation.elementId || animation.id || "");
4185
+ return;
4348
4186
  }
4349
- return host;
4350
- };
4351
-
4352
- // src/helpers/cookie.ts
4353
- var getCookieSync = ({
4354
- name,
4355
- canTrack
4356
- }) => {
4357
- try {
4358
- if (!canTrack) {
4359
- return void 0;
4187
+ Array.from(elements).forEach((element) => {
4188
+ augmentAnimation(animation, element);
4189
+ let triggered = false;
4190
+ let pendingAnimation = false;
4191
+ function immediateOnScroll() {
4192
+ if (!triggered && isScrolledIntoView(element)) {
4193
+ triggered = true;
4194
+ pendingAnimation = true;
4195
+ setTimeout(() => {
4196
+ assign(element.style, animation.steps[1].styles);
4197
+ if (!animation.repeat) {
4198
+ document.removeEventListener("scroll", onScroll);
4199
+ }
4200
+ setTimeout(() => {
4201
+ pendingAnimation = false;
4202
+ if (!animation.repeat) {
4203
+ element.style.transition = "";
4204
+ element.style.transitionDelay = "";
4205
+ }
4206
+ }, (animation.duration + (animation.delay || 0)) * 1e3 + 100);
4207
+ });
4208
+ } else if (animation.repeat && triggered && !pendingAnimation && !isScrolledIntoView(element)) {
4209
+ triggered = false;
4210
+ assign(element.style, animation.steps[0].styles);
4211
+ }
4360
4212
  }
4361
- return document.cookie.split("; ").find((row) => row.startsWith(`${name}=`))?.split("=")[1];
4362
- } catch (err) {
4363
- logger.warn("[COOKIE] GET error: ", err?.message || err);
4364
- return void 0;
4365
- }
4366
- };
4367
- var getCookie = async (args) => getCookieSync(args);
4368
- var stringifyCookie = (cookie) => cookie.map(([key, value]) => value ? `${key}=${value}` : key).filter(checkIsDefined).join("; ");
4369
- var SECURE_CONFIG = [["secure", ""], ["SameSite", "None"]];
4370
- var createCookieString = ({
4371
- name,
4372
- value,
4373
- expires
4374
- }) => {
4375
- const secure = isBrowser() ? location.protocol === "https:" : true;
4376
- const secureObj = secure ? SECURE_CONFIG : [[]];
4377
- const expiresObj = expires ? [["expires", expires.toUTCString()]] : [[]];
4378
- const cookieValue = [[name, value], ...expiresObj, ["path", "/"], ["domain", getTopLevelDomain(window.location.hostname)], ...secureObj];
4379
- const cookie = stringifyCookie(cookieValue);
4380
- return cookie;
4381
- };
4382
- var setCookie = async ({
4383
- name,
4384
- value,
4385
- expires,
4386
- canTrack
4387
- }) => {
4388
- try {
4389
- if (!canTrack) {
4390
- return;
4213
+ const onScroll = throttle(immediateOnScroll, 200, {
4214
+ leading: false
4215
+ });
4216
+ function isScrolledIntoView(elem) {
4217
+ const rect = elem.getBoundingClientRect();
4218
+ const windowHeight = window.innerHeight;
4219
+ const thresholdPercent = (animation.thresholdPercent || 0) / 100;
4220
+ const threshold = thresholdPercent * windowHeight;
4221
+ return rect.bottom > threshold && rect.top < windowHeight - threshold;
4391
4222
  }
4392
- const cookie = createCookieString({
4393
- name,
4394
- value,
4395
- expires
4223
+ const defaultState = animation.steps[0].styles;
4224
+ function attachDefaultState() {
4225
+ assign(element.style, defaultState);
4226
+ }
4227
+ attachDefaultState();
4228
+ setTimeout(() => {
4229
+ element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
4230
+ if (animation.delay) {
4231
+ element.style.transitionDelay = animation.delay + "s";
4232
+ }
4396
4233
  });
4397
- document.cookie = cookie;
4398
- } catch (err) {
4399
- logger.warn("[COOKIE] SET error: ", err?.message || err);
4400
- }
4401
- };
4402
-
4403
- // src/helpers/uuid.ts
4404
- function uuidv4() {
4405
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
4406
- const r = Math.random() * 16 | 0, v2 = c == "x" ? r : r & 3 | 8;
4407
- return v2.toString(16);
4234
+ document.addEventListener("scroll", onScroll, {
4235
+ capture: true,
4236
+ passive: true
4237
+ });
4238
+ immediateOnScroll();
4408
4239
  });
4409
4240
  }
4410
- function uuid() {
4411
- return uuidv4().replace(/-/g, "");
4412
- }
4413
4241
 
4414
- // src/helpers/sessionId.ts
4415
- var SESSION_LOCAL_STORAGE_KEY = "builderSessionId";
4416
- var getSessionId = async ({
4417
- canTrack
4418
- }) => {
4419
- if (!canTrack) {
4420
- return void 0;
4421
- }
4422
- const sessionId = await getCookie({
4423
- name: SESSION_LOCAL_STORAGE_KEY,
4424
- canTrack
4242
+ // src/helpers/css.ts
4243
+ var convertStyleMapToCSSArray = (style) => {
4244
+ const cssProps = Object.entries(style).map(([key, value]) => {
4245
+ if (typeof value === "string") {
4246
+ return `${camelToKebabCase(key)}: ${value};`;
4247
+ } else {
4248
+ return void 0;
4249
+ }
4425
4250
  });
4426
- if (checkIsDefined(sessionId)) {
4427
- return sessionId;
4251
+ return cssProps.filter(checkIsDefined);
4252
+ };
4253
+ var convertStyleMapToCSS = (style) => convertStyleMapToCSSArray(style).join("\n");
4254
+ var createCssClass = ({
4255
+ mediaQuery,
4256
+ className,
4257
+ styles
4258
+ }) => {
4259
+ const cssClass = `.${className} {
4260
+ ${convertStyleMapToCSS(styles)}
4261
+ }`;
4262
+ if (mediaQuery) {
4263
+ return `${mediaQuery} {
4264
+ ${cssClass}
4265
+ }`;
4428
4266
  } else {
4429
- const newSessionId = createSessionId();
4430
- setSessionId({
4431
- id: newSessionId,
4432
- canTrack
4433
- });
4434
- return newSessionId;
4267
+ return cssClass;
4435
4268
  }
4436
4269
  };
4437
- var createSessionId = () => uuid();
4438
- var setSessionId = ({
4439
- id: id2,
4440
- canTrack
4441
- }) => setCookie({
4442
- name: SESSION_LOCAL_STORAGE_KEY,
4443
- value: id2,
4444
- canTrack
4445
- });
4446
4270
 
4447
- // src/helpers/localStorage.ts
4448
- var getLocalStorage = () => isBrowser() && typeof localStorage !== "undefined" ? localStorage : void 0;
4449
- var getLocalStorageItem = ({
4450
- key,
4451
- canTrack
4271
+ // src/functions/transform-style-property.ts
4272
+ function transformStyleProperty({
4273
+ style
4274
+ }) {
4275
+ return style;
4276
+ }
4277
+
4278
+ // src/functions/get-style.ts
4279
+ var getStyle = ({
4280
+ block,
4281
+ context
4452
4282
  }) => {
4453
- try {
4454
- if (canTrack) {
4455
- return getLocalStorage()?.getItem(key);
4456
- }
4457
- return void 0;
4458
- } catch (err) {
4459
- return void 0;
4283
+ return mapStyleObjToStrIfNeeded(transformStyleProperty({
4284
+ style: block.style || {},
4285
+ context,
4286
+ block
4287
+ }));
4288
+ };
4289
+ function mapStyleObjToStrIfNeeded(style) {
4290
+ switch (TARGET) {
4291
+ case "svelte":
4292
+ case "vue":
4293
+ case "solid":
4294
+ case "angular":
4295
+ return convertStyleMapToCSSArray(style).join(" ");
4296
+ case "qwik":
4297
+ case "reactNative":
4298
+ case "react":
4299
+ case "rsc":
4300
+ return style;
4460
4301
  }
4302
+ }
4303
+
4304
+ // src/components/block/block.helpers.ts
4305
+ var checkIsComponentRestricted = (component, model) => {
4306
+ if (!component)
4307
+ return true;
4308
+ if (!model)
4309
+ return false;
4310
+ return component.models && component.models.length > 0 && !component.models.includes(model);
4461
4311
  };
4462
- var setLocalStorageItem = ({
4463
- key,
4464
- canTrack,
4465
- value
4312
+ var getComponent = ({
4313
+ block,
4314
+ registeredComponents,
4315
+ model
4466
4316
  }) => {
4467
- try {
4468
- if (canTrack) {
4469
- getLocalStorage()?.setItem(key, value);
4470
- }
4471
- } catch (err) {
4317
+ const componentName = block.component?.name;
4318
+ if (!componentName) {
4319
+ return null;
4320
+ }
4321
+ const ref = registeredComponents[componentName];
4322
+ if (!ref || checkIsComponentRestricted(ref, model)) {
4323
+ return void 0;
4324
+ } else {
4325
+ return ref;
4472
4326
  }
4473
4327
  };
4474
-
4475
- // src/helpers/visitorId.ts
4476
- var VISITOR_LOCAL_STORAGE_KEY = "builderVisitorId";
4477
- var getVisitorId = ({
4478
- canTrack
4328
+ var getRepeatItemData = ({
4329
+ block,
4330
+ context
4479
4331
  }) => {
4480
- if (!canTrack) {
4332
+ const {
4333
+ repeat,
4334
+ ...blockWithoutRepeat
4335
+ } = block;
4336
+ if (!repeat?.collection) {
4481
4337
  return void 0;
4482
4338
  }
4483
- const visitorId = getLocalStorageItem({
4484
- key: VISITOR_LOCAL_STORAGE_KEY,
4485
- canTrack
4339
+ const itemsArray = evaluate({
4340
+ code: repeat.collection,
4341
+ localState: context.localState,
4342
+ rootState: context.rootState,
4343
+ rootSetState: context.rootSetState,
4344
+ context: context.context
4486
4345
  });
4487
- if (checkIsDefined(visitorId)) {
4488
- return visitorId;
4489
- } else {
4490
- const newVisitorId = createVisitorId();
4491
- setVisitorId({
4492
- id: newVisitorId,
4493
- canTrack
4494
- });
4495
- return newVisitorId;
4346
+ if (!Array.isArray(itemsArray)) {
4347
+ return void 0;
4348
+ }
4349
+ const collectionName = repeat.collection.split(".").pop();
4350
+ const itemNameToUse = repeat.itemName || (collectionName ? collectionName + "Item" : "item");
4351
+ const repeatArray = itemsArray.map((item, index) => ({
4352
+ context: {
4353
+ ...context,
4354
+ localState: {
4355
+ ...context.localState,
4356
+ $index: index,
4357
+ $item: item,
4358
+ [itemNameToUse]: item,
4359
+ [`$${itemNameToUse}Index`]: index
4360
+ }
4361
+ },
4362
+ block: blockWithoutRepeat
4363
+ }));
4364
+ return repeatArray;
4365
+ };
4366
+ var provideLinkComponent = (block, linkComponent) => {
4367
+ if (block?.shouldReceiveBuilderProps?.builderLinkComponent)
4368
+ return {
4369
+ builderLinkComponent: linkComponent
4370
+ };
4371
+ return {};
4372
+ };
4373
+ var provideRegisteredComponents = (block, registeredComponents, model) => {
4374
+ if (block?.shouldReceiveBuilderProps?.builderComponents) {
4375
+ const filteredRegisteredComponents = Object.fromEntries(Object.entries(registeredComponents).filter(([_, component]) => {
4376
+ return !checkIsComponentRestricted(component, model);
4377
+ }));
4378
+ return {
4379
+ builderComponents: filteredRegisteredComponents
4380
+ };
4496
4381
  }
4382
+ return {};
4497
4383
  };
4498
- var createVisitorId = () => uuid();
4499
- var setVisitorId = ({
4500
- id: id2,
4501
- canTrack
4502
- }) => setLocalStorageItem({
4503
- key: VISITOR_LOCAL_STORAGE_KEY,
4504
- value: id2,
4505
- canTrack
4384
+ var provideBuilderBlock = (block, builderBlock) => {
4385
+ if (block?.shouldReceiveBuilderProps?.builderBlock)
4386
+ return {
4387
+ builderBlock
4388
+ };
4389
+ return {};
4390
+ };
4391
+ var provideBuilderContext = (block, context) => {
4392
+ if (block?.shouldReceiveBuilderProps?.builderContext)
4393
+ return {
4394
+ builderContext: context
4395
+ };
4396
+ return {};
4397
+ };
4398
+ var generateKey = (index) => {
4399
+ return index.toString();
4400
+ };
4401
+
4402
+ // src/functions/event-handler-name.ts
4403
+ function capitalizeFirstLetter(string) {
4404
+ return string.charAt(0).toUpperCase() + string.slice(1);
4405
+ }
4406
+ var getEventHandlerName = (key) => `on${capitalizeFirstLetter(key)}`;
4407
+
4408
+ // src/functions/get-block-actions-handler.ts
4409
+ var createEventHandler = (value, options) => (event) => evaluate({
4410
+ code: value,
4411
+ context: options.context,
4412
+ localState: options.localState,
4413
+ rootState: options.rootState,
4414
+ rootSetState: options.rootSetState,
4415
+ event,
4416
+ isExpression: false,
4417
+ trackingContext: options.trackingContext
4506
4418
  });
4507
4419
 
4508
- // src/functions/log-fetch.ts
4509
- function logFetch(url) {
4510
- if (typeof process !== "undefined" && process.env?.DEBUG) {
4511
- if (String(process.env.DEBUG) == "true") {
4512
- logger.log(url);
4420
+ // src/functions/get-block-actions.ts
4421
+ function getBlockActions(options) {
4422
+ const obj = {};
4423
+ const optionActions = options.block.actions ?? {};
4424
+ for (const key in optionActions) {
4425
+ if (!optionActions.hasOwnProperty(key)) {
4426
+ continue;
4427
+ }
4428
+ const value = optionActions[key];
4429
+ let eventHandlerName = getEventHandlerName(key);
4430
+ if (options.stripPrefix) {
4431
+ switch (TARGET) {
4432
+ case "vue":
4433
+ eventHandlerName = eventHandlerName.replace("v-on:", "");
4434
+ break;
4435
+ case "svelte":
4436
+ eventHandlerName = eventHandlerName.replace("on:", "");
4437
+ break;
4438
+ }
4513
4439
  }
4440
+ obj[eventHandlerName] = createEventHandler(value, options);
4514
4441
  }
4442
+ return obj;
4515
4443
  }
4516
4444
 
4517
- // src/functions/track/index.ts
4518
- var getTrackingEventData = async ({
4519
- canTrack
4520
- }) => {
4521
- if (!canTrack) {
4522
- return {
4523
- visitorId: void 0,
4524
- sessionId: void 0
4525
- };
4526
- }
4527
- const sessionId = await getSessionId({
4528
- canTrack
4529
- });
4530
- const visitorId = getVisitorId({
4531
- canTrack
4532
- });
4445
+ // src/functions/transform-block-properties.ts
4446
+ function transformBlockProperties({
4447
+ properties
4448
+ }) {
4449
+ return properties;
4450
+ }
4451
+
4452
+ // src/functions/get-block-properties.ts
4453
+ var extractRelevantRootBlockProperties = (block) => {
4533
4454
  return {
4534
- sessionId,
4535
- visitorId
4455
+ href: block.href
4536
4456
  };
4537
4457
  };
4538
- var createEvent = async ({
4539
- type: eventType,
4540
- canTrack,
4541
- apiKey,
4542
- metadata,
4543
- ...properties
4544
- }) => ({
4545
- type: eventType,
4546
- data: {
4547
- ...properties,
4548
- metadata: {
4549
- url: location.href,
4550
- ...metadata
4551
- },
4552
- ...await getTrackingEventData({
4553
- canTrack
4458
+ function getBlockProperties({
4459
+ block,
4460
+ context
4461
+ }) {
4462
+ const properties = {
4463
+ ...extractRelevantRootBlockProperties(block),
4464
+ ...block.properties,
4465
+ "builder-id": block.id,
4466
+ style: getStyle({
4467
+ block,
4468
+ context
4554
4469
  }),
4555
- userAttributes: getUserAttributes(),
4556
- ownerId: apiKey
4470
+ [getClassPropName()]: [block.id, "builder-block", block.class, block.properties?.class].filter(Boolean).join(" ")
4471
+ };
4472
+ return transformBlockProperties({
4473
+ properties,
4474
+ context,
4475
+ block
4476
+ });
4477
+ }
4478
+
4479
+ // src/components/block/components/block-wrapper.tsx
4480
+ function BlockWrapper(props) {
4481
+ return createComponent(dynamic_renderer_default, {
4482
+ get TagName() {
4483
+ return props.Wrapper;
4484
+ },
4485
+ get attributes() {
4486
+ return getBlockProperties({
4487
+ block: props.block,
4488
+ context: props.context
4489
+ });
4490
+ },
4491
+ get actionAttributes() {
4492
+ return getBlockActions({
4493
+ block: props.block,
4494
+ rootState: props.context.rootState,
4495
+ rootSetState: props.context.rootSetState,
4496
+ localState: props.context.localState,
4497
+ context: props.context.context,
4498
+ stripPrefix: true,
4499
+ trackingContext: {
4500
+ apiKey: props.context.apiKey,
4501
+ canTrack: props.context.canTrack ?? true,
4502
+ contentId: props.context.content?.id,
4503
+ variationId: props.context.content?.testVariationId
4504
+ }
4505
+ });
4506
+ },
4507
+ get children() {
4508
+ return props.children;
4509
+ }
4510
+ });
4511
+ }
4512
+ var block_wrapper_default = BlockWrapper;
4513
+
4514
+ // src/functions/is-previewing.ts
4515
+ function isPreviewing(search) {
4516
+ const searchToUse = search || (isBrowser() ? window.location.search : void 0);
4517
+ if (!searchToUse) {
4518
+ return false;
4557
4519
  }
4520
+ const normalizedSearch = getSearchString(searchToUse);
4521
+ return Boolean(normalizedSearch.indexOf("builder.preview=") !== -1);
4522
+ }
4523
+
4524
+ // src/functions/register-component.ts
4525
+ var createRegisterComponentMessage = (info) => ({
4526
+ type: "builder.registerComponent",
4527
+ data: serializeIncludingFunctions(info)
4558
4528
  });
4559
- async function _track({
4560
- apiHost,
4561
- ...eventProps
4562
- }) {
4563
- if (!eventProps.apiKey) {
4564
- logger.error("Missing API key for track call. Please provide your API key.");
4565
- return;
4529
+ var serializeFn = (fnValue) => {
4530
+ const fnStr = fnValue.toString().trim();
4531
+ const isArrowWithoutParens = /^[a-zA-Z0-9_]+\s*=>/i.test(fnStr);
4532
+ const appendFunction = !fnStr.startsWith("function") && !fnStr.startsWith("async") && !fnStr.startsWith("(") && !isArrowWithoutParens;
4533
+ return `return (${appendFunction ? "function " : ""}${fnStr}).apply(this, arguments)`;
4534
+ };
4535
+ function serializeIncludingFunctions(info) {
4536
+ return JSON.parse(JSON.stringify(info, (key, value) => {
4537
+ if (typeof value === "function") {
4538
+ return serializeFn(value);
4539
+ }
4540
+ return value;
4541
+ }));
4542
+ }
4543
+
4544
+ // src/functions/register.ts
4545
+ var registry = {};
4546
+ function register(type, info) {
4547
+ if (type === "plugin") {
4548
+ info = serializeIncludingFunctions(info);
4566
4549
  }
4567
- if (!eventProps.canTrack) {
4568
- return;
4550
+ let typeList = registry[type];
4551
+ if (!typeList) {
4552
+ typeList = registry[type] = [];
4569
4553
  }
4570
- if (isEditing()) {
4571
- return;
4554
+ typeList.push(info);
4555
+ if (isBrowser()) {
4556
+ const message = {
4557
+ type: "builder.register",
4558
+ data: {
4559
+ type,
4560
+ info
4561
+ }
4562
+ };
4563
+ try {
4564
+ parent.postMessage(message, "*");
4565
+ if (parent !== window) {
4566
+ window.postMessage(message, "*");
4567
+ }
4568
+ } catch (err) {
4569
+ }
4572
4570
  }
4573
- if (!(isBrowser() || TARGET === "reactNative")) {
4574
- return;
4571
+ }
4572
+ function registerAction(action) {
4573
+ if (isBrowser()) {
4574
+ const actionClone = JSON.parse(JSON.stringify(action));
4575
+ if (action.action) {
4576
+ actionClone.action = action.action.toString();
4577
+ }
4578
+ window.parent?.postMessage({
4579
+ type: "builder.registerAction",
4580
+ data: actionClone
4581
+ }, "*");
4575
4582
  }
4576
- const baseUrl = apiHost || "https://cdn.builder.io";
4577
- const url = `${baseUrl}/api/v1/track`;
4578
- logFetch(url);
4579
- return fetch(url, {
4580
- method: "POST",
4581
- body: JSON.stringify({
4582
- events: [await createEvent(eventProps)]
4583
- }),
4584
- headers: {
4585
- "content-type": "application/json",
4586
- ...getSdkHeaders()
4587
- },
4588
- mode: "cors"
4589
- }).catch((err) => {
4590
- });
4591
4583
  }
4592
- var track = (args) => _track({
4593
- ...args,
4594
- canTrack: true
4595
- });
4584
+
4585
+ // src/functions/set-editor-settings.ts
4586
+ var settings = {};
4587
+ function setEditorSettings(newSettings) {
4588
+ if (isBrowser()) {
4589
+ Object.assign(settings, newSettings);
4590
+ const message = {
4591
+ type: "builder.settingsChange",
4592
+ data: settings
4593
+ };
4594
+ parent.postMessage(message, "*");
4595
+ }
4596
+ }
4597
+
4598
+ // src/functions/get-builder-search-params/index.ts
4599
+ var BUILDER_SEARCHPARAMS_PREFIX = "builder.";
4600
+ var BUILDER_OPTIONS_PREFIX = "options.";
4601
+ var getBuilderSearchParams = (_options) => {
4602
+ if (!_options) {
4603
+ return {};
4604
+ }
4605
+ const options = normalizeSearchParams(_options);
4606
+ const newOptions = {};
4607
+ Object.keys(options).forEach((key) => {
4608
+ if (key.startsWith(BUILDER_SEARCHPARAMS_PREFIX)) {
4609
+ const trimmedKey = key.replace(BUILDER_SEARCHPARAMS_PREFIX, "").replace(BUILDER_OPTIONS_PREFIX, "");
4610
+ newOptions[trimmedKey] = options[key];
4611
+ }
4612
+ });
4613
+ return newOptions;
4614
+ };
4615
+ var getBuilderSearchParamsFromWindow = () => {
4616
+ if (!isBrowser()) {
4617
+ return {};
4618
+ }
4619
+ const searchParams = new URLSearchParams(window.location.search);
4620
+ return getBuilderSearchParams(searchParams);
4621
+ };
4596
4622
 
4597
4623
  // src/functions/is-from-trusted-host.ts
4598
4624
  var DEFAULT_TRUSTED_HOSTS = ["*.beta.builder.io", "beta.builder.io", "builder.io", "localhost", "qa.builder.io"];
@@ -5333,7 +5359,13 @@ function InteractiveElement(props) {
5333
5359
  rootState: props.context.rootState,
5334
5360
  rootSetState: props.context.rootSetState,
5335
5361
  localState: props.context.localState,
5336
- context: props.context.context
5362
+ context: props.context.context,
5363
+ trackingContext: {
5364
+ apiKey: props.context.apiKey,
5365
+ canTrack: props.context.canTrack ?? true,
5366
+ contentId: props.context.content?.id,
5367
+ variationId: props.context.content?.testVariationId
5368
+ }
5337
5369
  })
5338
5370
  } : {};
5339
5371
  });