@builder.io/sdk-react 0.6.4 → 0.7.1-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 (37) hide show
  1. package/lib/browser/index.cjs +25 -25
  2. package/lib/browser/index.mjs +617 -587
  3. package/lib/{node/server-entry-f7504f89.mjs → browser/server-entry-13b7e1e6.mjs} +208 -190
  4. package/lib/browser/server-entry-c98db16c.js +2 -0
  5. package/lib/browser/server-entry.cjs +1 -1
  6. package/lib/browser/server-entry.mjs +1 -1
  7. package/lib/edge/index.cjs +32 -32
  8. package/lib/edge/index.mjs +1284 -1226
  9. package/lib/{browser/server-entry-f7504f89.mjs → edge/server-entry-13b7e1e6.mjs} +208 -190
  10. package/lib/edge/server-entry-c98db16c.js +2 -0
  11. package/lib/edge/server-entry.cjs +1 -1
  12. package/lib/edge/server-entry.mjs +1 -1
  13. package/lib/index.cjs +14 -0
  14. package/lib/index.mjs +10 -0
  15. package/lib/node/index.cjs +68 -28
  16. package/lib/node/index.mjs +929 -802
  17. package/lib/{edge/server-entry-f7504f89.mjs → node/server-entry-13b7e1e6.mjs} +208 -190
  18. package/lib/node/server-entry-c98db16c.js +2 -0
  19. package/lib/node/server-entry.cjs +1 -1
  20. package/lib/node/server-entry.mjs +1 -1
  21. package/package.json +3 -1
  22. package/types/blocks/image/image.d.ts +1 -1
  23. package/types/constants/sdk-version.d.ts +1 -1
  24. package/types/functions/evaluate/choose-eval.d.ts +6 -0
  25. package/types/functions/evaluate/evaluate.d.ts +1 -5
  26. package/types/functions/evaluate/helpers.d.ts +7 -1
  27. package/types/functions/evaluate/node-runtime/index.d.ts +1 -1
  28. package/types/functions/evaluate/node-runtime/node-runtime.d.ts +2 -0
  29. package/types/functions/evaluate/node-runtime/safeDynamicRequire.d.ts +13 -0
  30. package/types/functions/get-content/types.d.ts +94 -3
  31. package/types/functions/is-node-runtime.d.ts +4 -0
  32. package/types/node-runtime/index.d.ts +1 -0
  33. package/types/node-runtime/node-runtime.d.ts +1 -0
  34. package/types/node-runtime.d.ts +1 -0
  35. package/lib/browser/server-entry-2e639417.js +0 -2
  36. package/lib/edge/server-entry-2e639417.js +0 -2
  37. package/lib/node/server-entry-2e639417.js +0 -2
@@ -0,0 +1,2 @@
1
+ "use strict";const v=t=>JSON.parse(JSON.stringify(t)),p="react",h="[Builder.io]: ",l={log:(...t)=>console.log(h,...t),error:(...t)=>console.error(h,...t),warn:(...t)=>console.warn(h,...t),debug:(...t)=>console.debug(h,...t)};function a(){return typeof window<"u"&&typeof document<"u"}function rt(){return a()&&window.self!==window.top}function I(){return rt()&&window.location.search.indexOf("builder.frameEditing=")!==-1}const ot=()=>{if(a()){const t=new URL(location.href);return t.pathname===""&&(t.pathname="/"),t}else return console.warn("Cannot get location for tracking in non-browser environment"),null},st=()=>typeof navigator=="object"&&navigator.userAgent||"",U=()=>{const t=st(),e={Android(){return t.match(/Android/i)},BlackBerry(){return t.match(/BlackBerry/i)},iOS(){return t.match(/iPhone|iPod/i)},Opera(){return t.match(/Opera Mini/i)},Windows(){return t.match(/IEMobile/i)||t.match(/WPDesktop/i)},any(){return e.Android()||e.BlackBerry()||e.iOS()||e.Opera()||e.Windows()||p==="reactNative"}},n=t.match(/Tablet|iPad/i),r=ot();return{urlPath:r==null?void 0:r.pathname,host:(r==null?void 0:r.host)||(r==null?void 0:r.hostname),device:n?"tablet":e.any()?"mobile":"desktop"}},d=t=>t!=null,it=[],at=t=>({type:"builder.registerComponent",data:F(t)}),ct=t=>{const e=t.toString().trim();return`return (${!e.startsWith("function")&&!e.startsWith("(")?"function ":""}${e}).apply(this, arguments)`},ut=t=>typeof t=="function"?ct(t):v(t),F=({inputs:t,...e})=>({...v(e),inputs:t==null?void 0:t.map(n=>Object.entries(n).reduce((r,[o,s])=>({...r,[o]:ut(s)}),{}))});function lt(){return typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:globalThis}function dt(){const t=lt().fetch;if(typeof t>"u")throw console.warn(`Builder SDK could not find a global fetch function. Make sure you have a polyfill for fetch in your project.
2
+ For more information, read https://github.com/BuilderIO/this-package-uses-fetch`),new Error("Builder SDK could not find a global `fetch` function");return t}const M=dt(),ft=t=>{if(t==="localhost"||t==="127.0.0.1")return t;const e=t.split(".");return e.length>2?e.slice(1).join("."):t},D=({name:t,canTrack:e})=>{var n;try{return e?(n=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`)))==null?void 0:n.split("=")[1]:void 0}catch(r){l.warn("[COOKIE] GET error: ",(r==null?void 0:r.message)||r);return}},K=async t=>D(t),ht=t=>t.map(([e,n])=>n?`${e}=${n}`:e).filter(d).join("; "),gt=[["secure",""],["SameSite","None"]],pt=({name:t,value:e,expires:n})=>{const o=(a()?location.protocol==="https:":!0)?gt:[[]],s=n?[["expires",n.toUTCString()]]:[[]],c=[[t,e],...s,["path","/"],["domain",ft(window.location.hostname)],...o];return ht(c)},_=async({name:t,value:e,expires:n,canTrack:r})=>{try{if(!r)return;const o=pt({name:t,value:e,expires:n});document.cookie=o}catch(o){l.warn("[COOKIE] SET error: ",(o==null?void 0:o.message)||o)}};function yt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function G(){return yt().replace(/-/g,"")}const W="builderSessionId",mt=async({canTrack:t})=>{if(!t)return;const e=await K({name:W,canTrack:t});if(d(e))return e;{const n=St();return wt({id:n,canTrack:t}),n}},St=()=>G(),wt=({id:t,canTrack:e})=>_({name:W,value:t,canTrack:e}),J=()=>a()&&typeof localStorage<"u"?localStorage:void 0,bt=({key:t,canTrack:e})=>{var n;try{return e?(n=J())==null?void 0:n.getItem(t):void 0}catch(r){console.debug("[LocalStorage] GET error: ",r);return}},vt=({key:t,canTrack:e,value:n})=>{var r;try{e&&((r=J())==null||r.setItem(t,n))}catch(o){console.debug("[LocalStorage] SET error: ",o)}},z="builderVisitorId",It=({canTrack:t})=>{if(!t)return;const e=bt({key:z,canTrack:t});if(d(e))return e;{const n=Ct();return kt({id:n,canTrack:t}),n}},Ct=()=>G(),kt=({id:t,canTrack:e})=>vt({key:z,value:t,canTrack:e}),Et=async({canTrack:t})=>{if(!t)return{visitorId:void 0,sessionId:void 0};const e=await mt({canTrack:t}),n=It({canTrack:t});return{sessionId:e,visitorId:n}},Ot=async({type:t,canTrack:e,apiKey:n,metadata:r,...o})=>({type:t,data:{...o,metadata:{url:location.href,...r},...await Et({canTrack:e}),userAttributes:U(),ownerId:n}});async function X(t){if(!t.apiKey){l.error("Missing API key for track call. Please provide your API key.");return}if(t.canTrack&&!I()&&(a()||p==="reactNative"))return fetch("https://cdn.builder.io/api/v1/track",{method:"POST",body:JSON.stringify({events:[await Ot(t)]}),headers:{"content-type":"application/json"},mode:"cors"}).catch(e=>{console.error("Failed to track: ",e)})}const Pt=t=>X({...t,canTrack:!0}),L={};function At(t,e){let n=L[t];if(n||(n=L[t]=[]),n.push(e),a()){const r={type:"builder.register",data:{type:t,info:e}};try{parent.postMessage(r,"*"),parent!==window&&window.postMessage(r,"*")}catch(o){console.debug("Could not postmessage",o)}}}const xt="builder.tests",C=t=>`${xt}.${t}`,Tt=({contentId:t})=>K({name:C(t),canTrack:!0}),Rt=({contentId:t})=>D({name:C(t),canTrack:!0}),Bt=({contentId:t,value:e})=>_({name:C(t),value:e,canTrack:!0}),q=t=>d(t.id)&&d(t.variations)&&Object.keys(t.variations).length>0,Vt=({id:t,variations:e})=>{var o;let n=0;const r=Math.random();for(const s in e){const c=(o=e[s])==null?void 0:o.testRatio;if(n+=c,r<n)return s}return t},H=t=>{const e=Vt(t);return Bt({contentId:t.id,value:e}).catch(n=>{l.error("could not store A/B test variation: ",n)}),e},Y=({item:t,testGroupId:e})=>{const n=t.variations[e];return e===t.id||!n?{testVariationId:t.id,testVariationName:"Default"}:{data:n.data,testVariationId:n.id,testVariationName:n.name||(n.id===t.id?"Default":"")}},Lt=({item:t,canTrack:e})=>{if(!e)return t;if(!t)return;if(!q(t))return t;const n=Rt({contentId:t.id})||H({variations:t.variations,id:t.id}),r=Y({item:t,testGroupId:n});return{...t,...r}},Nt=async({item:t,canTrack:e})=>{if(!e||!q(t))return t;const r=await Tt({contentId:t.id})||H({variations:t.variations,id:t.id}),o=Y({item:t,testGroupId:r});return{...t,...o}},Q=t=>d(t)?t:!0;function g(t,e=null,n="."){return Object.keys(t).reduce((r,o)=>{const s=t[o],c=[e,o].filter(Boolean).join(n);return[typeof s=="object",s!==null,!(Array.isArray(s)&&s.length===0)].every(Boolean)?{...r,...g(s,c,n)}:{...r,[c]:s}},{})}const N="builder.",$t="options.",jt=t=>{const e={};return t.forEach((n,r)=>{e[r]=n}),e},k=t=>{if(!t)return{};const e=Z(t),n={};return Object.keys(e).forEach(r=>{if(r.startsWith(N)){const o=r.replace(N,"").replace($t,"");n[o]=e[r]}}),n},Ut=()=>{if(!a())return{};const t=new URLSearchParams(window.location.search);return k(t)},Z=t=>t instanceof URLSearchParams?jt(t):t,Ft="v3",$=t=>typeof t=="number"&&!isNaN(t)&&t>=0,E=t=>{let{noTraverse:e=!1}=t;const{limit:n=30,userAttributes:r,query:o,model:s,apiKey:c,includeRefs:y=!0,enrich:A,locale:x,apiVersion:m=Ft,fields:T,omit:et,offset:S,cacheSeconds:w,staleCacheSeconds:b,sort:R,includeUnpublished:B}=t;if(!c)throw new Error("Missing API key");if(!["v2","v3"].includes(m))throw new Error(`Invalid apiVersion: expected 'v2' or 'v3', received '${m}'`);(t.limit===void 0||t.limit>1)&&!("noTraverse"in t)&&(e=!0);const i=new URL(`https://cdn.builder.io/api/${m}/content/${s}?apiKey=${c}&limit=${n}&noTraverse=${e}&includeRefs=${y}${x?`&locale=${x}`:""}${A?`&enrich=${A}`:""}`);if(i.searchParams.set("omit",et||"meta.componentsUsed"),T&&i.searchParams.set("fields",T),Number.isFinite(S)&&S>-1&&i.searchParams.set("offset",String(Math.floor(S))),typeof B=="boolean"&&i.searchParams.set("includeUnpublished",String(B)),w&&$(w)&&i.searchParams.set("cacheSeconds",String(w)),b&&$(b)&&i.searchParams.set("staleCacheSeconds",String(b)),R){const u=g({sort:R});for(const f in u)i.searchParams.set(f,JSON.stringify(u[f]))}const nt={...Ut(),...Z(t.options||{})},V=g(nt);for(const u in V)i.searchParams.set(u,String(V[u]));if(r&&i.searchParams.set("userAttributes",JSON.stringify(r)),o){const u=g({query:o});for(const f in u)i.searchParams.set(f,JSON.stringify(u[f]))}return i},Mt=t=>"results"in t;async function O(t){const e=await P({...t,limit:1});return e&&e.results[0]||null}const Dt=O,Kt=async t=>{const e=E(t);return await(await M(e.href)).json()},tt=async(t,e,n=E(t))=>{const r=Q(t.canTrack);if(n.search.includes("preview="),!r||!(a()||p==="reactNative"))return e;try{const o=[];for(const s of e.results)o.push(await Nt({item:s,canTrack:r}));e.results=o}catch(o){l.error("Could not process A/B tests. ",o)}return e};async function P(t){try{const e=E(t),n=await Kt(t);return Mt(n)?tt(t,n):(l.error("Error fetching data. ",{url:e,content:n,options:t}),null)}catch(e){return l.error("Error fetching data. ",e),null}}const _t=P;function Gt(){return!a()||I()?!1:location.search.indexOf("builder.preview=")!==-1}const j={};function Wt(t){if(a()){Object.assign(j,t);const e={type:"builder.settingsChange",data:j};parent.postMessage(e,"*")}}const Jt=async t=>{var r,o,s;const e=t.path||((r=t.url)==null?void 0:r.pathname)||((o=t.userAttributes)==null?void 0:o.urlPath),n={...t,apiKey:t.apiKey,model:t.model||"page",userAttributes:{...t.userAttributes,...e?{urlPath:e}:{}},options:k(t.searchParams||((s=t.url)==null?void 0:s.searchParams)||t.options)};return{apiKey:n.apiKey,model:n.model,content:await O(n)}};exports.TARGET=p;exports._processContentResult=tt;exports._track=X;exports.checkIsDefined=d;exports.components=it;exports.createRegisterComponentMessage=at;exports.fastClone=v;exports.fetch=M;exports.fetchBuilderProps=Jt;exports.fetchEntries=P;exports.fetchOneEntry=O;exports.getAllContent=_t;exports.getBuilderSearchParams=k;exports.getContent=Dt;exports.getDefaultCanTrack=Q;exports.getUserAttributes=U;exports.handleABTestingSync=Lt;exports.isBrowser=a;exports.isEditing=I;exports.isPreviewing=Gt;exports.logger=l;exports.register=At;exports.serializeComponentInfo=F;exports.setEditorSettings=Wt;exports.track=Pt;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./server-entry-2e639417.js");exports._processContentResult=e._processContentResult;exports.createRegisterComponentMessage=e.createRegisterComponentMessage;exports.fetchBuilderProps=e.fetchBuilderProps;exports.fetchEntries=e.fetchEntries;exports.fetchOneEntry=e.fetchOneEntry;exports.getAllContent=e.getAllContent;exports.getBuilderSearchParams=e.getBuilderSearchParams;exports.getContent=e.getContent;exports.isEditing=e.isEditing;exports.isPreviewing=e.isPreviewing;exports.register=e.register;exports.setEditorSettings=e.setEditorSettings;exports.track=e.track;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./server-entry-c98db16c.js");exports._processContentResult=e._processContentResult;exports.createRegisterComponentMessage=e.createRegisterComponentMessage;exports.fetchBuilderProps=e.fetchBuilderProps;exports.fetchEntries=e.fetchEntries;exports.fetchOneEntry=e.fetchOneEntry;exports.getAllContent=e.getAllContent;exports.getBuilderSearchParams=e.getBuilderSearchParams;exports.getContent=e.getContent;exports.isEditing=e.isEditing;exports.isPreviewing=e.isPreviewing;exports.register=e.register;exports.setEditorSettings=e.setEditorSettings;exports.track=e.track;
@@ -1,4 +1,4 @@
1
- import { _ as t, c as a, h as r, f as i, b as n, g, e as o, d as c, i as d, a as f, r as h, s as l, t as p } from "./server-entry-f7504f89.mjs";
1
+ import { _ as t, c as a, h as r, f as i, b as n, g, e as o, d as c, i as d, a as f, r as h, s as l, t as p } from "./server-entry-13b7e1e6.mjs";
2
2
  export {
3
3
  t as _processContentResult,
4
4
  a as createRegisterComponentMessage,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@builder.io/sdk-react",
3
3
  "description": "Builder.io SDK for React",
4
- "version": "0.6.4",
4
+ "version": "0.7.1-0",
5
5
  "files": [
6
6
  "lib",
7
7
  "types"
@@ -94,6 +94,7 @@
94
94
  }
95
95
  },
96
96
  "scripts": {
97
+ "release": "npm publish",
97
98
  "types": "tsc",
98
99
  "build": "nx run-many -p @builder.io/sdk-react -t types build:node build:edge build:browser",
99
100
  "build:node": "SDK_ENV=node vite build --mode lib",
@@ -101,6 +102,7 @@
101
102
  "build:browser": "SDK_ENV=browser vite build --mode lib"
102
103
  },
103
104
  "peerDependencies": {
105
+ "isolated-vm": "^4.6.0",
104
106
  "react": "^18.2.0"
105
107
  },
106
108
  "devDependencies": {
@@ -11,7 +11,7 @@ export interface ImageProps {
11
11
  backgroundPosition?: string;
12
12
  srcset?: string;
13
13
  aspectRatio?: number;
14
- children?: JSX.Element;
14
+ children?: any;
15
15
  fitContent?: boolean;
16
16
  builderBlock?: BuilderBlock;
17
17
  noWebp?: boolean;
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.6.4";
1
+ export declare const SDK_VERSION = "0.7.1-0";
@@ -0,0 +1,6 @@
1
+ import type { ExecutorArgs } from './helpers.js';
2
+ /**
3
+ * Even though we have separate runtimes for browser/node/edge, sometimes frameworks will
4
+ * end up sending the server runtime code to the browser (most notably in dev mode).
5
+ */
6
+ export declare const chooseBrowserOrServerEval: (args: ExecutorArgs) => any;
@@ -1,6 +1,2 @@
1
- import type { ExecutorArgs } from './helpers.js';
2
- export type EvaluatorArgs = Omit<ExecutorArgs, 'builder' | 'event'> & {
3
- event?: Event;
4
- isExpression?: boolean;
5
- };
1
+ import type { EvaluatorArgs } from './helpers.js';
6
2
  export declare function evaluate({ code, context, localState, rootState, rootSetState, event, isExpression }: EvaluatorArgs): any;
@@ -1,5 +1,9 @@
1
1
  import type { BuilderContextInterface, BuilderRenderState } from '../../context/types.js';
2
- import type { getUserAttributes } from '../track/helpers.js';
2
+ import { getUserAttributes } from '../track/helpers.js';
3
+ export type EvaluatorArgs = Omit<ExecutorArgs, 'builder' | 'event'> & {
4
+ event?: Event;
5
+ isExpression?: boolean;
6
+ };
3
7
  export type BuilderGlobals = {
4
8
  isEditing: boolean | undefined;
5
9
  isBrowser: boolean | undefined;
@@ -16,3 +20,5 @@ export type FunctionArguments = ReturnType<typeof getFunctionArguments>;
16
20
  export declare const getFunctionArguments: ({ builder, context, event, state }: Pick<ExecutorArgs, "context" | "builder" | "event"> & {
17
21
  state: BuilderRenderState;
18
22
  }) => [string, Event | BuilderRenderState | import("../../context/types.js").BuilderRenderContext | BuilderGlobals][];
23
+ export declare const getBuilderGlobals: () => BuilderGlobals;
24
+ export declare const parseCode: (code: string, { isExpression }: Pick<EvaluatorArgs, 'isExpression'>) => string;
@@ -1 +1 @@
1
- export { evaluator } from '../browser-runtime/index.js';
1
+ export { runInNode as evaluator } from './node-runtime.js';
@@ -0,0 +1,2 @@
1
+ import type { ExecutorArgs } from '../helpers.js';
2
+ export declare const runInNode: ({ code, builder, context, event, localState, rootSetState, rootState }: ExecutorArgs) => any;
@@ -0,0 +1,13 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="react-native" />
3
+ /**
4
+ * Allows us to require node-specific code safely within bundlers.
5
+ *
6
+ * https://github.com/laverdet/isolated-vm/issues/423
7
+ *
8
+ * NOTE: this code should only ever run in `node`, and never in an `edge` runtime.
9
+ * This is guaranteed by the fact that each SDK has separate bundles for each runtime.
10
+ * However, it might still end up running in the `browser` if the `node` bundle is loaded in the
11
+ * browser (which happens in many apps' dev mode, and certain other scenarios like Qwik's prod mode).
12
+ */
13
+ export declare let safeDynamicRequire: typeof require;
@@ -5,11 +5,42 @@ export interface GetContentOptions {
5
5
  apiKey: string;
6
6
  /** Number of items to fetch. Default is 1 */
7
7
  limit?: number;
8
- /** User attributes to target on, such as { urlPath: '/foo', device: 'mobile', ...etc } */
8
+ /**
9
+ * Use to specify an offset for pagination of results. The default is 0.
10
+ */
11
+ offset?: number;
12
+ /**
13
+ * User attribute key value pairs to be used for targeting
14
+ * https://www.builder.io/c/docs/custom-targeting-attributes
15
+ *
16
+ * e.g.
17
+ * ```js
18
+ * userAttributes: {
19
+ * urlPath: '/',
20
+ * returnVisitor: true,
21
+ * device: 'mobile'
22
+ * }
23
+ * ```
24
+ */
9
25
  userAttributes?: (Record<string, string> & {
10
26
  urlPath?: string;
11
27
  }) | null;
12
- /** Custom query */
28
+ /**
29
+ * Mongodb style query of your data. E.g.:
30
+ *
31
+ * ```js
32
+ * query: {
33
+ * id: 'abc123',
34
+ * data: {
35
+ * myCustomField: { $gt: 20 },
36
+ * }
37
+ * }
38
+ * ```
39
+ *
40
+ * See more info on MongoDB's query operators and format.
41
+ *
42
+ * @see {@link https://docs.mongodb.com/manual/reference/operator/query/}
43
+ */
13
44
  query?: Record<string, any>;
14
45
  /**
15
46
  * Any other API options.
@@ -30,7 +61,7 @@ export interface GetContentOptions {
30
61
  */
31
62
  canTrack?: boolean;
32
63
  /**
33
- * Include references in the response. Defaults to `true`.
64
+ * Include content of references in the response. Defaults to `true`.
34
65
  * @deprecated use `enrich` instead
35
66
  */
36
67
  includeRefs?: boolean;
@@ -48,4 +79,64 @@ export interface GetContentOptions {
48
79
  * Defaults to `v3`.
49
80
  */
50
81
  apiVersion?: 'v2' | 'v3';
82
+ /**
83
+ * Only include these fields.
84
+ * Note: 'omit' takes precedence over 'fields'
85
+ *
86
+ * @example
87
+ * ```
88
+ * fields: 'id, name, data.customField'
89
+ * ```
90
+ */
91
+ fields?: string;
92
+ /**
93
+ * Omit only these fields.
94
+ * Note: 'omit' takes precedence over 'fields'
95
+ *
96
+ * @example
97
+ * ```
98
+ * omit: 'data.bigField,data.blocks'
99
+ * ```
100
+ */
101
+ omit?: string;
102
+ /**
103
+ * Seconds to cache content. Sets the max-age of the cache-control header
104
+ * response header.
105
+ *
106
+ * Use a higher value for better performance, lower for content that will change more frequently
107
+ *
108
+ * @see {@link https://www.builder.io/c/docs/query-api#__next:~:text=%26includeRefs%3Dtrue-,cacheSeconds,-No}
109
+ */
110
+ cacheSeconds?: number;
111
+ /**
112
+ * Builder.io uses stale-while-revalidate caching at the CDN level. This means we always serve
113
+ * from edge cache and update caches in the background for maximum possible performance. This also
114
+ * means that the more frequently content is requested, the more fresh it will be. The longest we
115
+ * will ever hold something in stale cache is 1 day by default, and you can set this to be shorter
116
+ * yourself as well. We suggest keeping this high unless you have content that must change rapidly
117
+ * and gets very little traffic.
118
+ *
119
+ * @see {@link https://www.fastly.com/blog/prevent-application-network-instability-serve-stale-content}
120
+ */
121
+ staleCacheSeconds?: number;
122
+ /**
123
+ * Property to order results by.
124
+ * Use 1 for ascending and -1 for descending.
125
+ *
126
+ * The key is what you're sorting on, so the following example sorts by createdDate
127
+ * and because the value is 1, the sort is ascending.
128
+ *
129
+ * @example
130
+ * ```
131
+ * createdDate: 1
132
+ * ```
133
+ */
134
+ sort?: {
135
+ [key: string]: 1 | -1;
136
+ };
137
+ /**
138
+ * Include content entries in a response that are still in
139
+ * draft mode and un-archived. Default is false.
140
+ */
141
+ includeUnpublished?: boolean;
51
142
  }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Identifies node runtime
3
+ */
4
+ export declare function isNodeRuntime(): boolean;
@@ -0,0 +1 @@
1
+ export { evaluator } from './node-runtime.js';
@@ -0,0 +1 @@
1
+ export declare const evaluator: ({ code, builder, context, event, localState, rootSetState, rootState }: ExecutorArgs) => any;
@@ -0,0 +1 @@
1
+ export declare const evaluator: (code: string) => any;
@@ -1,2 +0,0 @@
1
- "use strict";const m=t=>JSON.parse(JSON.stringify(t)),g="react",f="[Builder.io]: ",c={log:(...t)=>console.log(f,...t),error:(...t)=>console.error(f,...t),warn:(...t)=>console.warn(f,...t),debug:(...t)=>console.debug(f,...t)};function s(){return typeof window<"u"&&typeof document<"u"}function q(){return s()&&window.self!==window.top}function w(){return q()&&window.location.search.indexOf("builder.frameEditing=")!==-1}const H=()=>{if(s()){const t=new URL(location.href);return t.pathname===""&&(t.pathname="/"),t}else return console.warn("Cannot get location for tracking in non-browser environment"),null},Y=()=>typeof navigator=="object"&&navigator.userAgent||"",R=()=>{const t=Y(),e={Android(){return t.match(/Android/i)},BlackBerry(){return t.match(/BlackBerry/i)},iOS(){return t.match(/iPhone|iPod/i)},Opera(){return t.match(/Opera Mini/i)},Windows(){return t.match(/IEMobile/i)||t.match(/WPDesktop/i)},any(){return e.Android()||e.BlackBerry()||e.iOS()||e.Opera()||e.Windows()||g==="reactNative"}},n=t.match(/Tablet|iPad/i),r=H();return{urlPath:r==null?void 0:r.pathname,host:(r==null?void 0:r.host)||(r==null?void 0:r.hostname),device:n?"tablet":e.any()?"mobile":"desktop"}},u=t=>t!=null,Q=[],Z=t=>({type:"builder.registerComponent",data:B(t)}),tt=t=>{const e=t.toString().trim();return`return (${!e.startsWith("function")&&!e.startsWith("(")?"function ":""}${e}).apply(this, arguments)`},et=t=>typeof t=="function"?tt(t):m(t),B=({inputs:t,...e})=>({...m(e),inputs:t==null?void 0:t.map(n=>Object.entries(n).reduce((r,[o,i])=>({...r,[o]:et(i)}),{}))});function nt(){return typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:globalThis}function rt(){const t=nt().fetch;if(typeof t>"u")throw console.warn(`Builder SDK could not find a global fetch function. Make sure you have a polyfill for fetch in your project.
2
- For more information, read https://github.com/BuilderIO/this-package-uses-fetch`),new Error("Builder SDK could not find a global `fetch` function");return t}const V=rt(),ot=t=>{if(t==="localhost"||t==="127.0.0.1")return t;const e=t.split(".");return e.length>2?e.slice(1).join("."):t},L=({name:t,canTrack:e})=>{var n;try{return e?(n=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`)))==null?void 0:n.split("=")[1]:void 0}catch(r){c.warn("[COOKIE] GET error: ",(r==null?void 0:r.message)||r);return}},$=async t=>L(t),it=t=>t.map(([e,n])=>n?`${e}=${n}`:e).filter(u).join("; "),st=[["secure",""],["SameSite","None"]],at=({name:t,value:e,expires:n})=>{const o=(s()?location.protocol==="https:":!0)?st:[[]],i=n?[["expires",n.toUTCString()]]:[[]],a=[[t,e],...i,["path","/"],["domain",ot(window.location.hostname)],...o];return it(a)},j=async({name:t,value:e,expires:n,canTrack:r})=>{try{if(!r)return;const o=at({name:t,value:e,expires:n});document.cookie=o}catch(o){c.warn("[COOKIE] SET error: ",(o==null?void 0:o.message)||o)}};function ct(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function D(){return ct().replace(/-/g,"")}const F="builderSessionId",ut=async({canTrack:t})=>{if(!t)return;const e=await $({name:F,canTrack:t});if(u(e))return e;{const n=lt();return dt({id:n,canTrack:t}),n}},lt=()=>D(),dt=({id:t,canTrack:e})=>j({name:F,value:t,canTrack:e}),K=()=>s()&&typeof localStorage<"u"?localStorage:void 0,ft=({key:t,canTrack:e})=>{var n;try{return e?(n=K())==null?void 0:n.getItem(t):void 0}catch(r){console.debug("[LocalStorage] GET error: ",r);return}},gt=({key:t,canTrack:e,value:n})=>{var r;try{e&&((r=K())==null||r.setItem(t,n))}catch(o){console.debug("[LocalStorage] SET error: ",o)}},M="builderVisitorId",ht=({canTrack:t})=>{if(!t)return;const e=ft({key:M,canTrack:t});if(u(e))return e;{const n=pt();return yt({id:n,canTrack:t}),n}},pt=()=>D(),yt=({id:t,canTrack:e})=>gt({key:M,value:t,canTrack:e}),mt=async({canTrack:t})=>{if(!t)return{visitorId:void 0,sessionId:void 0};const e=await ut({canTrack:t}),n=ht({canTrack:t});return{sessionId:e,visitorId:n}},wt=async({type:t,canTrack:e,apiKey:n,metadata:r,...o})=>({type:t,data:{...o,metadata:{url:location.href,...r},...await mt({canTrack:e}),userAttributes:R(),ownerId:n}});async function N(t){if(!t.apiKey){c.error("Missing API key for track call. Please provide your API key.");return}if(t.canTrack&&!w()&&(s()||g==="reactNative"))return fetch("https://cdn.builder.io/api/v1/track",{method:"POST",body:JSON.stringify({events:[await wt(t)]}),headers:{"content-type":"application/json"},mode:"cors"}).catch(e=>{console.error("Failed to track: ",e)})}const St=t=>N({...t,canTrack:!0}),x={};function It(t,e){let n=x[t];if(n||(n=x[t]=[]),n.push(e),s()){const r={type:"builder.register",data:{type:t,info:e}};try{parent.postMessage(r,"*"),parent!==window&&window.postMessage(r,"*")}catch(o){console.debug("Could not postmessage",o)}}}const vt="builder.tests",S=t=>`${vt}.${t}`,bt=({contentId:t})=>$({name:S(t),canTrack:!0}),Ct=({contentId:t})=>L({name:S(t),canTrack:!0}),Et=({contentId:t,value:e})=>j({name:S(t),value:e,canTrack:!0}),U=t=>u(t.id)&&u(t.variations)&&Object.keys(t.variations).length>0,kt=({id:t,variations:e})=>{var o;let n=0;const r=Math.random();for(const i in e){const a=(o=e[i])==null?void 0:o.testRatio;if(n+=a,r<n)return i}return t},_=t=>{const e=kt(t);return Et({contentId:t.id,value:e}).catch(n=>{c.error("could not store A/B test variation: ",n)}),e},G=({item:t,testGroupId:e})=>{const n=t.variations[e];return e===t.id||!n?{testVariationId:t.id,testVariationName:"Default"}:{data:n.data,testVariationId:n.id,testVariationName:n.name||(n.id===t.id?"Default":"")}},Ot=({item:t,canTrack:e})=>{if(!e)return t;if(!t)return;if(!U(t))return t;const n=Ct({contentId:t.id})||_({variations:t.variations,id:t.id}),r=G({item:t,testGroupId:n});return{...t,...r}},At=async({item:t,canTrack:e})=>{if(!e||!U(t))return t;const r=await bt({contentId:t.id})||_({variations:t.variations,id:t.id}),o=G({item:t,testGroupId:r});return{...t,...o}},W=t=>u(t)?t:!0;function y(t,e=null,n="."){return Object.keys(t).reduce((r,o)=>{const i=t[o],a=[e,o].filter(Boolean).join(n);return[typeof i=="object",i!==null,!(Array.isArray(i)&&i.length===0)].every(Boolean)?{...r,...y(i,a,n)}:{...r,[a]:i}},{})}const P="builder.",xt="options.",Pt=t=>{const e={};return t.forEach((n,r)=>{e[r]=n}),e},I=t=>{if(!t)return{};const e=z(t),n={};return Object.keys(e).forEach(r=>{if(r.startsWith(P)){const o=r.replace(P,"").replace(xt,"");n[o]=e[r]}}),n},Tt=()=>{if(!s())return{};const t=new URLSearchParams(window.location.search);return I(t)},z=t=>t instanceof URLSearchParams?Pt(t):t,Rt="v3",v=t=>{const{limit:e=30,userAttributes:n,query:r,noTraverse:o=!1,model:i,apiKey:a,includeRefs:h=!0,enrich:E,locale:k,apiVersion:p=Rt}=t;if(!a)throw new Error("Missing API key");if(!["v2","v3"].includes(p))throw new Error(`Invalid apiVersion: expected 'v2' or 'v3', received '${p}'`);const d=new URL(`https://cdn.builder.io/api/${p}/content/${i}?apiKey=${a}&limit=${e}&noTraverse=${o}&includeRefs=${h}${k?`&locale=${k}`:""}${E?`&enrich=${E}`:""}`),X={...Tt(),...z(t.options||{})},O=y(X);for(const l in O)d.searchParams.set(l,String(O[l]));if(n&&d.searchParams.set("userAttributes",JSON.stringify(n)),r){const l=y({query:r});for(const A in l)d.searchParams.set(A,JSON.stringify(l[A]))}return d},Bt=t=>"results"in t;async function b(t){const e=await C({...t,limit:1});return e&&e.results[0]||null}const Vt=b,Lt=async t=>{const e=v(t);return await(await V(e.href)).json()},J=async(t,e,n=v(t))=>{const r=W(t.canTrack);if(n.search.includes("preview="),!r||!(s()||g==="reactNative"))return e;try{const o=[];for(const i of e.results)o.push(await At({item:i,canTrack:r}));e.results=o}catch(o){c.error("Could not process A/B tests. ",o)}return e};async function C(t){try{const e=v(t),n=await Lt(t);return Bt(n)?J(t,n):(c.error("Error fetching data. ",{url:e,content:n,options:t}),null)}catch(e){return c.error("Error fetching data. ",e),null}}const $t=C;function jt(){return!s()||w()?!1:location.search.indexOf("builder.preview=")!==-1}const T={};function Dt(t){if(s()){Object.assign(T,t);const e={type:"builder.settingsChange",data:T};parent.postMessage(e,"*")}}const Ft=async t=>{var r,o,i;const e=t.path||((r=t.url)==null?void 0:r.pathname)||((o=t.userAttributes)==null?void 0:o.urlPath),n={...t,apiKey:t.apiKey,model:t.model||"page",userAttributes:{...t.userAttributes,...e?{urlPath:e}:{}},options:I(t.searchParams||((i=t.url)==null?void 0:i.searchParams)||t.options)};return{apiKey:n.apiKey,model:n.model,content:await b(n)}};exports.TARGET=g;exports._processContentResult=J;exports._track=N;exports.checkIsDefined=u;exports.components=Q;exports.createRegisterComponentMessage=Z;exports.fastClone=m;exports.fetch=V;exports.fetchBuilderProps=Ft;exports.fetchEntries=C;exports.fetchOneEntry=b;exports.getAllContent=$t;exports.getBuilderSearchParams=I;exports.getContent=Vt;exports.getDefaultCanTrack=W;exports.getUserAttributes=R;exports.handleABTestingSync=Ot;exports.isBrowser=s;exports.isEditing=w;exports.isPreviewing=jt;exports.logger=c;exports.register=It;exports.serializeComponentInfo=B;exports.setEditorSettings=Dt;exports.track=St;
@@ -1,2 +0,0 @@
1
- "use strict";const m=t=>JSON.parse(JSON.stringify(t)),g="react",f="[Builder.io]: ",c={log:(...t)=>console.log(f,...t),error:(...t)=>console.error(f,...t),warn:(...t)=>console.warn(f,...t),debug:(...t)=>console.debug(f,...t)};function s(){return typeof window<"u"&&typeof document<"u"}function q(){return s()&&window.self!==window.top}function w(){return q()&&window.location.search.indexOf("builder.frameEditing=")!==-1}const H=()=>{if(s()){const t=new URL(location.href);return t.pathname===""&&(t.pathname="/"),t}else return console.warn("Cannot get location for tracking in non-browser environment"),null},Y=()=>typeof navigator=="object"&&navigator.userAgent||"",R=()=>{const t=Y(),e={Android(){return t.match(/Android/i)},BlackBerry(){return t.match(/BlackBerry/i)},iOS(){return t.match(/iPhone|iPod/i)},Opera(){return t.match(/Opera Mini/i)},Windows(){return t.match(/IEMobile/i)||t.match(/WPDesktop/i)},any(){return e.Android()||e.BlackBerry()||e.iOS()||e.Opera()||e.Windows()||g==="reactNative"}},n=t.match(/Tablet|iPad/i),r=H();return{urlPath:r==null?void 0:r.pathname,host:(r==null?void 0:r.host)||(r==null?void 0:r.hostname),device:n?"tablet":e.any()?"mobile":"desktop"}},u=t=>t!=null,Q=[],Z=t=>({type:"builder.registerComponent",data:B(t)}),tt=t=>{const e=t.toString().trim();return`return (${!e.startsWith("function")&&!e.startsWith("(")?"function ":""}${e}).apply(this, arguments)`},et=t=>typeof t=="function"?tt(t):m(t),B=({inputs:t,...e})=>({...m(e),inputs:t==null?void 0:t.map(n=>Object.entries(n).reduce((r,[o,i])=>({...r,[o]:et(i)}),{}))});function nt(){return typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:globalThis}function rt(){const t=nt().fetch;if(typeof t>"u")throw console.warn(`Builder SDK could not find a global fetch function. Make sure you have a polyfill for fetch in your project.
2
- For more information, read https://github.com/BuilderIO/this-package-uses-fetch`),new Error("Builder SDK could not find a global `fetch` function");return t}const V=rt(),ot=t=>{if(t==="localhost"||t==="127.0.0.1")return t;const e=t.split(".");return e.length>2?e.slice(1).join("."):t},L=({name:t,canTrack:e})=>{var n;try{return e?(n=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`)))==null?void 0:n.split("=")[1]:void 0}catch(r){c.warn("[COOKIE] GET error: ",(r==null?void 0:r.message)||r);return}},$=async t=>L(t),it=t=>t.map(([e,n])=>n?`${e}=${n}`:e).filter(u).join("; "),st=[["secure",""],["SameSite","None"]],at=({name:t,value:e,expires:n})=>{const o=(s()?location.protocol==="https:":!0)?st:[[]],i=n?[["expires",n.toUTCString()]]:[[]],a=[[t,e],...i,["path","/"],["domain",ot(window.location.hostname)],...o];return it(a)},j=async({name:t,value:e,expires:n,canTrack:r})=>{try{if(!r)return;const o=at({name:t,value:e,expires:n});document.cookie=o}catch(o){c.warn("[COOKIE] SET error: ",(o==null?void 0:o.message)||o)}};function ct(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function D(){return ct().replace(/-/g,"")}const F="builderSessionId",ut=async({canTrack:t})=>{if(!t)return;const e=await $({name:F,canTrack:t});if(u(e))return e;{const n=lt();return dt({id:n,canTrack:t}),n}},lt=()=>D(),dt=({id:t,canTrack:e})=>j({name:F,value:t,canTrack:e}),K=()=>s()&&typeof localStorage<"u"?localStorage:void 0,ft=({key:t,canTrack:e})=>{var n;try{return e?(n=K())==null?void 0:n.getItem(t):void 0}catch(r){console.debug("[LocalStorage] GET error: ",r);return}},gt=({key:t,canTrack:e,value:n})=>{var r;try{e&&((r=K())==null||r.setItem(t,n))}catch(o){console.debug("[LocalStorage] SET error: ",o)}},M="builderVisitorId",ht=({canTrack:t})=>{if(!t)return;const e=ft({key:M,canTrack:t});if(u(e))return e;{const n=pt();return yt({id:n,canTrack:t}),n}},pt=()=>D(),yt=({id:t,canTrack:e})=>gt({key:M,value:t,canTrack:e}),mt=async({canTrack:t})=>{if(!t)return{visitorId:void 0,sessionId:void 0};const e=await ut({canTrack:t}),n=ht({canTrack:t});return{sessionId:e,visitorId:n}},wt=async({type:t,canTrack:e,apiKey:n,metadata:r,...o})=>({type:t,data:{...o,metadata:{url:location.href,...r},...await mt({canTrack:e}),userAttributes:R(),ownerId:n}});async function N(t){if(!t.apiKey){c.error("Missing API key for track call. Please provide your API key.");return}if(t.canTrack&&!w()&&(s()||g==="reactNative"))return fetch("https://cdn.builder.io/api/v1/track",{method:"POST",body:JSON.stringify({events:[await wt(t)]}),headers:{"content-type":"application/json"},mode:"cors"}).catch(e=>{console.error("Failed to track: ",e)})}const St=t=>N({...t,canTrack:!0}),x={};function It(t,e){let n=x[t];if(n||(n=x[t]=[]),n.push(e),s()){const r={type:"builder.register",data:{type:t,info:e}};try{parent.postMessage(r,"*"),parent!==window&&window.postMessage(r,"*")}catch(o){console.debug("Could not postmessage",o)}}}const vt="builder.tests",S=t=>`${vt}.${t}`,bt=({contentId:t})=>$({name:S(t),canTrack:!0}),Ct=({contentId:t})=>L({name:S(t),canTrack:!0}),Et=({contentId:t,value:e})=>j({name:S(t),value:e,canTrack:!0}),U=t=>u(t.id)&&u(t.variations)&&Object.keys(t.variations).length>0,kt=({id:t,variations:e})=>{var o;let n=0;const r=Math.random();for(const i in e){const a=(o=e[i])==null?void 0:o.testRatio;if(n+=a,r<n)return i}return t},_=t=>{const e=kt(t);return Et({contentId:t.id,value:e}).catch(n=>{c.error("could not store A/B test variation: ",n)}),e},G=({item:t,testGroupId:e})=>{const n=t.variations[e];return e===t.id||!n?{testVariationId:t.id,testVariationName:"Default"}:{data:n.data,testVariationId:n.id,testVariationName:n.name||(n.id===t.id?"Default":"")}},Ot=({item:t,canTrack:e})=>{if(!e)return t;if(!t)return;if(!U(t))return t;const n=Ct({contentId:t.id})||_({variations:t.variations,id:t.id}),r=G({item:t,testGroupId:n});return{...t,...r}},At=async({item:t,canTrack:e})=>{if(!e||!U(t))return t;const r=await bt({contentId:t.id})||_({variations:t.variations,id:t.id}),o=G({item:t,testGroupId:r});return{...t,...o}},W=t=>u(t)?t:!0;function y(t,e=null,n="."){return Object.keys(t).reduce((r,o)=>{const i=t[o],a=[e,o].filter(Boolean).join(n);return[typeof i=="object",i!==null,!(Array.isArray(i)&&i.length===0)].every(Boolean)?{...r,...y(i,a,n)}:{...r,[a]:i}},{})}const P="builder.",xt="options.",Pt=t=>{const e={};return t.forEach((n,r)=>{e[r]=n}),e},I=t=>{if(!t)return{};const e=z(t),n={};return Object.keys(e).forEach(r=>{if(r.startsWith(P)){const o=r.replace(P,"").replace(xt,"");n[o]=e[r]}}),n},Tt=()=>{if(!s())return{};const t=new URLSearchParams(window.location.search);return I(t)},z=t=>t instanceof URLSearchParams?Pt(t):t,Rt="v3",v=t=>{const{limit:e=30,userAttributes:n,query:r,noTraverse:o=!1,model:i,apiKey:a,includeRefs:h=!0,enrich:E,locale:k,apiVersion:p=Rt}=t;if(!a)throw new Error("Missing API key");if(!["v2","v3"].includes(p))throw new Error(`Invalid apiVersion: expected 'v2' or 'v3', received '${p}'`);const d=new URL(`https://cdn.builder.io/api/${p}/content/${i}?apiKey=${a}&limit=${e}&noTraverse=${o}&includeRefs=${h}${k?`&locale=${k}`:""}${E?`&enrich=${E}`:""}`),X={...Tt(),...z(t.options||{})},O=y(X);for(const l in O)d.searchParams.set(l,String(O[l]));if(n&&d.searchParams.set("userAttributes",JSON.stringify(n)),r){const l=y({query:r});for(const A in l)d.searchParams.set(A,JSON.stringify(l[A]))}return d},Bt=t=>"results"in t;async function b(t){const e=await C({...t,limit:1});return e&&e.results[0]||null}const Vt=b,Lt=async t=>{const e=v(t);return await(await V(e.href)).json()},J=async(t,e,n=v(t))=>{const r=W(t.canTrack);if(n.search.includes("preview="),!r||!(s()||g==="reactNative"))return e;try{const o=[];for(const i of e.results)o.push(await At({item:i,canTrack:r}));e.results=o}catch(o){c.error("Could not process A/B tests. ",o)}return e};async function C(t){try{const e=v(t),n=await Lt(t);return Bt(n)?J(t,n):(c.error("Error fetching data. ",{url:e,content:n,options:t}),null)}catch(e){return c.error("Error fetching data. ",e),null}}const $t=C;function jt(){return!s()||w()?!1:location.search.indexOf("builder.preview=")!==-1}const T={};function Dt(t){if(s()){Object.assign(T,t);const e={type:"builder.settingsChange",data:T};parent.postMessage(e,"*")}}const Ft=async t=>{var r,o,i;const e=t.path||((r=t.url)==null?void 0:r.pathname)||((o=t.userAttributes)==null?void 0:o.urlPath),n={...t,apiKey:t.apiKey,model:t.model||"page",userAttributes:{...t.userAttributes,...e?{urlPath:e}:{}},options:I(t.searchParams||((i=t.url)==null?void 0:i.searchParams)||t.options)};return{apiKey:n.apiKey,model:n.model,content:await b(n)}};exports.TARGET=g;exports._processContentResult=J;exports._track=N;exports.checkIsDefined=u;exports.components=Q;exports.createRegisterComponentMessage=Z;exports.fastClone=m;exports.fetch=V;exports.fetchBuilderProps=Ft;exports.fetchEntries=C;exports.fetchOneEntry=b;exports.getAllContent=$t;exports.getBuilderSearchParams=I;exports.getContent=Vt;exports.getDefaultCanTrack=W;exports.getUserAttributes=R;exports.handleABTestingSync=Ot;exports.isBrowser=s;exports.isEditing=w;exports.isPreviewing=jt;exports.logger=c;exports.register=It;exports.serializeComponentInfo=B;exports.setEditorSettings=Dt;exports.track=St;
@@ -1,2 +0,0 @@
1
- "use strict";const m=t=>JSON.parse(JSON.stringify(t)),g="react",f="[Builder.io]: ",c={log:(...t)=>console.log(f,...t),error:(...t)=>console.error(f,...t),warn:(...t)=>console.warn(f,...t),debug:(...t)=>console.debug(f,...t)};function s(){return typeof window<"u"&&typeof document<"u"}function q(){return s()&&window.self!==window.top}function w(){return q()&&window.location.search.indexOf("builder.frameEditing=")!==-1}const H=()=>{if(s()){const t=new URL(location.href);return t.pathname===""&&(t.pathname="/"),t}else return console.warn("Cannot get location for tracking in non-browser environment"),null},Y=()=>typeof navigator=="object"&&navigator.userAgent||"",R=()=>{const t=Y(),e={Android(){return t.match(/Android/i)},BlackBerry(){return t.match(/BlackBerry/i)},iOS(){return t.match(/iPhone|iPod/i)},Opera(){return t.match(/Opera Mini/i)},Windows(){return t.match(/IEMobile/i)||t.match(/WPDesktop/i)},any(){return e.Android()||e.BlackBerry()||e.iOS()||e.Opera()||e.Windows()||g==="reactNative"}},n=t.match(/Tablet|iPad/i),r=H();return{urlPath:r==null?void 0:r.pathname,host:(r==null?void 0:r.host)||(r==null?void 0:r.hostname),device:n?"tablet":e.any()?"mobile":"desktop"}},u=t=>t!=null,Q=[],Z=t=>({type:"builder.registerComponent",data:B(t)}),tt=t=>{const e=t.toString().trim();return`return (${!e.startsWith("function")&&!e.startsWith("(")?"function ":""}${e}).apply(this, arguments)`},et=t=>typeof t=="function"?tt(t):m(t),B=({inputs:t,...e})=>({...m(e),inputs:t==null?void 0:t.map(n=>Object.entries(n).reduce((r,[o,i])=>({...r,[o]:et(i)}),{}))});function nt(){return typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:globalThis}function rt(){const t=nt().fetch;if(typeof t>"u")throw console.warn(`Builder SDK could not find a global fetch function. Make sure you have a polyfill for fetch in your project.
2
- For more information, read https://github.com/BuilderIO/this-package-uses-fetch`),new Error("Builder SDK could not find a global `fetch` function");return t}const V=rt(),ot=t=>{if(t==="localhost"||t==="127.0.0.1")return t;const e=t.split(".");return e.length>2?e.slice(1).join("."):t},L=({name:t,canTrack:e})=>{var n;try{return e?(n=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`)))==null?void 0:n.split("=")[1]:void 0}catch(r){c.warn("[COOKIE] GET error: ",(r==null?void 0:r.message)||r);return}},$=async t=>L(t),it=t=>t.map(([e,n])=>n?`${e}=${n}`:e).filter(u).join("; "),st=[["secure",""],["SameSite","None"]],at=({name:t,value:e,expires:n})=>{const o=(s()?location.protocol==="https:":!0)?st:[[]],i=n?[["expires",n.toUTCString()]]:[[]],a=[[t,e],...i,["path","/"],["domain",ot(window.location.hostname)],...o];return it(a)},j=async({name:t,value:e,expires:n,canTrack:r})=>{try{if(!r)return;const o=at({name:t,value:e,expires:n});document.cookie=o}catch(o){c.warn("[COOKIE] SET error: ",(o==null?void 0:o.message)||o)}};function ct(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function D(){return ct().replace(/-/g,"")}const F="builderSessionId",ut=async({canTrack:t})=>{if(!t)return;const e=await $({name:F,canTrack:t});if(u(e))return e;{const n=lt();return dt({id:n,canTrack:t}),n}},lt=()=>D(),dt=({id:t,canTrack:e})=>j({name:F,value:t,canTrack:e}),K=()=>s()&&typeof localStorage<"u"?localStorage:void 0,ft=({key:t,canTrack:e})=>{var n;try{return e?(n=K())==null?void 0:n.getItem(t):void 0}catch(r){console.debug("[LocalStorage] GET error: ",r);return}},gt=({key:t,canTrack:e,value:n})=>{var r;try{e&&((r=K())==null||r.setItem(t,n))}catch(o){console.debug("[LocalStorage] SET error: ",o)}},M="builderVisitorId",ht=({canTrack:t})=>{if(!t)return;const e=ft({key:M,canTrack:t});if(u(e))return e;{const n=pt();return yt({id:n,canTrack:t}),n}},pt=()=>D(),yt=({id:t,canTrack:e})=>gt({key:M,value:t,canTrack:e}),mt=async({canTrack:t})=>{if(!t)return{visitorId:void 0,sessionId:void 0};const e=await ut({canTrack:t}),n=ht({canTrack:t});return{sessionId:e,visitorId:n}},wt=async({type:t,canTrack:e,apiKey:n,metadata:r,...o})=>({type:t,data:{...o,metadata:{url:location.href,...r},...await mt({canTrack:e}),userAttributes:R(),ownerId:n}});async function N(t){if(!t.apiKey){c.error("Missing API key for track call. Please provide your API key.");return}if(t.canTrack&&!w()&&(s()||g==="reactNative"))return fetch("https://cdn.builder.io/api/v1/track",{method:"POST",body:JSON.stringify({events:[await wt(t)]}),headers:{"content-type":"application/json"},mode:"cors"}).catch(e=>{console.error("Failed to track: ",e)})}const St=t=>N({...t,canTrack:!0}),x={};function It(t,e){let n=x[t];if(n||(n=x[t]=[]),n.push(e),s()){const r={type:"builder.register",data:{type:t,info:e}};try{parent.postMessage(r,"*"),parent!==window&&window.postMessage(r,"*")}catch(o){console.debug("Could not postmessage",o)}}}const vt="builder.tests",S=t=>`${vt}.${t}`,bt=({contentId:t})=>$({name:S(t),canTrack:!0}),Ct=({contentId:t})=>L({name:S(t),canTrack:!0}),Et=({contentId:t,value:e})=>j({name:S(t),value:e,canTrack:!0}),U=t=>u(t.id)&&u(t.variations)&&Object.keys(t.variations).length>0,kt=({id:t,variations:e})=>{var o;let n=0;const r=Math.random();for(const i in e){const a=(o=e[i])==null?void 0:o.testRatio;if(n+=a,r<n)return i}return t},_=t=>{const e=kt(t);return Et({contentId:t.id,value:e}).catch(n=>{c.error("could not store A/B test variation: ",n)}),e},G=({item:t,testGroupId:e})=>{const n=t.variations[e];return e===t.id||!n?{testVariationId:t.id,testVariationName:"Default"}:{data:n.data,testVariationId:n.id,testVariationName:n.name||(n.id===t.id?"Default":"")}},Ot=({item:t,canTrack:e})=>{if(!e)return t;if(!t)return;if(!U(t))return t;const n=Ct({contentId:t.id})||_({variations:t.variations,id:t.id}),r=G({item:t,testGroupId:n});return{...t,...r}},At=async({item:t,canTrack:e})=>{if(!e||!U(t))return t;const r=await bt({contentId:t.id})||_({variations:t.variations,id:t.id}),o=G({item:t,testGroupId:r});return{...t,...o}},W=t=>u(t)?t:!0;function y(t,e=null,n="."){return Object.keys(t).reduce((r,o)=>{const i=t[o],a=[e,o].filter(Boolean).join(n);return[typeof i=="object",i!==null,!(Array.isArray(i)&&i.length===0)].every(Boolean)?{...r,...y(i,a,n)}:{...r,[a]:i}},{})}const P="builder.",xt="options.",Pt=t=>{const e={};return t.forEach((n,r)=>{e[r]=n}),e},I=t=>{if(!t)return{};const e=z(t),n={};return Object.keys(e).forEach(r=>{if(r.startsWith(P)){const o=r.replace(P,"").replace(xt,"");n[o]=e[r]}}),n},Tt=()=>{if(!s())return{};const t=new URLSearchParams(window.location.search);return I(t)},z=t=>t instanceof URLSearchParams?Pt(t):t,Rt="v3",v=t=>{const{limit:e=30,userAttributes:n,query:r,noTraverse:o=!1,model:i,apiKey:a,includeRefs:h=!0,enrich:E,locale:k,apiVersion:p=Rt}=t;if(!a)throw new Error("Missing API key");if(!["v2","v3"].includes(p))throw new Error(`Invalid apiVersion: expected 'v2' or 'v3', received '${p}'`);const d=new URL(`https://cdn.builder.io/api/${p}/content/${i}?apiKey=${a}&limit=${e}&noTraverse=${o}&includeRefs=${h}${k?`&locale=${k}`:""}${E?`&enrich=${E}`:""}`),X={...Tt(),...z(t.options||{})},O=y(X);for(const l in O)d.searchParams.set(l,String(O[l]));if(n&&d.searchParams.set("userAttributes",JSON.stringify(n)),r){const l=y({query:r});for(const A in l)d.searchParams.set(A,JSON.stringify(l[A]))}return d},Bt=t=>"results"in t;async function b(t){const e=await C({...t,limit:1});return e&&e.results[0]||null}const Vt=b,Lt=async t=>{const e=v(t);return await(await V(e.href)).json()},J=async(t,e,n=v(t))=>{const r=W(t.canTrack);if(n.search.includes("preview="),!r||!(s()||g==="reactNative"))return e;try{const o=[];for(const i of e.results)o.push(await At({item:i,canTrack:r}));e.results=o}catch(o){c.error("Could not process A/B tests. ",o)}return e};async function C(t){try{const e=v(t),n=await Lt(t);return Bt(n)?J(t,n):(c.error("Error fetching data. ",{url:e,content:n,options:t}),null)}catch(e){return c.error("Error fetching data. ",e),null}}const $t=C;function jt(){return!s()||w()?!1:location.search.indexOf("builder.preview=")!==-1}const T={};function Dt(t){if(s()){Object.assign(T,t);const e={type:"builder.settingsChange",data:T};parent.postMessage(e,"*")}}const Ft=async t=>{var r,o,i;const e=t.path||((r=t.url)==null?void 0:r.pathname)||((o=t.userAttributes)==null?void 0:o.urlPath),n={...t,apiKey:t.apiKey,model:t.model||"page",userAttributes:{...t.userAttributes,...e?{urlPath:e}:{}},options:I(t.searchParams||((i=t.url)==null?void 0:i.searchParams)||t.options)};return{apiKey:n.apiKey,model:n.model,content:await b(n)}};exports.TARGET=g;exports._processContentResult=J;exports._track=N;exports.checkIsDefined=u;exports.components=Q;exports.createRegisterComponentMessage=Z;exports.fastClone=m;exports.fetch=V;exports.fetchBuilderProps=Ft;exports.fetchEntries=C;exports.fetchOneEntry=b;exports.getAllContent=$t;exports.getBuilderSearchParams=I;exports.getContent=Vt;exports.getDefaultCanTrack=W;exports.getUserAttributes=R;exports.handleABTestingSync=Ot;exports.isBrowser=s;exports.isEditing=w;exports.isPreviewing=jt;exports.logger=c;exports.register=It;exports.serializeComponentInfo=B;exports.setEditorSettings=Dt;exports.track=St;