@builder.io/sdk-react-native 0.2.3 → 0.4.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 (88) hide show
  1. package/dist/blocks/button/button.js +1 -0
  2. package/dist/blocks/columns/columns.js +2 -1
  3. package/dist/blocks/custom-code/custom-code.js +1 -0
  4. package/dist/blocks/embed/embed.js +1 -0
  5. package/dist/blocks/form/form.js +1 -0
  6. package/dist/blocks/fragment/fragment.js +1 -0
  7. package/dist/blocks/img/img.js +1 -0
  8. package/dist/blocks/input/input.js +1 -0
  9. package/dist/blocks/raw-text/raw-text.js +1 -0
  10. package/dist/blocks/section/section.js +1 -0
  11. package/dist/blocks/select/select.js +1 -0
  12. package/dist/blocks/submit-button/submit-button.js +1 -0
  13. package/dist/blocks/symbol/symbol.js +2 -1
  14. package/dist/blocks/textarea/textarea.js +1 -0
  15. package/dist/components/render-block/block-styles.js +4 -1
  16. package/dist/components/render-block/render-block.helpers.js +8 -20
  17. package/dist/components/render-block/render-block.js +28 -21
  18. package/dist/components/render-block/render-component.js +4 -3
  19. package/dist/components/render-block/render-repeated-block.js +4 -2
  20. package/dist/components/render-blocks.js +1 -0
  21. package/dist/components/render-content/builder-editing.js +1 -0
  22. package/dist/components/render-content/components/render-styles.js +2 -1
  23. package/dist/components/render-content/render-content.js +48 -10
  24. package/dist/components/render-content/wrap-component-ref.js +5 -0
  25. package/dist/components/render-content-variants/helpers.js +137 -0
  26. package/dist/components/render-content-variants/render-content-variants.js +73 -0
  27. package/dist/components/render-inlined-styles.js +2 -12
  28. package/dist/constants/sdk-version.js +4 -0
  29. package/dist/context/builder.context.js +3 -2
  30. package/dist/functions/evaluate.js +25 -3
  31. package/dist/functions/evaluate.test.js +19 -0
  32. package/dist/functions/get-block-actions-handler.js +3 -1
  33. package/dist/functions/get-content/generate-content-url.js +2 -2
  34. package/dist/functions/get-content/generate-content-url.test.js +15 -0
  35. package/dist/functions/get-content/index.js +36 -19
  36. package/dist/functions/get-processed-block.js +16 -4
  37. package/dist/functions/get-processed-block.test.js +3 -1
  38. package/dist/helpers/ab-tests.js +123 -6
  39. package/dist/helpers/canTrack.js +6 -0
  40. package/dist/helpers/cookie.js +9 -2
  41. package/dist/helpers/logger.js +2 -1
  42. package/dist/index.js +17 -10
  43. package/dist/scripts/init-editing.js +2 -0
  44. package/package.json +2 -5
  45. package/src/blocks/button/button.jsx +1 -0
  46. package/src/blocks/columns/columns.jsx +2 -1
  47. package/src/blocks/custom-code/custom-code.jsx +1 -0
  48. package/src/blocks/embed/embed.jsx +1 -0
  49. package/src/blocks/form/form.jsx +1 -0
  50. package/src/blocks/fragment/fragment.jsx +1 -0
  51. package/src/blocks/img/img.jsx +1 -0
  52. package/src/blocks/input/input.jsx +1 -0
  53. package/src/blocks/raw-text/raw-text.jsx +1 -0
  54. package/src/blocks/section/section.jsx +1 -0
  55. package/src/blocks/select/select.jsx +1 -0
  56. package/src/blocks/submit-button/submit-button.jsx +1 -0
  57. package/src/blocks/symbol/symbol.jsx +2 -1
  58. package/src/blocks/textarea/textarea.jsx +1 -0
  59. package/src/components/render-block/block-styles.jsx +4 -1
  60. package/src/components/render-block/render-block.helpers.js +7 -19
  61. package/src/components/render-block/render-block.jsx +24 -23
  62. package/src/components/render-block/render-component.jsx +5 -5
  63. package/src/components/render-block/render-repeated-block.jsx +4 -2
  64. package/src/components/render-blocks.jsx +1 -0
  65. package/src/components/render-content/builder-editing.jsx +1 -0
  66. package/src/components/render-content/components/render-styles.jsx +4 -3
  67. package/src/components/render-content/render-content.jsx +54 -9
  68. package/src/components/render-content/wrap-component-ref.js +4 -0
  69. package/src/components/render-content-variants/helpers.js +139 -0
  70. package/src/components/render-content-variants/render-content-variants.jsx +101 -0
  71. package/src/components/render-inlined-styles.jsx +2 -22
  72. package/src/constants/sdk-version.js +1 -0
  73. package/src/context/builder.context.js +3 -2
  74. package/src/functions/evaluate.js +27 -3
  75. package/src/functions/evaluate.test.js +17 -0
  76. package/src/functions/get-block-actions-handler.js +3 -1
  77. package/src/functions/get-content/generate-content-url.js +2 -1
  78. package/src/functions/get-content/generate-content-url.test.js +15 -0
  79. package/src/functions/get-content/index.js +35 -18
  80. package/src/functions/get-processed-block.js +20 -4
  81. package/src/functions/get-processed-block.test.js +3 -1
  82. package/src/helpers/ab-tests.js +132 -10
  83. package/src/helpers/canTrack.js +5 -0
  84. package/src/helpers/cookie.js +9 -2
  85. package/src/helpers/logger.js +2 -1
  86. package/src/index.js +18 -7
  87. package/src/scripts/init-editing.js +2 -0
  88. package/src/functions/get-content/ab-testing.js +0 -99
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ 'use client';
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || function (mod) {
20
+ if (mod && mod.__esModule) return mod;
21
+ var result = {};
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
+ __setModuleDefault(result, mod);
24
+ return result;
25
+ };
26
+ var __importDefault = (this && this.__importDefault) || function (mod) {
27
+ return (mod && mod.__esModule) ? mod : { "default": mod };
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ const React = __importStar(require("react"));
31
+ const react_native_1 = require("react-native");
32
+ const react_1 = require("react");
33
+ const helpers_1 = require("./helpers");
34
+ const render_content_1 = __importDefault(require("../render-content/render-content"));
35
+ const canTrack_1 = require("../../helpers/canTrack");
36
+ const render_inlined_styles_1 = __importDefault(require("../render-inlined-styles"));
37
+ const ab_tests_1 = require("../../helpers/ab-tests");
38
+ function RenderContentVariants(props) {
39
+ var _a, _b, _c, _d, _e;
40
+ const [variantScriptStr, setVariantScriptStr] = (0, react_1.useState)(() => {
41
+ var _a;
42
+ return (0, helpers_1.getVariantsScriptString)((0, helpers_1.getVariants)(props.content).map((value) => ({
43
+ id: value.id,
44
+ testRatio: value.testRatio,
45
+ })), ((_a = props.content) === null || _a === void 0 ? void 0 : _a.id) || "");
46
+ });
47
+ const [shouldRenderVariants, setShouldRenderVariants] = (0, react_1.useState)(() => (0, helpers_1.checkShouldRunVariants)({
48
+ canTrack: (0, canTrack_1.getDefaultCanTrack)(props.canTrack),
49
+ content: props.content,
50
+ }));
51
+ const [hideVariantsStyleString, setHideVariantsStyleString] = (0, react_1.useState)(() => (0, helpers_1.getVariants)(props.content)
52
+ .map((value) => `.variant-${value.id} { display: none; } `)
53
+ .join(""));
54
+ const [contentToRender, setContentToRender] = (0, react_1.useState)(() => (0, helpers_1.checkShouldRunVariants)({
55
+ canTrack: (0, canTrack_1.getDefaultCanTrack)(props.canTrack),
56
+ content: props.content,
57
+ })
58
+ ? props.content
59
+ : (0, ab_tests_1.handleABTestingSync)({
60
+ item: props.content,
61
+ canTrack: (0, canTrack_1.getDefaultCanTrack)(props.canTrack),
62
+ }));
63
+ return (React.createElement(React.Fragment, null,
64
+ shouldRenderVariants ? (React.createElement(React.Fragment, null,
65
+ React.createElement(render_inlined_styles_1.default, { id: `variants-styles-${(_a = props.content) === null || _a === void 0 ? void 0 : _a.id}`, styles: hideVariantsStyleString }),
66
+ React.createElement(react_native_1.View, { id: `variants-script-${(_b = props.content) === null || _b === void 0 ? void 0 : _b.id}`, dangerouslySetInnerHTML: { __html: variantScriptStr } }), (_c = (0, helpers_1.getVariants)(props.content)) === null || _c === void 0 ? void 0 :
67
+ _c.map((variant) => {
68
+ var _a;
69
+ return (React.createElement(render_content_1.default, { key: variant.id, content: variant, apiKey: props.apiKey, apiVersion: props.apiVersion, canTrack: props.canTrack, customComponents: props.customComponents, hideContent: true, parentContentId: (_a = props.content) === null || _a === void 0 ? void 0 : _a.id, isSsrAbTest: shouldRenderVariants }));
70
+ }))) : null,
71
+ React.createElement(render_content_1.default, { model: props.model, content: contentToRender, apiKey: props.apiKey, apiVersion: props.apiVersion, canTrack: props.canTrack, customComponents: props.customComponents, classNameProp: `variant-${(_d = props.content) === null || _d === void 0 ? void 0 : _d.id}`, parentContentId: (_e = props.content) === null || _e === void 0 ? void 0 : _e.id, isSsrAbTest: shouldRenderVariants })));
72
+ }
73
+ exports.default = RenderContentVariants;
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ 'use client';
2
3
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
4
  if (k2 === undefined) k2 = k;
4
5
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -25,18 +26,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
25
26
  Object.defineProperty(exports, "__esModule", { value: true });
26
27
  const React = __importStar(require("react"));
27
28
  const react_native_1 = require("react-native");
28
- const target_js_1 = require("../constants/target.js");
29
29
  function RenderInlinedStyles(props) {
30
- function tag() {
31
- // NOTE: we have to obfusctate the name of the tag due to a limitation in the svelte-preprocessor plugin.
32
- // https://github.com/sveltejs/vite-plugin-svelte/issues/315#issuecomment-1109000027
33
- return "sty" + "le";
34
- }
35
- function injectedStyleScript() {
36
- return `<${tag()}>${props.styles}</${tag()}>`;
37
- }
38
- return (React.createElement(React.Fragment, null, target_js_1.TARGET === "svelte" || target_js_1.TARGET === "qwik" ? (React.createElement(React.Fragment, null,
39
- React.createElement(react_native_1.View, { dangerouslySetInnerHTML: { __html: props.styles } }))) : (React.createElement(react_native_1.View, null,
40
- React.createElement(react_native_1.Text, null, props.styles)))));
30
+ return (React.createElement(react_native_1.View, { dangerouslySetInnerHTML: { __html: props.styles }, id: props.id }));
41
31
  }
42
32
  exports.default = RenderInlinedStyles;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SDK_VERSION = void 0;
4
+ exports.SDK_VERSION = "0.4.0";
@@ -5,9 +5,10 @@ const react_1 = require("react");
5
5
  var stdin_default = (0, react_1.createContext)({
6
6
  content: null,
7
7
  context: {},
8
- state: {},
9
- setState() {
8
+ localState: void 0,
9
+ rootSetState() {
10
10
  },
11
+ rootState: {},
11
12
  apiKey: null,
12
13
  apiVersion: void 0,
13
14
  registeredComponents: {},
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.evaluate = void 0;
3
+ exports.flattenState = exports.evaluate = void 0;
4
4
  const is_browser_js_1 = require("./is-browser.js");
5
5
  const is_editing_js_1 = require("./is-editing.js");
6
- function evaluate({ code, context, state, event, isExpression = true }) {
6
+ function evaluate({ code, context, localState, rootState, rootSetState, event, isExpression = true }) {
7
7
  if (code === "") {
8
8
  console.warn("Skipping evaluation of empty code block.");
9
9
  return;
@@ -16,10 +16,32 @@ function evaluate({ code, context, state, event, isExpression = true }) {
16
16
  const useReturn = isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "));
17
17
  const useCode = useReturn ? `return (${code});` : code;
18
18
  try {
19
- return new Function("builder", "Builder", "state", "context", "event", useCode)(builder, builder, state, context, event);
19
+ return new Function("builder", "Builder", "state", "context", "event", useCode)(builder, builder, flattenState(rootState, localState, rootSetState), context, event);
20
20
  }
21
21
  catch (e) {
22
22
  console.warn("Builder custom code error: \n While Evaluating: \n ", useCode, "\n", e);
23
23
  }
24
24
  }
25
25
  exports.evaluate = evaluate;
26
+ function flattenState(rootState, localState, rootSetState) {
27
+ if (rootState === localState) {
28
+ throw new Error("rootState === localState");
29
+ }
30
+ return new Proxy(rootState, {
31
+ get: (_, prop) => {
32
+ if (localState && prop in localState) {
33
+ return localState[prop];
34
+ }
35
+ return rootState[prop];
36
+ },
37
+ set: (_, prop, value) => {
38
+ if (localState && prop in localState) {
39
+ throw new Error("Writing to local state is not allowed as it is read-only.");
40
+ }
41
+ rootState[prop] = value;
42
+ rootSetState == null ? void 0 : rootSetState(rootState);
43
+ return true;
44
+ }
45
+ });
46
+ }
47
+ exports.flattenState = flattenState;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const evaluate_1 = require("./evaluate");
4
+ describe("flatten state", () => {
5
+ it("should behave normally when no PROTO_STATE", () => {
6
+ const localState = {};
7
+ const rootState = { foo: "bar" };
8
+ const flattened = (0, evaluate_1.flattenState)(rootState, localState, void 0);
9
+ expect(flattened.foo).toEqual("bar");
10
+ flattened.foo = "baz";
11
+ expect(rootState.foo).toEqual("baz");
12
+ });
13
+ it("should shadow write ", () => {
14
+ const rootState = { foo: "foo" };
15
+ const localState = { foo: "baz" };
16
+ const flattened = (0, evaluate_1.flattenState)(rootState, localState, void 0);
17
+ expect(() => flattened.foo = "bar").toThrow("Writing to local state is not allowed as it is read-only.");
18
+ });
19
+ });
@@ -5,7 +5,9 @@ const evaluate_js_1 = require("./evaluate.js");
5
5
  const createEventHandler = (value, options) => (event) => (0, evaluate_js_1.evaluate)({
6
6
  code: value,
7
7
  context: options.context,
8
- state: options.state,
8
+ localState: options.localState,
9
+ rootState: options.rootState,
10
+ rootSetState: options.rootSetState,
9
11
  event,
10
12
  isExpression: false
11
13
  });
@@ -21,14 +21,14 @@ const flatten_js_1 = require("../../helpers/flatten.js");
21
21
  const index_js_1 = require("../get-builder-search-params/index.js");
22
22
  const api_version_1 = require("../../types/api-version");
23
23
  const generateContentUrl = (options) => {
24
- const { limit = 30, userAttributes, query, noTraverse = false, model, apiKey, includeRefs = true, locale, apiVersion = api_version_1.DEFAULT_API_VERSION } = options;
24
+ const { limit = 30, userAttributes, query, noTraverse = false, model, apiKey, includeRefs = true, enrich, locale, apiVersion = api_version_1.DEFAULT_API_VERSION } = options;
25
25
  if (!apiKey) {
26
26
  throw new Error("Missing API key");
27
27
  }
28
28
  if (!["v2", "v3"].includes(apiVersion)) {
29
29
  throw new Error(`Invalid apiVersion: expected 'v2' or 'v3', received '${apiVersion}'`);
30
30
  }
31
- const url = new URL(`https://cdn.builder.io/api/${apiVersion}/content/${model}?apiKey=${apiKey}&limit=${limit}&noTraverse=${noTraverse}&includeRefs=${includeRefs}${locale ? `&locale=${locale}` : ""}`);
31
+ const url = new URL(`https://cdn.builder.io/api/${apiVersion}/content/${model}?apiKey=${apiKey}&limit=${limit}&noTraverse=${noTraverse}&includeRefs=${includeRefs}${locale ? `&locale=${locale}` : ""}${enrich ? `&enrich=${enrich}` : ""}`);
32
32
  const queryOptions = __spreadValues(__spreadValues({}, (0, index_js_1.getBuilderSearchParamsFromWindow)()), (0, index_js_1.normalizeSearchParams)(options.options || {}));
33
33
  const flattened = (0, flatten_js_1.flatten)(queryOptions);
34
34
  for (const key in flattened) {
@@ -81,4 +81,19 @@ describe("Generate Content URL", () => {
81
81
  });
82
82
  }).toThrow(`Invalid apiVersion: expected 'v2' or 'v3', received 'INVALID_API_VERSION'`);
83
83
  });
84
+ test("generate content url with enrich option true", () => {
85
+ const output = (0, generate_content_url_1.generateContentUrl)({
86
+ apiKey: testKey,
87
+ model: testModel,
88
+ enrich: true
89
+ });
90
+ expect(output).toMatchSnapshot();
91
+ });
92
+ test("generate content url with enrich option not present", () => {
93
+ const output = (0, generate_content_url_1.generateContentUrl)({
94
+ apiKey: testKey,
95
+ model: testModel
96
+ });
97
+ expect(output).toMatchSnapshot();
98
+ });
84
99
  });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getContent = exports.getAllContent = void 0;
3
+ exports.processContentResult = exports.getContent = exports.getAllContent = void 0;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __defProps = Object.defineProperties;
6
6
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
@@ -42,42 +42,59 @@ var __async = (__this, __arguments, generator) => {
42
42
  step((generator = generator.apply(__this, __arguments)).next());
43
43
  });
44
44
  };
45
+ const target_js_1 = require("../../constants/target.js");
46
+ const ab_tests_js_1 = require("../../helpers/ab-tests.js");
47
+ const canTrack_js_1 = require("../../helpers/canTrack.js");
45
48
  const logger_js_1 = require("../../helpers/logger.js");
46
49
  const get_fetch_js_1 = require("../get-fetch.js");
47
- const ab_testing_js_1 = require("./ab-testing.js");
50
+ const is_browser_js_1 = require("../is-browser.js");
48
51
  const generate_content_url_js_1 = require("./generate-content-url.js");
52
+ const checkContentHasResults = (content) => "results" in content;
49
53
  function getContent(options) {
50
54
  return __async(this, null, function* () {
51
55
  const allContent = yield getAllContent(__spreadProps(__spreadValues({}, options), { limit: 1 }));
52
- if (allContent && "results" in allContent) {
53
- return (allContent == null ? void 0 : allContent.results[0]) || null;
56
+ if (allContent && checkContentHasResults(allContent)) {
57
+ return allContent.results[0] || null;
54
58
  }
55
59
  return null;
56
60
  });
57
61
  }
58
62
  exports.getContent = getContent;
63
+ const fetchContent = (options) => __async(void 0, null, function* () {
64
+ const url = (0, generate_content_url_js_1.generateContentUrl)(options);
65
+ const res = yield (0, get_fetch_js_1.fetch)(url.href);
66
+ const content = yield res.json();
67
+ return content;
68
+ });
69
+ const processContentResult = (options, content) => __async(void 0, null, function* () {
70
+ const canTrack = (0, canTrack_js_1.getDefaultCanTrack)(options.canTrack);
71
+ if (!canTrack)
72
+ return content;
73
+ if (!((0, is_browser_js_1.isBrowser)() || target_js_1.TARGET === "reactNative"))
74
+ return content;
75
+ try {
76
+ const newResults = [];
77
+ for (const item of content.results) {
78
+ newResults.push(yield (0, ab_tests_js_1.handleABTesting)({ item, canTrack }));
79
+ }
80
+ content.results = newResults;
81
+ }
82
+ catch (e) {
83
+ logger_js_1.logger.error("Could not process A/B tests. ", e);
84
+ }
85
+ return content;
86
+ });
87
+ exports.processContentResult = processContentResult;
59
88
  function getAllContent(options) {
60
89
  return __async(this, null, function* () {
61
90
  try {
62
91
  const url = (0, generate_content_url_js_1.generateContentUrl)(options);
63
- const res = yield (0, get_fetch_js_1.fetch)(url.href);
64
- const content = yield res.json();
65
- if ("status" in content && !("results" in content)) {
92
+ const content = yield fetchContent(options);
93
+ if (!checkContentHasResults(content)) {
66
94
  logger_js_1.logger.error("Error fetching data. ", { url, content, options });
67
95
  return content;
68
96
  }
69
- const canTrack = options.canTrack !== false;
70
- try {
71
- if (canTrack && Array.isArray(content.results)) {
72
- for (const item of content.results) {
73
- yield (0, ab_testing_js_1.handleABTesting)({ item, canTrack });
74
- }
75
- }
76
- }
77
- catch (e) {
78
- logger_js_1.logger.error("Could not setup A/B testing. ", e);
79
- }
80
- return content;
97
+ return processContentResult(options, content);
81
98
  }
82
99
  catch (error) {
83
100
  logger_js_1.logger.error("Error fetching data. ", error);
@@ -24,7 +24,7 @@ const evaluate_js_1 = require("./evaluate.js");
24
24
  const fast_clone_js_1 = require("./fast-clone.js");
25
25
  const set_js_1 = require("./set.js");
26
26
  const transform_block_js_1 = require("./transform-block.js");
27
- const evaluateBindings = ({ block, context, state }) => {
27
+ const evaluateBindings = ({ block, context, localState, rootState, rootSetState }) => {
28
28
  if (!block.bindings) {
29
29
  return block;
30
30
  }
@@ -35,15 +35,27 @@ const evaluateBindings = ({ block, context, state }) => {
35
35
  });
36
36
  for (const binding in block.bindings) {
37
37
  const expression = block.bindings[binding];
38
- const value = (0, evaluate_js_1.evaluate)({ code: expression, state, context });
38
+ const value = (0, evaluate_js_1.evaluate)({
39
+ code: expression,
40
+ localState,
41
+ rootState,
42
+ rootSetState,
43
+ context
44
+ });
39
45
  (0, set_js_1.set)(copied, binding, value);
40
46
  }
41
47
  return copied;
42
48
  };
43
- function getProcessedBlock({ block, context, shouldEvaluateBindings, state }) {
49
+ function getProcessedBlock({ block, context, shouldEvaluateBindings, localState, rootState, rootSetState }) {
44
50
  const transformedBlock = (0, transform_block_js_1.transformBlock)(block);
45
51
  if (shouldEvaluateBindings) {
46
- return evaluateBindings({ block: transformedBlock, state, context });
52
+ return evaluateBindings({
53
+ block: transformedBlock,
54
+ localState,
55
+ rootState,
56
+ rootSetState,
57
+ context
58
+ });
47
59
  }
48
60
  else {
49
61
  return transformedBlock;
@@ -22,7 +22,9 @@ test("Can process bindings", () => {
22
22
  const processed = (0, get_processed_block_js_1.getProcessedBlock)({
23
23
  block,
24
24
  context: {},
25
- state: { test: "hello" },
25
+ rootState: { test: "hello" },
26
+ rootSetState: void 0,
27
+ localState: void 0,
26
28
  shouldEvaluateBindings: true
27
29
  });
28
30
  expect(processed).not.toEqual(block);
@@ -1,10 +1,127 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.setContentVariationCookie = exports.getContentVariationCookie = void 0;
3
+ exports.handleABTestingSync = exports.handleABTesting = void 0;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ }
26
+ catch (e) {
27
+ reject(e);
28
+ }
29
+ };
30
+ var rejected = (value) => {
31
+ try {
32
+ step(generator.throw(value));
33
+ }
34
+ catch (e) {
35
+ reject(e);
36
+ }
37
+ };
38
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
39
+ step((generator = generator.apply(__this, __arguments)).next());
40
+ });
41
+ };
4
42
  const cookie_js_1 = require("./cookie.js");
5
- const BUILDER_STORE_PREFIX = "builderio.variations";
43
+ const nullable_js_1 = require("../helpers/nullable.js");
44
+ const logger_js_1 = require("./logger.js");
45
+ const BUILDER_STORE_PREFIX = "builder.tests";
6
46
  const getContentTestKey = (id) => `${BUILDER_STORE_PREFIX}.${id}`;
7
- const getContentVariationCookie = ({ contentId, canTrack }) => (0, cookie_js_1.getCookie)({ name: getContentTestKey(contentId), canTrack });
8
- exports.getContentVariationCookie = getContentVariationCookie;
9
- const setContentVariationCookie = ({ contentId, canTrack, value }) => (0, cookie_js_1.setCookie)({ name: getContentTestKey(contentId), value, canTrack });
10
- exports.setContentVariationCookie = setContentVariationCookie;
47
+ const getContentVariationCookie = ({ contentId }) => (0, cookie_js_1.getCookie)({ name: getContentTestKey(contentId), canTrack: true });
48
+ const getContentVariationCookieSync = ({ contentId }) => (0, cookie_js_1.getCookieSync)({ name: getContentTestKey(contentId), canTrack: true });
49
+ const setContentVariationCookie = ({ contentId, value }) => (0, cookie_js_1.setCookie)({ name: getContentTestKey(contentId), value, canTrack: true });
50
+ const checkIsBuilderContentWithVariations = (item) => (0, nullable_js_1.checkIsDefined)(item.id) && (0, nullable_js_1.checkIsDefined)(item.variations) && Object.keys(item.variations).length > 0;
51
+ const getRandomVariationId = ({ id, variations }) => {
52
+ var _a;
53
+ let n = 0;
54
+ const random = Math.random();
55
+ for (const id2 in variations) {
56
+ const testRatio = (_a = variations[id2]) == null ? void 0 : _a.testRatio;
57
+ n += testRatio;
58
+ if (random < n) {
59
+ return id2;
60
+ }
61
+ }
62
+ return id;
63
+ };
64
+ const getAndSetVariantId = (args) => {
65
+ const randomVariationId = getRandomVariationId(args);
66
+ setContentVariationCookie({
67
+ contentId: args.id,
68
+ value: randomVariationId
69
+ }).catch((err) => {
70
+ logger_js_1.logger.error("could not store A/B test variation: ", err);
71
+ });
72
+ return randomVariationId;
73
+ };
74
+ const getTestFields = ({ item, testGroupId }) => {
75
+ const variationValue = item.variations[testGroupId];
76
+ if (testGroupId === item.id || !variationValue) {
77
+ return {
78
+ testVariationId: item.id,
79
+ testVariationName: "Default"
80
+ };
81
+ }
82
+ else {
83
+ return {
84
+ data: variationValue.data,
85
+ testVariationId: variationValue.id,
86
+ testVariationName: variationValue.name || (variationValue.id === item.id ? "Default" : "")
87
+ };
88
+ }
89
+ };
90
+ const handleABTestingSync = ({ item, canTrack }) => {
91
+ if (!canTrack) {
92
+ return item;
93
+ }
94
+ if (!item) {
95
+ return void 0;
96
+ }
97
+ if (!checkIsBuilderContentWithVariations(item)) {
98
+ return item;
99
+ }
100
+ const testGroupId = getContentVariationCookieSync({
101
+ contentId: item.id
102
+ }) || getAndSetVariantId({
103
+ variations: item.variations,
104
+ id: item.id
105
+ });
106
+ const variationValue = getTestFields({ item, testGroupId });
107
+ return __spreadValues(__spreadValues({}, item), variationValue);
108
+ };
109
+ exports.handleABTestingSync = handleABTestingSync;
110
+ const handleABTesting = (_0) => __async(void 0, [_0], function* ({ item, canTrack }) {
111
+ if (!canTrack) {
112
+ return item;
113
+ }
114
+ if (!checkIsBuilderContentWithVariations(item)) {
115
+ return item;
116
+ }
117
+ const cookieValue = yield getContentVariationCookie({
118
+ contentId: item.id
119
+ });
120
+ const testGroupId = cookieValue || getAndSetVariantId({
121
+ variations: item.variations,
122
+ id: item.id
123
+ });
124
+ const variationValue = getTestFields({ item, testGroupId });
125
+ return __spreadValues(__spreadValues({}, item), variationValue);
126
+ });
127
+ exports.handleABTesting = handleABTesting;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDefaultCanTrack = void 0;
4
+ const nullable_1 = require("./nullable");
5
+ const getDefaultCanTrack = (canTrack) => (0, nullable_1.checkIsDefined)(canTrack) ? canTrack : true;
6
+ exports.getDefaultCanTrack = getDefaultCanTrack;
@@ -26,6 +26,7 @@ var __async = (__this, __arguments, generator) => {
26
26
  step((generator = generator.apply(__this, __arguments)).next());
27
27
  });
28
28
  };
29
+ const logger_js_1 = require("./logger.js");
29
30
  const react_native_storage_1 = __importDefault(require("react-native-storage"));
30
31
  const is_browser_js_1 = require("../functions/is-browser.js");
31
32
  const async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage"));
@@ -52,7 +53,10 @@ const getCookie = (_0) => __async(void 0, [_0], function* ({ name, canTrack }) {
52
53
  return data.value;
53
54
  }
54
55
  catch (err) {
55
- console.debug("[COOKIE] GET error: ", err);
56
+ if ((err == null ? void 0 : err.name) !== "NotFoundError") {
57
+ logger_js_1.logger.warn("[COOKIE] GET error: ", (err == null ? void 0 : err.message) || err);
58
+ }
59
+ return void 0;
56
60
  }
57
61
  });
58
62
  exports.getCookie = getCookie;
@@ -64,7 +68,10 @@ const setCookie = (_0) => __async(void 0, [_0], function* ({ name, value, expire
64
68
  yield storage.save({ key: getStorageName(name), data: { value }, expires });
65
69
  }
66
70
  catch (err) {
67
- console.warn("[COOKIE] SET error: ", err);
71
+ if ((err == null ? void 0 : err.name) !== "NotFoundError") {
72
+ logger_js_1.logger.warn("[COOKIE] SET error: ", (err == null ? void 0 : err.message) || err);
73
+ }
74
+ return void 0;
68
75
  }
69
76
  });
70
77
  exports.setCookie = setCookie;
@@ -5,6 +5,7 @@ const MSG_PREFIX = "[Builder.io]: ";
5
5
  const logger = {
6
6
  log: (...message) => console.log(MSG_PREFIX, ...message),
7
7
  error: (...message) => console.error(MSG_PREFIX, ...message),
8
- warn: (...message) => console.warn(MSG_PREFIX, ...message)
8
+ warn: (...message) => console.warn(MSG_PREFIX, ...message),
9
+ debug: (...message) => console.debug(MSG_PREFIX, ...message)
9
10
  };
10
11
  exports.logger = logger;
package/dist/index.js CHANGED
@@ -14,15 +14,22 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.track = void 0;
17
+ exports.track = exports.setEditorSettings = exports.register = exports.processContentResult = exports.isPreviewing = exports.isEditing = exports.getContent = exports.getAllContent = exports.createRegisterComponentMessage = void 0;
18
18
  __exportStar(require("./index-helpers/top-of-file.js"), exports);
19
19
  __exportStar(require("./index-helpers/blocks-exports.js"), exports);
20
- __exportStar(require("./functions/is-editing.js"), exports);
21
- __exportStar(require("./functions/is-previewing.js"), exports);
22
- __exportStar(require("./functions/register-component.js"), exports);
23
- __exportStar(require("./functions/register.js"), exports);
24
- __exportStar(require("./functions/set-editor-settings.js"), exports);
25
- __exportStar(require("./functions/get-content/index.js"), exports);
26
- __exportStar(require("./functions/get-builder-search-params/index.js"), exports);
27
- const index_js_1 = require("./functions/track/index.js");
28
- Object.defineProperty(exports, "track", { enumerable: true, get: function () { return index_js_1.track; } });
20
+ const is_editing_js_1 = require("./functions/is-editing.js");
21
+ Object.defineProperty(exports, "isEditing", { enumerable: true, get: function () { return is_editing_js_1.isEditing; } });
22
+ const is_previewing_js_1 = require("./functions/is-previewing.js");
23
+ Object.defineProperty(exports, "isPreviewing", { enumerable: true, get: function () { return is_previewing_js_1.isPreviewing; } });
24
+ const register_component_js_1 = require("./functions/register-component.js");
25
+ Object.defineProperty(exports, "createRegisterComponentMessage", { enumerable: true, get: function () { return register_component_js_1.createRegisterComponentMessage; } });
26
+ const register_js_1 = require("./functions/register.js");
27
+ Object.defineProperty(exports, "register", { enumerable: true, get: function () { return register_js_1.register; } });
28
+ const set_editor_settings_js_1 = require("./functions/set-editor-settings.js");
29
+ Object.defineProperty(exports, "setEditorSettings", { enumerable: true, get: function () { return set_editor_settings_js_1.setEditorSettings; } });
30
+ const index_js_1 = require("./functions/get-content/index.js");
31
+ Object.defineProperty(exports, "getAllContent", { enumerable: true, get: function () { return index_js_1.getAllContent; } });
32
+ Object.defineProperty(exports, "getContent", { enumerable: true, get: function () { return index_js_1.getContent; } });
33
+ Object.defineProperty(exports, "processContentResult", { enumerable: true, get: function () { return index_js_1.processContentResult; } });
34
+ const index_js_2 = require("./functions/track/index.js");
35
+ Object.defineProperty(exports, "track", { enumerable: true, get: function () { return index_js_2.track; } });
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.setupBrowserForEditing = exports.registerInsertMenu = void 0;
4
+ const sdk_version_js_1 = require("../constants/sdk-version.js");
4
5
  const target_js_1 = require("../constants/target.js");
5
6
  const is_browser_js_1 = require("../functions/is-browser.js");
6
7
  const register_js_1 = require("../functions/register.js");
@@ -35,6 +36,7 @@ const setupBrowserForEditing = (options = {}) => {
35
36
  type: "builder.sdkInfo",
36
37
  data: {
37
38
  target: target_js_1.TARGET,
39
+ version: sdk_version_js_1.SDK_VERSION,
38
40
  supportsPatchUpdates: false,
39
41
  supportsAddBlockScoping: true,
40
42
  supportsCustomBreakpoints: true
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@builder.io/sdk-react-native",
3
3
  "description": "Builder.io SDK for React Native",
4
- "version": "0.2.3",
4
+ "version": "0.4.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
@@ -13,10 +13,7 @@
13
13
  "dist"
14
14
  ],
15
15
  "scripts": {
16
- "build": "tsc",
17
- "release:patch": "yarn run build && npm version patch && npm publish",
18
- "release:minor": "yarn run build && npm version minor && npm publish",
19
- "release:dev": "yarn run build && npm version prerelease && npm publish --tag dev"
16
+ "build": "tsc"
20
17
  },
21
18
  "dependencies": {
22
19
  "@react-native-async-storage/async-storage": "^1.17.10",
@@ -1,3 +1,4 @@
1
+ 'use client';
1
2
  import BaseText from "../BaseText";
2
3
  import * as React from "react";
3
4
  import {