@builder.io/sdk 2.0.6 → 2.0.8

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 (40) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/index.browser.js +2721 -1
  3. package/dist/index.browser.js.map +1 -1
  4. package/dist/index.cjs.js +31 -38
  5. package/dist/index.cjs.js.map +1 -1
  6. package/dist/index.d.ts +7 -7
  7. package/dist/index.esm.js +24 -33
  8. package/dist/index.esm.js.map +1 -1
  9. package/dist/index.umd.js +33 -37
  10. package/dist/index.umd.js.map +1 -1
  11. package/dist/package.json +13 -9
  12. package/dist/src/builder.class.d.ts +861 -862
  13. package/dist/src/builder.class.js.map +1 -1
  14. package/dist/src/classes/animator.class.d.ts +26 -26
  15. package/dist/src/classes/cookies.class.d.ts +15 -15
  16. package/dist/src/classes/observable.class.d.ts +27 -27
  17. package/dist/src/classes/promise.class.d.ts +17 -17
  18. package/dist/src/classes/query-string.class.d.ts +9 -9
  19. package/dist/src/classes/query-string.class.test.d.ts +1 -1
  20. package/dist/src/constants/builder.d.ts +2 -2
  21. package/dist/src/functions/assign.function.d.ts +1 -1
  22. package/dist/src/functions/fetch.function.d.ts +28 -28
  23. package/dist/src/functions/finder.function.d.ts +10 -10
  24. package/dist/src/functions/get-top-level-domain.d.ts +6 -6
  25. package/dist/src/functions/next-tick.function.d.ts +1 -1
  26. package/dist/src/functions/next-tick.function.js +1 -7
  27. package/dist/src/functions/next-tick.function.js.map +1 -1
  28. package/dist/src/functions/omit.function.d.ts +1 -1
  29. package/dist/src/functions/server-only-require.function.d.ts +3 -3
  30. package/dist/src/functions/throttle.function.d.ts +1 -1
  31. package/dist/src/functions/to-error.d.ts +13 -13
  32. package/dist/src/functions/uuid.d.ts +8 -8
  33. package/dist/src/types/api-version.d.ts +2 -2
  34. package/dist/src/types/content.d.ts +31 -31
  35. package/dist/src/types/element.d.ts +60 -60
  36. package/dist/src/url.d.ts +9 -9
  37. package/dist/src/url.test.d.ts +1 -1
  38. package/dist/tsconfig.tsbuildinfo +1 -1
  39. package/package.json +13 -9
  40. package/project.json +4 -0
@@ -1,2 +1,2722 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define("@builder.io/sdk",["exports"],t):t(e.BuilderIO={})}(this,function(exports){"use strict";var __assign=function(){return(__assign=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};!function(){if("undefined"==typeof window||"function"==typeof window.CustomEvent)return!1;window.CustomEvent=function(e,t){t=t||{bubbles:!1,cancelable:!1,detail:null};var i=document.createEvent("CustomEvent");return i.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),i}}();var isSafari="undefined"!=typeof window&&/^((?!chrome|android).)*safari/i.test(window.navigator.userAgent);function nextTick(e){if("function"==typeof setImmediate&&"undefined"==typeof window)return setImmediate(e);if(isSafari||"undefined"==typeof MutationObserver)setTimeout(e);else{var t=0,i=new MutationObserver(function(){return e()}),n=document.createTextNode("");i.observe(n,{characterData:!0}),n.data=String(t=++t)}}var PROPERTY_NAME_DENY_LIST=Object.freeze(["__proto__","prototype","constructor"]),QueryString=function(){function e(){}return e.parseDeep=function(e){var t=this.parse(e);return this.deepen(t)},e.stringifyDeep=function(e){var t=this.flatten(e);return this.stringify(t)},e.parse=function(e){for(var t={},i=("?"===e[0]?e.substr(1):e).split("&"),n=0;n<i.length;n++){var r=i[n].split("=");try{t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]||"")}catch(e){}}return t},e.stringify=function(e){var t="";for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];t&&(t+="&"),t+=encodeURIComponent(i)+"="+encodeURIComponent(n)}return t},e.deepen=function(e){var t={};for(var i in e){for(var n=t,r=i.split("."),o=r.pop(),s=0,a=r;s<a.length;s++){var u=a[s];assertAllowedPropertyName(u),n=n[u]=n[u]||{}}n[o]=e[i]}return t},e.flatten=function(e,t,i){for(var n in void 0===i&&(i={}),e){var r=e[n],o=t?t+"."+n:n;r&&"object"==typeof r?this.flatten(r,o,i):i[o]=r}return i},e}();function assertAllowedPropertyName(e){if(PROPERTY_NAME_DENY_LIST.indexOf(e)>=0)throw new Error('Property name "'.concat(e,'" is not allowed'))}var version="2.0.5",Subscription=function(){function e(e,t){this.listeners=e,this.listener=t,this.unsubscribed=!1,this.otherSubscriptions=[]}return Object.defineProperty(e.prototype,"closed",{get:function(){return this.unsubscribed},enumerable:!1,configurable:!0}),e.prototype.add=function(e){this.otherSubscriptions.push(e)},e.prototype.unsubscribe=function(){if(!this.unsubscribed){if(this.listener&&this.listeners){var e=this.listeners.indexOf(this.listener);e>-1&&this.listeners.splice(e,1)}this.otherSubscriptions.forEach(function(e){return e.unsubscribe()}),this.unsubscribed=!0}},e}(),BehaviorSubject=function(){function e(e){var t=this;this.value=e,this.listeners=[],this.errorListeners=[],this.then=function(){for(var e,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];return(e=t.toPromise()).then.apply(e,i)}}return e.prototype.next=function(e){this.value=e;for(var t=0,i=this.listeners;t<i.length;t++){(0,i[t])(e)}},e.prototype.map=function(t){var i=new e(t(this.value));return this.subscribe(function(e){i.next(t(e))}),this.catch(function(e){i.error(e)}),i},e.prototype.catch=function(e){return this.errorListeners.push(e),new Subscription(this.errorListeners,e)},e.prototype.error=function(e){for(var t=0,i=this.errorListeners;t<i.length;t++){(0,i[t])(e)}},e.prototype.subscribe=function(e,t){return this.listeners.push(e),t&&this.errorListeners.push(t),new Subscription(this.listeners,e)},e.prototype.toPromise=function(){var e=this;return new Promise(function(t,i){var n=e.subscribe(function(e){t(e),n.unsubscribe()},function(e){i(e),n.unsubscribe()})})},e.prototype.promise=function(){return this.toPromise()},e}(),State={Pending:"Pending",Fulfilled:"Fulfilled",Rejected:"Rejected"};function isFunction(e){return e&&"function"==typeof e}function isObject(e){return e&&"object"==typeof e}var TinyPromise=function(){function e(e){this._state=State.Pending,this._handlers=[],this._value=null,e(this._resolve.bind(this),this._reject.bind(this))}return e.prototype._resolve=function(t){var i=this;if(t instanceof e)t.then(this._resolve.bind(this),this._reject.bind(this));else if(isObject(t)||isFunction(t)){var n=!1;try{var r=t.then;isFunction(r)?r.call(t,function(e){n||i._resolve(e),n=!0},function(e){n||i._reject(e),n=!0}):this._fulfill(t)}catch(e){n||this._reject(e)}}else this._fulfill(t)},e.prototype._fulfill=function(e){var t=this;this._state=State.Fulfilled,this._value=e,this._handlers.forEach(function(e){return t._callHandler(e)})},e.prototype._reject=function(e){var t=this;this._state=State.Rejected,this._value=e,this._handlers.forEach(function(e){return t._callHandler(e)})},e.prototype._isPending=function(){return this._state===State.Pending},e.prototype._isFulfilled=function(){return this._state===State.Fulfilled},e.prototype._isRejected=function(){return this._state===State.Rejected},e.prototype._addHandler=function(e,t){this._handlers.push({onFulfilled:e,onRejected:t})},e.prototype._callHandler=function(e){this._isFulfilled()&&isFunction(e.onFulfilled)?e.onFulfilled(this._value):this._isRejected()&&isFunction(e.onRejected)&&e.onRejected(this._value)},e.prototype.then=function(t,i){var n=this;switch(this._state){case State.Pending:return new e(function(e,r){n._addHandler(function(i){nextTick(function(){try{isFunction(t)?e(t(i)):e(i)}catch(e){r(e)}})},function(t){nextTick(function(){try{isFunction(i)?e(i(t)):r(t)}catch(e){r(e)}})})});case State.Fulfilled:return new e(function(e,i){nextTick(function(){try{isFunction(t)?e(t(n._value)):e(n._value)}catch(e){i(e)}})});case State.Rejected:return new e(function(e,t){nextTick(function(){try{isFunction(i)?e(i(n._value)):t(n._value)}catch(e){t(e)}})})}},e}(),Promise$1="undefined"!=typeof Promise?Promise:TinyPromise,serverOnlyRequire;try{serverOnlyRequire=eval("require")}catch(e){serverOnlyRequire=function(){return null}}var serverOnlyRequire$1=serverOnlyRequire;function promiseResolve(e){return new Promise$1(function(t){return t(e)})}function tinyFetch(e,t){return void 0===t&&(t={}),new Promise$1(function(i,n){var r=new XMLHttpRequest;if(r.open(t.method||"get",e,!0),t.headers)for(var o in t.headers)r.setRequestHeader(o,t.headers[o]);function s(){var e=[],t=[],i={},n=void 0;return r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(r,o,s){var a=o;return e.push(a=a.toLowerCase()),t.push([a,s]),n=i[a],i[a]=n?"".concat(n,",").concat(s):s,""}),{ok:2==(r.status/100|0),status:r.status,statusText:r.statusText,url:r.responseURL,clone:s,text:function(){return promiseResolve(r.responseText)},json:function(){return promiseResolve(r.responseText).then(JSON.parse)},blob:function(){return promiseResolve(new Blob([r.response]))},headers:{keys:function(){return e},entries:function(){return t},get:function(e){return i[e.toLowerCase()]},has:function(e){return e.toLowerCase()in i}}}}r.withCredentials="include"===t.credentials,r.onload=function(){i(s())},r.onerror=n,r.send(t.body)})}function getFetch(){var e=void 0;if(globalThis.fetch)null!=e||(e=globalThis.fetch);else if("undefined"==typeof window)try{null!=e||(e=serverOnlyRequire$1("node-fetch"))}catch(e){console.warn("node-fetch is not installed. consider polyfilling fetch or installing node-fetch."),console.warn(e)}return null!=e?e:tinyFetch}function assign(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=Object(e),r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o)for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])}return n}function throttle(e,t,i){var n,r,o;void 0===i&&(i={});var s=null,a=0,u=function(){a=!1===i.leading?0:Date.now(),s=null,o=e.apply(n,r),s||(n=r=null)};return function(){var c=Date.now();a||!1!==i.leading||(a=c);var l=t-(c-a);return n=this,r=arguments,l<=0||l>t?(s&&(clearTimeout(s),s=null),a=c,o=e.apply(n,r),s||(n=r=null)):s||!1===i.trailing||(s=setTimeout(u,l)),o}}var camelCaseToKebabCase=function(e){return e?e.replace(/([A-Z])/g,function(e){return"-".concat(e[0].toLowerCase())}):""},Animator=function(){function e(){}return e.prototype.bindAnimations=function(e){for(var t=0,i=e;t<i.length;t++){var n=i[t];switch(n.trigger){case"pageLoad":this.triggerAnimation(n);break;case"hover":this.bindHoverAnimation(n);break;case"scrollInView":this.bindScrollInViewAnimation(n)}}},e.prototype.warnElementNotPresent=function(e){console.warn("Cannot animate element: element with ID ".concat(e," not found!"))},e.prototype.augmentAnimation=function(e,t){for(var i=this.getAllStylesUsed(e),n=getComputedStyle(t),r=0,o=[e.steps[0].styles,e.steps[e.steps.length-1].styles];r<o.length;r++)for(var s=o[r],a=0,u=i;a<u.length;a++){var c=u[a];c in s||(s[c]=n[c])}},e.prototype.getAllStylesUsed=function(e){for(var t=[],i=0,n=e.steps;i<n.length;i++){var r=n[i];for(var o in r.styles)-1===t.indexOf(o)&&t.push(o)}return t},e.prototype.triggerAnimation=function(e){var t=this,i=Array.prototype.slice.call(document.getElementsByClassName(e.elementId||e.id||""));i.length?Array.from(i).forEach(function(i){t.augmentAnimation(e,i),i.style.transition="none",i.style.transitionDelay="0",assign(i.style,e.steps[0].styles),setTimeout(function(){i.style.transition="all ".concat(e.duration,"s ").concat(camelCaseToKebabCase(e.easing)),e.delay&&(i.style.transitionDelay=e.delay+"s"),assign(i.style,e.steps[1].styles),setTimeout(function(){i.style.transition="",i.style.transitionDelay=""},1e3*(e.delay||0)+1e3*e.duration+100)})}):this.warnElementNotPresent(e.elementId||e.id||"")},e.prototype.bindHoverAnimation=function(e){var t=this,i=Array.prototype.slice.call(document.getElementsByClassName(e.elementId||e.id||""));i.length?Array.from(i).forEach(function(i){t.augmentAnimation(e,i);var n=e.steps[0].styles,r=e.steps[1].styles;function o(){assign(i.style,n)}o(),i.addEventListener("mouseenter",function(){assign(i.style,r)}),i.addEventListener("mouseleave",o),setTimeout(function(){i.style.transition="all ".concat(e.duration,"s ").concat(camelCaseToKebabCase(e.easing)),e.delay&&(i.style.transitionDelay=e.delay+"s")})}):this.warnElementNotPresent(e.elementId||e.id||"")},e.prototype.bindScrollInViewAnimation=function(e){var t=this,i=Array.prototype.slice.call(document.getElementsByClassName(e.elementId||e.id||""));i.length?Array.from(i).forEach(function(i){t.augmentAnimation(e,i);var n=!1,r=!1;function o(){!n&&a(i)?(n=!0,r=!0,setTimeout(function(){assign(i.style,e.steps[1].styles),e.repeat||document.removeEventListener("scroll",s),setTimeout(function(){r=!1,e.repeat||(i.style.transition="",i.style.transitionDelay="")},1e3*(e.duration+(e.delay||0))+100)})):e.repeat&&n&&!r&&!a(i)&&(n=!1,assign(i.style,e.steps[0].styles))}var s=throttle(o,200,{leading:!1});function a(t){var i=t.getBoundingClientRect(),n=window.innerHeight,r=(e.thresholdPercent||0)/100*n;return i.bottom>r&&i.top<n-r}var u=e.steps[0].styles;assign(i.style,u),setTimeout(function(){i.style.transition="all ".concat(e.duration,"s ").concat(camelCaseToKebabCase(e.easing)),e.delay&&(i.style.transitionDelay=e.delay+"s")}),document.addEventListener("scroll",s,{capture:!0,passive:!0}),o()}):this.warnElementNotPresent(e.elementId||e.id||"")},e}();function getTopLevelDomain(e){var t=e.split(".");return t.length>2?t.slice(1).join("."):e}var fieldContentRegExp=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Cookies=function(){function e(e,t){this.request=e,this.response=t}return e.prototype.get=function(e){var t=this.request.headers.cookie;if(t){var i=t.match(getPattern(e));if(i)return i[1]}},e.prototype.set=function(e,t,i){var n=this.response,r=this.request,o=n.getHeader("Set-Cookie")||[],s=void 0!==this.secure?!!this.secure:"https"===r.protocol||r.connection.encrypted,a=new Cookie(e,t,i);if("string"==typeof o&&(o=[o]),!s&&i&&i.secure)throw new Error("Cannot send secure cookie over unencrypted connection");return a.secure=s,i&&"secure"in i&&(a.secure=!!i.secure),a.domain=r.headers.host&&getTopLevelDomain(r.headers.host),pushCookie(o,a),n.setHeader.call(n,"Set-Cookie",o),this},e}(),Cookie=function(){function e(e,t,i){if(this.path="/",this.domain=void 0,this.httpOnly=!0,this.sameSite=!1,this.secure=!1,this.overwrite=!1,this.name="",this.value="",!fieldContentRegExp.test(e))throw new TypeError("argument name is invalid");if(t&&!fieldContentRegExp.test(t))throw new TypeError("argument value is invalid");t||(this.expires=new Date(0)),this.name=e,this.value=t||"",i.expires&&(this.expires=i.expires),i.secure&&(this.secure=i.secure)}return e.prototype.toString=function(){return"".concat(this.name,"=").concat(this.value)},e.prototype.toHeader=function(){var e=this.toString();return this.maxAge&&(this.expires=new Date(Date.now()+this.maxAge)),this.path&&(e+="; path=".concat(this.path)),this.expires&&(e+="; expires=".concat(this.expires.toUTCString())),this.domain&&(e+="; domain=".concat(this.domain)),e+="; SameSite=".concat(!0===this.sameSite?"strict":"None"),this.secure&&(e+="; secure"),this.httpOnly&&(e+="; httponly"),e},e}();function getPattern(e){return new RegExp("(?:^|;) *".concat(e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"=([^;]*)"))}function pushCookie(e,t){if(t.overwrite)for(var i=e.length-1;i>=0;i--)0===e[i].indexOf("".concat(t.name,"="))&&e.splice(i,1);e.push(t.toHeader())}function omit(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=Object.assign({},e),r=0,o=t;r<o.length;r++){delete n[o[r]]}return n}function uuidv4(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})}function uuid(){return uuidv4().replace(/-/g,"")}function emptyUrl(){return{query:null,port:null,auth:null,hash:null,host:null,hostname:null,href:null,path:null,pathname:null,protocol:null,search:null,slashes:null}}function parse(e){var t,i=emptyUrl();return""===e||"/"===e[0]?(t=new URL(e,"http://0.0.0.0/"),i.href=t.href,i.href=i.href.slice(14)):(t=new URL(e),i.href=t.href,i.port=""===t.port?null:t.port,i.hash=""===t.hash?null:t.hash,i.host=t.host,i.hostname=t.hostname,i.href=t.href,i.pathname=t.pathname,i.protocol=t.protocol,i.slashes="/"===e[t.protocol.length]),i.search=t.search,i.query=t.search.slice(1),i.path="".concat(t.pathname).concat(t.search),i.pathname=t.pathname,i}function pad(e,t){for(;e.length<t;)e="0"+e;return e}function fold(e,t){var i,n;if(0===t.length)return e;for(i=0,n=t.length;i<n;i++)e=(e<<5)-e+t.charCodeAt(i),e|=0;return e<0?-2*e:e}function foldObject(e,t,i){return Object.keys(t).sort().reduce(function(e,n){return foldValue(e,t[n],n,i)},e)}function foldValue(e,t,i,n){var r=fold(fold(fold(e,i),toString(t)),typeof t);if(null===t)return fold(r,"null");if(void 0===t)return fold(r,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return fold(r,"[Circular]"+i);n.push(t);var o=foldObject(r,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return o;try{return fold(o,String(t.valueOf()))}catch(e){return fold(o,"[valueOf exception]"+(e.stack||e.message))}}return fold(r,t.toString())}function toString(e){return Object.prototype.toString.call(e)}function sum(e){return pad(foldValue(0,e,"",[]).toString(16),8)}var hashSum=sum;function toError(e){return e instanceof Error?e:new Error(String(e))}var DEFAULT_API_VERSION="v3";function datePlusMinutes(e){return void 0===e&&(e=30),new Date(Date.now()+6e4*e)}var isPositiveNumber=function(e){return"number"==typeof e&&!isNaN(e)&&e>=0},isReactNative="object"==typeof navigator&&"ReactNative"===navigator.product,validEnvList=["production","qa","test","development","dev","cdn-qa","cloud","fast","cdn2","cdn-prod"];function getQueryParam(e,t){for(var i=(e.split("?")[1]||"").split("&"),n=0;n<i.length;n++){var r=i[n].split("=");if(decodeURIComponent(r[0])===t)return decodeURIComponent(r[1])}return null}var urlParser={parse:function(e){var t=document.createElement("a");t.href=e;for(var i={},n=0,r=["username","password","host","hostname","port","protocol","origin","pathname","search","hash"];n<r.length;n++){var o=r[n];i[o]=t[o]}return!i.pathname&&""!==i.pathname||"string"!=typeof i.pathname||0===i.pathname.indexOf("/")||(i.pathname="/"+i.pathname),i}},parse$1=isReactNative?function(){return emptyUrl()}:"object"==typeof window?urlParser.parse:parse;function setCookie(e,t,i){try{var n="";i&&(n="; expires="+i.toUTCString());var r=!isBrowser||"https:"===location.protocol;document.cookie=e+"="+(t||"")+n+"; path=/"+"; domain=".concat(getTopLevelDomain(location.hostname))+(r?";secure ; SameSite=None":"")}catch(e){console.warn("Could not set cookie",e)}}function getCookie(e){try{return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null}catch(e){console.warn("Could not get cookie",e)}}function size(e){return Object.keys(e).length}function find(e,t){for(var i=e,n=i.length>>>0,r=arguments[1],o=0;o<n;o++){var s=i[o];if(t.call(r,s,o,i))return s}}var sessionStorageKey="builderSessionId",localStorageKey="builderVisitorId",isBrowser="undefined"!=typeof window&&!isReactNative,isIframe=isBrowser&&window.top!==window.self;function BuilderComponent(e){return void 0===e&&(e={}),Builder.Component(e)}var Builder=function(){function e(t,i,n,r,o,s){void 0===t&&(t=null),void 0===r&&(r=!1),void 0===o&&(o=null);var a=this;if(this.request=i,this.response=n,this.eventsQueue=[],this.throttledClearEventsQueue=throttle(function(){a.processEventsQueue(),a.setCookie(sessionStorageKey,a.sessionId,datePlusMinutes(30))},5),this.env="production",this.sessionId=this.getSessionId(),this.targetContent=!0,this.contentPerRequest=1,this.allowCustomFonts=!0,this.cookies=null,this.cachebust=!1,this.overrideParams="",this.noCache=!1,this.preview=!1,this.apiVersion$=new BehaviorSubject(void 0),this.canTrack$=new BehaviorSubject(!this.browserTrackingDisabled),this.apiKey$=new BehaviorSubject(null),this.authToken$=new BehaviorSubject(null),this.userAttributesChanged=new BehaviorSubject(null),this.editingMode$=new BehaviorSubject(isIframe),this.editingModel$=new BehaviorSubject(null),this.userAgent="object"==typeof navigator&&navigator.userAgent||"",this.trackingHooks=[],this.visitorId=this.getVisitorId(),this.autoTrack=!!e.isBrowser&&!(this.isDevelopmentEnv||e.isBrowser&&-1!==location.search.indexOf("builder.preview=")),this.trackingUserAttributes={},this.blockContentLoading="",this.observersByKey={},this.noEditorUpdates={},this.overrides={},this.queryOptions={},this.getContentQueue=null,this.priorContentQueue=null,this.testCookiePrefix="builder.tests",this.cookieQueue=[],e.isBrowser&&!r&&e.singletonInstance)return e.singletonInstance;this.request&&this.response&&(this.setUserAgent(this.request.headers["user-agent"]||""),this.cookies=new Cookies(this.request,this.response)),t&&(this.apiKey=t),s&&(this.apiVersion=s),o&&(this.authToken=o),isBrowser&&(this.bindMessageListeners(),e.isEditing&&parent.postMessage({type:"builder.animatorOptions",data:{options:{version:2}}},"*")),isIframe&&this.messageFrameLoaded(),this.canTrack$.subscribe(function(e){if(e){if("undefined"!=typeof sessionStorage)try{sessionStorage.getItem(sessionStorageKey)||sessionStorage.setItem(sessionStorageKey,a.sessionId)}catch(e){console.debug("Session storage error",e)}a.eventsQueue.length&&a.throttledClearEventsQueue(),a.cookieQueue.length&&(a.cookieQueue.forEach(function(e){a.setCookie(e[0],e[1])}),a.cookieQueue.length=0)}}),isBrowser&&(this.setTestsFromUrl(),this.getOverridesFromQueryString())}return e.register=function(t,i){var n=this.registry[t];if(n||(n=this.registry[t]=[]),n.push(i),e.isBrowser){var r={type:"builder.register",data:{type:t,info:i}};try{parent.postMessage(r,"*"),parent!==window&&window.postMessage(r,"*")}catch(e){console.debug("Could not postmessage",e)}}this.registryChange.next(this.registry)},e.registerEditor=function(t){if(e.isBrowser){window.postMessage({type:"builder.registerEditor",data:omit(t,"component")},"*");var i=location.hostname;e.isTrustedHost(i)||console.error("Builder.registerEditor() called in the wrong environment! You cannot load custom editors from your app, they must be loaded through the Builder.io app itself. Follow the readme here for more details: https://github.com/builderio/builder/tree/master/plugins/cloudinary or contact chat us in our Spectrum community for help: https://spectrum.chat/builder")}this.editors.push(t)},e.registerPlugin=function(e){this.plugins.push(e)},e.registerAction=function(e){this.actions.push(e)},e.registerTrustedHost=function(e){this.trustedHosts.push(e)},e.setServerContext=function(e){this.serverContext=e},e.isTrustedHost=function(e){return this.trustedHosts.findIndex(function(t){return t===e||e.endsWith(".".concat(t))})>-1},e.runAction=function(e){if(!("string"==typeof e?find(this.actions,function(t){return t.name===e}):e))throw new Error("Action not found: ".concat(e))},e.fields=function(e,t){var i;null===(i=window.parent)||void 0===i||i.postMessage({type:"builder.fields",data:{name:e,fields:t}},"*")},e.set=function(t){e.register("editor.settings",t)},e.import=function(t){if(e.isBrowser){var i=window.System;if(i)return i.import("https://cdn.builder.io/systemjs/".concat(t));console.warn("System.js not available. Please include System.js when using Builder.import")}else console.warn("Builder.import used on the server - this should only be used in the browser")},Object.defineProperty(e,"editingPage",{get:function(){return this._editingPage},set:function(e){this._editingPage=e,isBrowser&&isIframe&&(e?document.body.classList.add("builder-editing-page"):document.body.classList.remove("builder-editing-page"))},enumerable:!1,configurable:!0}),e.prepareComponentSpecToSend=function(e){return __assign(__assign(__assign({},e),e.inputs&&{inputs:e.inputs.map(function(e){for(var t,i=0,n=["onChange","showIf"];i<n.length;i++){var r=n[i];if(e[r]&&"function"==typeof e[r]){var o=e[r];e=__assign(__assign({},e),((t={})[r]="return (".concat(o.toString(),").apply(this, arguments)"),t))}}return e})}),{hooks:Object.keys(e.hooks||{}).reduce(function(t,i){var n=e.hooks&&e.hooks[i];return n?(t[i]="string"==typeof n?n:"return (".concat(n.toString(),").apply(this, arguments)"),t):t},{}),class:void 0})},e.registerBlock=function(e,t){this.registerComponent(e,t)},e.registerComponent=function(e,t){var i,n=__assign(__assign({class:e},e.builderOptions),t);if(this.addComponent(n),t.models&&this.singletonInstance.editingModel?isBrowser&&t.models.includes(this.singletonInstance.editingModel):isBrowser){var r=this.prepareComponentSpecToSend(n);null===(i=window.parent)||void 0===i||i.postMessage({type:"builder.registerComponent",data:r},"*")}},e.addComponent=function(e){var t=find(this.components,function(t){return t.name===e.name});if(t){if(t.class&&!e.class)return;this.components.splice(this.components.indexOf(t),1,e)}else this.components.push(e)},e.component=function(e){var t=this;return void 0===e&&(e={}),function(i){var n,r=__assign(__assign({},e),{class:i});r.name||(r.name=i.name),t.addComponent(r);var o=t.prepareComponentSpecToSend(r);return isBrowser&&(null===(n=window.parent)||void 0===n||n.postMessage({type:"builder.registerComponent",data:o},"*")),i}},Object.defineProperty(e,"Component",{get:function(){return this.component},enumerable:!1,configurable:!0}),e.prototype.processEventsQueue=function(){if(this.eventsQueue.length){var t=this.eventsQueue;this.eventsQueue=[];for(var i=__assign(__assign({},e.overrideUserAttributes),this.trackingUserAttributes),n=0,r=t;n<r.length;n++){var o=r[n];o.data.metadata||(o.data.metadata={}),o.data.metadata.user||(o.data.metadata.user={}),Object.assign(o.data.metadata.user,i,o.data.metadata.user)}var s=this.host;getFetch()("".concat(s,"/api/v1/track"),{method:"POST",body:JSON.stringify({events:t}),headers:{"content-type":"application/json"},mode:"cors"}).catch(function(){})}},Object.defineProperty(e.prototype,"browserTrackingDisabled",{get:function(){return e.isBrowser&&Boolean(window.builderNoTrack||!navigator.cookieEnabled)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"canTrack",{get:function(){return this.canTrack$.value},set:function(e){this.canTrack!==e&&this.canTrack$.next(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"apiVersion",{get:function(){return this.apiVersion$.value},set:function(e){this.apiVersion!==e&&this.apiVersion$.next(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"editingMode",{get:function(){return this.editingMode$.value},set:function(e){e!==this.editingMode&&this.editingMode$.next(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"editingModel",{get:function(){return this.editingModel$.value},set:function(e){e!==this.editingModel&&this.editingModel$.next(e)},enumerable:!1,configurable:!0}),e.prototype.findParentElement=function(e,t,i){if(void 0===i&&(i=!0),!(e instanceof HTMLElement))return null;var n=i?e:e.parentElement;do{if(!n)return null;if(t(n))return n}while(n=n.parentElement);return null},e.prototype.findBuilderParent=function(e){return this.findParentElement(e,function(e){var t=e.getAttribute("builder-id")||e.id;return Boolean(t&&0===t.indexOf("builder-"))})},e.prototype.setUserAgent=function(e){this.userAgent=e||""},e.prototype.setTrackingHook=function(e){this.trackingHooks.push(e)},e.prototype.track=function(t,i,n){if(void 0===i&&(i={}),!isIframe&&isBrowser&&!e.isPreviewing){var r=this.apiKey;if(r){for(var o=JSON.parse(JSON.stringify({type:t,data:__assign(__assign({},omit(i,"meta")),{metadata:__assign(__assign({sdkVersion:e.VERSION,url:location.href},i.meta),i.metadata),ownerId:r,userAttributes:this.getUserAttributes(),sessionId:this.sessionId,visitorId:this.visitorId})})),s=0,a=this.trackingHooks;s<a.length;s++){var u=(0,a[s])(o,n||{});u&&(o=u)}this.eventsQueue.push(o),this.canTrack&&this.throttledClearEventsQueue()}else console.error('Builder integration error: Looks like the Builder SDK has not been initialized properly (your API key has not been set). Make sure you are calling `builder.init("«YOUR-API-KEY»");` as early as possible in your application\'s code.')}},e.prototype.getSessionId=function(){var t=this,i=null;try{e.isBrowser&&"undefined"!=typeof sessionStorage&&(i=this.getCookie(sessionStorageKey))}catch(e){console.debug("Session storage error",e)}return i||(i=uuid()),e.isBrowser&&setTimeout(function(){try{t.canTrack&&t.setCookie(sessionStorageKey,i,datePlusMinutes(30))}catch(e){console.debug("Cookie setting error",e)}}),i},e.prototype.getVisitorId=function(){var t=this;if(this.visitorId)return this.visitorId;var i=null;try{e.isBrowser&&"undefined"!=typeof localStorage&&(i=localStorage.getItem(localStorageKey))}catch(e){console.debug("Local storage error",e)}return i||(i=uuid()),this.visitorId=i,e.isBrowser&&setTimeout(function(){try{t.canTrack&&"undefined"!=typeof localStorage&&i&&localStorage.setItem(localStorageKey,i)}catch(e){console.debug("Session storage error",e)}}),i},e.prototype.trackImpression=function(t,i,n,r){isIframe||!isBrowser||e.isPreviewing||this.track("impression",{contentId:t,variationId:i!==t?i:void 0,metadata:n},r)},e.prototype.trackConversion=function(t,i,n,r,o){if(!isIframe&&isBrowser&&!e.isPreviewing){var s="object"==typeof i?i:r,a="string"==typeof i?i:void 0;this.track("conversion",{amount:t,variationId:n,meta:s,contentId:a},o)}},Object.defineProperty(e.prototype,"isDevelopmentEnv",{get:function(){return e.isIframe||e.isBrowser&&("localhost"===location.hostname||""!==location.port)||"production"!==this.env},enumerable:!1,configurable:!0}),e.prototype.trackInteraction=function(t,i,n,r,o){if(void 0===n&&(n=!1),!isIframe&&isBrowser&&!e.isPreviewing){var s=r&&r.target,a=s&&this.findBuilderParent(s),u={};if(r){var c=r.clientX,l=r.clientY;if(s){var d=c-(g=s.getBoundingClientRect()).left,h=l-g.top,p=m(d/g.width),f=m(h/g.height);u.targetOffset={x:p,y:f}}if(a){var g;d=c-(g=a.getBoundingClientRect()).left,h=l-g.top,p=m(d/g.width),f=m(h/g.height);u.builderTargetOffset={x:p,y:f}}}var v=a&&(a.getAttribute("builder-id")||a.id);v&&a&&(u.builderElementIndex=[].slice.call(document.getElementsByClassName(v)).indexOf(a)),this.track("click",{contentId:t,metadata:u,variationId:i!==t?i:void 0,unique:!n,targetBuilderElement:v||void 0},o)}function m(e){return Math.round(1e3*e)/1e3}},e.prototype.component=function(t){return void 0===t&&(t={}),e.component(t)},Object.defineProperty(e.prototype,"apiKey",{get:function(){return this.apiKey$.value},set:function(e){this.apiKey$.next(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"authToken",{get:function(){return this.authToken$.value},set:function(e){this.authToken$.next(e)},enumerable:!1,configurable:!0}),e.prototype.modifySearch=function(e){return e.replace(/(^|&|\?)(builder_.*?)=/gi,function(e,t,i){return t+i.replace(/_/g,".")+"="})},e.prototype.setTestsFromUrl=function(){var e=this.getLocation().search,t=QueryString.parseDeep(this.modifySearch(e||"").substr(1)),i=t.builder&&t.builder.tests;if(i&&"object"==typeof i)for(var n in i)i.hasOwnProperty(n)&&this.setTestCookie(n,i[n])},e.prototype.resetOverrides=function(){e.overrideUserAttributes={},this.cachebust=!1,this.noCache=!1,this.preview=!1,this.editingModel=null,this.overrides={},this.env="production",this.userAgent="",this.request=void 0,this.response=void 0},e.prototype.getOverridesFromQueryString=function(){var t=this.getLocation(),i=QueryString.parseDeep(this.modifySearch(t.search||"").substr(1)),n=i.builder;if(n){var r=n.userAttributes,o=n.overrides,s=n.env,a=(n.host,n.api),u=n.cachebust,c=n.noCache,l=n.preview,d=n.editing,h=n.frameEditing,p=n.options,f=n.params;if(r&&this.setUserAttributes(r),p&&(this.queryOptions=__assign(__assign(__assign({},p.locale&&{locale:p.locale}),p.includeRefs&&{includeRefs:p.includeRefs}),p.enrich&&{enrich:p.enrich})),o&&(this.overrides=o),validEnvList.indexOf(s||a)>-1&&(this.env=s||a),e.isEditing){var g=h||d||l;g&&"true"!==g&&(this.editingModel=g)}u&&(this.cachebust=!0),c&&(this.noCache=!0),l&&(this.preview=!0),i&&(this.overrideParams=f)}},e.prototype.messageFrameLoaded=function(){var e;null===(e=window.parent)||void 0===e||e.postMessage({type:"builder.loaded",data:{value:!0}},"*")},e.prototype.bindMessageListeners=function(){var t=this;isBrowser&&addEventListener("message",function(i){var n,r,o,s,a,u=parse$1(i.origin),c=-1===["builder.register","builder.registerComponent"].indexOf(null===(n=i.data)||void 0===n?void 0:n.type),l=u.hostname&&e.isTrustedHost(u.hostname);if(!c||l){var d=i.data;if(d)switch(d.type){case"builder.ping":null===(r=window.parent)||void 0===r||r.postMessage({type:"builder.pong",data:{}},"*");break;case"builder.register":if(i.source===window)break;var h=d.data;if(!h)break;var p=h.type,f=h.info,g=e.registry[p];g||(g=e.registry[p]=[]),g.push(f),e.registryChange.next(e.registry);break;case"builder.settingsChange":if(i.source===window)break;var v=d.data;if(!v)break;Object.assign(e.settings,v),e.settingsChange.next(e.settings);break;case"builder.registerEditor":if(i.source===window)break;var m=d.data;if(!m)break;var y=!!m.component;e.editors.every(function(t,i){return m.name!==t.name||!(t.component&&!y)&&(e.editors[i]=t,!1)});break;case"builder.triggerAnimation":e.animator.triggerAnimation(d.data);break;case"builder.contentUpdate":var b=d.data.key||d.data.alias||d.data.entry||d.data.modelName,w=d.data.data,k=t.observersByKey[b];k&&!t.noEditorUpdates[b]&&k.next([w]);break;case"builder.getComponents":null===(o=window.parent)||void 0===o||o.postMessage({type:"builder.components",data:e.components.map(function(t){return e.prepareComponentSpecToSend(t)})},"*");break;case"builder.editingModel":t.editingModel=d.data.model;break;case"builder.registerComponent":var C=d.data;e.addComponent(C);break;case"builder.blockContentLoading":"string"==typeof d.data.model&&(t.blockContentLoading=d.data.model);break;case"builder.editingMode":d.data?(t.editingMode=!0,document.body.classList.add("builder-editing")):(t.editingMode=!1,document.body.classList.remove("builder-editing"));break;case"builder.editingPageMode":var S=d.data;e.editingPage=S;break;case"builder.overrideUserAttributes":var _=d.data;assign(e.overrideUserAttributes,_),t.flushGetContentQueue(!0);break;case"builder.overrideTestGroup":var x=d.data,T=x.variationId,I=x.contentId;T&&I&&(t.setTestCookie(I,T),t.flushGetContentQueue(!0));break;case"builder.evaluate":var P=d.data.text,B=d.data.arguments||[],O=d.data.id,E=new Function(P),A=void 0,j=null;try{A=E.apply(t,B)}catch(e){j=toError(e)}j?null===(s=window.parent)||void 0===s||s.postMessage({type:"builder.evaluateError",data:{id:O,error:j.message}},"*"):A&&"function"==typeof A.then?A.then(function(e){var t;null===(t=window.parent)||void 0===t||t.postMessage({type:"builder.evaluateResult",data:{id:O,result:e}},"*")}).catch(console.error):null===(a=window.parent)||void 0===a||a.postMessage({type:"builder.evaluateResult",data:{result:A,id:O}},"*")}}})},Object.defineProperty(e.prototype,"defaultCanTrack",{get:function(){return Boolean(e.isBrowser&&navigator.userAgent.trim()&&!navigator.userAgent.match(/bot|crawler|spider|robot|crawling|prerender|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|phantom|headless|selenium|puppeteer/i)&&!this.browserTrackingDisabled)},enumerable:!1,configurable:!0}),e.prototype.init=function(e,t,i,n,r,o){return void 0===t&&(t=this.defaultCanTrack),i&&(this.request=i),n&&(this.response=n),this.canTrack=t,this.apiKey=e,r&&(this.authToken=r),o&&(this.apiVersion=o),this},Object.defineProperty(e.prototype,"previewingModel",{get:function(){var e=this.getLocation().search;return QueryString.parse((e||"").substr(1))["builder.preview"]},enumerable:!1,configurable:!0}),e.prototype.getLocation=function(){var e,t={};return this.request?t=parse$1(null!==(e=this.request.url)&&void 0!==e?e:""):"object"==typeof location&&(t=parse$1(location.href)),""===t.pathname&&(t.pathname="/"),t},e.prototype.getUserAttributes=function(t){void 0===t&&(t=this.userAgent||"");var i={Android:function(){return t.match(/Android/i)},BlackBerry:function(){return t.match(/BlackBerry/i)},iOS:function(){return t.match(/iPhone|iPod/i)},Opera:function(){return t.match(/Opera Mini/i)},Windows:function(){return t.match(/IEMobile/i)||t.match(/WPDesktop/i)},any:function(){return i.Android()||i.BlackBerry()||i.iOS()||i.Opera()||i.Windows()}},n=t.match(/Tablet|iPad/i),r=this.getLocation();return __assign({urlPath:r.pathname,host:r.host||r.hostname,device:n?"tablet":i.any()?"mobile":"desktop"},e.overrideUserAttributes)},e.prototype.setUserAttributes=function(t){assign(e.overrideUserAttributes,t),this.userAttributesChanged.next(t)},e.prototype.setTrackingUserAttributes=function(e){assign(this.trackingUserAttributes,e)},e.prototype.get=function(t,i){void 0===i&&(i={});var n=this;return e.isBrowser?(i.apiKey&&!this.apiKey&&(this.apiKey=i.apiKey),i.authToken&&!this.authToken&&(this.authToken=i.authToken),i.apiVersion&&!this.apiVersion&&(this.apiVersion=i.apiVersion)):(n=new e(i.apiKey||this.apiKey,i.req,i.res,void 0,i.authToken||this.authToken,i.apiVersion||this.apiVersion)).setUserAttributes(this.getUserAttributes()),n.queueGetContent(t,i).map(function(t){var i=t&&t[0];if(e.isStatic)return i;var n=i&&i.data;return n?(void 0!==n.blocksString&&(n.blocks=JSON.parse(n.blocksString),delete n.blocksString),{data:n,id:i.id,variationId:i.testVariationId||i.variationId||null,testVariationId:i.testVariationId||i.variationId||null,testVariationName:i.testVariationName||null,lastUpdated:i.lastUpdated||null}):null})},e.prototype.queueGetContent=function(t,i){var n=this;void 0===i&&(i={});var r=i.key||i.alias||t,o=this.editingModel===t,s=this.observersByKey[r];"DEMO"!==this.apiKey||this.overrides[r]||i.initialContent||(i.initialContent=[]);var a=i.initialContent;if(s&&(!s.value||i.cache))return s.value&&nextTick(function(){s.next(s.value)}),s;if(o&&e.isBrowser&&parent.postMessage({type:"builder.updateContent",data:{options:i}},"*"),!a)if(this.getContentQueue||(this.getContentQueue=[]),this.getContentQueue.push(__assign(__assign({},i),{model:t,key:r})),this.getContentQueue&&this.getContentQueue.length>=this.contentPerRequest){var u=this.getContentQueue.slice();this.getContentQueue=[],nextTick(function(){n.flushGetContentQueue(!1,u)})}else nextTick(function(){n.flushGetContentQueue()});var c=new BehaviorSubject(null);return this.observersByKey[r]=c,i.noEditorUpdates&&(this.noEditorUpdates[r]=!0),a&&nextTick(function(){c.next(a)}),c},e.prototype.requestUrl=function(e,t){return getFetch()(e,__assign({next:__assign({revalidate:1},null==t?void 0:t.next)},t)).then(function(e){return e.json()})},Object.defineProperty(e.prototype,"host",{get:function(){switch(this.env){case"qa":return"https://qa.builder.io";case"test":return"https://builder-io-test.web.app";case"fast":return"https://fast.builder.io";case"cloud":return"https://cloud.builder.io";case"cdn2":return"https://cdn2.builder.io";case"cdn-qa":return"https://cdn-qa.builder.io";case"development":case"dev":return"http://localhost:5000";case"cdn-prod":return"https://cdn.builder.io";default:return e.overrideHost||"https://cdn.builder.io"}},enumerable:!1,configurable:!0}),e.prototype.flushGetContentQueue=function(t,i){var n=this;if(void 0===t&&(t=!1),!this.apiKey)throw new Error("Fetching content failed, expected apiKey to be defined instead got: ".concat(this.apiKey));if(this.apiVersion){if(!["v1","v3"].includes(this.apiVersion))throw new Error("Invalid apiVersion: expected 'v1' or 'v3', received '".concat(this.apiVersion,"'"))}else this.apiVersion=DEFAULT_API_VERSION;if(t||this.getContentQueue){var r=i||(t?this.priorContentQueue:this.getContentQueue)||[];this.getOverridesFromQueryString();var o=__assign(__assign({omit:r[0].omit||"meta.componentsUsed",apiKey:this.apiKey},r[0].options),this.queryOptions);r[0].locale&&(o.locale=r[0].locale),r[0].fields&&(o.fields=r[0].fields),r[0].format&&(o.format=r[0].format);var s="undefined"!=typeof location?QueryString.parseDeep(location.search.substr(1)):{},a=r&&r[0].userAttributes?r[0].userAttributes:this.targetContent?this.getUserAttributes():{urlPath:this.getLocation().pathname};if(r.find(function(e){return!!e.includeUrl})){var u=this.getLocation();u.origin&&(o.url="".concat(u.origin).concat(u.pathname).concat(u.search))}var c=null==i?void 0:i.find(function(e){return e.url});if((null==c?void 0:c.url)&&(a.urlPath=c.url.split("?")[0]),o.userAttributes=a,t||i||(this.priorContentQueue=r,this.getContentQueue=null),(this.cachebust||isIframe||s.cachebust||s["builder.cachebust"]||"production"!==this.env)&&(o.cachebust=!0),e.isEditing&&(o.isEditing=!0),(this.noCache||"production"!==this.env)&&(o.noCache=!0),size(this.overrides))for(var l in this.overrides)this.overrides.hasOwnProperty(l)&&(o["overrides.".concat(l)]=this.overrides[l]);for(var d=0,h=r;d<h.length;d++){var p=h[d];p.format&&(o.format=p.format),p.static&&(o.static=p.static),p.cachebust&&(o.cachebust=p.cachebust),isPositiveNumber(p.cacheSeconds)&&(o.cacheSeconds=p.cacheSeconds),isPositiveNumber(p.staleCacheSeconds)&&(o.staleCacheSeconds=p.staleCacheSeconds);for(var f=0,g=["prerender","extractCss","limit","offset","query","preview","model","entry","rev","static"];f<g.length;f++){var v=p[l=g[f]];void 0!==v&&(o.options=o.options||{},o.options[p.key]=o.options[p.key]||{},o.options[p.key][l]=JSON.stringify(v))}}this.preview&&(o.preview="true");var m=Object.keys(o).length>0,y=this.host,b=r.map(function(e){return encodeURIComponent(e.key)}).join(",");if(this.overrideParams)assign(o,omit(QueryString.parse(this.overrideParams),"apiKey"));var w=QueryString.stringifyDeep(o),k=o.format,C={headers:{},next:{revalidate:1}};this.authToken&&(C.headers=__assign(__assign({},C.headers),{Authorization:"Bearer ".concat(this.authToken)}));var S="solid"===k||"react"===k?"codegen":"query",_="query"===S?this.apiVersion:"v1",x="".concat(y,"/api/").concat(_,"/").concat(S,"/").concat(this.apiKey,"/").concat(b)+(o&&m?"?".concat(w):"");return getFetch()(x,C).then(function(e){return e.json()}).then(function(t){for(var i=0,o=r;i<o.length;i++){var s=o[i],a=s.key;if(s.model!==n.blockContentLoading||s.noEditorUpdates){n.editingModel===s.model&&e.isEditing&&parent.postMessage({type:"builder.updateContent",data:{options:s}},"*");var u=n.observersByKey[a];if(!u)return;var c=t[a],l=c;if(c){var d=e.isServer?l:n.processResultsForTests(l);u.next(d)}else{if((n.getLocation().search||"").includes("builder.preview="+s.model)){u.next([{id:"preview",name:"Preview",data:{}}])}u.next([])}}}},function(e){for(var t=0,i=r;t<i.length;t++){var o=i[t],s=n.observersByKey[o.key];if(!s)return;s.error(e)}})}},e.prototype.processResultsForTests=function(e){var t,i=this,n=e.map(function(e){if(!e.variations)return e;var t=i.getTestCookie(e.id),n=t===e.id?e:e.variations[t];if(n)return __assign(__assign({},e),{data:n.data,variationId:t,testVariationId:t,testVariationName:n.name});if(i.canTrack&&e.variations&&size(e.variations)){var r=0,o=Math.random();for(var s in e.variations){var a=e.variations[s];if(o<(r+=a.testRatio)){i.setTestCookie(e.id,a.id);var u=a.name||(a.id===e.id?"Default variation":"");return __assign(__assign({},e),{data:a.data,variationId:a.id,testVariationId:a.id,variationName:u,testVariationName:u})}}i.setTestCookie(e.id,e.id)}return __assign(__assign(__assign({},e),{variationId:e.id}),e.variations&&size(e.variations)&&{testVariationId:e.id,testVariationName:"Default variation"})});return isIframe&&(null===(t=window.parent)||void 0===t||t.postMessage({type:"builder.contentResults",data:{results:n}},"*")),n},e.prototype.getTestCookie=function(e){return this.getCookie("".concat(this.testCookiePrefix,".").concat(e))},e.prototype.setTestCookie=function(e,t){if(this.canTrack){var i=new Date;return i.setDate(i.getDate()+30),this.setCookie("".concat(this.testCookiePrefix,".").concat(e),t,i)}this.cookieQueue.push([e,t])},e.prototype.getCookie=function(t){return this.cookies?this.cookies.get(t):e.isBrowser&&getCookie(t)},e.prototype.setCookie=function(t,i,n){return!this.cookies||e.isServer&&e.isStatic?e.isBrowser&&setCookie(t,i,n):this.cookies.set(t,i,{expires:n,secure:"https:"===this.getLocation().protocol})},e.prototype.getContent=function(e,t){if(void 0===t&&(t={}),!this.apiKey)throw new Error("Fetching content from model ".concat(e," failed, expected apiKey to be defined instead got: ").concat(this.apiKey));return this.queueGetContent(e,t)},e.prototype.getAll=function(t,i){void 0===i&&(i={});var n=this;return e.isBrowser?(i.apiKey&&!this.apiKey&&(this.apiKey=i.apiKey),i.apiVersion&&!this.apiVersion&&(this.apiVersion=i.apiVersion)):(n=new e(i.apiKey||this.apiKey,i.req,i.res,!1,null,i.apiVersion||this.apiVersion)).setUserAttributes(this.getUserAttributes()),n.getContent(t,__assign(__assign({limit:30},i),{key:i.key||e.isBrowser?"".concat(t,":").concat(hashSum(omit(i,"initialContent","req","res"))):void 0})).promise()},e.VERSION=version,e.components=[],e.isStatic=!0,e.animator=new Animator,e.nextTick=nextTick,e.throttle=throttle,e.editors=[],e.trustedHosts=["builder.io","localhost"],e.plugins=[],e.actions=[],e.registry={},e.registryChange=new BehaviorSubject({}),e._editingPage=!1,e.isIframe=isIframe,e.isBrowser=isBrowser,e.isReactNative=isReactNative,e.isServer=!isBrowser&&!isReactNative,e.previewingModel=e.isBrowser&&getQueryParam(location.href,"builder.preview"),e.settings={},e.settingsChange=new BehaviorSubject({}),e.isEditing=Boolean(isIframe&&(document.referrer&&document.referrer.match(/builder\.io|localhost:1234/)||-1!==location.search.indexOf("builder.frameEditing="))),e.isPreviewing=Boolean(isBrowser&&(-1!==location.search.indexOf("builder.preview=")||-1!==location.search.indexOf("builder.frameEditing="))),e.isReact=!1,e.overrideUserAttributes={},e}(),builder=new Builder(null,void 0,void 0,!0);Builder.singletonInstance=builder,exports.Builder=Builder,exports.BuilderComponent=BuilderComponent,exports.isBrowser=isBrowser,exports.BehaviorSubject=BehaviorSubject,exports.Subscription=Subscription,exports.builder=builder,Object.defineProperty(exports,"__esModule",{value:!0})});
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define('@builder.io/sdk', ['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BuilderIO = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+
22
+ var __assign = function() {
23
+ __assign = Object.assign || function __assign(t) {
24
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
25
+ s = arguments[i];
26
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
27
+ }
28
+ return t;
29
+ };
30
+ return __assign.apply(this, arguments);
31
+ };
32
+
33
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
34
+ var e = new Error(message);
35
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
36
+ };
37
+
38
+ (function () {
39
+ if (typeof window === 'undefined' || typeof window.CustomEvent === 'function') return false;
40
+
41
+ function CustomEvent(event, params) {
42
+ params = params || { bubbles: false, cancelable: false, detail: null };
43
+ var evt = document.createEvent('CustomEvent');
44
+ evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
45
+ return evt;
46
+ }
47
+
48
+ window.CustomEvent = CustomEvent;
49
+ })();
50
+
51
+ var isSafari = typeof window !== 'undefined' &&
52
+ /^((?!chrome|android).)*safari/i.test(window.navigator.userAgent);
53
+ var isClient = typeof window !== 'undefined';
54
+ // TODO: queue all of these in a debounceNextTick
55
+ function nextTick(fn) {
56
+ // if (typeof process !== 'undefined' && process.nextTick) {
57
+ // console.log('process.nextTick?');
58
+ // process.nextTick(fn);
59
+ // return;
60
+ // }
61
+ // FIXME: fix the real safari issue of this randomly not working
62
+ if (!isClient || isSafari || typeof MutationObserver === 'undefined') {
63
+ setTimeout(fn);
64
+ return;
65
+ }
66
+ var called = 0;
67
+ var observer = new MutationObserver(function () { return fn(); });
68
+ var element = document.createTextNode('');
69
+ observer.observe(element, {
70
+ characterData: true,
71
+ });
72
+ // tslint:disable-next-line
73
+ element.data = String((called = ++called));
74
+ }
75
+
76
+ var PROPERTY_NAME_DENY_LIST = Object.freeze(['__proto__', 'prototype', 'constructor']);
77
+ // TODO: unit tests
78
+ var QueryString = /** @class */ (function () {
79
+ function QueryString() {
80
+ }
81
+ QueryString.parseDeep = function (queryString) {
82
+ var obj = this.parse(queryString);
83
+ return this.deepen(obj);
84
+ };
85
+ QueryString.stringifyDeep = function (obj) {
86
+ var map = this.flatten(obj);
87
+ return this.stringify(map);
88
+ };
89
+ QueryString.parse = function (queryString) {
90
+ var query = {};
91
+ var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
92
+ for (var i = 0; i < pairs.length; i++) {
93
+ var pair = pairs[i].split('=');
94
+ // TODO: node support?
95
+ try {
96
+ query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
97
+ }
98
+ catch (error) {
99
+ // Ignore malformed URI components
100
+ }
101
+ }
102
+ return query;
103
+ };
104
+ QueryString.stringify = function (map) {
105
+ var str = '';
106
+ for (var key in map) {
107
+ if (map.hasOwnProperty(key)) {
108
+ var value = map[key];
109
+ if (str) {
110
+ str += '&';
111
+ }
112
+ str += encodeURIComponent(key) + '=' + encodeURIComponent(value);
113
+ }
114
+ }
115
+ return str;
116
+ };
117
+ QueryString.deepen = function (map) {
118
+ // FIXME; Should be type Tree = Record<string, string | Tree>
119
+ // requires a typescript upgrade.
120
+ var output = {};
121
+ for (var k in map) {
122
+ var t = output;
123
+ var parts = k.split('.');
124
+ var key = parts.pop();
125
+ for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
126
+ var part = parts_1[_i];
127
+ assertAllowedPropertyName(part);
128
+ t = t[part] = t[part] || {};
129
+ }
130
+ t[key] = map[k];
131
+ }
132
+ return output;
133
+ };
134
+ QueryString.flatten = function (obj, _current, _res) {
135
+ if (_res === void 0) { _res = {}; }
136
+ for (var key in obj) {
137
+ var value = obj[key];
138
+ var newKey = _current ? _current + '.' + key : key;
139
+ if (value && typeof value === 'object') {
140
+ this.flatten(value, newKey, _res);
141
+ }
142
+ else {
143
+ _res[newKey] = value;
144
+ }
145
+ }
146
+ return _res;
147
+ };
148
+ return QueryString;
149
+ }());
150
+ function assertAllowedPropertyName(name) {
151
+ if (PROPERTY_NAME_DENY_LIST.indexOf(name) >= 0)
152
+ throw new Error("Property name \"".concat(name, "\" is not allowed"));
153
+ }
154
+
155
+ var version = "2.0.7";
156
+
157
+ var Subscription = /** @class */ (function () {
158
+ function Subscription(listeners, listener) {
159
+ this.listeners = listeners;
160
+ this.listener = listener;
161
+ this.unsubscribed = false;
162
+ this.otherSubscriptions = [];
163
+ }
164
+ Object.defineProperty(Subscription.prototype, "closed", {
165
+ get: function () {
166
+ return this.unsubscribed;
167
+ },
168
+ enumerable: false,
169
+ configurable: true
170
+ });
171
+ Subscription.prototype.add = function (subscription) {
172
+ this.otherSubscriptions.push(subscription);
173
+ };
174
+ Subscription.prototype.unsubscribe = function () {
175
+ if (this.unsubscribed) {
176
+ return;
177
+ }
178
+ if (this.listener && this.listeners) {
179
+ var index = this.listeners.indexOf(this.listener);
180
+ if (index > -1) {
181
+ this.listeners.splice(index, 1);
182
+ }
183
+ }
184
+ this.otherSubscriptions.forEach(function (sub) { return sub.unsubscribe(); });
185
+ this.unsubscribed = true;
186
+ };
187
+ return Subscription;
188
+ }());
189
+ // TODO: follow minimal basic spec: https://github.com/tc39/proposal-observable
190
+ var BehaviorSubject = /** @class */ (function () {
191
+ function BehaviorSubject(value) {
192
+ var _this = this;
193
+ this.value = value;
194
+ this.listeners = [];
195
+ this.errorListeners = [];
196
+ this.then = function () {
197
+ var _a;
198
+ var args = [];
199
+ for (var _i = 0; _i < arguments.length; _i++) {
200
+ args[_i] = arguments[_i];
201
+ }
202
+ return (_a = _this.toPromise()).then.apply(_a, args);
203
+ };
204
+ }
205
+ BehaviorSubject.prototype.next = function (value) {
206
+ this.value = value;
207
+ for (var _i = 0, _a = this.listeners; _i < _a.length; _i++) {
208
+ var listener = _a[_i];
209
+ listener(value);
210
+ }
211
+ };
212
+ // TODO: implement this as PIPE instead
213
+ BehaviorSubject.prototype.map = function (fn) {
214
+ var newSubject = new BehaviorSubject(fn(this.value));
215
+ // TODO: on destroy delete these
216
+ this.subscribe(function (val) {
217
+ newSubject.next(fn(val));
218
+ });
219
+ this.catch(function (err) {
220
+ newSubject.error(err);
221
+ });
222
+ return newSubject;
223
+ };
224
+ BehaviorSubject.prototype.catch = function (errorListener) {
225
+ this.errorListeners.push(errorListener);
226
+ return new Subscription(this.errorListeners, errorListener);
227
+ };
228
+ BehaviorSubject.prototype.error = function (error) {
229
+ for (var _i = 0, _a = this.errorListeners; _i < _a.length; _i++) {
230
+ var listener = _a[_i];
231
+ listener(error);
232
+ }
233
+ };
234
+ BehaviorSubject.prototype.subscribe = function (listener, errorListener) {
235
+ this.listeners.push(listener);
236
+ if (errorListener) {
237
+ this.errorListeners.push(errorListener);
238
+ }
239
+ return new Subscription(this.listeners, listener);
240
+ };
241
+ BehaviorSubject.prototype.toPromise = function () {
242
+ var _this = this;
243
+ return new Promise(function (resolve, reject) {
244
+ var subscription = _this.subscribe(function (value) {
245
+ resolve(value);
246
+ subscription.unsubscribe();
247
+ }, function (err) {
248
+ reject(err);
249
+ subscription.unsubscribe();
250
+ });
251
+ });
252
+ };
253
+ BehaviorSubject.prototype.promise = function () {
254
+ return this.toPromise();
255
+ };
256
+ return BehaviorSubject;
257
+ }());
258
+
259
+ var State = {
260
+ Pending: 'Pending',
261
+ Fulfilled: 'Fulfilled',
262
+ Rejected: 'Rejected',
263
+ };
264
+ function isFunction(val) {
265
+ return val && typeof val === 'function';
266
+ }
267
+ function isObject(val) {
268
+ return val && typeof val === 'object';
269
+ }
270
+ var TinyPromise = /** @class */ (function () {
271
+ function TinyPromise(executor) {
272
+ this._state = State.Pending;
273
+ this._handlers = [];
274
+ this._value = null;
275
+ executor(this._resolve.bind(this), this._reject.bind(this));
276
+ }
277
+ TinyPromise.prototype._resolve = function (x) {
278
+ var _this = this;
279
+ if (x instanceof TinyPromise) {
280
+ x.then(this._resolve.bind(this), this._reject.bind(this));
281
+ }
282
+ else if (isObject(x) || isFunction(x)) {
283
+ var called_1 = false;
284
+ try {
285
+ var thenable = x.then;
286
+ if (isFunction(thenable)) {
287
+ thenable.call(x, function (result) {
288
+ if (!called_1)
289
+ _this._resolve(result);
290
+ called_1 = true;
291
+ return undefined;
292
+ }, function (error) {
293
+ if (!called_1)
294
+ _this._reject(error);
295
+ called_1 = true;
296
+ return undefined;
297
+ });
298
+ }
299
+ else {
300
+ this._fulfill(x);
301
+ }
302
+ }
303
+ catch (ex) {
304
+ if (!called_1) {
305
+ this._reject(ex);
306
+ }
307
+ }
308
+ }
309
+ else {
310
+ this._fulfill(x);
311
+ }
312
+ };
313
+ TinyPromise.prototype._fulfill = function (result) {
314
+ var _this = this;
315
+ this._state = State.Fulfilled;
316
+ this._value = result;
317
+ this._handlers.forEach(function (handler) { return _this._callHandler(handler); });
318
+ };
319
+ TinyPromise.prototype._reject = function (error) {
320
+ var _this = this;
321
+ this._state = State.Rejected;
322
+ this._value = error;
323
+ this._handlers.forEach(function (handler) { return _this._callHandler(handler); });
324
+ };
325
+ TinyPromise.prototype._isPending = function () {
326
+ return this._state === State.Pending;
327
+ };
328
+ TinyPromise.prototype._isFulfilled = function () {
329
+ return this._state === State.Fulfilled;
330
+ };
331
+ TinyPromise.prototype._isRejected = function () {
332
+ return this._state === State.Rejected;
333
+ };
334
+ TinyPromise.prototype._addHandler = function (onFulfilled, onRejected) {
335
+ this._handlers.push({
336
+ onFulfilled: onFulfilled,
337
+ onRejected: onRejected,
338
+ });
339
+ };
340
+ TinyPromise.prototype._callHandler = function (handler) {
341
+ if (this._isFulfilled() && isFunction(handler.onFulfilled)) {
342
+ handler.onFulfilled(this._value);
343
+ }
344
+ else if (this._isRejected() && isFunction(handler.onRejected)) {
345
+ handler.onRejected(this._value);
346
+ }
347
+ };
348
+ TinyPromise.prototype.then = function (onFulfilled, onRejected) {
349
+ var _this = this;
350
+ switch (this._state) {
351
+ case State.Pending: {
352
+ return new TinyPromise(function (resolve, reject) {
353
+ _this._addHandler(function (value) {
354
+ nextTick(function () {
355
+ try {
356
+ if (isFunction(onFulfilled)) {
357
+ resolve(onFulfilled(value));
358
+ }
359
+ else {
360
+ resolve(value);
361
+ }
362
+ }
363
+ catch (ex) {
364
+ reject(ex);
365
+ }
366
+ });
367
+ }, function (error) {
368
+ nextTick(function () {
369
+ try {
370
+ if (isFunction(onRejected)) {
371
+ resolve(onRejected(error));
372
+ }
373
+ else {
374
+ reject(error);
375
+ }
376
+ }
377
+ catch (ex) {
378
+ reject(ex);
379
+ }
380
+ });
381
+ });
382
+ });
383
+ }
384
+ case State.Fulfilled: {
385
+ return new TinyPromise(function (resolve, reject) {
386
+ nextTick(function () {
387
+ try {
388
+ if (isFunction(onFulfilled)) {
389
+ resolve(onFulfilled(_this._value));
390
+ }
391
+ else {
392
+ resolve(_this._value);
393
+ }
394
+ }
395
+ catch (ex) {
396
+ reject(ex);
397
+ }
398
+ });
399
+ });
400
+ }
401
+ case State.Rejected: {
402
+ return new TinyPromise(function (resolve, reject) {
403
+ nextTick(function () {
404
+ try {
405
+ if (isFunction(onRejected)) {
406
+ resolve(onRejected(_this._value));
407
+ }
408
+ else {
409
+ reject(_this._value);
410
+ }
411
+ }
412
+ catch (ex) {
413
+ reject(ex);
414
+ }
415
+ });
416
+ });
417
+ }
418
+ }
419
+ };
420
+ return TinyPromise;
421
+ }());
422
+ var Promise$1 = (typeof Promise !== 'undefined' ? Promise : TinyPromise);
423
+
424
+ // Webpack workaround to conditionally require certain external modules
425
+ // only on the server and not bundle them on the client
426
+ var serverOnlyRequire;
427
+ try {
428
+ // tslint:disable-next-line:no-eval
429
+ serverOnlyRequire = eval('require');
430
+ }
431
+ catch (err) {
432
+ // all good
433
+ serverOnlyRequire = (function () { return null; });
434
+ }
435
+ var serverOnlyRequire$1 = serverOnlyRequire;
436
+
437
+ function promiseResolve(value) {
438
+ return new Promise$1(function (resolve) { return resolve(value); });
439
+ }
440
+ // Adapted from https://raw.githubusercontent.com/developit/unfetch/master/src/index.mjs
441
+ function tinyFetch(url, options) {
442
+ if (options === void 0) { options = {}; }
443
+ return new Promise$1(function (resolve, reject) {
444
+ var request = new XMLHttpRequest();
445
+ request.open(options.method || 'get', url, true);
446
+ if (options.headers) {
447
+ for (var i in options.headers) {
448
+ request.setRequestHeader(i, options.headers[i]);
449
+ }
450
+ }
451
+ request.withCredentials = options.credentials === 'include';
452
+ request.onload = function () {
453
+ resolve(response());
454
+ };
455
+ request.onerror = reject;
456
+ request.send(options.body);
457
+ function response() {
458
+ var keys = [];
459
+ var all = [];
460
+ var headers = {};
461
+ var header = undefined;
462
+ request
463
+ .getAllResponseHeaders()
464
+ .replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function (_match, _key, value) {
465
+ var key = _key;
466
+ keys.push((key = key.toLowerCase()));
467
+ all.push([key, value]);
468
+ header = headers[key];
469
+ headers[key] = header ? "".concat(header, ",").concat(value) : value;
470
+ return '';
471
+ });
472
+ return {
473
+ ok: ((request.status / 100) | 0) === 2,
474
+ status: request.status,
475
+ statusText: request.statusText,
476
+ url: request.responseURL,
477
+ clone: response,
478
+ text: function () { return promiseResolve(request.responseText); },
479
+ json: function () { return promiseResolve(request.responseText).then(JSON.parse); },
480
+ blob: function () { return promiseResolve(new Blob([request.response])); },
481
+ headers: {
482
+ keys: function () { return keys; },
483
+ entries: function () { return all; },
484
+ get: function (n) { return headers[n.toLowerCase()]; },
485
+ has: function (n) { return n.toLowerCase() in headers; },
486
+ },
487
+ };
488
+ }
489
+ });
490
+ }
491
+ function getFetch() {
492
+ // If fetch is defined, in the browser, via polyfill, or in a Cloudflare worker, use it.
493
+ var _fetch = undefined;
494
+ if (globalThis.fetch) {
495
+ _fetch !== null && _fetch !== void 0 ? _fetch : (_fetch = globalThis.fetch);
496
+ }
497
+ else if (typeof window === 'undefined') {
498
+ // If fetch is not defined, in a Node.js environment, use node-fetch.
499
+ try {
500
+ // node-fetch@^3 is ESM only, and will throw error on require.
501
+ _fetch !== null && _fetch !== void 0 ? _fetch : (_fetch = serverOnlyRequire$1('node-fetch'));
502
+ }
503
+ catch (e) {
504
+ // If node-fetch is not installed, use tiny-fetch.
505
+ console.warn('node-fetch is not installed. consider polyfilling fetch or installing node-fetch.');
506
+ console.warn(e);
507
+ }
508
+ }
509
+ // Otherwise, use tiny-fetch.
510
+ return _fetch !== null && _fetch !== void 0 ? _fetch : tinyFetch;
511
+ }
512
+
513
+ function assign(target) {
514
+ var to = Object(target);
515
+ for (var index = 1; index < arguments.length; index++) {
516
+ var nextSource = arguments[index];
517
+ if (nextSource != null) {
518
+ // Skip over if undefined or null
519
+ for (var nextKey in nextSource) {
520
+ // Avoid bugs when hasOwnProperty is shadowed
521
+ if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
522
+ to[nextKey] = nextSource[nextKey];
523
+ }
524
+ }
525
+ }
526
+ }
527
+ return to;
528
+ }
529
+
530
+ function throttle(func, wait, options) {
531
+ if (options === void 0) { options = {}; }
532
+ var context;
533
+ var args;
534
+ var result;
535
+ var timeout = null;
536
+ var previous = 0;
537
+ var later = function () {
538
+ previous = options.leading === false ? 0 : Date.now();
539
+ timeout = null;
540
+ result = func.apply(context, args);
541
+ if (!timeout)
542
+ context = args = null;
543
+ };
544
+ return function () {
545
+ var now = Date.now();
546
+ if (!previous && options.leading === false)
547
+ previous = now;
548
+ var remaining = wait - (now - previous);
549
+ context = this;
550
+ args = arguments;
551
+ if (remaining <= 0 || remaining > wait) {
552
+ if (timeout) {
553
+ clearTimeout(timeout);
554
+ timeout = null;
555
+ }
556
+ previous = now;
557
+ result = func.apply(context, args);
558
+ if (!timeout)
559
+ context = args = null;
560
+ }
561
+ else if (!timeout && options.trailing !== false) {
562
+ timeout = setTimeout(later, remaining);
563
+ }
564
+ return result;
565
+ };
566
+ }
567
+
568
+ var camelCaseToKebabCase = function (str) {
569
+ return str ? str.replace(/([A-Z])/g, function (g) { return "-".concat(g[0].toLowerCase()); }) : '';
570
+ };
571
+ var Animator = /** @class */ (function () {
572
+ function Animator() {
573
+ }
574
+ Animator.prototype.bindAnimations = function (animations) {
575
+ for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
576
+ var animation = animations_1[_i];
577
+ switch (animation.trigger) {
578
+ case 'pageLoad':
579
+ this.triggerAnimation(animation);
580
+ break;
581
+ case 'hover':
582
+ this.bindHoverAnimation(animation);
583
+ break;
584
+ case 'scrollInView':
585
+ this.bindScrollInViewAnimation(animation);
586
+ break;
587
+ }
588
+ }
589
+ };
590
+ Animator.prototype.warnElementNotPresent = function (id) {
591
+ console.warn("Cannot animate element: element with ID ".concat(id, " not found!"));
592
+ };
593
+ Animator.prototype.augmentAnimation = function (animation, element) {
594
+ var stylesUsed = this.getAllStylesUsed(animation);
595
+ var computedStyle = getComputedStyle(element);
596
+ // const computedStyle = getComputedStyle(element);
597
+ // // FIXME: this will break if original load is in one reponsive size then resize to another hmmm
598
+ // Need to use transform instead of left since left can change on screen sizes
599
+ var firstStyles = animation.steps[0].styles;
600
+ var lastStyles = animation.steps[animation.steps.length - 1].styles;
601
+ var bothStyles = [firstStyles, lastStyles];
602
+ // FIXME: this won't work as expected for augmented animations - may need the editor itself to manage this
603
+ for (var _i = 0, bothStyles_1 = bothStyles; _i < bothStyles_1.length; _i++) {
604
+ var styles = bothStyles_1[_i];
605
+ for (var _a = 0, stylesUsed_1 = stylesUsed; _a < stylesUsed_1.length; _a++) {
606
+ var style = stylesUsed_1[_a];
607
+ if (!(style in styles)) {
608
+ styles[style] = computedStyle[style];
609
+ }
610
+ }
611
+ }
612
+ };
613
+ Animator.prototype.getAllStylesUsed = function (animation) {
614
+ var properties = [];
615
+ for (var _i = 0, _a = animation.steps; _i < _a.length; _i++) {
616
+ var step = _a[_i];
617
+ for (var key in step.styles) {
618
+ if (properties.indexOf(key) === -1) {
619
+ properties.push(key);
620
+ }
621
+ }
622
+ }
623
+ return properties;
624
+ };
625
+ Animator.prototype.triggerAnimation = function (animation) {
626
+ var _this = this;
627
+ // TODO: do for ALL elements
628
+ var elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ''));
629
+ if (!elements.length) {
630
+ this.warnElementNotPresent(animation.elementId || animation.id || '');
631
+ return;
632
+ }
633
+ Array.from(elements).forEach(function (element) {
634
+ _this.augmentAnimation(animation, element);
635
+ // TODO: do this properly, may have other animations of different properties
636
+ // TODO: only override the properties
637
+ // TODO: if there is an entrance and hover animation, the transition duration will get effed
638
+ // element.setAttribute('style', '');
639
+ // const styledUsed = this.getAllStylesUsed(animation);
640
+ element.style.transition = 'none';
641
+ element.style.transitionDelay = '0';
642
+ assign(element.style, animation.steps[0].styles);
643
+ // TODO: queue/batch these timeouts
644
+ // TODO: only include properties explicitly set in the animation
645
+ // using Object.keys(styles)
646
+ setTimeout(function () {
647
+ element.style.transition = "all ".concat(animation.duration, "s ").concat(camelCaseToKebabCase(animation.easing));
648
+ if (animation.delay) {
649
+ element.style.transitionDelay = animation.delay + 's';
650
+ }
651
+ assign(element.style, animation.steps[1].styles);
652
+ // TODO: maybe remove/reset transitoin property after animation duration
653
+ // TODO: queue timers
654
+ setTimeout(function () {
655
+ // TODO: what if has other transition (reset back to what it was)
656
+ element.style.transition = '';
657
+ element.style.transitionDelay = '';
658
+ }, (animation.delay || 0) * 1000 + animation.duration * 1000 + 100);
659
+ });
660
+ });
661
+ };
662
+ Animator.prototype.bindHoverAnimation = function (animation) {
663
+ var _this = this;
664
+ // TODO: is it multiple binding when editing...?
665
+ // TODO: unbind on element remove
666
+ // TODO: apply to ALL elements
667
+ var elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ''));
668
+ if (!elements.length) {
669
+ this.warnElementNotPresent(animation.elementId || animation.id || '');
670
+ return;
671
+ }
672
+ Array.from(elements).forEach(function (element) {
673
+ _this.augmentAnimation(animation, element);
674
+ var defaultState = animation.steps[0].styles;
675
+ var hoverState = animation.steps[1].styles;
676
+ function attachDefaultState() {
677
+ assign(element.style, defaultState);
678
+ }
679
+ function attachHoverState() {
680
+ assign(element.style, hoverState);
681
+ }
682
+ attachDefaultState();
683
+ element.addEventListener('mouseenter', attachHoverState);
684
+ element.addEventListener('mouseleave', attachDefaultState);
685
+ // TODO: queue/batch these timeouts
686
+ setTimeout(function () {
687
+ element.style.transition = "all ".concat(animation.duration, "s ").concat(camelCaseToKebabCase(animation.easing));
688
+ if (animation.delay) {
689
+ element.style.transitionDelay = animation.delay + 's';
690
+ }
691
+ });
692
+ });
693
+ };
694
+ // TODO: unbind on element remove
695
+ Animator.prototype.bindScrollInViewAnimation = function (animation) {
696
+ var _this = this;
697
+ // TODO: apply to ALL matching elements
698
+ var elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ''));
699
+ if (!elements.length) {
700
+ this.warnElementNotPresent(animation.elementId || animation.id || '');
701
+ return;
702
+ }
703
+ // TODO: if server side rendered and scrolled into view don't animate...
704
+ Array.from(elements).forEach(function (element) {
705
+ _this.augmentAnimation(animation, element);
706
+ var triggered = false;
707
+ var pendingAnimation = false;
708
+ function immediateOnScroll() {
709
+ if (!triggered && isScrolledIntoView(element)) {
710
+ triggered = true;
711
+ pendingAnimation = true;
712
+ setTimeout(function () {
713
+ assign(element.style, animation.steps[1].styles);
714
+ if (!animation.repeat) {
715
+ document.removeEventListener('scroll', onScroll);
716
+ }
717
+ setTimeout(function () {
718
+ pendingAnimation = false;
719
+ if (!animation.repeat) {
720
+ element.style.transition = '';
721
+ element.style.transitionDelay = '';
722
+ }
723
+ }, (animation.duration + (animation.delay || 0)) * 1000 + 100);
724
+ });
725
+ }
726
+ else if (animation.repeat &&
727
+ triggered &&
728
+ !pendingAnimation &&
729
+ !isScrolledIntoView(element)) {
730
+ // we want to repeat the animation every time the the element is out of view and back again
731
+ triggered = false;
732
+ assign(element.style, animation.steps[0].styles);
733
+ }
734
+ }
735
+ // TODO: roll all of these in one for more efficiency of checking all the rects
736
+ var onScroll = throttle(immediateOnScroll, 200, { leading: false });
737
+ // TODO: fully in view or partially
738
+ function isScrolledIntoView(elem) {
739
+ var rect = elem.getBoundingClientRect();
740
+ var windowHeight = window.innerHeight;
741
+ var thresholdPercent = (animation.thresholdPercent || 0) / 100;
742
+ var threshold = thresholdPercent * windowHeight;
743
+ // TODO: partial in view? or what if element is larger than screen itself
744
+ return (rect.bottom > threshold && rect.top < windowHeight - threshold // Element is peeking top or bottom
745
+ // (rect.top > 0 && rect.bottom < window.innerHeight) || // element fits within the screen and is fully on screen (not hanging off at all)
746
+ // (rect.top < 0 && rect.bottom > window.innerHeight) // element is larger than the screen and hangs over the top and bottom
747
+ );
748
+ }
749
+ var defaultState = animation.steps[0].styles;
750
+ function attachDefaultState() {
751
+ assign(element.style, defaultState);
752
+ }
753
+ attachDefaultState();
754
+ // TODO: queue/batch these timeouts!
755
+ setTimeout(function () {
756
+ element.style.transition = "all ".concat(animation.duration, "s ").concat(camelCaseToKebabCase(animation.easing));
757
+ if (animation.delay) {
758
+ element.style.transitionDelay = animation.delay + 's';
759
+ }
760
+ });
761
+ // TODO: one listener for everything
762
+ document.addEventListener('scroll', onScroll, { capture: true, passive: true });
763
+ // Do an initial check
764
+ immediateOnScroll();
765
+ });
766
+ };
767
+ return Animator;
768
+ }());
769
+
770
+ /**
771
+ * Only gets one level up from hostname
772
+ * wwww.example.com -> example.com
773
+ * www.example.co.uk -> example.co.uk
774
+ */
775
+ function getTopLevelDomain(host) {
776
+ var parts = host.split('.');
777
+ if (parts.length > 2) {
778
+ return parts.slice(1).join('.');
779
+ }
780
+ return host;
781
+ }
782
+
783
+ /**
784
+ * RegExp to match field-content in RFC 7230 sec 3.2
785
+ *
786
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
787
+ * field-vchar = VCHAR / obs-text
788
+ * obs-text = %x80-FF
789
+ */
790
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
791
+ var Cookies = /** @class */ (function () {
792
+ function Cookies(request, response) {
793
+ this.request = request;
794
+ this.response = response;
795
+ }
796
+ Cookies.prototype.get = function (name) {
797
+ var header = this.request.headers['cookie'];
798
+ if (!header) {
799
+ return;
800
+ }
801
+ var match = header.match(getPattern(name));
802
+ if (!match) {
803
+ return;
804
+ }
805
+ var value = match[1];
806
+ return value;
807
+ };
808
+ Cookies.prototype.set = function (name, value, opts) {
809
+ var res = this.response;
810
+ var req = this.request;
811
+ var headers = res.getHeader('Set-Cookie') || [];
812
+ // TODO: just make this always true
813
+ var secure = this.secure !== undefined
814
+ ? !!this.secure
815
+ : req.protocol === 'https' || req.connection.encrypted;
816
+ var cookie = new Cookie(name, value, opts);
817
+ if (typeof headers === 'string') {
818
+ headers = [headers];
819
+ }
820
+ if (!secure && opts && opts.secure) {
821
+ throw new Error('Cannot send secure cookie over unencrypted connection');
822
+ }
823
+ cookie.secure = secure;
824
+ if (opts && 'secure' in opts) {
825
+ cookie.secure = !!opts.secure;
826
+ }
827
+ cookie.domain = req.headers.host && getTopLevelDomain(req.headers.host);
828
+ pushCookie(headers, cookie);
829
+ var setHeader = res.setHeader;
830
+ setHeader.call(res, 'Set-Cookie', headers);
831
+ return this;
832
+ };
833
+ return Cookies;
834
+ }());
835
+ var Cookie = /** @class */ (function () {
836
+ function Cookie(name, value, attrs) {
837
+ this.path = '/';
838
+ this.domain = undefined;
839
+ this.httpOnly = true;
840
+ this.sameSite = false;
841
+ this.secure = false;
842
+ this.overwrite = false;
843
+ this.name = '';
844
+ this.value = '';
845
+ if (!fieldContentRegExp.test(name)) {
846
+ throw new TypeError('argument name is invalid');
847
+ }
848
+ if (value && !fieldContentRegExp.test(value)) {
849
+ throw new TypeError('argument value is invalid');
850
+ }
851
+ if (!value) {
852
+ this.expires = new Date(0);
853
+ }
854
+ this.name = name;
855
+ this.value = value || '';
856
+ if (attrs.expires) {
857
+ this.expires = attrs.expires;
858
+ }
859
+ if (attrs.secure) {
860
+ this.secure = attrs.secure;
861
+ }
862
+ }
863
+ Cookie.prototype.toString = function () {
864
+ return "".concat(this.name, "=").concat(this.value);
865
+ };
866
+ Cookie.prototype.toHeader = function () {
867
+ var header = this.toString();
868
+ if (this.maxAge) {
869
+ this.expires = new Date(Date.now() + this.maxAge);
870
+ }
871
+ if (this.path) {
872
+ header += "; path=".concat(this.path);
873
+ }
874
+ if (this.expires) {
875
+ header += "; expires=".concat(this.expires.toUTCString());
876
+ }
877
+ if (this.domain) {
878
+ header += "; domain=".concat(this.domain);
879
+ }
880
+ // TODO: samesite=none by default (?)
881
+ header += "; SameSite=".concat(this.sameSite === true ? 'strict' : 'None');
882
+ // TODO: On by default
883
+ if (this.secure) {
884
+ header += '; secure';
885
+ }
886
+ if (this.httpOnly) {
887
+ header += '; httponly';
888
+ }
889
+ return header;
890
+ };
891
+ return Cookie;
892
+ }());
893
+ function getPattern(name) {
894
+ return new RegExp("(?:^|;) *".concat(name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'), "=([^;]*)"));
895
+ }
896
+ function pushCookie(headers, cookie) {
897
+ if (cookie.overwrite) {
898
+ for (var i = headers.length - 1; i >= 0; i--) {
899
+ if (headers[i].indexOf("".concat(cookie.name, "=")) === 0) {
900
+ headers.splice(i, 1);
901
+ }
902
+ }
903
+ }
904
+ headers.push(cookie.toHeader());
905
+ }
906
+
907
+ function omit(obj) {
908
+ var values = [];
909
+ for (var _i = 1; _i < arguments.length; _i++) {
910
+ values[_i - 1] = arguments[_i];
911
+ }
912
+ var newObject = Object.assign({}, obj);
913
+ for (var _a = 0, values_1 = values; _a < values_1.length; _a++) {
914
+ var key = values_1[_a];
915
+ delete newObject[key];
916
+ }
917
+ return newObject;
918
+ }
919
+
920
+ /**
921
+ * @credit https://stackoverflow.com/a/2117523
922
+ */
923
+ function uuidv4() {
924
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
925
+ var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
926
+ return v.toString(16);
927
+ });
928
+ }
929
+ /**
930
+ * Slightly cleaner and smaller UUIDs
931
+ */
932
+ function uuid() {
933
+ return uuidv4().replace(/-/g, '');
934
+ }
935
+
936
+ function emptyUrl() {
937
+ return {
938
+ query: null,
939
+ port: null,
940
+ auth: null,
941
+ hash: null,
942
+ host: null,
943
+ hostname: null,
944
+ href: null,
945
+ path: null,
946
+ pathname: null,
947
+ protocol: null,
948
+ search: null,
949
+ slashes: null,
950
+ };
951
+ }
952
+ // Replacement for `url.parse` using `URL` global object that works with relative paths.
953
+ // Assumptions: this function operates in a NodeJS environment.
954
+ function parse$1(url) {
955
+ var out = emptyUrl();
956
+ var u;
957
+ var pathOnly = url === '' || url[0] === '/';
958
+ if (pathOnly) {
959
+ u = new URL(url, 'http://0.0.0.0/');
960
+ out.href = u.href;
961
+ out.href = out.href.slice(14); // remove 'http://0.0.0.0/'
962
+ }
963
+ else {
964
+ u = new URL(url);
965
+ out.href = u.href;
966
+ out.port = u.port === '' ? null : u.port;
967
+ out.hash = u.hash === '' ? null : u.hash;
968
+ out.host = u.host;
969
+ out.hostname = u.hostname;
970
+ out.href = u.href;
971
+ out.pathname = u.pathname;
972
+ out.protocol = u.protocol;
973
+ out.slashes = url[u.protocol.length] === '/'; // check if the mimetype is proceeded by a slash
974
+ }
975
+ out.search = u.search;
976
+ out.query = u.search.slice(1); // remove '?'
977
+ out.path = "".concat(u.pathname).concat(u.search);
978
+ out.pathname = u.pathname;
979
+ return out;
980
+ }
981
+
982
+ function pad (hash, len) {
983
+ while (hash.length < len) {
984
+ hash = '0' + hash;
985
+ }
986
+ return hash;
987
+ }
988
+
989
+ function fold (hash, text) {
990
+ var i;
991
+ var chr;
992
+ var len;
993
+ if (text.length === 0) {
994
+ return hash;
995
+ }
996
+ for (i = 0, len = text.length; i < len; i++) {
997
+ chr = text.charCodeAt(i);
998
+ hash = ((hash << 5) - hash) + chr;
999
+ hash |= 0;
1000
+ }
1001
+ return hash < 0 ? hash * -2 : hash;
1002
+ }
1003
+
1004
+ function foldObject (hash, o, seen) {
1005
+ return Object.keys(o).sort().reduce(foldKey, hash);
1006
+ function foldKey (hash, key) {
1007
+ return foldValue(hash, o[key], key, seen);
1008
+ }
1009
+ }
1010
+
1011
+ function foldValue (input, value, key, seen) {
1012
+ var hash = fold(fold(fold(input, key), toString(value)), typeof value);
1013
+ if (value === null) {
1014
+ return fold(hash, 'null');
1015
+ }
1016
+ if (value === undefined) {
1017
+ return fold(hash, 'undefined');
1018
+ }
1019
+ if (typeof value === 'object' || typeof value === 'function') {
1020
+ if (seen.indexOf(value) !== -1) {
1021
+ return fold(hash, '[Circular]' + key);
1022
+ }
1023
+ seen.push(value);
1024
+
1025
+ var objHash = foldObject(hash, value, seen);
1026
+
1027
+ if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
1028
+ return objHash;
1029
+ }
1030
+
1031
+ try {
1032
+ return fold(objHash, String(value.valueOf()))
1033
+ } catch (err) {
1034
+ return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
1035
+ }
1036
+ }
1037
+ return fold(hash, value.toString());
1038
+ }
1039
+
1040
+ function toString (o) {
1041
+ return Object.prototype.toString.call(o);
1042
+ }
1043
+
1044
+ function sum (o) {
1045
+ return pad(foldValue(0, o, '', []).toString(16), 8);
1046
+ }
1047
+
1048
+ var hashSum = sum;
1049
+
1050
+ /**
1051
+ * Safe conversion to error type. Intended to be used in catch blocks where the
1052
+ * value is not guaranteed to be an error.
1053
+ *
1054
+ * @example
1055
+ * try {
1056
+ * throw new Error('Something went wrong')
1057
+ * }
1058
+ * catch (err: unknown) {
1059
+ * const error: Error = toError(err)
1060
+ * }
1061
+ */
1062
+ function toError(err) {
1063
+ if (err instanceof Error)
1064
+ return err;
1065
+ return new Error(String(err));
1066
+ }
1067
+
1068
+ var DEFAULT_API_VERSION = 'v3';
1069
+
1070
+ function datePlusMinutes(minutes) {
1071
+ if (minutes === void 0) { minutes = 30; }
1072
+ return new Date(Date.now() + minutes * 60000);
1073
+ }
1074
+ var isPositiveNumber = function (thing) {
1075
+ return typeof thing === 'number' && !isNaN(thing) && thing >= 0;
1076
+ };
1077
+ var isReactNative = typeof navigator === 'object' && navigator.product === 'ReactNative';
1078
+ var validEnvList = [
1079
+ 'production',
1080
+ 'qa',
1081
+ 'test',
1082
+ 'development',
1083
+ 'dev',
1084
+ 'cdn-qa',
1085
+ 'cloud',
1086
+ 'fast',
1087
+ 'cdn2',
1088
+ 'cdn-prod',
1089
+ ];
1090
+ function getQueryParam(url, variable) {
1091
+ var query = url.split('?')[1] || '';
1092
+ var vars = query.split('&');
1093
+ for (var i = 0; i < vars.length; i++) {
1094
+ var pair = vars[i].split('=');
1095
+ if (decodeURIComponent(pair[0]) === variable) {
1096
+ return decodeURIComponent(pair[1]);
1097
+ }
1098
+ }
1099
+ return null;
1100
+ }
1101
+ var urlParser = {
1102
+ parse: function (url) {
1103
+ var el = document.createElement('a');
1104
+ el.href = url;
1105
+ var out = {};
1106
+ var props = [
1107
+ 'username',
1108
+ 'password',
1109
+ 'host',
1110
+ 'hostname',
1111
+ 'port',
1112
+ 'protocol',
1113
+ 'origin',
1114
+ 'pathname',
1115
+ 'search',
1116
+ 'hash',
1117
+ ];
1118
+ for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
1119
+ var prop = props_1[_i];
1120
+ out[prop] = el[prop];
1121
+ }
1122
+ // IE 11 pathname handling workaround
1123
+ // (IE omits preceeding '/', unlike other browsers)
1124
+ if ((out.pathname || out.pathname === '') &&
1125
+ typeof out.pathname === 'string' &&
1126
+ out.pathname.indexOf('/') !== 0) {
1127
+ out.pathname = '/' + out.pathname;
1128
+ }
1129
+ return out;
1130
+ },
1131
+ };
1132
+ var parse = isReactNative
1133
+ ? function () { return emptyUrl(); }
1134
+ : typeof window === 'object'
1135
+ ? urlParser.parse
1136
+ : parse$1;
1137
+ function setCookie(name, value, expires) {
1138
+ try {
1139
+ var expiresString = '';
1140
+ // TODO: need to know if secure server side
1141
+ if (expires) {
1142
+ expiresString = '; expires=' + expires.toUTCString();
1143
+ }
1144
+ var secure = isBrowser ? location.protocol === 'https:' : true;
1145
+ document.cookie =
1146
+ name +
1147
+ '=' +
1148
+ (value || '') +
1149
+ expiresString +
1150
+ '; path=/' +
1151
+ "; domain=".concat(getTopLevelDomain(location.hostname)) +
1152
+ (secure ? ';secure ; SameSite=None' : '');
1153
+ }
1154
+ catch (err) {
1155
+ console.warn('Could not set cookie', err);
1156
+ }
1157
+ }
1158
+ function getCookie(name) {
1159
+ try {
1160
+ return (decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' +
1161
+ encodeURIComponent(name).replace(/[\-\.\+\*]/g, '\\$&') +
1162
+ '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null);
1163
+ }
1164
+ catch (err) {
1165
+ console.warn('Could not get cookie', err);
1166
+ }
1167
+ }
1168
+ function size(object) {
1169
+ return Object.keys(object).length;
1170
+ }
1171
+ function find(target, callback) {
1172
+ var list = target;
1173
+ // Makes sures is always has an positive integer as length.
1174
+ var length = list.length >>> 0;
1175
+ var thisArg = arguments[1];
1176
+ for (var i = 0; i < length; i++) {
1177
+ var element = list[i];
1178
+ if (callback.call(thisArg, element, i, list)) {
1179
+ return element;
1180
+ }
1181
+ }
1182
+ }
1183
+ var sessionStorageKey = 'builderSessionId';
1184
+ var localStorageKey = 'builderVisitorId';
1185
+ var isBrowser = typeof window !== 'undefined' && !isReactNative;
1186
+ var isIframe = isBrowser && window.top !== window.self;
1187
+ function BuilderComponent(info) {
1188
+ if (info === void 0) { info = {}; }
1189
+ return Builder.Component(info);
1190
+ }
1191
+ var Builder = /** @class */ (function () {
1192
+ function Builder(apiKey, request, response, forceNewInstance, authToken, apiVersion) {
1193
+ if (apiKey === void 0) { apiKey = null; }
1194
+ if (forceNewInstance === void 0) { forceNewInstance = false; }
1195
+ if (authToken === void 0) { authToken = null; }
1196
+ var _this = this;
1197
+ this.request = request;
1198
+ this.response = response;
1199
+ this.eventsQueue = [];
1200
+ this.throttledClearEventsQueue = throttle(function () {
1201
+ _this.processEventsQueue();
1202
+ // Extend the session cookie
1203
+ _this.setCookie(sessionStorageKey, _this.sessionId, datePlusMinutes(30));
1204
+ }, 5);
1205
+ this.env = 'production';
1206
+ this.sessionId = this.getSessionId();
1207
+ this.targetContent = true;
1208
+ this.contentPerRequest = 1;
1209
+ // TODO: make array or function
1210
+ this.allowCustomFonts = true;
1211
+ this.cookies = null;
1212
+ // TODO: api options object
1213
+ this.cachebust = false;
1214
+ this.overrideParams = '';
1215
+ this.noCache = false;
1216
+ this.preview = false;
1217
+ this.apiVersion$ = new BehaviorSubject(undefined);
1218
+ this.canTrack$ = new BehaviorSubject(!this.browserTrackingDisabled);
1219
+ this.apiKey$ = new BehaviorSubject(null);
1220
+ this.authToken$ = new BehaviorSubject(null);
1221
+ this.userAttributesChanged = new BehaviorSubject(null);
1222
+ this.editingMode$ = new BehaviorSubject(isIframe);
1223
+ // TODO: decorator to do this stuff with the get/set (how do with typing too? compiler?)
1224
+ this.editingModel$ = new BehaviorSubject(null);
1225
+ this.userAgent = (typeof navigator === 'object' && navigator.userAgent) || '';
1226
+ this.trackingHooks = [];
1227
+ // Set this to control the userId
1228
+ // TODO: allow changing it mid session and updating existing data to be associated
1229
+ // e.g. for when a user navigates and then logs in
1230
+ this.visitorId = this.getVisitorId();
1231
+ this.autoTrack = !Builder.isBrowser
1232
+ ? false
1233
+ : !this.isDevelopmentEnv &&
1234
+ !(Builder.isBrowser && location.search.indexOf('builder.preview=') !== -1);
1235
+ this.trackingUserAttributes = {};
1236
+ this.blockContentLoading = '';
1237
+ this.observersByKey = {};
1238
+ this.noEditorUpdates = {};
1239
+ this.overrides = {};
1240
+ this.queryOptions = {};
1241
+ this.getContentQueue = null;
1242
+ this.priorContentQueue = null;
1243
+ this.testCookiePrefix = 'builder.tests';
1244
+ this.cookieQueue = [];
1245
+ // TODO: use a window variable for this perhaps, e.g. bc webcomponents may be loading builder twice
1246
+ // with it's and react (use rollup build to fix)
1247
+ if (Builder.isBrowser && !forceNewInstance && Builder.singletonInstance) {
1248
+ return Builder.singletonInstance;
1249
+ }
1250
+ if (this.request && this.response) {
1251
+ this.setUserAgent(this.request.headers['user-agent'] || '');
1252
+ this.cookies = new Cookies(this.request, this.response);
1253
+ }
1254
+ if (apiKey) {
1255
+ this.apiKey = apiKey;
1256
+ }
1257
+ if (apiVersion) {
1258
+ this.apiVersion = apiVersion;
1259
+ }
1260
+ if (authToken) {
1261
+ this.authToken = authToken;
1262
+ }
1263
+ if (isBrowser) {
1264
+ this.bindMessageListeners();
1265
+ if (Builder.isEditing) {
1266
+ parent.postMessage({
1267
+ type: 'builder.animatorOptions',
1268
+ data: {
1269
+ options: {
1270
+ version: 2,
1271
+ },
1272
+ },
1273
+ }, '*');
1274
+ }
1275
+ // TODO: postmessage to parent the builder info for every package
1276
+ // type: 'builder.sdk', data: { name: '@builder.io/react', version: '0.1.23' }
1277
+ // (window as any).BUILDER_VERSION = Builder.VERSION;
1278
+ // Ensure always one Builder global singleton
1279
+ // TODO: some people won't want this, e.g. rakuten
1280
+ // Maybe hide this behind symbol or on document, etc
1281
+ // if ((window as any).Builder) {
1282
+ // Builder.components = (window as any).Builder.components;
1283
+ // } else {
1284
+ // (window as any).Builder = Builder;
1285
+ // }
1286
+ }
1287
+ if (isIframe) {
1288
+ this.messageFrameLoaded();
1289
+ }
1290
+ // TODO: on destroy clear subscription
1291
+ this.canTrack$.subscribe(function (value) {
1292
+ if (value) {
1293
+ if (typeof sessionStorage !== 'undefined') {
1294
+ try {
1295
+ if (!sessionStorage.getItem(sessionStorageKey)) {
1296
+ sessionStorage.setItem(sessionStorageKey, _this.sessionId);
1297
+ }
1298
+ }
1299
+ catch (err) {
1300
+ console.debug('Session storage error', err);
1301
+ }
1302
+ }
1303
+ if (_this.eventsQueue.length) {
1304
+ _this.throttledClearEventsQueue();
1305
+ }
1306
+ if (_this.cookieQueue.length) {
1307
+ _this.cookieQueue.forEach(function (item) {
1308
+ _this.setCookie(item[0], item[1]);
1309
+ });
1310
+ _this.cookieQueue.length = 0;
1311
+ }
1312
+ }
1313
+ });
1314
+ if (isBrowser) {
1315
+ // TODO: defer so subclass constructor runs and injects location service
1316
+ this.setTestsFromUrl();
1317
+ // TODO: do this on every request send?
1318
+ this.getOverridesFromQueryString();
1319
+ }
1320
+ }
1321
+ Builder.register = function (type, info) {
1322
+ // TODO: all must have name and can't conflict?
1323
+ var typeList = this.registry[type];
1324
+ if (!typeList) {
1325
+ typeList = this.registry[type] = [];
1326
+ }
1327
+ typeList.push(info);
1328
+ if (Builder.isBrowser) {
1329
+ var message = {
1330
+ type: 'builder.register',
1331
+ data: {
1332
+ type: type,
1333
+ info: info,
1334
+ },
1335
+ };
1336
+ try {
1337
+ parent.postMessage(message, '*');
1338
+ if (parent !== window) {
1339
+ window.postMessage(message, '*');
1340
+ }
1341
+ }
1342
+ catch (err) {
1343
+ console.debug('Could not postmessage', err);
1344
+ }
1345
+ }
1346
+ this.registryChange.next(this.registry);
1347
+ };
1348
+ Builder.registerEditor = function (info) {
1349
+ if (Builder.isBrowser) {
1350
+ window.postMessage({
1351
+ type: 'builder.registerEditor',
1352
+ data: omit(info, 'component'),
1353
+ }, '*');
1354
+ var hostname = location.hostname;
1355
+ if (!Builder.isTrustedHost(hostname)) {
1356
+ console.error('Builder.registerEditor() called in the wrong environment! You cannot load custom editors from your app, they must be loaded through the Builder.io app itself. Follow the readme here for more details: https://github.com/builderio/builder/tree/master/plugins/cloudinary or contact chat us in our Spectrum community for help: https://spectrum.chat/builder');
1357
+ }
1358
+ }
1359
+ this.editors.push(info);
1360
+ };
1361
+ Builder.registerPlugin = function (info) {
1362
+ this.plugins.push(info);
1363
+ };
1364
+ Builder.registerAction = function (action) {
1365
+ this.actions.push(action);
1366
+ };
1367
+ Builder.registerTrustedHost = function (host) {
1368
+ this.trustedHosts.push(host);
1369
+ };
1370
+ /**
1371
+ * @param context @type {import('isolated-vm').Context}
1372
+ * Use this function to control the execution context of custom code on the server.
1373
+ * const ivm = require('isolated-vm');
1374
+ * const isolate = new ivm.Isolate({ memoryLimit: 128 });
1375
+ * const context = isolate.createContextSync();
1376
+ * Builder.setServerContext(context);
1377
+ */
1378
+ Builder.setServerContext = function (context) {
1379
+ this.serverContext = context;
1380
+ };
1381
+ Builder.isTrustedHost = function (hostname) {
1382
+ return (this.trustedHosts.findIndex(function (trustedHost) { return trustedHost === hostname || hostname.endsWith(".".concat(trustedHost)); }) > -1);
1383
+ };
1384
+ Builder.runAction = function (action) {
1385
+ // TODO
1386
+ var actionObject = typeof action === 'string' ? find(this.actions, function (item) { return item.name === action; }) : action;
1387
+ if (!actionObject) {
1388
+ throw new Error("Action not found: ".concat(action));
1389
+ }
1390
+ };
1391
+ Builder.fields = function (name, fields) {
1392
+ var _a;
1393
+ (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({
1394
+ type: 'builder.fields',
1395
+ data: { name: name, fields: fields },
1396
+ }, '*');
1397
+ };
1398
+ /**
1399
+ * @deprecated
1400
+ * @hidden
1401
+ *
1402
+ * Use Builder.register('editor.settings', {}) instead.
1403
+ */
1404
+ Builder.set = function (settings) {
1405
+ Builder.register('editor.settings', settings);
1406
+ };
1407
+ Builder.import = function (packageName) {
1408
+ if (!Builder.isBrowser) {
1409
+ // TODO: server side support *maybe*
1410
+ console.warn('Builder.import used on the server - this should only be used in the browser');
1411
+ return;
1412
+ }
1413
+ var System = window.System;
1414
+ if (!System) {
1415
+ console.warn('System.js not available. Please include System.js when using Builder.import');
1416
+ return;
1417
+ }
1418
+ return System.import("https://cdn.builder.io/systemjs/".concat(packageName));
1419
+ };
1420
+ Object.defineProperty(Builder, "editingPage", {
1421
+ // useCdnApi = false;
1422
+ get: function () {
1423
+ return this._editingPage;
1424
+ },
1425
+ set: function (editingPage) {
1426
+ this._editingPage = editingPage;
1427
+ if (isBrowser && isIframe) {
1428
+ if (editingPage) {
1429
+ document.body.classList.add('builder-editing-page');
1430
+ }
1431
+ else {
1432
+ document.body.classList.remove('builder-editing-page');
1433
+ }
1434
+ }
1435
+ },
1436
+ enumerable: false,
1437
+ configurable: true
1438
+ });
1439
+ Builder.prepareComponentSpecToSend = function (spec) {
1440
+ return __assign(__assign(__assign({}, spec), (spec.inputs && {
1441
+ inputs: spec.inputs.map(function (input) {
1442
+ var _a;
1443
+ // TODO: do for nexted fields too
1444
+ // TODO: probably just convert all functions, not just
1445
+ // TODO: put this in input hooks: { onChange: ..., showIf: ... }
1446
+ var keysToConvertFnToString = ['onChange', 'showIf'];
1447
+ for (var _i = 0, keysToConvertFnToString_1 = keysToConvertFnToString; _i < keysToConvertFnToString_1.length; _i++) {
1448
+ var key = keysToConvertFnToString_1[_i];
1449
+ if (input[key] && typeof input[key] === 'function') {
1450
+ var fn = input[key];
1451
+ input = __assign(__assign({}, input), (_a = {}, _a[key] = "return (".concat(fn.toString(), ").apply(this, arguments)"), _a));
1452
+ }
1453
+ }
1454
+ return input;
1455
+ }),
1456
+ })), { hooks: Object.keys(spec.hooks || {}).reduce(function (memo, key) {
1457
+ var value = spec.hooks && spec.hooks[key];
1458
+ if (!value) {
1459
+ return memo;
1460
+ }
1461
+ if (typeof value === 'string') {
1462
+ memo[key] = value;
1463
+ }
1464
+ else {
1465
+ memo[key] = "return (".concat(value.toString(), ").apply(this, arguments)");
1466
+ }
1467
+ return memo;
1468
+ }, {}), class: undefined });
1469
+ };
1470
+ Builder.registerBlock = function (component, options) {
1471
+ this.registerComponent(component, options);
1472
+ };
1473
+ Builder.registerComponent = function (component, options) {
1474
+ var _a;
1475
+ var spec = __assign(__assign({ class: component }, component.builderOptions), options);
1476
+ this.addComponent(spec);
1477
+ var editable = options.models && this.singletonInstance.editingModel
1478
+ ? isBrowser && options.models.includes(this.singletonInstance.editingModel)
1479
+ : isBrowser;
1480
+ if (editable) {
1481
+ var sendSpec = this.prepareComponentSpecToSend(spec);
1482
+ (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({
1483
+ type: 'builder.registerComponent',
1484
+ data: sendSpec,
1485
+ }, '*');
1486
+ }
1487
+ };
1488
+ Builder.addComponent = function (component) {
1489
+ var current = find(this.components, function (item) { return item.name === component.name; });
1490
+ if (current) {
1491
+ // FIXME: why does sometimes we get an extra post without class - probably
1492
+ // from postMessage handler wrong in some place
1493
+ if (current.class && !component.class) {
1494
+ return;
1495
+ }
1496
+ this.components.splice(this.components.indexOf(current), 1, component);
1497
+ }
1498
+ else {
1499
+ this.components.push(component);
1500
+ }
1501
+ };
1502
+ // TODO: style guide, etc off this system as well?
1503
+ Builder.component = function (info) {
1504
+ var _this = this;
1505
+ if (info === void 0) { info = {}; }
1506
+ return function (component) {
1507
+ var _a;
1508
+ var spec = __assign(__assign({}, info), { class: component });
1509
+ if (!spec.name) {
1510
+ spec.name = component.name;
1511
+ }
1512
+ _this.addComponent(spec);
1513
+ var sendSpec = _this.prepareComponentSpecToSend(spec);
1514
+ // TODO: serialize component name and inputs
1515
+ if (isBrowser) {
1516
+ (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({
1517
+ type: 'builder.registerComponent',
1518
+ data: sendSpec,
1519
+ }, '*');
1520
+ }
1521
+ return component;
1522
+ };
1523
+ };
1524
+ Object.defineProperty(Builder, "Component", {
1525
+ get: function () {
1526
+ return this.component;
1527
+ },
1528
+ enumerable: false,
1529
+ configurable: true
1530
+ });
1531
+ Builder.prototype.processEventsQueue = function () {
1532
+ if (!this.eventsQueue.length) {
1533
+ return;
1534
+ }
1535
+ var events = this.eventsQueue;
1536
+ this.eventsQueue = [];
1537
+ var fullUserAttributes = __assign(__assign({}, Builder.overrideUserAttributes), this.trackingUserAttributes);
1538
+ for (var _i = 0, events_1 = events; _i < events_1.length; _i++) {
1539
+ var event_1 = events_1[_i];
1540
+ if (!event_1.data.metadata) {
1541
+ event_1.data.metadata = {};
1542
+ }
1543
+ if (!event_1.data.metadata.user) {
1544
+ event_1.data.metadata.user = {};
1545
+ }
1546
+ Object.assign(event_1.data.metadata.user, fullUserAttributes, event_1.data.metadata.user);
1547
+ }
1548
+ var host = this.host;
1549
+ getFetch()("".concat(host, "/api/v1/track"), {
1550
+ method: 'POST',
1551
+ body: JSON.stringify({ events: events }),
1552
+ headers: {
1553
+ 'content-type': 'application/json',
1554
+ },
1555
+ mode: 'cors',
1556
+ }).catch(function () {
1557
+ // Not the end of the world
1558
+ });
1559
+ };
1560
+ Object.defineProperty(Builder.prototype, "browserTrackingDisabled", {
1561
+ get: function () {
1562
+ return Builder.isBrowser && Boolean(window.builderNoTrack || !navigator.cookieEnabled);
1563
+ },
1564
+ enumerable: false,
1565
+ configurable: true
1566
+ });
1567
+ Object.defineProperty(Builder.prototype, "canTrack", {
1568
+ get: function () {
1569
+ return this.canTrack$.value;
1570
+ },
1571
+ set: function (canTrack) {
1572
+ if (this.canTrack !== canTrack) {
1573
+ this.canTrack$.next(canTrack);
1574
+ }
1575
+ },
1576
+ enumerable: false,
1577
+ configurable: true
1578
+ });
1579
+ Object.defineProperty(Builder.prototype, "apiVersion", {
1580
+ get: function () {
1581
+ return this.apiVersion$.value;
1582
+ },
1583
+ set: function (apiVersion) {
1584
+ if (this.apiVersion !== apiVersion) {
1585
+ this.apiVersion$.next(apiVersion);
1586
+ }
1587
+ },
1588
+ enumerable: false,
1589
+ configurable: true
1590
+ });
1591
+ Object.defineProperty(Builder.prototype, "editingMode", {
1592
+ get: function () {
1593
+ return this.editingMode$.value;
1594
+ },
1595
+ set: function (value) {
1596
+ if (value !== this.editingMode) {
1597
+ this.editingMode$.next(value);
1598
+ }
1599
+ },
1600
+ enumerable: false,
1601
+ configurable: true
1602
+ });
1603
+ Object.defineProperty(Builder.prototype, "editingModel", {
1604
+ get: function () {
1605
+ return this.editingModel$.value;
1606
+ },
1607
+ set: function (value) {
1608
+ if (value !== this.editingModel) {
1609
+ this.editingModel$.next(value);
1610
+ }
1611
+ },
1612
+ enumerable: false,
1613
+ configurable: true
1614
+ });
1615
+ Builder.prototype.findParentElement = function (target, callback, checkElement) {
1616
+ if (checkElement === void 0) { checkElement = true; }
1617
+ if (!(target instanceof HTMLElement)) {
1618
+ return null;
1619
+ }
1620
+ var parent = checkElement ? target : target.parentElement;
1621
+ do {
1622
+ if (!parent) {
1623
+ return null;
1624
+ }
1625
+ var matches = callback(parent);
1626
+ if (matches) {
1627
+ return parent;
1628
+ }
1629
+ } while ((parent = parent.parentElement));
1630
+ return null;
1631
+ };
1632
+ Builder.prototype.findBuilderParent = function (target) {
1633
+ return this.findParentElement(target, function (el) {
1634
+ var id = el.getAttribute('builder-id') || el.id;
1635
+ return Boolean(id && id.indexOf('builder-') === 0);
1636
+ });
1637
+ };
1638
+ Builder.prototype.setUserAgent = function (userAgent) {
1639
+ this.userAgent = userAgent || '';
1640
+ };
1641
+ /**
1642
+ * Set a hook to modify events being tracked from builder, such as impressions and clicks
1643
+ *
1644
+ * For example, to track the model ID of each event associated with content for querying
1645
+ * by mode, you can do
1646
+ *
1647
+ * builder.setTrackingHook((event, context) => {
1648
+ * if (context.content) {
1649
+ * event.data.metadata.modelId = context.content.modelId
1650
+ * }
1651
+ * })
1652
+ */
1653
+ Builder.prototype.setTrackingHook = function (hook) {
1654
+ this.trackingHooks.push(hook);
1655
+ };
1656
+ Builder.prototype.track = function (eventName, properties, context) {
1657
+ if (properties === void 0) { properties = {}; }
1658
+ // TODO: queue up track requests and fire them off when canTrack set to true - otherwise may get lots of clicks with no impressions
1659
+ if (isIframe || !isBrowser || Builder.isPreviewing) {
1660
+ return;
1661
+ }
1662
+ var apiKey = this.apiKey;
1663
+ if (!apiKey) {
1664
+ console.error('Builder integration error: Looks like the Builder SDK has not been initialized properly (your API key has not been set). Make sure you are calling `builder.init("«YOUR-API-KEY»");` as early as possible in your application\'s code.');
1665
+ return;
1666
+ }
1667
+ var eventData = JSON.parse(JSON.stringify({
1668
+ type: eventName,
1669
+ data: __assign(__assign({}, omit(properties, 'meta')), { metadata: __assign(__assign({ sdkVersion: Builder.VERSION, url: location.href }, properties.meta), properties.metadata), ownerId: apiKey, userAttributes: this.getUserAttributes(), sessionId: this.sessionId, visitorId: this.visitorId }),
1670
+ }));
1671
+ for (var _i = 0, _a = this.trackingHooks; _i < _a.length; _i++) {
1672
+ var hook = _a[_i];
1673
+ var returnValue = hook(eventData, context || {});
1674
+ if (returnValue) {
1675
+ eventData = returnValue;
1676
+ }
1677
+ }
1678
+ // batch events
1679
+ this.eventsQueue.push(eventData);
1680
+ if (this.canTrack) {
1681
+ this.throttledClearEventsQueue();
1682
+ }
1683
+ };
1684
+ Builder.prototype.getSessionId = function () {
1685
+ var _this = this;
1686
+ var sessionId = null;
1687
+ try {
1688
+ if (Builder.isBrowser && typeof sessionStorage !== 'undefined') {
1689
+ sessionId = this.getCookie(sessionStorageKey);
1690
+ }
1691
+ }
1692
+ catch (err) {
1693
+ console.debug('Session storage error', err);
1694
+ // It's ok
1695
+ }
1696
+ if (!sessionId) {
1697
+ sessionId = uuid();
1698
+ }
1699
+ // Give the app a second to start up and set canTrack to false if needed
1700
+ if (Builder.isBrowser) {
1701
+ setTimeout(function () {
1702
+ try {
1703
+ if (_this.canTrack) {
1704
+ _this.setCookie(sessionStorageKey, sessionId, datePlusMinutes(30));
1705
+ }
1706
+ }
1707
+ catch (err) {
1708
+ console.debug('Cookie setting error', err);
1709
+ }
1710
+ });
1711
+ }
1712
+ return sessionId;
1713
+ };
1714
+ Builder.prototype.getVisitorId = function () {
1715
+ var _this = this;
1716
+ if (this.visitorId) {
1717
+ return this.visitorId;
1718
+ }
1719
+ var visitorId = null;
1720
+ try {
1721
+ if (Builder.isBrowser && typeof localStorage !== 'undefined') {
1722
+ // TODO: cookie instead?
1723
+ visitorId = localStorage.getItem(localStorageKey);
1724
+ }
1725
+ }
1726
+ catch (err) {
1727
+ console.debug('Local storage error', err);
1728
+ // It's ok
1729
+ }
1730
+ if (!visitorId) {
1731
+ visitorId = uuid();
1732
+ }
1733
+ this.visitorId = visitorId;
1734
+ // Give the app a second to start up and set canTrack to false if needed
1735
+ if (Builder.isBrowser) {
1736
+ setTimeout(function () {
1737
+ try {
1738
+ if (_this.canTrack && typeof localStorage !== 'undefined' && visitorId) {
1739
+ localStorage.setItem(localStorageKey, visitorId);
1740
+ }
1741
+ }
1742
+ catch (err) {
1743
+ console.debug('Session storage error', err);
1744
+ }
1745
+ });
1746
+ }
1747
+ return visitorId;
1748
+ };
1749
+ Builder.prototype.trackImpression = function (contentId, variationId, properties, context) {
1750
+ if (isIframe || !isBrowser || Builder.isPreviewing) {
1751
+ return;
1752
+ }
1753
+ // TODO: use this.track method
1754
+ this.track('impression', {
1755
+ contentId: contentId,
1756
+ variationId: variationId !== contentId ? variationId : undefined,
1757
+ metadata: properties,
1758
+ }, context);
1759
+ };
1760
+ Builder.prototype.trackConversion = function (amount, contentId, variationId, customProperties, context) {
1761
+ if (isIframe || !isBrowser || Builder.isPreviewing) {
1762
+ return;
1763
+ }
1764
+ var meta = typeof contentId === 'object' ? contentId : customProperties;
1765
+ var useContentId = typeof contentId === 'string' ? contentId : undefined;
1766
+ this.track('conversion', { amount: amount, variationId: variationId, meta: meta, contentId: useContentId }, context);
1767
+ };
1768
+ Object.defineProperty(Builder.prototype, "isDevelopmentEnv", {
1769
+ // TODO: set this for QA
1770
+ get: function () {
1771
+ // Automatic determining of development environment
1772
+ return (Builder.isIframe ||
1773
+ (Builder.isBrowser && (location.hostname === 'localhost' || location.port !== '')) ||
1774
+ this.env !== 'production');
1775
+ },
1776
+ enumerable: false,
1777
+ configurable: true
1778
+ });
1779
+ Builder.prototype.trackInteraction = function (contentId, variationId, alreadyTrackedOne, event, context) {
1780
+ if (alreadyTrackedOne === void 0) { alreadyTrackedOne = false; }
1781
+ if (isIframe || !isBrowser || Builder.isPreviewing) {
1782
+ return;
1783
+ }
1784
+ var target = event && event.target;
1785
+ var targetBuilderElement = target && this.findBuilderParent(target);
1786
+ function round(num) {
1787
+ return Math.round(num * 1000) / 1000;
1788
+ }
1789
+ var metadata = {};
1790
+ if (event) {
1791
+ var clientX = event.clientX, clientY = event.clientY;
1792
+ if (target) {
1793
+ var targetRect = target.getBoundingClientRect();
1794
+ var xOffset = clientX - targetRect.left;
1795
+ var yOffset = clientY - targetRect.top;
1796
+ var xRatio = round(xOffset / targetRect.width);
1797
+ var yRatio = round(yOffset / targetRect.height);
1798
+ metadata.targetOffset = {
1799
+ x: xRatio,
1800
+ y: yRatio,
1801
+ };
1802
+ }
1803
+ if (targetBuilderElement) {
1804
+ var targetRect = targetBuilderElement.getBoundingClientRect();
1805
+ var xOffset = clientX - targetRect.left;
1806
+ var yOffset = clientY - targetRect.top;
1807
+ var xRatio = round(xOffset / targetRect.width);
1808
+ var yRatio = round(yOffset / targetRect.height);
1809
+ metadata.builderTargetOffset = {
1810
+ x: xRatio,
1811
+ y: yRatio,
1812
+ };
1813
+ }
1814
+ }
1815
+ var builderId = targetBuilderElement &&
1816
+ (targetBuilderElement.getAttribute('builder-id') || targetBuilderElement.id);
1817
+ if (builderId && targetBuilderElement) {
1818
+ metadata.builderElementIndex = [].slice
1819
+ .call(document.getElementsByClassName(builderId))
1820
+ .indexOf(targetBuilderElement);
1821
+ }
1822
+ this.track('click', {
1823
+ contentId: contentId,
1824
+ metadata: metadata,
1825
+ variationId: variationId !== contentId ? variationId : undefined,
1826
+ unique: !alreadyTrackedOne,
1827
+ targetBuilderElement: builderId || undefined,
1828
+ }, context);
1829
+ };
1830
+ Builder.prototype.component = function (info) {
1831
+ if (info === void 0) { info = {}; }
1832
+ return Builder.component(info);
1833
+ };
1834
+ Object.defineProperty(Builder.prototype, "apiKey", {
1835
+ get: function () {
1836
+ return this.apiKey$.value;
1837
+ },
1838
+ set: function (key) {
1839
+ this.apiKey$.next(key);
1840
+ },
1841
+ enumerable: false,
1842
+ configurable: true
1843
+ });
1844
+ Object.defineProperty(Builder.prototype, "authToken", {
1845
+ get: function () {
1846
+ return this.authToken$.value;
1847
+ },
1848
+ set: function (token) {
1849
+ this.authToken$.next(token);
1850
+ },
1851
+ enumerable: false,
1852
+ configurable: true
1853
+ });
1854
+ Builder.prototype.modifySearch = function (search) {
1855
+ return search.replace(/(^|&|\?)(builder_.*?)=/gi, function (_match, group1, group2) { return group1 + group2.replace(/_/g, '.') + '='; });
1856
+ };
1857
+ Builder.prototype.setTestsFromUrl = function () {
1858
+ var search = this.getLocation().search;
1859
+ var params = QueryString.parseDeep(this.modifySearch(search || '').substr(1));
1860
+ var tests = params.builder && params.builder.tests;
1861
+ if (tests && typeof tests === 'object') {
1862
+ for (var key in tests) {
1863
+ if (tests.hasOwnProperty(key)) {
1864
+ this.setTestCookie(key, tests[key]);
1865
+ }
1866
+ }
1867
+ }
1868
+ };
1869
+ Builder.prototype.resetOverrides = function () {
1870
+ // Ugly - pass down instances per request instead using react context
1871
+ // or use builder.get('foo', { req, res }) in react...........
1872
+ Builder.overrideUserAttributes = {};
1873
+ this.cachebust = false;
1874
+ this.noCache = false;
1875
+ this.preview = false;
1876
+ this.editingModel = null;
1877
+ this.overrides = {};
1878
+ this.env = 'production';
1879
+ this.userAgent = '';
1880
+ this.request = undefined;
1881
+ this.response = undefined;
1882
+ };
1883
+ Builder.prototype.getOverridesFromQueryString = function () {
1884
+ var location = this.getLocation();
1885
+ var params = QueryString.parseDeep(this.modifySearch(location.search || '').substr(1));
1886
+ var builder = params.builder;
1887
+ if (builder) {
1888
+ var userAttributes = builder.userAttributes, overrides = builder.overrides, env = builder.env; builder.host; var api = builder.api, cachebust = builder.cachebust, noCache = builder.noCache, preview = builder.preview, editing = builder.editing, frameEditing = builder.frameEditing, options = builder.options, overrideParams = builder.params;
1889
+ if (userAttributes) {
1890
+ this.setUserAttributes(userAttributes);
1891
+ }
1892
+ if (options) {
1893
+ // picking only locale, includeRefs, and enrich for now
1894
+ this.queryOptions = __assign(__assign(__assign({}, (options.locale && { locale: options.locale })), (options.includeRefs && { includeRefs: options.includeRefs })), (options.enrich && { enrich: options.enrich }));
1895
+ }
1896
+ if (overrides) {
1897
+ this.overrides = overrides;
1898
+ }
1899
+ if (validEnvList.indexOf(env || api) > -1) {
1900
+ this.env = env || api;
1901
+ }
1902
+ if (Builder.isEditing) {
1903
+ var editingModel = frameEditing || editing || preview;
1904
+ if (editingModel && editingModel !== 'true') {
1905
+ this.editingModel = editingModel;
1906
+ }
1907
+ }
1908
+ if (cachebust) {
1909
+ this.cachebust = true;
1910
+ }
1911
+ if (noCache) {
1912
+ this.noCache = true;
1913
+ }
1914
+ if (preview) {
1915
+ this.preview = true;
1916
+ }
1917
+ if (params) {
1918
+ this.overrideParams = overrideParams;
1919
+ }
1920
+ }
1921
+ };
1922
+ Builder.prototype.messageFrameLoaded = function () {
1923
+ var _a;
1924
+ (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({
1925
+ type: 'builder.loaded',
1926
+ data: {
1927
+ value: true,
1928
+ },
1929
+ }, '*');
1930
+ };
1931
+ Builder.prototype.bindMessageListeners = function () {
1932
+ var _this = this;
1933
+ if (isBrowser) {
1934
+ addEventListener('message', function (event) {
1935
+ var _a, _b, _c, _d, _e;
1936
+ var url = parse(event.origin);
1937
+ var isRestricted = ['builder.register', 'builder.registerComponent'].indexOf((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === -1;
1938
+ var isTrusted = url.hostname && Builder.isTrustedHost(url.hostname);
1939
+ if (isRestricted && !isTrusted) {
1940
+ return;
1941
+ }
1942
+ var data = event.data;
1943
+ if (data) {
1944
+ switch (data.type) {
1945
+ case 'builder.ping': {
1946
+ (_b = window.parent) === null || _b === void 0 ? void 0 : _b.postMessage({
1947
+ type: 'builder.pong',
1948
+ data: {},
1949
+ }, '*');
1950
+ break;
1951
+ }
1952
+ case 'builder.register': {
1953
+ // TODO: possibly do this for all...
1954
+ if (event.source === window) {
1955
+ break;
1956
+ }
1957
+ var options = data.data;
1958
+ if (!options) {
1959
+ break;
1960
+ }
1961
+ var type = options.type, info = options.info;
1962
+ // TODO: all must have name and can't conflict?
1963
+ var typeList = Builder.registry[type];
1964
+ if (!typeList) {
1965
+ typeList = Builder.registry[type] = [];
1966
+ }
1967
+ typeList.push(info);
1968
+ Builder.registryChange.next(Builder.registry);
1969
+ break;
1970
+ }
1971
+ case 'builder.settingsChange': {
1972
+ // TODO: possibly do this for all...
1973
+ if (event.source === window) {
1974
+ break;
1975
+ }
1976
+ var settings = data.data;
1977
+ if (!settings) {
1978
+ break;
1979
+ }
1980
+ Object.assign(Builder.settings, settings);
1981
+ Builder.settingsChange.next(Builder.settings);
1982
+ break;
1983
+ }
1984
+ case 'builder.registerEditor': {
1985
+ // TODO: possibly do this for all...
1986
+ if (event.source === window) {
1987
+ break;
1988
+ }
1989
+ var info_1 = data.data;
1990
+ if (!info_1) {
1991
+ break;
1992
+ }
1993
+ var hasComponent_1 = !!info_1.component;
1994
+ Builder.editors.every(function (thisInfo, index) {
1995
+ if (info_1.name === thisInfo.name) {
1996
+ if (thisInfo.component && !hasComponent_1) {
1997
+ return false;
1998
+ }
1999
+ else {
2000
+ Builder.editors[index] = thisInfo;
2001
+ }
2002
+ return false;
2003
+ }
2004
+ return true;
2005
+ });
2006
+ break;
2007
+ }
2008
+ case 'builder.triggerAnimation': {
2009
+ Builder.animator.triggerAnimation(data.data);
2010
+ break;
2011
+ }
2012
+ case 'builder.contentUpdate':
2013
+ var key = data.data.key || data.data.alias || data.data.entry || data.data.modelName;
2014
+ var contentData = data.data.data; // hmmm...
2015
+ var observer = _this.observersByKey[key];
2016
+ if (observer && !_this.noEditorUpdates[key]) {
2017
+ observer.next([contentData]);
2018
+ }
2019
+ break;
2020
+ case 'builder.getComponents':
2021
+ (_c = window.parent) === null || _c === void 0 ? void 0 : _c.postMessage({
2022
+ type: 'builder.components',
2023
+ data: Builder.components.map(function (item) { return Builder.prepareComponentSpecToSend(item); }),
2024
+ }, '*');
2025
+ break;
2026
+ case 'builder.editingModel':
2027
+ _this.editingModel = data.data.model;
2028
+ break;
2029
+ case 'builder.registerComponent':
2030
+ var componentData = data.data;
2031
+ Builder.addComponent(componentData);
2032
+ break;
2033
+ case 'builder.blockContentLoading':
2034
+ if (typeof data.data.model === 'string') {
2035
+ _this.blockContentLoading = data.data.model;
2036
+ }
2037
+ break;
2038
+ case 'builder.editingMode':
2039
+ var editingMode = data.data;
2040
+ if (editingMode) {
2041
+ _this.editingMode = true;
2042
+ document.body.classList.add('builder-editing');
2043
+ }
2044
+ else {
2045
+ _this.editingMode = false;
2046
+ document.body.classList.remove('builder-editing');
2047
+ }
2048
+ break;
2049
+ case 'builder.editingPageMode':
2050
+ var editingPageMode = data.data;
2051
+ Builder.editingPage = editingPageMode;
2052
+ break;
2053
+ case 'builder.overrideUserAttributes':
2054
+ var userAttributes = data.data;
2055
+ assign(Builder.overrideUserAttributes, userAttributes);
2056
+ _this.flushGetContentQueue(true);
2057
+ // TODO: refetch too
2058
+ break;
2059
+ case 'builder.overrideTestGroup':
2060
+ var _f = data.data, variationId = _f.variationId, contentId = _f.contentId;
2061
+ if (variationId && contentId) {
2062
+ _this.setTestCookie(contentId, variationId);
2063
+ _this.flushGetContentQueue(true);
2064
+ }
2065
+ break;
2066
+ case 'builder.evaluate': {
2067
+ var text = data.data.text;
2068
+ var args = data.data.arguments || [];
2069
+ var id_1 = data.data.id;
2070
+ // tslint:disable-next-line:no-function-constructor-with-string-args
2071
+ var fn = new Function(text);
2072
+ var result = void 0;
2073
+ var error = null;
2074
+ try {
2075
+ result = fn.apply(_this, args);
2076
+ }
2077
+ catch (err) {
2078
+ error = toError(err);
2079
+ }
2080
+ if (error) {
2081
+ (_d = window.parent) === null || _d === void 0 ? void 0 : _d.postMessage({
2082
+ type: 'builder.evaluateError',
2083
+ data: { id: id_1, error: error.message },
2084
+ }, '*');
2085
+ }
2086
+ else {
2087
+ if (result && typeof result.then === 'function') {
2088
+ result
2089
+ .then(function (finalResult) {
2090
+ var _a;
2091
+ (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({
2092
+ type: 'builder.evaluateResult',
2093
+ data: { id: id_1, result: finalResult },
2094
+ }, '*');
2095
+ })
2096
+ .catch(console.error);
2097
+ }
2098
+ else {
2099
+ (_e = window.parent) === null || _e === void 0 ? void 0 : _e.postMessage({
2100
+ type: 'builder.evaluateResult',
2101
+ data: { result: result, id: id_1 },
2102
+ }, '*');
2103
+ }
2104
+ }
2105
+ break;
2106
+ }
2107
+ }
2108
+ }
2109
+ });
2110
+ }
2111
+ };
2112
+ Object.defineProperty(Builder.prototype, "defaultCanTrack", {
2113
+ get: function () {
2114
+ return Boolean(Builder.isBrowser &&
2115
+ navigator.userAgent.trim() &&
2116
+ !navigator.userAgent.match(/bot|crawler|spider|robot|crawling|prerender|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|phantom|headless|selenium|puppeteer/i) &&
2117
+ !this.browserTrackingDisabled);
2118
+ },
2119
+ enumerable: false,
2120
+ configurable: true
2121
+ });
2122
+ Builder.prototype.init = function (apiKey, canTrack, req, res, authToken, apiVersion) {
2123
+ if (canTrack === void 0) { canTrack = this.defaultCanTrack; }
2124
+ if (req) {
2125
+ this.request = req;
2126
+ }
2127
+ if (res) {
2128
+ this.response = res;
2129
+ }
2130
+ this.canTrack = canTrack;
2131
+ this.apiKey = apiKey;
2132
+ if (authToken) {
2133
+ this.authToken = authToken;
2134
+ }
2135
+ if (apiVersion) {
2136
+ this.apiVersion = apiVersion;
2137
+ }
2138
+ return this;
2139
+ };
2140
+ Object.defineProperty(Builder.prototype, "previewingModel", {
2141
+ get: function () {
2142
+ var search = this.getLocation().search;
2143
+ var params = QueryString.parse((search || '').substr(1));
2144
+ return params['builder.preview'];
2145
+ },
2146
+ enumerable: false,
2147
+ configurable: true
2148
+ });
2149
+ // TODO: allow adding location object as property and/or in constructor
2150
+ Builder.prototype.getLocation = function () {
2151
+ var _a;
2152
+ var parsedLocation = {};
2153
+ // in ssr mode
2154
+ if (this.request) {
2155
+ parsedLocation = parse((_a = this.request.url) !== null && _a !== void 0 ? _a : '');
2156
+ }
2157
+ else if (typeof location === 'object') {
2158
+ // in the browser
2159
+ parsedLocation = parse(location.href);
2160
+ }
2161
+ // IE11 bug with parsed path being empty string
2162
+ // causes issues with our user targeting
2163
+ if (parsedLocation.pathname === '') {
2164
+ parsedLocation.pathname = '/';
2165
+ }
2166
+ return parsedLocation;
2167
+ };
2168
+ Builder.prototype.getUserAttributes = function (userAgent) {
2169
+ if (userAgent === void 0) { userAgent = this.userAgent || ''; }
2170
+ var isMobile = {
2171
+ Android: function () {
2172
+ return userAgent.match(/Android/i);
2173
+ },
2174
+ BlackBerry: function () {
2175
+ return userAgent.match(/BlackBerry/i);
2176
+ },
2177
+ iOS: function () {
2178
+ return userAgent.match(/iPhone|iPod/i);
2179
+ },
2180
+ Opera: function () {
2181
+ return userAgent.match(/Opera Mini/i);
2182
+ },
2183
+ Windows: function () {
2184
+ return userAgent.match(/IEMobile/i) || userAgent.match(/WPDesktop/i);
2185
+ },
2186
+ any: function () {
2187
+ return (isMobile.Android() ||
2188
+ isMobile.BlackBerry() ||
2189
+ isMobile.iOS() ||
2190
+ isMobile.Opera() ||
2191
+ isMobile.Windows());
2192
+ },
2193
+ };
2194
+ var isTablet = userAgent.match(/Tablet|iPad/i);
2195
+ var url = this.getLocation();
2196
+ return __assign({ urlPath: url.pathname, host: url.host || url.hostname,
2197
+ // TODO: maybe an option to choose to target off of mobile/tablet/desktop or just mobile/desktop
2198
+ device: isTablet ? 'tablet' : isMobile.any() ? 'mobile' : 'desktop' }, Builder.overrideUserAttributes);
2199
+ };
2200
+ Builder.prototype.setUserAttributes = function (options) {
2201
+ assign(Builder.overrideUserAttributes, options);
2202
+ this.userAttributesChanged.next(options);
2203
+ };
2204
+ /**
2205
+ * Set user attributes just for tracking purposes.
2206
+ *
2207
+ * Do this so properties exist on event objects for querying insights, but
2208
+ * won't affect targeting
2209
+ *
2210
+ * Use this when you want to track properties but don't need to target off
2211
+ * of them to optimize cache efficiency
2212
+ */
2213
+ Builder.prototype.setTrackingUserAttributes = function (attributes) {
2214
+ assign(this.trackingUserAttributes, attributes);
2215
+ };
2216
+ Builder.prototype.get = function (modelName, options) {
2217
+ if (options === void 0) { options = {}; }
2218
+ var instance = this;
2219
+ if (!Builder.isBrowser) {
2220
+ instance = new Builder(options.apiKey || this.apiKey, options.req, options.res, undefined, options.authToken || this.authToken, options.apiVersion || this.apiVersion);
2221
+ instance.setUserAttributes(this.getUserAttributes());
2222
+ }
2223
+ else {
2224
+ // NOTE: All these are when .init is not called and the customer
2225
+ // directly calls .get on the singleton instance of Builder
2226
+ if (options.apiKey && !this.apiKey) {
2227
+ this.apiKey = options.apiKey;
2228
+ }
2229
+ if (options.authToken && !this.authToken) {
2230
+ this.authToken = options.authToken;
2231
+ }
2232
+ if (options.apiVersion && !this.apiVersion) {
2233
+ this.apiVersion = options.apiVersion;
2234
+ }
2235
+ }
2236
+ return instance.queueGetContent(modelName, options).map(
2237
+ /* map( */ function (matches) {
2238
+ var match = matches && matches[0];
2239
+ if (Builder.isStatic) {
2240
+ return match;
2241
+ }
2242
+ var matchData = match && match.data;
2243
+ if (!matchData) {
2244
+ return null;
2245
+ }
2246
+ if (typeof matchData.blocksString !== 'undefined') {
2247
+ matchData.blocks = JSON.parse(matchData.blocksString);
2248
+ delete matchData.blocksString;
2249
+ }
2250
+ return {
2251
+ // TODO: add ab test info here and other high level stuff
2252
+ data: matchData,
2253
+ id: match.id,
2254
+ variationId: match.testVariationId || match.variationId || null,
2255
+ testVariationId: match.testVariationId || match.variationId || null,
2256
+ testVariationName: match.testVariationName || null,
2257
+ lastUpdated: match.lastUpdated || null,
2258
+ };
2259
+ });
2260
+ // );
2261
+ };
2262
+ // TODO: entry id in options
2263
+ Builder.prototype.queueGetContent = function (modelName, options) {
2264
+ var _this = this;
2265
+ if (options === void 0) { options = {}; }
2266
+ // TODO: if query do modelName + query
2267
+ var key = options.key ||
2268
+ options.alias ||
2269
+ // TODO: SDKs only pass entry key when given to them, and never when editing...
2270
+ // options.entry ||
2271
+ // TODO: this is ugly - instead of multiple of same model with different options are sent
2272
+ // say requires key/alias. Or if not perhaps make a reliable hash of the options and use that.
2273
+ // TODO: store last user state on last request and if user attributes different now
2274
+ // give a warning that need to use keys to request new contente
2275
+ // (options &&
2276
+ // Object.keys(options).filter(key => key !== 'model').length &&
2277
+ // JSON.stringify({ model: modelName, ...options, initialContent: undefined })) ||
2278
+ modelName;
2279
+ var isEditingThisModel = this.editingModel === modelName;
2280
+ // TODO: include params in this key........
2281
+ var currentObservable = this.observersByKey[key];
2282
+ // if (options.query && options.query._id) {
2283
+ // this.flushGetContentQueue([options])
2284
+ // }
2285
+ if (this.apiKey === 'DEMO' && !this.overrides[key] && !options.initialContent) {
2286
+ options.initialContent = [];
2287
+ }
2288
+ var initialContent = options.initialContent;
2289
+ // TODO: refresh option in options
2290
+ if (currentObservable && (!currentObservable.value || options.cache)) {
2291
+ // TODO: test if this ran, otherwise on 404 some observers may never be called...
2292
+ if (currentObservable.value) {
2293
+ nextTick(function () {
2294
+ // TODO: return a new observable and only that one fires subscribers, don't refire for existing ones
2295
+ currentObservable.next(currentObservable.value);
2296
+ });
2297
+ }
2298
+ return currentObservable;
2299
+ }
2300
+ if (isEditingThisModel) {
2301
+ if (Builder.isBrowser) {
2302
+ parent.postMessage({ type: 'builder.updateContent', data: { options: options } }, '*');
2303
+ }
2304
+ }
2305
+ if (!initialContent /* || isEditingThisModel */) {
2306
+ if (!this.getContentQueue) {
2307
+ this.getContentQueue = [];
2308
+ }
2309
+ this.getContentQueue.push(__assign(__assign({}, options), { model: modelName, key: key }));
2310
+ if (this.getContentQueue && this.getContentQueue.length >= this.contentPerRequest) {
2311
+ var queue_1 = this.getContentQueue.slice();
2312
+ this.getContentQueue = [];
2313
+ nextTick(function () {
2314
+ _this.flushGetContentQueue(false, queue_1);
2315
+ });
2316
+ }
2317
+ else {
2318
+ nextTick(function () {
2319
+ _this.flushGetContentQueue();
2320
+ });
2321
+ }
2322
+ }
2323
+ var observable = new BehaviorSubject(null);
2324
+ this.observersByKey[key] = observable;
2325
+ if (options.noEditorUpdates) {
2326
+ this.noEditorUpdates[key] = true;
2327
+ }
2328
+ if (initialContent) {
2329
+ nextTick(function () {
2330
+ // TODO: need to testModify this I think...?
2331
+ observable.next(initialContent);
2332
+ });
2333
+ }
2334
+ return observable;
2335
+ };
2336
+ // this is needed to satisfy the Angular SDK, which used to rely on the more complex version of `requestUrl`.
2337
+ // even though we only use `fetch()` now, we prefer to keep the old behavior and use the `fetch` that comes from
2338
+ // the core SDK for consistency
2339
+ Builder.prototype.requestUrl = function (url, options) {
2340
+ return getFetch()(url, __assign({ next: __assign({ revalidate: 1 }, options === null || options === void 0 ? void 0 : options.next) }, options)).then(function (res) { return res.json(); });
2341
+ };
2342
+ Object.defineProperty(Builder.prototype, "host", {
2343
+ get: function () {
2344
+ switch (this.env) {
2345
+ case 'qa':
2346
+ return 'https://qa.builder.io';
2347
+ case 'test':
2348
+ return 'https://builder-io-test.web.app';
2349
+ case 'fast':
2350
+ return 'https://fast.builder.io';
2351
+ case 'cloud':
2352
+ return 'https://cloud.builder.io';
2353
+ case 'cdn2':
2354
+ return 'https://cdn2.builder.io';
2355
+ case 'cdn-qa':
2356
+ return 'https://cdn-qa.builder.io';
2357
+ case 'development':
2358
+ case 'dev':
2359
+ return 'http://localhost:5000';
2360
+ case 'cdn-prod':
2361
+ return 'https://cdn.builder.io';
2362
+ default:
2363
+ return Builder.overrideHost || 'https://cdn.builder.io';
2364
+ }
2365
+ },
2366
+ enumerable: false,
2367
+ configurable: true
2368
+ });
2369
+ Builder.prototype.flushGetContentQueue = function (usePastQueue, useQueue) {
2370
+ var _this = this;
2371
+ if (usePastQueue === void 0) { usePastQueue = false; }
2372
+ if (!this.apiKey) {
2373
+ throw new Error("Fetching content failed, expected apiKey to be defined instead got: ".concat(this.apiKey));
2374
+ }
2375
+ if (this.apiVersion) {
2376
+ if (!['v1', 'v3'].includes(this.apiVersion)) {
2377
+ throw new Error("Invalid apiVersion: expected 'v1' or 'v3', received '".concat(this.apiVersion, "'"));
2378
+ }
2379
+ }
2380
+ else {
2381
+ this.apiVersion = DEFAULT_API_VERSION;
2382
+ }
2383
+ if (!usePastQueue && !this.getContentQueue) {
2384
+ return;
2385
+ }
2386
+ var queue = useQueue || (usePastQueue ? this.priorContentQueue : this.getContentQueue) || [];
2387
+ // TODO: do this on every request send?
2388
+ this.getOverridesFromQueryString();
2389
+ var queryParams = __assign(__assign({
2390
+ // TODO: way to force a request to be in a separate queue. or just lower queue limit to be 1 by default
2391
+ omit: queue[0].omit || 'meta.componentsUsed', apiKey: this.apiKey }, queue[0].options), this.queryOptions);
2392
+ if (queue[0].locale) {
2393
+ queryParams.locale = queue[0].locale;
2394
+ }
2395
+ if (queue[0].fields) {
2396
+ queryParams.fields = queue[0].fields;
2397
+ }
2398
+ if (queue[0].format) {
2399
+ queryParams.format = queue[0].format;
2400
+ }
2401
+ var pageQueryParams = typeof location !== 'undefined'
2402
+ ? QueryString.parseDeep(location.search.substr(1))
2403
+ : {};
2404
+ var userAttributes =
2405
+ // FIXME: HACK: only checks first in queue for user attributes overrides, should check all
2406
+ // TODO: merge user attributes provided here with defaults and current user attiributes (?)
2407
+ queue && queue[0].userAttributes
2408
+ ? queue[0].userAttributes
2409
+ : this.targetContent
2410
+ ? this.getUserAttributes()
2411
+ : {
2412
+ urlPath: this.getLocation().pathname,
2413
+ };
2414
+ var fullUrlQueueItem = queue.find(function (item) { return !!item.includeUrl; });
2415
+ if (fullUrlQueueItem) {
2416
+ var location_1 = this.getLocation();
2417
+ if (location_1.origin) {
2418
+ queryParams.url = "".concat(location_1.origin).concat(location_1.pathname).concat(location_1.search);
2419
+ }
2420
+ }
2421
+ var urlQueueItem = useQueue === null || useQueue === void 0 ? void 0 : useQueue.find(function (item) { return item.url; });
2422
+ if (urlQueueItem === null || urlQueueItem === void 0 ? void 0 : urlQueueItem.url) {
2423
+ userAttributes.urlPath = urlQueueItem.url.split('?')[0];
2424
+ }
2425
+ // TODO: merge in the attribute from query string ones
2426
+ // TODO: make this an option per component/request
2427
+ queryParams.userAttributes = userAttributes;
2428
+ if (!usePastQueue && !useQueue) {
2429
+ this.priorContentQueue = queue;
2430
+ this.getContentQueue = null;
2431
+ }
2432
+ var cachebust = this.cachebust ||
2433
+ isIframe ||
2434
+ pageQueryParams.cachebust ||
2435
+ pageQueryParams['builder.cachebust'];
2436
+ if (cachebust || this.env !== 'production') {
2437
+ queryParams.cachebust = true;
2438
+ }
2439
+ if (Builder.isEditing) {
2440
+ queryParams.isEditing = true;
2441
+ }
2442
+ if (this.noCache || this.env !== 'production') {
2443
+ queryParams.noCache = true;
2444
+ }
2445
+ if (size(this.overrides)) {
2446
+ for (var key in this.overrides) {
2447
+ if (this.overrides.hasOwnProperty(key)) {
2448
+ queryParams["overrides.".concat(key)] = this.overrides[key];
2449
+ }
2450
+ }
2451
+ }
2452
+ for (var _i = 0, queue_2 = queue; _i < queue_2.length; _i++) {
2453
+ var options = queue_2[_i];
2454
+ if (options.format) {
2455
+ queryParams.format = options.format;
2456
+ }
2457
+ // TODO: remove me and make permodel
2458
+ if (options.static) {
2459
+ queryParams.static = options.static;
2460
+ }
2461
+ if (options.cachebust) {
2462
+ queryParams.cachebust = options.cachebust;
2463
+ }
2464
+ if (isPositiveNumber(options.cacheSeconds)) {
2465
+ queryParams.cacheSeconds = options.cacheSeconds;
2466
+ }
2467
+ if (isPositiveNumber(options.staleCacheSeconds)) {
2468
+ queryParams.staleCacheSeconds = options.staleCacheSeconds;
2469
+ }
2470
+ var properties = [
2471
+ 'prerender',
2472
+ 'extractCss',
2473
+ 'limit',
2474
+ 'offset',
2475
+ 'query',
2476
+ 'preview',
2477
+ 'model',
2478
+ 'entry',
2479
+ 'rev',
2480
+ 'static',
2481
+ ];
2482
+ for (var _a = 0, properties_1 = properties; _a < properties_1.length; _a++) {
2483
+ var key = properties_1[_a];
2484
+ var value = options[key];
2485
+ if (value !== undefined) {
2486
+ queryParams.options = queryParams.options || {};
2487
+ queryParams.options[options.key] = queryParams.options[options.key] || {};
2488
+ queryParams.options[options.key][key] = JSON.stringify(value);
2489
+ }
2490
+ }
2491
+ }
2492
+ if (this.preview) {
2493
+ queryParams.preview = 'true';
2494
+ }
2495
+ var hasParams = Object.keys(queryParams).length > 0;
2496
+ // TODO: option to force dev or qa api here
2497
+ var host = this.host;
2498
+ var keyNames = queue.map(function (item) { return encodeURIComponent(item.key); }).join(',');
2499
+ if (this.overrideParams) {
2500
+ var params = omit(QueryString.parse(this.overrideParams), 'apiKey');
2501
+ assign(queryParams, params);
2502
+ }
2503
+ var queryStr = QueryString.stringifyDeep(queryParams);
2504
+ var format = queryParams.format;
2505
+ var requestOptions = { headers: {}, next: { revalidate: 1 } };
2506
+ if (this.authToken) {
2507
+ requestOptions.headers = __assign(__assign({}, requestOptions.headers), { Authorization: "Bearer ".concat(this.authToken) });
2508
+ }
2509
+ var fn = format === 'solid' || format === 'react' ? 'codegen' : 'query';
2510
+ // NOTE: this is a hack to get around the fact that the codegen endpoint is not yet available in v3
2511
+ var apiVersionBasedOnFn = fn === 'query' ? this.apiVersion : 'v1';
2512
+ var url = "".concat(host, "/api/").concat(apiVersionBasedOnFn, "/").concat(fn, "/").concat(this.apiKey, "/").concat(keyNames) +
2513
+ (queryParams && hasParams ? "?".concat(queryStr) : '');
2514
+ var promise = getFetch()(url, requestOptions)
2515
+ .then(function (res) { return res.json(); })
2516
+ .then(function (result) {
2517
+ for (var _i = 0, queue_3 = queue; _i < queue_3.length; _i++) {
2518
+ var options = queue_3[_i];
2519
+ var keyName = options.key;
2520
+ if (options.model === _this.blockContentLoading && !options.noEditorUpdates) {
2521
+ continue;
2522
+ }
2523
+ var isEditingThisModel = _this.editingModel === options.model;
2524
+ if (isEditingThisModel && Builder.isEditing) {
2525
+ parent.postMessage({ type: 'builder.updateContent', data: { options: options } }, '*');
2526
+ // return;
2527
+ }
2528
+ var observer = _this.observersByKey[keyName];
2529
+ if (!observer) {
2530
+ return;
2531
+ }
2532
+ var data = result[keyName];
2533
+ var sorted = data; // sortBy(data, item => item.priority);
2534
+ if (data) {
2535
+ var testModifiedResults = Builder.isServer
2536
+ ? sorted
2537
+ : _this.processResultsForTests(sorted);
2538
+ observer.next(testModifiedResults);
2539
+ }
2540
+ else {
2541
+ var search = _this.getLocation().search;
2542
+ if ((search || '').includes('builder.preview=' + options.model)) {
2543
+ var previewData = {
2544
+ id: 'preview',
2545
+ name: 'Preview',
2546
+ data: {},
2547
+ };
2548
+ observer.next([previewData]);
2549
+ }
2550
+ observer.next([]);
2551
+ }
2552
+ }
2553
+ }, function (err) {
2554
+ for (var _i = 0, queue_4 = queue; _i < queue_4.length; _i++) {
2555
+ var options = queue_4[_i];
2556
+ var observer = _this.observersByKey[options.key];
2557
+ if (!observer) {
2558
+ return;
2559
+ }
2560
+ observer.error(err);
2561
+ }
2562
+ });
2563
+ return promise;
2564
+ };
2565
+ Builder.prototype.processResultsForTests = function (results) {
2566
+ var _this = this;
2567
+ var _a;
2568
+ var mappedResults = results.map(function (item) {
2569
+ if (!item.variations) {
2570
+ return item;
2571
+ }
2572
+ var cookieValue = _this.getTestCookie(item.id);
2573
+ var cookieVariation = cookieValue === item.id ? item : item.variations[cookieValue];
2574
+ if (cookieVariation) {
2575
+ return __assign(__assign({}, item), { data: cookieVariation.data, variationId: cookieValue, testVariationId: cookieValue, testVariationName: cookieVariation.name });
2576
+ }
2577
+ if (_this.canTrack && item.variations && size(item.variations)) {
2578
+ var n = 0;
2579
+ var random = Math.random();
2580
+ for (var id in item.variations) {
2581
+ var variation = item.variations[id];
2582
+ var testRatio = variation.testRatio;
2583
+ n += testRatio;
2584
+ if (random < n) {
2585
+ _this.setTestCookie(item.id, variation.id);
2586
+ var variationName = variation.name || (variation.id === item.id ? 'Default variation' : '');
2587
+ return __assign(__assign({}, item), { data: variation.data, variationId: variation.id, testVariationId: variation.id, variationName: variationName, testVariationName: variationName });
2588
+ }
2589
+ }
2590
+ _this.setTestCookie(item.id, item.id);
2591
+ }
2592
+ return __assign(__assign(__assign({}, item), { variationId: item.id }), (item.variations &&
2593
+ size(item.variations) && {
2594
+ testVariationId: item.id,
2595
+ testVariationName: 'Default variation',
2596
+ }));
2597
+ });
2598
+ if (isIframe) {
2599
+ (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({ type: 'builder.contentResults', data: { results: mappedResults } }, '*');
2600
+ }
2601
+ return mappedResults;
2602
+ };
2603
+ Builder.prototype.getTestCookie = function (contentId) {
2604
+ return this.getCookie("".concat(this.testCookiePrefix, ".").concat(contentId));
2605
+ };
2606
+ Builder.prototype.setTestCookie = function (contentId, variationId) {
2607
+ if (!this.canTrack) {
2608
+ this.cookieQueue.push([contentId, variationId]);
2609
+ return;
2610
+ }
2611
+ // 30 days from now
2612
+ var future = new Date();
2613
+ future.setDate(future.getDate() + 30);
2614
+ return this.setCookie("".concat(this.testCookiePrefix, ".").concat(contentId), variationId, future);
2615
+ };
2616
+ Builder.prototype.getCookie = function (name) {
2617
+ if (this.cookies) {
2618
+ return this.cookies.get(name);
2619
+ }
2620
+ return Builder.isBrowser && getCookie(name);
2621
+ };
2622
+ Builder.prototype.setCookie = function (name, value, expires) {
2623
+ if (this.cookies && !(Builder.isServer && Builder.isStatic)) {
2624
+ return this.cookies.set(name, value, {
2625
+ expires: expires,
2626
+ secure: this.getLocation().protocol === 'https:',
2627
+ });
2628
+ }
2629
+ return Builder.isBrowser && setCookie(name, value, expires);
2630
+ };
2631
+ Builder.prototype.getContent = function (modelName, options) {
2632
+ if (options === void 0) { options = {}; }
2633
+ if (!this.apiKey) {
2634
+ throw new Error("Fetching content from model ".concat(modelName, " failed, expected apiKey to be defined instead got: ").concat(this.apiKey));
2635
+ }
2636
+ return this.queueGetContent(modelName, options);
2637
+ };
2638
+ Builder.prototype.getAll = function (modelName, options) {
2639
+ if (options === void 0) { options = {}; }
2640
+ var instance = this;
2641
+ if (!Builder.isBrowser) {
2642
+ instance = new Builder(options.apiKey || this.apiKey, options.req, options.res, false, null, options.apiVersion || this.apiVersion);
2643
+ instance.setUserAttributes(this.getUserAttributes());
2644
+ }
2645
+ else {
2646
+ // NOTE: All these are when .init is not called and the customer
2647
+ // directly calls .get on the singleton instance of Builder
2648
+ if (options.apiKey && !this.apiKey) {
2649
+ this.apiKey = options.apiKey;
2650
+ }
2651
+ if (options.apiVersion && !this.apiVersion) {
2652
+ this.apiVersion = options.apiVersion;
2653
+ }
2654
+ }
2655
+ return instance
2656
+ .getContent(modelName, __assign(__assign({ limit: 30 }, options), { key: options.key ||
2657
+ // Make the key include all options, so we don't reuse cache for the same content fetched
2658
+ // with different options
2659
+ Builder.isBrowser
2660
+ ? "".concat(modelName, ":").concat(hashSum(omit(options, 'initialContent', 'req', 'res')))
2661
+ : undefined }))
2662
+ .promise();
2663
+ };
2664
+ /**
2665
+ * @hidden
2666
+ * @deprecated. This is buggy, and always behind by a version.
2667
+ */
2668
+ Builder.VERSION = version;
2669
+ Builder.components = [];
2670
+ /**
2671
+ * Makes it so that a/b tests generate code like {@link
2672
+ * https://www.builder.io/blog/high-performance-no-code#__next:~:text=Static%20generated%20A%2FB%20testing}
2673
+ * instead of the old way where we render only one test group at a time on the
2674
+ * server. This is the preferred/better way not and we should ultimately make it
2675
+ * the default
2676
+ */
2677
+ Builder.isStatic = true;
2678
+ Builder.animator = new Animator();
2679
+ Builder.nextTick = nextTick;
2680
+ Builder.throttle = throttle;
2681
+ Builder.editors = [];
2682
+ Builder.trustedHosts = ['builder.io', 'localhost'];
2683
+ Builder.plugins = [];
2684
+ Builder.actions = [];
2685
+ Builder.registry = {};
2686
+ Builder.registryChange = new BehaviorSubject({});
2687
+ Builder._editingPage = false;
2688
+ Builder.isIframe = isIframe;
2689
+ Builder.isBrowser = isBrowser;
2690
+ Builder.isReactNative = isReactNative;
2691
+ Builder.isServer = !isBrowser && !isReactNative;
2692
+ Builder.previewingModel = Builder.isBrowser && getQueryParam(location.href, 'builder.preview');
2693
+ Builder.settings = {};
2694
+ Builder.settingsChange = new BehaviorSubject({});
2695
+ // TODO: this is quick and dirty, do better implementation later. Also can be unreliable
2696
+ // if page 301s etc. Use a query param instead? also could have issues with redirects. Injecting var could
2697
+ // work but is async...
2698
+ Builder.isEditing = Boolean(isIframe &&
2699
+ ((document.referrer && document.referrer.match(/builder\.io|localhost:1234/)) ||
2700
+ location.search.indexOf('builder.frameEditing=') !== -1));
2701
+ Builder.isPreviewing = Boolean(isBrowser &&
2702
+ (location.search.indexOf('builder.preview=') !== -1 ||
2703
+ location.search.indexOf('builder.frameEditing=') !== -1));
2704
+ Builder.isReact = false;
2705
+ Builder.overrideUserAttributes = {};
2706
+ return Builder;
2707
+ }());
2708
+
2709
+ var builder = new Builder(null, undefined, undefined, true);
2710
+ Builder.singletonInstance = builder;
2711
+
2712
+ exports.BehaviorSubject = BehaviorSubject;
2713
+ exports.Builder = Builder;
2714
+ exports.BuilderComponent = BuilderComponent;
2715
+ exports.Subscription = Subscription;
2716
+ exports.builder = builder;
2717
+ exports.isBrowser = isBrowser;
2718
+
2719
+ Object.defineProperty(exports, '__esModule', { value: true });
2720
+
2721
+ }));
2
2722
  //# sourceMappingURL=index.browser.js.map