@callimacus/thamyr-core 4.13.1 → 4.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,13 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [4.13.2](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.13.1...thamyr-core-v4.13.2) (2026-10-28)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **core:** the socket handshake carries the visitor's intent session id, so rounds get session intent on any API host ([#859](https://github.com/callimacus/thamyr-sdk/issues/859)) ([8270ac2](https://github.com/callimacus/thamyr-sdk/commit/8270ac2a90caacc53e7c89698ccc11ca3b5c81f2))
12
+
6
13
  ## [4.13.1](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.13.0...thamyr-core-v4.13.1) (2026-10-27)
7
14
 
8
15
 
package/dist/esm/index.js CHANGED
@@ -5,5 +5,5 @@
5
5
  * See LICENSE.md for the full terms.
6
6
  *
7
7
  */
8
- export*from"@callimacus/intent";import{io as e}from"socket.io-client";const t={ERROR:"error",CHAPTER_EVENT:"chapter-event",CHAPTER_DELETED:"chapter-deleted",STORY_RESET:"story-reset",STORY_CREATED:"story-created",STORY_SHARED:"story-shared",BLOCK_PATCH:"block-patch",CART_COMMAND:"cart-command"},n={ERROR:"error",SYSTEM_MESSAGE:"system-message",SERVER_STATUS:"server-status",SERVER_RESPONSE:"server-response"},r={CLIENT_READY:"client-ready",USER_INTERACTION:"user-interaction"},s={question:"question",content:"content",topic:"topic",tag:"tag",image:"image",video:"video",gallery:"gallery",relatedQuestion:"relatedQuestion",page:"page",customInteraction:"customInteraction",customPage:"customPage"},i={masonry:"masonry",carousel:"carousel"},o={understandingQuery:1,craftingAnswer:2,curatingContent:3,done:4};function a(e){return e.type.startsWith("custom:")}function c(e){return"set"in e.type&&e.type.set}function u(e){return"master"in e.type&&e.type.master}const l={debug:0,info:1,warn:2,error:3,silent:4};const d=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...e)=>{this.log("debug",...e)};info=(...e)=>{this.log("info",...e)};warn=(...e)=>{this.log("warn",...e)};error=(...e)=>{this.log("error",...e)};log(e,...t){if(!(this.config.enabled&&l[e]>=l[this.config.level]))return;const{prefix:n}=this.config,r=void 0===n||""===n?t:[n,...t];console[e](...r)}configure(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}};function h(e,t){const n=new URL(e),r=decodeURIComponent(n.pathname.slice(1)),s=(new TextEncoder).encode(JSON.stringify({bucket:"storage.callimacus.ai",key:r,edits:t})).toBase64();return`${n.origin}/${encodeURIComponent(s)}`}function y(){const e="undefined"==typeof crypto?void 0:crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if("function"==typeof e?.getRandomValues)e.getRandomValues(t);else for(let e=0;e<16;e++)t[e]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=[...t].map(e=>e.toString(16).padStart(2,"0"));return[n.slice(0,4).join(""),n.slice(4,6).join(""),n.slice(6,8).join(""),n.slice(8,10).join(""),n.slice(10,16).join("")].join("-")}var f,p;function m(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.audioUrl&&"string"==typeof t.mimeType}function g(e){if("object"==typeof e&&null!==e)for(const t of Object.values(e))if(m(t))return t}!function(e){e.GET_STORY="get-story",e.CREATE_ROUND="create-round",e.RESET_STORY="reset-story",e.BACK_FROM_ROUND="back-from-round",e.SHARE_STORY="share-story",e.GET_SHARED_STORY="get-shared-story",e.SUGGEST="suggest"}(f||(f={})),function(e){e.ROUND_CREATED="round-created",e.ROUND_EVENT="round-event",e.ROUND_COMPLETED="round-completed",e.ERROR="error"}(p||(p={}));const v={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class b{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(e={}){const t=e.minVisibilityRatio??v.minVisibilityRatio;this.config={productSelector:e.productSelector??v.productSelector,blockSelector:e.blockSelector??v.blockSelector,maxTrackedElements:e.maxTrackedElements??v.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,t))}}rescanUi(){if(!this.canUseDom())return;let e,t;try{e=document.querySelectorAll(this.config.productSelector),t=document.querySelectorAll(this.config.blockSelector)}catch(e){return void d.warn("UI Observer: invalid selector, skipping rescan:",e)}const n=Date.now();for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),r=this.calculateVisibilityRatio(e);this.syncTrackedElement(t,{bounds:e,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),r=this.calculateVisibilityRatio(t);this.syncTrackedBlock(e,{bounds:t,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const e=[...this.elements].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[t]of e)this.elements.delete(t),this.elementRefs.delete(t)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const e=[...this.blocks].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[t]of e)this.blocks.delete(t),this.blockRefs.delete(t)}syncTrackedElement(e,t){const n=this.resolveElementId(e),r=this.resolveBlockId(e),s=this.createTrackingKey(n,r),i=this.elementKeys.get(e);void 0!==i&&""!==i&&i!==s&&(this.elements.delete(i),this.elementRefs.delete(i)),this.elementKeys.set(e,s),this.elementRefs.set(s,e),this.elements.set(s,{id:n,blockId:r,trackingKey:s,...t})}syncTrackedBlock(e,t){const n=this.resolveTrackedBlockId(e),r=this.blockKeys.get(e),s=n;void 0!==r&&""!==r&&r!==s&&(this.blocks.delete(r),this.blockRefs.delete(r)),this.blockKeys.set(e,s),this.blockRefs.set(s,e),this.blocks.set(s,{id:n,...t})}resolveElementId(e){return[e.dataset.productId,e.dataset.productid,e.dataset.sku,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.productId??this.elements.size}`}resolveBlockId(e){let t;try{t=e.closest(this.config.blockSelector)??void 0}catch{return}return t instanceof HTMLElement?this.resolveTrackedBlockId(t):void 0}resolveTrackedBlockId(e){return[e.dataset.blockId,e.dataset.blockid,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.blockId??this.blocks.size}`}createTrackingKey(e,t){return void 0===t||""===t?e:`${e}::${t}`}normalizeRect(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,left:e.left,right:e.right,bottom:e.bottom}}calculateVisibilityRatio(e){const t=Math.max(0,Math.min(e.right,window.innerWidth)-Math.max(e.left,0))*Math.max(0,Math.min(e.bottom,window.innerHeight)-Math.max(e.top,0)),n=e.width*e.height;if(n<=0)return 0;const r=window.innerWidth*window.innerHeight,s=r>0?Math.min(n,r):n;return Math.min(1,Math.max(0,t/s))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const e=[],t=[],n=Date.now();for(const[t,n]of this.elements){const r=this.elementRefs.get(t);r?.isConnected?n.visibilityRatio<=0||e.push({blockId:n.blockId,element:{id:n.id,bounds:n.bounds,isVisible:n.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:n.visibilityRatio}}):(this.elements.delete(t),this.elementRefs.delete(t))}for(const[e,n]of this.blocks){const r=this.blockRefs.get(e);r?.isConnected?n.visibilityRatio<this.config.minVisibilityRatio||t.push(n.id):(this.blocks.delete(e),this.blockRefs.delete(e))}const r=e.slice(0,this.config.maxTrackedElements);return{timestamp:n,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...t,...r.flatMap(e=>e.blockId??[])])],elements:r.map(e=>e.element)}}}function k(e){const{data:t}=e;if("object"!=typeof t||null===t)return;const{code:n,reason:r}=t;return"number"==typeof n?{code:n,..."string"==typeof r&&{reason:r}}:void 0}const w=3;function R(e,t){return e>=500&&t<3}function T(e,t){return t?void 0:k(e)??{code:0}}class E{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=v;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{d.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(r.CLIENT_READY)}),this.socket.on("disconnect",()=>{d.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",e=>{this.updateConnectionStatus(!1);const t=T(e,this.socket?.active??!0);t&&(d.error("Connection refused by Callimacus:",e.message,t.reason??""),this.notifyRejection(t,e.message),this.scheduleHandshakeRetry(t.code))}),this.socket.on(n.ERROR,e=>{d.error("Received error from Callimacus:",e),this.notifyErrorListeners(e)}),this.socket.io.on("reconnect",e=>{d.info(`Reconnected to Callimacus after ${e} attempts`)}),this.socket.io.on("reconnect_attempt",e=>{d.info(`Attempting to reconnect: attempt ${e}`)}),this.socket.io.on("reconnect_error",e=>{d.error("Reconnection error:",e)}),this.socket.io.on("reconnect_failed",()=>{d.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(n.SERVER_RESPONSE,e=>{this.notifyServerResponseListeners(e)}))}notifyServerResponseListeners(e){this.serverResponseListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in server response listener:",e)}})}updateConnectionStatus(e){this.connectionStatusListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in connection status listener:",e)}})}notifyRejection(e,t){this.notifyErrorListeners({code:e.code,message:t,...void 0!==e.reason&&{reason:e.reason}})}scheduleHandshakeRetry(e){if(!this.socket)return;if(this.clearHandshakeRetry(),!R(e,this.handshakeRetryAttempts))return void(e>=500&&(d.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:e,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const t=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,d.info(`Retrying Callimacus connection in ${t}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*t)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(e){this.errorListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in error listener:",e)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(e=>{navigator.geolocation.getCurrentPosition(t=>{e(t)},()=>{e(void 0)})})}enrichPayloadWithUiContext(e){try{this.ensureUiObserver();const t=this.uiObserver?.getSnapshot();return t?{...e,context:{...e.context,uiSnapshot:t}}:e}catch(t){return d.error("Error enriching payload with UI context:",t),e}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new b(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(e){const t=new URL(e),n=new URL("thamyr",t).pathname;return{origin:t.origin,path:n}}connect(t="wss://localhost:4000",n,r){this.socket&&(d.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const s=this.socketEndpoint(t);let i;"undefined"!=typeof window&&void 0!==globalThis.location&&(i=globalThis.location.href);const o={...void 0!==i&&""!==i&&{referrer:i},...r};d.info("Connecting to Thamyr at",s),this.socket=e(s.origin,{path:s.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:n,auth:o}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),d.info("Disconnected from Callimacus"))}configureUiObserver(e){if(!e)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...v,enabled:!1});const t=e.enabled??(void 0!==e.productSelector||void 0!==e.blockSelector||void 0!==e.maxTrackedElements||void 0!==e.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...e,enabled:t},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new b(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(e,t){if(!this.socket)return void d.error("Socket is not connected. Cannot send interaction.");if(e===f.SUGGEST)return void d.error("SUGGEST is a request/response command. Use suggest() instead.");if(e===f.BACK_FROM_ROUND){if(void 0===t.chapterId)return void d.error("BACK_FROM_ROUND requires chapterId.")}const n={type:e,payload:this.enrichPayloadWithUiContext(t)},s={id:y()};this.socket.emit(r.USER_INTERACTION,{type:n.type,payload:n.payload},s.id)}async suggest(e,t={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(e){const t=e?.suggestions;return{suggestions:Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}}(await this.socket.timeout(t.timeoutMs??4e3).emitWithAck(r.USER_INTERACTION,{type:f.SUGGEST,payload:e}))}catch(e){return d.warn("Suggestions failed or timed out; serving none.",e),{suggestions:[]}}}async gatherClientInfo(){const e="undefined"==typeof navigator?void 0:navigator,t="undefined"==typeof window?void 0:window.screen;return{userAgent:e?.userAgent??"",language:e?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===t?"":`${t.width}x${t.height}`,location:await this.getLocation()}}onServerResponse(e){return this.serverResponseListeners.add(e),()=>{this.serverResponseListeners.delete(e)}}onConnectionStatus(e){return this.connectionStatusListeners.add(e),()=>{this.connectionStatusListeners.delete(e)}}onError(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}}const S=new E,I=200;function C(e,t={}){if(void 0!==e&&e.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===e?{}:{value:e}},...t}}function O(e,t={}){const{block:n,payload:r,submissionId:s,value:i,...o}=t;return{inputEvent:{type:"customInteraction",data:{interactionId:e,...void 0!==n&&{nodeKey:n},...void 0!==r&&{payload:r},...void 0!==s&&{submissionId:s},...void 0!==i&&{value:i}}},...o}}function A(e){return e.receptors??e.intent??[]}function x(e){return"key"in e?e.key:void 0}const $="custom:addToCartResult";function _(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const D=e=>"string"==typeof e&&e.length>0,q=e=>_(e)&&D(e.size)&&D(e.variantId)&&"boolean"==typeof e.orderable;function N(e){if(!_(e.data)||!_(e.data.addToCart))return;const t=e.data.addToCart;return"error"===t.status?{status:"error"}:"resolved"===t.status&&D(t.variantId)&&D(t.productName)&&D(t.size)?{status:"resolved",variantId:t.variantId,productName:t.productName,size:t.size}:"size_selection_needed"===t.status&&D(t.productSku)&&D(t.productName)&&Array.isArray(t.availableSizes)&&t.availableSizes.every(q)?{status:"size_selection_needed",productSku:t.productSku,productName:t.productName,availableSizes:t.availableSizes}:void 0}const j=e=>_(e)?e:{};function U(e,t,n){const[r,...s]=t;if(!_(e)||!Object.hasOwn(e,r))return;const i=0===s.length?function(e,t){if(_(e)&&"string"==typeof e.docId)return{...e,values:{...j(e.values),...t.values},inputs:{...j(e.inputs),...t.inputs},textRuns:{...j(e.textRuns),...t.textRuns}}}(e[r],n):U(e[r],s,n);return i&&{...e,[r]:i}}function L(e,t){const n=e.blocks??[],r=e.id===t.chapterId?n.findIndex(e=>e.id===t.blockId):-1;if(-1===r)return e;const s=n[r],i=U(s.data,t.contentId.split("."),t);return i?{...e,blocks:n.with(r,{...s,data:i})}:e}function K(e){const t=/^\/?map\/(?<language>[^\/]+)(?:\/(?<slug>.*))?$/v.exec(e)?.groups,n=t?.language;if(void 0===n||""===n)return;const r=t?.slug;return void 0===r||""===r?{language:n}:{language:n,slug:r}}async function z(e){try{const{data:t}=await e();return t}catch(e){if("object"==typeof e&&null!==e&&404===e.status)return;throw e}}async function M(e,t){const n=K(t);if(!n)return;const{language:r,slug:s}=n;if(void 0===s){const{data:t}=await e.content.listDocuments({language:r},{throwOnError:!0});return{kind:"index",language:r,entries:t}}const i=`/map/${r}/${s}`,o=await z(async()=>e.content.getDocumentByPath({path:i},{throwOnError:!0}));if(o)return{kind:"document",language:r,slug:s,document:o};if(!s.includes("/"))return;const a=await z(async()=>e.skesis.getItemByPath({path:i},{throwOnError:!0}));return a&&{kind:"item",language:r,slug:s,itemPage:a}}const B=["link","ask","interact","cart","submit"],P=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),V=e=>"string"==typeof e&&e.trim().length>0,H=new Set(["http:","https:","mailto:","tel:"]),W=e=>{try{return H.has(new URL(e,"https://relative.invalid").protocol)}catch{return!1}};function G(e){const{id:t,value:n,payload:r,block:s}=e,i=void 0===n||"string"==typeof n||(e=>Array.isArray(e)&&e.every(e=>"string"==typeof e))(n),o=void 0===r||P(r);if(i&&o&&(void 0===s||"string"==typeof s)&&V(t))return{type:"interact",id:t,...void 0!==n&&{value:n},...void 0!==r&&{payload:r},...void 0!==s&&{block:s}}}function F(e){if(P(e))switch(e.type){case"link":return function(e){const{url:t,newTab:n}=e;return(void 0===n||"boolean"==typeof n)&&V(t)&&W(t)?{type:"link",url:t,...void 0!==n&&{newTab:n}}:void 0}(e);case"ask":return V(e.value)?{type:"ask",value:e.value}:void 0;case"interact":return G(e);case"cart":return V(e.productId)?{type:"cart",productId:e.productId}:void 0;case"submit":return V(e.form)?{type:"submit",form:e.form}:void 0;default:return}}function J(e){const t=e instanceof FormData?e:new FormData(e),n=[];for(const e of new Set(t.keys())){const r=t.getAll(e).filter(e=>"string"==typeof e),s=e.endsWith("[]");r.length>0&&n.push([s?e.slice(0,-2):e,s||r.length>1?r:r[0]])}return Object.fromEntries(n)}const Y="custom:deliverResult",Q=new Set(["done","pending","ambiguous","skipped"]),Z=e=>void 0===e||"string"==typeof e,X=e=>P(e)&&"string"==typeof e.message&&Z(e.field),ee=e=>P(e)&&"string"==typeof e.status&&Q.has(e.status)&&Z(e.ref);function te(e){const t=e.type===Y&&P(e.data)?e.data:void 0;if(void 0===t)return;const{status:n,submissionId:r,message:s,redirect:i,errors:o,results:a}=t;var c;return("accepted"===n||"refused"===n)&&V(r)&&Z(s)&&Z(i)&&(void 0===o||Array.isArray(o)&&o.every(X))&&(P(c=a)&&Object.values(c).every(ee))?{status:n,submissionId:r,results:a,...void 0!==s&&{message:s},...void 0!==i&&W(i)&&{redirect:i},...void 0!==o&&{errors:o}}:void 0}const ne="2026-10",re=15e3,se=2e4,ie="fragment CartFields on Cart {\n\tid checkoutUrl totalQuantity\n\tcost {subtotalAmount {amount currencyCode} totalAmount {amount currencyCode}}\n\tlines(first: 100) {nodes {\n\t\tid quantity\n\t\tmerchandise {... on ProductVariant {id title product {title handle} image {url altText} price {amount currencyCode} selectedOptions {name value}}}\n\t\tcost {totalAmount {amount currencyCode}}\n\t}}\n}",oe=(e,t,n)=>`mutation ${e}(${t}, $country: CountryCode) @inContext(country: $country) {${n} {cart {...CartFields} userErrors {code field message} warnings {code message target}}}\n${ie}`,ae=`query CartQuery($id: ID!, $country: CountryCode) @inContext(country: $country) {cart(id: $id) {...CartFields}}\n${ie}`,ce=oe("CartCreate","$input: CartInput!","cartCreate(input: $input)"),ue=oe("CartLinesAdd","$cartId: ID!, $lines: [CartLineInput!]!","cartLinesAdd(cartId: $cartId, lines: $lines)"),le=oe("CartLinesUpdate","$cartId: ID!, $lines: [CartLineUpdateInput!]!","cartLinesUpdate(cartId: $cartId, lines: $lines)"),de=oe("CartLinesRemove","$cartId: ID!, $lineIds: [ID!]!","cartLinesRemove(cartId: $cartId, lineIds: $lineIds)"),he="The store is busy. Try again in a moment.",ye="The store is not open to the cart: its storefront password may be on.",fe=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),pe=e=>"string"==typeof e&&""!==e,me=(e,t)=>({error:{code:e,message:t},warnings:[]});const ge=(e,t=[])=>({data:e,warnings:t}),ve=(e,t,n)=>({error:{code:e,message:t,...void 0!==n&&{status:n}},isRefusedAccess:!1}),be=e=>({error:{code:"cart_unavailable",message:"The store refused the cart request.",status:e},isRefusedAccess:!0}),ke=/^gid:\/\/shopify\/ProductVariant\/\d+$/v,we=e=>ke.test(e);const Re=(e,t)=>Number.isSafeInteger(e)&&e>=t,Te=e=>({...e,lines:e.lines?.nodes??[]});const Ee=e=>e.lines.map(e=>({id:e.id,merchandiseId:e.merchandise.id,quantity:e.quantity})),Se=e=>e.map(({merchandiseId:e,quantity:t})=>({merchandiseId:e,quantity:t}));function Ie(e,t){const n=Se(e),r=n.find(e=>e.merchandiseId===t.merchandiseId);return r?r.quantity+=t.quantity:n.push(t),n}async function Ce(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return ve("cart_unavailable",ye,0===t?void 0:t);if(430===t||429===t)return ve("throttled",he,t);if(401===t||403===t)return be(t);if(!e.ok)return ve("http",`The store answered ${t}.`,t);let n;try{n=await e.json()}catch{return ve("cart_unavailable",ye,t)}return fe(n)&&fe(n.data)?{data:n.data}:function(e,t){const n=fe(e)&&Array.isArray(e.errors)?e.errors:[],r=new Set(n.map(e=>fe(e)&&fe(e.extensions)?e.extensions.code:void 0));if(r.has("THROTTLED"))return ve("throttled",he,t);if(r.has("ACCESS_DENIED")||r.has("UNAUTHORIZED")||r.has("FORBIDDEN"))return be(t);const s=n.find(e=>fe(e)&&pe(e.message));return ve("graphql",fe(s)&&pe(s.message)?s.message:"The store could not read the cart request.",t)}(n,t)}const Oe=e=>e instanceof Error?e.message:String(e);async function Ae(e){return new Promise(t=>{setTimeout(t,e)})}function xe(e){return"function"==typeof AbortSignal.timeout?AbortSignal.timeout(e):void 0}function $e(){try{return localStorage}catch{return}}function _e(e){const t=new Map;return{getItem(n){try{const t=e?.getItem(n);if("string"==typeof t)return t}catch{}return t.get(n)??null},setItem(n,r){try{if(void 0!==e)return e.setItem(n,r),void t.delete(n)}catch{}t.set(n,r)},removeItem(n){t.delete(n);try{e?.removeItem(n)}catch{}}}}function De(e,t={}){const{waitMs:n=se,ttlMs:r=re,retryMs:s=50,settleMs:i=30}=t;return async(t,o)=>{const a=`${t}:lease`,c=`${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`,u=()=>{const t=function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;return fe(t)&&pe(t.owner)&&"number"==typeof t.expires?{owner:t.owner,expires:t.expires}:void 0}catch{return}}(e.getItem(a));return void 0!==t&&t.expires>Date.now()?t.owner:void 0},l=Date.now()+n;let d=!1;for(;!d;){if(void 0===u()){try{e.setItem(a,JSON.stringify({owner:c,expires:Date.now()+r}))}catch{return o()}if(await Ae(i),d=u()===c,d)continue}if(Date.now()>=l)throw new Error(`[thamyr] the ${t} lock was not granted within ${n} ms`);await Ae(s)}try{return await o()}finally{u()===c&&e.removeItem(a)}}}function qe(){return _e($e())}function Ne(e){const t=_e(e.storage??$e()),n=e.lock??function(){const e=globalThis.navigator?.locks;if("function"==typeof e?.request)return async(t,n)=>{const r=xe(se);return e.request(t,r?{signal:r}:{},async()=>n())}}()??De(t),r=e.fetch??(async(e,t)=>fetch(e,t)),s=e.navigate??(e=>{location.assign(e)});function i(e){const s=`callimacus:shopify-cart:${e.cartKey??e.storeDomain}`,i=`callimacus:shopify-cart-lock:${e.cartKey??e.storeDomain}`,o=void 0!==e.storefrontToken,a=()=>function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;if(!fe(t)||!pe(t.id)||!t.id.startsWith("gid://shopify/Cart/"))return;const n=Array.isArray(t.lines)?t.lines:[];return{id:t.id,lines:n.filter(e=>fe(e)&&pe(e.id)&&pe(e.merchandiseId)&&"number"==typeof e.quantity)}}catch{return}}(t.getItem(s));function c(e){return t.setItem(s,JSON.stringify({id:e.id,lines:Ee(e)})),e}function u(e){a()?.id===e&&t.removeItem(s)}async function l(t,n){const s={"Content-Type":"application/json",Accept:"application/json"};void 0!==e.storefrontToken&&(s["X-Shopify-Storefront-Access-Token"]=e.storefrontToken);try{const i=await r(`https://${e.storeDomain}/api/${ne}/graphql.json`,{method:"POST",headers:s,body:JSON.stringify({query:t,variables:{...n,country:e.country??null}}),redirect:"manual",signal:xe(1e4)});return await Ce(i)}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return ve("network",t?"The store did not answer in time.":"Could not reach the store. Check your connection and try again.")}}async function d(e){return l(ae,{id:e})}async function h(e,t,n){const r=await l(t,n);if("error"in r)return o&&r.isRefusedAccess?{refusedAccess:r.error}:{error:r.error,warnings:[]};const s=r.data[e];if(!fe(s))return me("graphql","The store answered without the cart.");const i=Array.isArray(s.userErrors)?s.userErrors:[],a=Array.isArray(s.warnings)?s.warnings:[];if(!s.cart&&i.every(e=>e.field?.includes("cartId")??!1))return{isGone:!0};const u=s.cart?c(Te(s.cart)):void 0;return i.length>0?{...void 0!==u&&{data:u},error:{code:"refused",message:i.map(e=>e.message).join(" "),userErrors:i},warnings:a}:ge(u,a)}function y(e,t){return"isGone"in e?(u(t),me("no_cart","The cart is no longer there.")):"refusedAccess"in e?{error:e.refusedAccess,warnings:[]}:e}async function f(t,r,s){let o,l=!1;try{o=await n(i,async()=>{l=!0;const n=a();return void 0!==n&&n.id!==s?n:0===t.length?(void 0!==s&&u(s),ge(void 0)):async function(t){const n={lines:t,...void 0!==e.country&&{buyerIdentity:{countryCode:e.country}},...void 0!==e.sourceName&&{sourceName:e.sourceName}},r=await h("cartCreate",ce,{input:n});return"isGone"in r?me("graphql","The store created no cart."):"refusedAccess"in r?{error:r.refusedAccess,warnings:[]}:r}(t)})}catch(e){return l?me("cart_unavailable",Oe(e)):me("busy","The cart is being set up in another tab. Try again in a moment.")}if("warnings"in o)return o;if(r.length>0)return y(await h("cartLinesAdd",ue,{cartId:o.id,lines:r}),o.id);const f=await d(o.id);return"error"in f?{error:f.error,warnings:[]}:ge(f.data.cart?c(Te(f.data.cart)):void 0)}return{hasToken:o,read:a,keep:c,drop:u,query:d,change:async function(e,t,n){const r=await h(t.field,t.document,{cartId:e.id,...t.variables});return"isGone"in r&&void 0!==n.whenGone?f(n.whenGone,n.added??[],e.id):"refusedAccess"in r?f(n.whenRefused,n.added??[],e.id):y(r,e.id)},createOnce:f}}let o=Promise.resolve();async function a(t){const n=o.then(async()=>async function(t){let n;try{n=await e.settings()}catch(e){return me("cart_unavailable",Oe(e))}if(!n.cartEnabled)return me("cart_disabled","The cart is off on this site.");const{storeDomain:r}=n;if(void 0===r)return me("cart_unavailable","No Shopify store is set up for this site.");try{return await t(i({...n,storeDomain:r}))}catch(e){return me("cart_unavailable",Oe(e))}}(t));return o=n.catch(()=>{}),n}async function c(){return a(async e=>{const t=e.read();if(void 0===t)return ge(void 0);const n=await e.query(t.id);return"error"in n?n.isRefusedAccess&&e.hasToken?e.createOnce(Se(t.lines),[],t.id):{error:n.error,warnings:[]}:n.data.cart?ge(e.keep(Te(n.data.cart))):(e.drop(t.id),ge(void 0))})}const u={getCart:c,async addItem(e,t=1){const n=function(e){if("string"==typeof e)return we(e)?e:/^\d+$/v.test(e)?`gid://shopify/ProductVariant/${e}`:void 0}(e);if(void 0===n)return me("invalid_input",`Not a Shopify product variant id: ${e}.`);if(!Re(t,1))return me("invalid_input",`Not a quantity to add: ${t}.`);const r={merchandiseId:n,quantity:t},s=await a(async e=>{const t=e.read();return void 0===t?e.createOnce([r],[r]):e.change(t,{field:"cartLinesAdd",document:ue,variables:{lines:[r]}},{whenGone:[r],whenRefused:Ie(t.lines,r),added:[r]})}),i=function(e,t){if(void 0!==e.error||void 0===e.data)return;const{lines:n}=e.data;for(const r of e.warnings){const e="MERCHANDISE_OUT_OF_STOCK"===r.code?n.find(e=>0===e.quantity&&e.merchandise.id===t):void 0;if(void 0!==e)return{line:e,warning:r}}}(s,n);if(void 0===i)return s;return{data:(await u.removeItem(i.line.id)).data??s.data,error:{code:"refused",message:i.warning.message},warnings:s.warnings}},removeItem:async e=>pe(e)?a(async t=>{const n=t.read();return void 0===n?me("no_cart","There is no cart yet."):t.change(n,{field:"cartLinesRemove",document:de,variables:{lineIds:[e]}},{whenRefused:Se(n.lines.filter(t=>t.id!==e))})}):me("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>pe(e)&&Re(t,0)?a(async n=>{const r=n.read();if(void 0===r)return me("no_cart","There is no cart yet.");const s=r.lines.map(n=>n.id===e?{...n,quantity:t}:n).filter(e=>e.quantity>0);return n.change(r,{field:"cartLinesUpdate",document:le,variables:{lines:[{id:e,quantity:t}]}},{whenRefused:Se(s)})}):me("invalid_input",`Not a cart line and quantity: ${e} × ${t}.`),async checkout(){const e=await c();if(void 0!==e.error)return{error:e.error,warnings:e.warnings};const t=e.data;if(void 0===t||0===t.totalQuantity)return me("no_cart","The cart is empty.");if(!function(e){try{return"https:"===new URL(e).protocol}catch{return!1}}(t.checkoutUrl))return me("cart_unavailable","The store answered without a checkout link.");try{s(t.checkoutUrl)}catch(e){return me("cart_unavailable",Oe(e))}return ge(t.checkoutUrl,e.warnings)}};return u}const je=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ue=e=>"string"==typeof e&&""!==e.trim()?e.trim():void 0;function Le(e){const t=e?.trim()??"";if(""!==t)try{const{host:e}=new URL(/^https?:\/\//iv.test(t)?t:`https://${t}`);return""===e?void 0:e}catch{return}}const Ke=e=>void 0!==e&&/^[a-z]{2}$/iv.test(e)?e.toUpperCase():void 0;const ze=(e,t)=>Le(e?.storeDomain)??t;function Me(e,t){const n=Le(e?.domain??t?.storeDomain),r=e?.storefrontToken??Ue(t?.storefrontToken),s=e?.sourceName??void 0,i=Ke(t?.country);return{cartEnabled:e?.cartEnabled??!0,...void 0!==n&&{storeDomain:n,cartKey:ze(t,n)},...void 0!==r&&{storefrontToken:r},...void 0!==s&&{sourceName:s},countries:e?.countries??{},...void 0!==i&&{country:i}}}async function Be(e,t){try{const n="function"==typeof AbortSignal.timeout?AbortSignal.timeout(5e3):void 0,{data:r,response:s}=await e.get({url:"/shopify/storefront",...void 0!==n&&{signal:n}});return Me(200===s?.status?function(e){if(!je(e)||"boolean"!=typeof e.cartEnabled)return;const t=je(e.countries)?Object.fromEntries(Object.entries(e.countries).filter(e=>"string"==typeof e[1])):{};return{domain:Ue(e.domain)??null,storefrontToken:Ue(e.storefrontToken)??null,sourceName:Ue(e.sourceName)??null,countries:t,cartEnabled:e.cartEnabled}}(r):void 0,t)}catch{return Me(void 0,t)}}function Pe(e,t){const{countries:n,country:r,...s}=e,i=function(e,t){if(void 0===t||""===t)return;const n=t.toLowerCase(),[r]=n.split(/[\-_]/v,1),s=Object.entries(e),i=s.find(([e])=>e.toLowerCase()===n)??s.find(([e])=>e.toLowerCase()===r);return Ke(i?.[1])}(n,t)??r;return{...s,...void 0!==i&&{country:i}}}const Ve={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},He=Object.entries({$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"});function We(e,t){t||(t=new Map);for(const n of e)"in"in n?n.key&&t.set(n.key,{in:n.in,map:n.map}):"key"in n?t.set(n.key,{map:n.map}):n.args&&We(n.args,t);return t}function Ge(e,t){const n={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},r=We(t);function s(e,t,r){let s=n[e];void 0===s&&(s=Object.create(null),n[e]=s),s[t]=r}let i;for(const[o,a]of e.entries())if(t[o]&&(i=t[o]),i)if("in"in i)if(i.key){const e=r.get(i.key),t=e.map||i.key;e.in&&s(e.in,t,a)}else n.body=a;else for(const[e,t]of Object.entries(a??{})){const o=r.get(e);if(o)if(o.in){const n=o.map||e;s(o.in,n,t)}else n[o.map]=t;else{const n=He.find(([t])=>e.startsWith(t));if(n){const[r,i]=n;s(i,e.slice(r.length),t)}else if("allowExtra"in i&&i.allowExtra)for(const[n,r]of Object.entries(i.allowExtra))if(r){s(n,e,t);break}}}return function(e){for(const[t,n]of Object.entries(e))"body"!==t&&(!n||"object"!=typeof n||Array.isArray(n)||Object.keys(n).length||delete e[t])}(n),n}const Fe=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),o=s.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):Je({allowReserved:e,name:n,value:t})).join(i);return"label"===r||"matrix"===r?i+o:o},Je=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},Ye=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:i})=>{if(s instanceof Date)return i?s.toISOString():`${n}=${s.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(s).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const i=t.join(",");switch(r){case"form":return`${n}=${i}`;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return i}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(s).map(([t,s])=>Je({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+a:a},Qe=/\{[^{}]+\}/g,Ze=({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let i=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(i=(({path:e,url:t})=>{let n=t;const r=t.match(Qe);if(r)for(const t of r){let r=!1,s=t.substring(1,t.length-1),i="simple";s.endsWith("*")&&(r=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),i="label"):s.startsWith(";")&&(s=s.substring(1),i="matrix");const o=e[s];if(null==o)continue;if(Array.isArray(o)){n=n.replace(t,Fe({explode:r,name:s,style:i,value:o}));continue}if("object"==typeof o){n=n.replace(t,Ye({explode:r,name:s,style:i,value:o,valueOnly:!0}));continue}if("matrix"===i){n=n.replace(t,`;${Je({name:s,value:o})}`);continue}const a=encodeURIComponent("label"===i?`.${o}`:o);n=n.replace(t,a)}return n})({path:t,url:i}));let o=n?r(n):"";return o.startsWith("?")&&(o=o.substring(1)),o&&(i+=`?${o}`),i};function Xe(e){const t=void 0!==e.body;if(t&&e.bodySerializer){if("serializedBody"in e){return void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null}return""!==e.body?e.body:null}if(t)return e.body}const et=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},tt=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const s in n){const i=n[s];if(null==i)continue;const o=e[s]||t;if(Array.isArray(i)){const e=Fe({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:i,...o.array});e&&r.push(e)}else if("object"==typeof i){const e=Ye({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:i,...o.object});e&&r.push(e)}else{const e=Je({allowReserved:o.allowReserved,name:s,value:i});e&&r.push(e)}}return r.join("&")},nt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`));const rt=e=>Ze({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:tt(e.querySerializer),url:e.url}),st=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=ot(e.headers,t.headers),n},it=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},ot=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?it(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t};class at{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}}const ct=tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),ut={"Content-Type":"application/json"},lt=(e={})=>({...Ve,headers:ut,parseAs:"auto",querySerializer:ct,...e}),dt=(e={})=>{let t=st(lt(),e);const n=()=>({...t}),r={error:new at,request:new at,response:new at},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:ot(t.headers,e.headers),serializedBody:void 0};n.security&&await async function(e){for(const t of e.security??[]){if(nt(e,t.name))continue;const n=await et(t,e.auth);if(!n)continue;const r=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[r]=n;break;case"cookie":e.headers.append("Cookie",`${r}=${n}`);break;default:e.headers.set(r,n)}}}(n),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type");return{opts:n,url:rt(n)}},i=async e=>{const n=e.throwOnError??t.throwOnError,i=e.responseStyle??t.responseStyle;let o,a;try{const{opts:t,url:n}=await s(e),i={redirect:"follow",...t,body:Xe(t)};o=new Request(n,i);for(const e of r.request.fns)e&&(o=await e(o,t));const c=t.fetch;a=await c(o);for(const e of r.response.fns)e&&(a=await e(a,o,t));const u={request:o,response:a};if(a.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(a.headers.get("Content-Type")):t.parseAs)??"json";if(204===a.status||"0"===a.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await a[e]();break;case"formData":n=new FormData;break;case"stream":n=a.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...u}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"text":n=await a[e]();break;case"json":{const e=await a.text();n=e?JSON.parse(e):{};break}case"stream":return"data"===t.responseStyle?a.body:{data:a.body,...u}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...u}}const l=await a.text();let d;try{d=JSON.parse(l)}catch{}throw d??l}catch(t){let s=t;for(const t of r.error.fns)t&&(s=await t(s,a,o,e));if(s=s||{},n)throw s;return"data"===i?void 0:{error:s,request:o,response:a}}},o=e=>t=>i({...t,method:e}),a=e=>async t=>{const{opts:n,url:i}=await s(t);return function({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:i,sseMaxRetryAttempts:o,sseMaxRetryDelay:a,sseSleepFn:c,url:u,...l}){let d;const h=c??(e=>new Promise(t=>setTimeout(t,e))),y=async function*(){let c=i??3e3,y=0;const f=l.signal??(new AbortController).signal;for(;!f.aborted;){y++;const i=l.headers instanceof Headers?l.headers:new Headers(l.headers);void 0!==d&&i.set("Last-Event-ID",d);try{const t={redirect:"follow",...l,body:l.serializedBody,headers:i,signal:f};let o=new Request(u,t);e&&(o=await e(u,t));const a=l.fetch??globalThis.fetch,h=await a(o);if(!h.ok)throw new Error(`SSE failed: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("No body in SSE response");const y=h.body.pipeThrough(new TextDecoderStream).getReader();let p="";const m=()=>{try{y.cancel()}catch{}};f.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await y.read();if(e)break;p+=t,p=p.replace(/\r\n?/g,"\n");const i=p.split("\n\n");p=i.pop()??"";for(const e of i){const t=e.split("\n"),i=[];let o,a;for(const e of t)if(e.startsWith("data:"))i.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))o=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let u=!1;if(i.length){const e=i.join("\n");try{a=JSON.parse(e),u=!0}catch{a=e}}u&&(s&&await s(a),r&&(a=await r(a))),n?.({data:a,event:o,id:d,retry:c}),i.length&&(yield a)}}}finally{f.removeEventListener("abort",m),y.releaseLock()}break}catch(e){if(t?.(e),void 0!==o&&y>=o)break;const n=Math.min(c*2**(y-1),a??3e4);await h(n)}}}();return{stream:y}}({...n,body:n.body,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of r.request.fns)e&&(s=await e(s,n));return s},serializedBody:Xe(n),url:i})};return{buildUrl:e=>rt({...t,...e}),connect:o("CONNECT"),delete:o("DELETE"),get:o("GET"),getConfig:n,head:o("HEAD"),interceptors:r,options:o("OPTIONS"),patch:o("PATCH"),post:o("POST"),put:o("PUT"),request:i,setConfig:e=>(t=st(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:o("TRACE")}};class ht{client;constructor(e){this.client=e.client}}class yt{defaultKey="default";instances=new Map;get(e){const t=this.instances.get(e??this.defaultKey);if(!t)throw new Error('No SDK client found. Create one with "new CallimacusApi()" to fix this error.');return t}set(e,t){this.instances.set(t??this.defaultKey,e)}}class ft extends ht{getPage(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/page/{language}/{id}",...t,...n})}listTopics(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}",...t,...n})}getTopicContents(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"idOrSlug"},{in:"query",key:"offset"},{in:"query",key:"limit"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}/{idOrSlug}",...t,...n})}getDocumentBySlug(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"slug"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/{language}/{slug}",...t,...n})}getDocumentByGroup(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"groupId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-group/{language}/{groupId}",...t,...n})}getDocumentByPath(e,t){const n=Ge([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-path",...t,...n})}listDocuments(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/documents/{language}",...t,...n})}}class pt extends ht{getShared(e,t){const n=Ge([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}share(e,t){const n=Ge([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}}class mt extends ht{getSimilar(e,t){const n=Ge([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"topK"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/similar",...t,...n})}getRecommendations(e,t){const n=Ge([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/recommendations",...t,...n})}}class gt extends ht{getLast(e,t){const n=Ge([e],[{args:[{in:"query",key:"storyId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/whisper",...t,...n})}}class vt extends ht{trackEvent(e,t){const n=Ge([e],[{args:[{in:"body",key:"storyId"},{in:"body",key:"eventName"},{in:"body",key:"content"},{in:"body",key:"payload"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/track-event",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class bt extends ht{getCart(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart",...e})}addItemToCart(e,t){const n=Ge([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/add",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}removeItemFromCart(e,t){const n=Ge([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/remove",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}updateProductQuantity(e,t){const n=Ge([e],[{args:[{in:"body",key:"productId"},{in:"body",key:"quantity"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/update",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class kt extends ht{getStorefrontSettings(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/shopify/storefront",...e})}}class wt extends ht{similar(e,t){const n=Ge([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"topK"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/similar",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}related(e,t){const n=Ge([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/related",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}getItemByPath(e,t){const n=Ge([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/item/by-path",...t,...n})}}class Rt extends ht{static __registry=new yt;constructor(e){super(e),Rt.__registry.set(this,e.key)}_content;get content(){return this._content??=new ft({client:this.client})}_stories;get stories(){return this._stories??=new pt({client:this.client})}_products;get products(){return this._products??=new mt({client:this.client})}_whisper;get whisper(){return this._whisper??=new gt({client:this.client})}_analytics;get analytics(){return this._analytics??=new vt({client:this.client})}_cart;get cart(){return this._cart??=new bt({client:this.client})}_shopify;get shopify(){return this._shopify??=new kt({client:this.client})}_skesis;get skesis(){return this._skesis??=new wt({client:this.client})}}class Tt extends Error{status;body;response;request;constructor(e,t,n){const r=t?.status,s=n?`${n.method} ${n.url}`:"request";let i=`[thamyr] ${s} failed before a response arrived`;t&&(i=t.ok?`[thamyr] ${s} → ${t.status}, but the response could not be processed`:`[thamyr] ${s} → ${t.status}`),super(i,e instanceof Error?{cause:e}:void 0),this.name="ThamyrHttpError",this.status=r,this.body=e,this.response=t,this.request=n}}function Et(e){const t=dt(lt({baseUrl:new URL("api/v3",e.endpoint).href,headers:{Authorization:`Bearer ${e.accessToken}`,"x-sl-access-token":e.accessToken},credentials:e.withCredentials?"include":"same-origin"}));return t.interceptors.error.use((e,n,r,s)=>{if(!(s.throwOnError??t.getConfig().throwOnError??!1)||!0===s.signal?.aborted)return e;return new Tt(""===e?{}:e??{},n,r)}),t}export{B as ACTION_TYPES,$ as ADD_TO_CART_RESULT_BLOCK,Rt as CallimacusApi,p as CallimacusEvent,E as CallimacusService,o as ChapterStatus,r as ClientEvents,Y as DELIVER_RESULT_BLOCK,i as GalleryMode,I as LANDING_VALUE_MAX_LENGTH,w as MAX_HANDSHAKE_RETRIES,s as SLInputEventType,ne as STOREFRONT_API_VERSION,n as ServerEvents,Tt as ThamyrHttpError,t as ThamyrResponseType,f as UserInteractionType,F as actionOf,N as addToCartResultOf,L as applyBlockPatch,x as blockKeyOf,S as callimacusService,Pe as cartSettingsFor,T as classifyConnectError,Et as createContractClient,qe as createPageStorage,Ne as createShopifyCart,te as deliverResultOf,g as extractTtsAudio,J as fieldsOf,O as interactionRound,a as isCustomBlock,u as isMasterProduct,c as isSetProduct,we as isVariantGid,C as landingRound,d as logger,Me as mergeShopifySettings,k as parseConnectRejection,K as parseMapPath,y as randomUuid,Be as readShopifySettings,A as receptorsOf,M as resolveMapPage,R as shouldRetryHandshake,h as transformImageUrl};
8
+ export*from"@callimacus/intent";import{io as e}from"socket.io-client";const t={ERROR:"error",CHAPTER_EVENT:"chapter-event",CHAPTER_DELETED:"chapter-deleted",STORY_RESET:"story-reset",STORY_CREATED:"story-created",STORY_SHARED:"story-shared",BLOCK_PATCH:"block-patch",CART_COMMAND:"cart-command"},n={ERROR:"error",SYSTEM_MESSAGE:"system-message",SERVER_STATUS:"server-status",SERVER_RESPONSE:"server-response"},r={CLIENT_READY:"client-ready",USER_INTERACTION:"user-interaction"},s={question:"question",content:"content",topic:"topic",tag:"tag",image:"image",video:"video",gallery:"gallery",relatedQuestion:"relatedQuestion",page:"page",customInteraction:"customInteraction",customPage:"customPage"},i={masonry:"masonry",carousel:"carousel"},o={understandingQuery:1,craftingAnswer:2,curatingContent:3,done:4};function a(e){return e.type.startsWith("custom:")}function c(e){return"set"in e.type&&e.type.set}function u(e){return"master"in e.type&&e.type.master}const d={debug:0,info:1,warn:2,error:3,silent:4};const l=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...e)=>{this.log("debug",...e)};info=(...e)=>{this.log("info",...e)};warn=(...e)=>{this.log("warn",...e)};error=(...e)=>{this.log("error",...e)};log(e,...t){if(!(this.config.enabled&&d[e]>=d[this.config.level]))return;const{prefix:n}=this.config,r=void 0===n||""===n?t:[n,...t];console[e](...r)}configure(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}};function h(e,t){const n=new URL(e),r=decodeURIComponent(n.pathname.slice(1)),s=(new TextEncoder).encode(JSON.stringify({bucket:"storage.callimacus.ai",key:r,edits:t})).toBase64();return`${n.origin}/${encodeURIComponent(s)}`}function y(){const e="undefined"==typeof crypto?void 0:crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if("function"==typeof e?.getRandomValues)e.getRandomValues(t);else for(let e=0;e<16;e++)t[e]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=[...t].map(e=>e.toString(16).padStart(2,"0"));return[n.slice(0,4).join(""),n.slice(4,6).join(""),n.slice(6,8).join(""),n.slice(8,10).join(""),n.slice(10,16).join("")].join("-")}var f,p;function m(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.audioUrl&&"string"==typeof t.mimeType}function g(e){if("object"==typeof e&&null!==e)for(const t of Object.values(e))if(m(t))return t}!function(e){e.GET_STORY="get-story",e.CREATE_ROUND="create-round",e.RESET_STORY="reset-story",e.BACK_FROM_ROUND="back-from-round",e.SHARE_STORY="share-story",e.GET_SHARED_STORY="get-shared-story",e.SUGGEST="suggest"}(f||(f={})),function(e){e.ROUND_CREATED="round-created",e.ROUND_EVENT="round-event",e.ROUND_COMPLETED="round-completed",e.ERROR="error"}(p||(p={}));const v={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class b{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(e={}){const t=e.minVisibilityRatio??v.minVisibilityRatio;this.config={productSelector:e.productSelector??v.productSelector,blockSelector:e.blockSelector??v.blockSelector,maxTrackedElements:e.maxTrackedElements??v.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,t))}}rescanUi(){if(!this.canUseDom())return;let e,t;try{e=document.querySelectorAll(this.config.productSelector),t=document.querySelectorAll(this.config.blockSelector)}catch(e){return void l.warn("UI Observer: invalid selector, skipping rescan:",e)}const n=Date.now();for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),r=this.calculateVisibilityRatio(e);this.syncTrackedElement(t,{bounds:e,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),r=this.calculateVisibilityRatio(t);this.syncTrackedBlock(e,{bounds:t,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const e=[...this.elements].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[t]of e)this.elements.delete(t),this.elementRefs.delete(t)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const e=[...this.blocks].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[t]of e)this.blocks.delete(t),this.blockRefs.delete(t)}syncTrackedElement(e,t){const n=this.resolveElementId(e),r=this.resolveBlockId(e),s=this.createTrackingKey(n,r),i=this.elementKeys.get(e);void 0!==i&&""!==i&&i!==s&&(this.elements.delete(i),this.elementRefs.delete(i)),this.elementKeys.set(e,s),this.elementRefs.set(s,e),this.elements.set(s,{id:n,blockId:r,trackingKey:s,...t})}syncTrackedBlock(e,t){const n=this.resolveTrackedBlockId(e),r=this.blockKeys.get(e),s=n;void 0!==r&&""!==r&&r!==s&&(this.blocks.delete(r),this.blockRefs.delete(r)),this.blockKeys.set(e,s),this.blockRefs.set(s,e),this.blocks.set(s,{id:n,...t})}resolveElementId(e){return[e.dataset.productId,e.dataset.productid,e.dataset.sku,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.productId??this.elements.size}`}resolveBlockId(e){let t;try{t=e.closest(this.config.blockSelector)??void 0}catch{return}return t instanceof HTMLElement?this.resolveTrackedBlockId(t):void 0}resolveTrackedBlockId(e){return[e.dataset.blockId,e.dataset.blockid,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.blockId??this.blocks.size}`}createTrackingKey(e,t){return void 0===t||""===t?e:`${e}::${t}`}normalizeRect(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,left:e.left,right:e.right,bottom:e.bottom}}calculateVisibilityRatio(e){const t=Math.max(0,Math.min(e.right,window.innerWidth)-Math.max(e.left,0))*Math.max(0,Math.min(e.bottom,window.innerHeight)-Math.max(e.top,0)),n=e.width*e.height;if(n<=0)return 0;const r=window.innerWidth*window.innerHeight,s=r>0?Math.min(n,r):n;return Math.min(1,Math.max(0,t/s))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const e=[],t=[],n=Date.now();for(const[t,n]of this.elements){const r=this.elementRefs.get(t);r?.isConnected?n.visibilityRatio<=0||e.push({blockId:n.blockId,element:{id:n.id,bounds:n.bounds,isVisible:n.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:n.visibilityRatio}}):(this.elements.delete(t),this.elementRefs.delete(t))}for(const[e,n]of this.blocks){const r=this.blockRefs.get(e);r?.isConnected?n.visibilityRatio<this.config.minVisibilityRatio||t.push(n.id):(this.blocks.delete(e),this.blockRefs.delete(e))}const r=e.slice(0,this.config.maxTrackedElements);return{timestamp:n,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...t,...r.flatMap(e=>e.blockId??[])])],elements:r.map(e=>e.element)}}}function k(e){const{data:t}=e;if("object"!=typeof t||null===t)return;const{code:n,reason:r}=t;return"number"==typeof n?{code:n,..."string"==typeof r&&{reason:r}}:void 0}const w=3;function R(e,t){return e>=500&&t<3}function T(e,t){return t?void 0:k(e)??{code:0}}class S{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=v;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{l.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(r.CLIENT_READY)}),this.socket.on("disconnect",()=>{l.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",e=>{this.updateConnectionStatus(!1);const t=T(e,this.socket?.active??!0);t&&(l.error("Connection refused by Callimacus:",e.message,t.reason??""),this.notifyRejection(t,e.message),this.scheduleHandshakeRetry(t.code))}),this.socket.on(n.ERROR,e=>{l.error("Received error from Callimacus:",e),this.notifyErrorListeners(e)}),this.socket.io.on("reconnect",e=>{l.info(`Reconnected to Callimacus after ${e} attempts`)}),this.socket.io.on("reconnect_attempt",e=>{l.info(`Attempting to reconnect: attempt ${e}`)}),this.socket.io.on("reconnect_error",e=>{l.error("Reconnection error:",e)}),this.socket.io.on("reconnect_failed",()=>{l.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(n.SERVER_RESPONSE,e=>{this.notifyServerResponseListeners(e)}))}notifyServerResponseListeners(e){this.serverResponseListeners.forEach(t=>{try{t(e)}catch(e){l.error("Error in server response listener:",e)}})}updateConnectionStatus(e){this.connectionStatusListeners.forEach(t=>{try{t(e)}catch(e){l.error("Error in connection status listener:",e)}})}notifyRejection(e,t){this.notifyErrorListeners({code:e.code,message:t,...void 0!==e.reason&&{reason:e.reason}})}scheduleHandshakeRetry(e){if(!this.socket)return;if(this.clearHandshakeRetry(),!R(e,this.handshakeRetryAttempts))return void(e>=500&&(l.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:e,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const t=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,l.info(`Retrying Callimacus connection in ${t}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*t)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(e){this.errorListeners.forEach(t=>{try{t(e)}catch(e){l.error("Error in error listener:",e)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(e=>{navigator.geolocation.getCurrentPosition(t=>{e(t)},()=>{e(void 0)})})}enrichPayloadWithUiContext(e){try{this.ensureUiObserver();const t=this.uiObserver?.getSnapshot();return t?{...e,context:{...e.context,uiSnapshot:t}}:e}catch(t){return l.error("Error enriching payload with UI context:",t),e}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new b(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(e){const t=new URL(e),n=new URL("thamyr",t).pathname;return{origin:t.origin,path:n}}connect(t="wss://localhost:4000",n,r){this.socket&&(l.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const s=this.socketEndpoint(t);let i;"undefined"!=typeof window&&void 0!==globalThis.location&&(i=globalThis.location.href);const o="undefined"==typeof document?void 0:function(e){const t="intent_sid=",n=e.split("; ").find(e=>e.startsWith(t))?.slice(11);return void 0===n||""===n?void 0:n}(document.cookie),a={...void 0!==i&&""!==i&&{referrer:i},...void 0!==o&&{intentSid:o},...r};l.info("Connecting to Thamyr at",s),this.socket=e(s.origin,{path:s.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:n,auth:a}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),l.info("Disconnected from Callimacus"))}configureUiObserver(e){if(!e)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...v,enabled:!1});const t=e.enabled??(void 0!==e.productSelector||void 0!==e.blockSelector||void 0!==e.maxTrackedElements||void 0!==e.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...e,enabled:t},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new b(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(e,t){if(!this.socket)return void l.error("Socket is not connected. Cannot send interaction.");if(e===f.SUGGEST)return void l.error("SUGGEST is a request/response command. Use suggest() instead.");if(e===f.BACK_FROM_ROUND){if(void 0===t.chapterId)return void l.error("BACK_FROM_ROUND requires chapterId.")}const n={type:e,payload:this.enrichPayloadWithUiContext(t)},s={id:y()};this.socket.emit(r.USER_INTERACTION,{type:n.type,payload:n.payload},s.id)}async suggest(e,t={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(e){const t=e?.suggestions;return{suggestions:Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}}(await this.socket.timeout(t.timeoutMs??4e3).emitWithAck(r.USER_INTERACTION,{type:f.SUGGEST,payload:e}))}catch(e){return l.warn("Suggestions failed or timed out; serving none.",e),{suggestions:[]}}}async gatherClientInfo(){const e="undefined"==typeof navigator?void 0:navigator,t="undefined"==typeof window?void 0:window.screen;return{userAgent:e?.userAgent??"",language:e?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===t?"":`${t.width}x${t.height}`,location:await this.getLocation()}}onServerResponse(e){return this.serverResponseListeners.add(e),()=>{this.serverResponseListeners.delete(e)}}onConnectionStatus(e){return this.connectionStatusListeners.add(e),()=>{this.connectionStatusListeners.delete(e)}}onError(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}}const E=new S,I=200;function C(e,t={}){if(void 0!==e&&e.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===e?{}:{value:e}},...t}}function O(e,t={}){const{block:n,payload:r,submissionId:s,value:i,...o}=t;return{inputEvent:{type:"customInteraction",data:{interactionId:e,...void 0!==n&&{nodeKey:n},...void 0!==r&&{payload:r},...void 0!==s&&{submissionId:s},...void 0!==i&&{value:i}}},...o}}function A(e){return e.receptors??e.intent??[]}function x(e){return"key"in e?e.key:void 0}const $="custom:addToCartResult";function _(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const D=e=>"string"==typeof e&&e.length>0,q=e=>_(e)&&D(e.size)&&D(e.variantId)&&"boolean"==typeof e.orderable;function N(e){if(!_(e.data)||!_(e.data.addToCart))return;const t=e.data.addToCart;return"error"===t.status?{status:"error"}:"resolved"===t.status&&D(t.variantId)&&D(t.productName)&&D(t.size)?{status:"resolved",variantId:t.variantId,productName:t.productName,size:t.size}:"size_selection_needed"===t.status&&D(t.productSku)&&D(t.productName)&&Array.isArray(t.availableSizes)&&t.availableSizes.every(q)?{status:"size_selection_needed",productSku:t.productSku,productName:t.productName,availableSizes:t.availableSizes}:void 0}const j=e=>_(e)?e:{};function U(e,t,n){const[r,...s]=t;if(!_(e)||!Object.hasOwn(e,r))return;const i=0===s.length?function(e,t){if(_(e)&&"string"==typeof e.docId)return{...e,values:{...j(e.values),...t.values},inputs:{...j(e.inputs),...t.inputs},textRuns:{...j(e.textRuns),...t.textRuns}}}(e[r],n):U(e[r],s,n);return i&&{...e,[r]:i}}function L(e,t){const n=e.blocks??[],r=e.id===t.chapterId?n.findIndex(e=>e.id===t.blockId):-1;if(-1===r)return e;const s=n[r],i=U(s.data,t.contentId.split("."),t);return i?{...e,blocks:n.with(r,{...s,data:i})}:e}function K(e){const t=/^\/?map\/(?<language>[^\/]+)(?:\/(?<slug>.*))?$/v.exec(e)?.groups,n=t?.language;if(void 0===n||""===n)return;const r=t?.slug;return void 0===r||""===r?{language:n}:{language:n,slug:r}}async function z(e){try{const{data:t}=await e();return t}catch(e){if("object"==typeof e&&null!==e&&404===e.status)return;throw e}}async function M(e,t){const n=K(t);if(!n)return;const{language:r,slug:s}=n;if(void 0===s){const{data:t}=await e.content.listDocuments({language:r},{throwOnError:!0});return{kind:"index",language:r,entries:t}}const i=`/map/${r}/${s}`,o=await z(async()=>e.content.getDocumentByPath({path:i},{throwOnError:!0}));if(o)return{kind:"document",language:r,slug:s,document:o};if(!s.includes("/"))return;const a=await z(async()=>e.skesis.getItemByPath({path:i},{throwOnError:!0}));return a&&{kind:"item",language:r,slug:s,itemPage:a}}const B=["link","ask","interact","cart","submit"],P=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),V=e=>"string"==typeof e&&e.trim().length>0,H=new Set(["http:","https:","mailto:","tel:"]),W=e=>{try{return H.has(new URL(e,"https://relative.invalid").protocol)}catch{return!1}};function G(e){const{id:t,value:n,payload:r,block:s}=e,i=void 0===n||"string"==typeof n||(e=>Array.isArray(e)&&e.every(e=>"string"==typeof e))(n),o=void 0===r||P(r);if(i&&o&&(void 0===s||"string"==typeof s)&&V(t))return{type:"interact",id:t,...void 0!==n&&{value:n},...void 0!==r&&{payload:r},...void 0!==s&&{block:s}}}function F(e){if(P(e))switch(e.type){case"link":return function(e){const{url:t,newTab:n}=e;return(void 0===n||"boolean"==typeof n)&&V(t)&&W(t)?{type:"link",url:t,...void 0!==n&&{newTab:n}}:void 0}(e);case"ask":return V(e.value)?{type:"ask",value:e.value}:void 0;case"interact":return G(e);case"cart":return V(e.productId)?{type:"cart",productId:e.productId}:void 0;case"submit":return V(e.form)?{type:"submit",form:e.form}:void 0;default:return}}function J(e){const t=e instanceof FormData?e:new FormData(e),n=[];for(const e of new Set(t.keys())){const r=t.getAll(e).filter(e=>"string"==typeof e),s=e.endsWith("[]");r.length>0&&n.push([s?e.slice(0,-2):e,s||r.length>1?r:r[0]])}return Object.fromEntries(n)}const Y="custom:deliverResult",Q=new Set(["done","pending","ambiguous","skipped"]),Z=e=>void 0===e||"string"==typeof e,X=e=>P(e)&&"string"==typeof e.message&&Z(e.field),ee=e=>P(e)&&"string"==typeof e.status&&Q.has(e.status)&&Z(e.ref);function te(e){const t=e.type===Y&&P(e.data)?e.data:void 0;if(void 0===t)return;const{status:n,submissionId:r,message:s,redirect:i,errors:o,results:a}=t;var c;return("accepted"===n||"refused"===n)&&V(r)&&Z(s)&&Z(i)&&(void 0===o||Array.isArray(o)&&o.every(X))&&(P(c=a)&&Object.values(c).every(ee))?{status:n,submissionId:r,results:a,...void 0!==s&&{message:s},...void 0!==i&&W(i)&&{redirect:i},...void 0!==o&&{errors:o}}:void 0}const ne="2026-10",re=15e3,se=2e4,ie="fragment CartFields on Cart {\n\tid checkoutUrl totalQuantity\n\tcost {subtotalAmount {amount currencyCode} totalAmount {amount currencyCode}}\n\tlines(first: 100) {nodes {\n\t\tid quantity\n\t\tmerchandise {... on ProductVariant {id title product {title handle} image {url altText} price {amount currencyCode} selectedOptions {name value}}}\n\t\tcost {totalAmount {amount currencyCode}}\n\t}}\n}",oe=(e,t,n)=>`mutation ${e}(${t}, $country: CountryCode) @inContext(country: $country) {${n} {cart {...CartFields} userErrors {code field message} warnings {code message target}}}\n${ie}`,ae=`query CartQuery($id: ID!, $country: CountryCode) @inContext(country: $country) {cart(id: $id) {...CartFields}}\n${ie}`,ce=oe("CartCreate","$input: CartInput!","cartCreate(input: $input)"),ue=oe("CartLinesAdd","$cartId: ID!, $lines: [CartLineInput!]!","cartLinesAdd(cartId: $cartId, lines: $lines)"),de=oe("CartLinesUpdate","$cartId: ID!, $lines: [CartLineUpdateInput!]!","cartLinesUpdate(cartId: $cartId, lines: $lines)"),le=oe("CartLinesRemove","$cartId: ID!, $lineIds: [ID!]!","cartLinesRemove(cartId: $cartId, lineIds: $lineIds)"),he="The store is busy. Try again in a moment.",ye="The store is not open to the cart: its storefront password may be on.",fe=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),pe=e=>"string"==typeof e&&""!==e,me=(e,t)=>({error:{code:e,message:t},warnings:[]});const ge=(e,t=[])=>({data:e,warnings:t}),ve=(e,t,n)=>({error:{code:e,message:t,...void 0!==n&&{status:n}},isRefusedAccess:!1}),be=e=>({error:{code:"cart_unavailable",message:"The store refused the cart request.",status:e},isRefusedAccess:!0}),ke=/^gid:\/\/shopify\/ProductVariant\/\d+$/v,we=e=>ke.test(e);const Re=(e,t)=>Number.isSafeInteger(e)&&e>=t,Te=e=>({...e,lines:e.lines?.nodes??[]});const Se=e=>e.lines.map(e=>({id:e.id,merchandiseId:e.merchandise.id,quantity:e.quantity})),Ee=e=>e.map(({merchandiseId:e,quantity:t})=>({merchandiseId:e,quantity:t}));function Ie(e,t){const n=Ee(e),r=n.find(e=>e.merchandiseId===t.merchandiseId);return r?r.quantity+=t.quantity:n.push(t),n}async function Ce(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return ve("cart_unavailable",ye,0===t?void 0:t);if(430===t||429===t)return ve("throttled",he,t);if(401===t||403===t)return be(t);if(!e.ok)return ve("http",`The store answered ${t}.`,t);let n;try{n=await e.json()}catch{return ve("cart_unavailable",ye,t)}return fe(n)&&fe(n.data)?{data:n.data}:function(e,t){const n=fe(e)&&Array.isArray(e.errors)?e.errors:[],r=new Set(n.map(e=>fe(e)&&fe(e.extensions)?e.extensions.code:void 0));if(r.has("THROTTLED"))return ve("throttled",he,t);if(r.has("ACCESS_DENIED")||r.has("UNAUTHORIZED")||r.has("FORBIDDEN"))return be(t);const s=n.find(e=>fe(e)&&pe(e.message));return ve("graphql",fe(s)&&pe(s.message)?s.message:"The store could not read the cart request.",t)}(n,t)}const Oe=e=>e instanceof Error?e.message:String(e);async function Ae(e){return new Promise(t=>{setTimeout(t,e)})}function xe(e){return"function"==typeof AbortSignal.timeout?AbortSignal.timeout(e):void 0}function $e(){try{return localStorage}catch{return}}function _e(e){const t=new Map;return{getItem(n){try{const t=e?.getItem(n);if("string"==typeof t)return t}catch{}return t.get(n)??null},setItem(n,r){try{if(void 0!==e)return e.setItem(n,r),void t.delete(n)}catch{}t.set(n,r)},removeItem(n){t.delete(n);try{e?.removeItem(n)}catch{}}}}function De(e,t={}){const{waitMs:n=se,ttlMs:r=re,retryMs:s=50,settleMs:i=30}=t;return async(t,o)=>{const a=`${t}:lease`,c=`${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`,u=()=>{const t=function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;return fe(t)&&pe(t.owner)&&"number"==typeof t.expires?{owner:t.owner,expires:t.expires}:void 0}catch{return}}(e.getItem(a));return void 0!==t&&t.expires>Date.now()?t.owner:void 0},d=Date.now()+n;let l=!1;for(;!l;){if(void 0===u()){try{e.setItem(a,JSON.stringify({owner:c,expires:Date.now()+r}))}catch{return o()}if(await Ae(i),l=u()===c,l)continue}if(Date.now()>=d)throw new Error(`[thamyr] the ${t} lock was not granted within ${n} ms`);await Ae(s)}try{return await o()}finally{u()===c&&e.removeItem(a)}}}function qe(){return _e($e())}function Ne(e){const t=_e(e.storage??$e()),n=e.lock??function(){const e=globalThis.navigator?.locks;if("function"==typeof e?.request)return async(t,n)=>{const r=xe(se);return e.request(t,r?{signal:r}:{},async()=>n())}}()??De(t),r=e.fetch??(async(e,t)=>fetch(e,t)),s=e.navigate??(e=>{location.assign(e)});function i(e){const s=`callimacus:shopify-cart:${e.cartKey??e.storeDomain}`,i=`callimacus:shopify-cart-lock:${e.cartKey??e.storeDomain}`,o=void 0!==e.storefrontToken,a=()=>function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;if(!fe(t)||!pe(t.id)||!t.id.startsWith("gid://shopify/Cart/"))return;const n=Array.isArray(t.lines)?t.lines:[];return{id:t.id,lines:n.filter(e=>fe(e)&&pe(e.id)&&pe(e.merchandiseId)&&"number"==typeof e.quantity)}}catch{return}}(t.getItem(s));function c(e){return t.setItem(s,JSON.stringify({id:e.id,lines:Se(e)})),e}function u(e){a()?.id===e&&t.removeItem(s)}async function d(t,n){const s={"Content-Type":"application/json",Accept:"application/json"};void 0!==e.storefrontToken&&(s["X-Shopify-Storefront-Access-Token"]=e.storefrontToken);try{const i=await r(`https://${e.storeDomain}/api/${ne}/graphql.json`,{method:"POST",headers:s,body:JSON.stringify({query:t,variables:{...n,country:e.country??null}}),redirect:"manual",signal:xe(1e4)});return await Ce(i)}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return ve("network",t?"The store did not answer in time.":"Could not reach the store. Check your connection and try again.")}}async function l(e){return d(ae,{id:e})}async function h(e,t,n){const r=await d(t,n);if("error"in r)return o&&r.isRefusedAccess?{refusedAccess:r.error}:{error:r.error,warnings:[]};const s=r.data[e];if(!fe(s))return me("graphql","The store answered without the cart.");const i=Array.isArray(s.userErrors)?s.userErrors:[],a=Array.isArray(s.warnings)?s.warnings:[];if(!s.cart&&i.every(e=>e.field?.includes("cartId")??!1))return{isGone:!0};const u=s.cart?c(Te(s.cart)):void 0;return i.length>0?{...void 0!==u&&{data:u},error:{code:"refused",message:i.map(e=>e.message).join(" "),userErrors:i},warnings:a}:ge(u,a)}function y(e,t){return"isGone"in e?(u(t),me("no_cart","The cart is no longer there.")):"refusedAccess"in e?{error:e.refusedAccess,warnings:[]}:e}async function f(t,r,s){let o,d=!1;try{o=await n(i,async()=>{d=!0;const n=a();return void 0!==n&&n.id!==s?n:0===t.length?(void 0!==s&&u(s),ge(void 0)):async function(t){const n={lines:t,...void 0!==e.country&&{buyerIdentity:{countryCode:e.country}},...void 0!==e.sourceName&&{sourceName:e.sourceName}},r=await h("cartCreate",ce,{input:n});return"isGone"in r?me("graphql","The store created no cart."):"refusedAccess"in r?{error:r.refusedAccess,warnings:[]}:r}(t)})}catch(e){return d?me("cart_unavailable",Oe(e)):me("busy","The cart is being set up in another tab. Try again in a moment.")}if("warnings"in o)return o;if(r.length>0)return y(await h("cartLinesAdd",ue,{cartId:o.id,lines:r}),o.id);const f=await l(o.id);return"error"in f?{error:f.error,warnings:[]}:ge(f.data.cart?c(Te(f.data.cart)):void 0)}return{hasToken:o,read:a,keep:c,drop:u,query:l,change:async function(e,t,n){const r=await h(t.field,t.document,{cartId:e.id,...t.variables});return"isGone"in r&&void 0!==n.whenGone?f(n.whenGone,n.added??[],e.id):"refusedAccess"in r?f(n.whenRefused,n.added??[],e.id):y(r,e.id)},createOnce:f}}let o=Promise.resolve();async function a(t){const n=o.then(async()=>async function(t){let n;try{n=await e.settings()}catch(e){return me("cart_unavailable",Oe(e))}if(!n.cartEnabled)return me("cart_disabled","The cart is off on this site.");const{storeDomain:r}=n;if(void 0===r)return me("cart_unavailable","No Shopify store is set up for this site.");try{return await t(i({...n,storeDomain:r}))}catch(e){return me("cart_unavailable",Oe(e))}}(t));return o=n.catch(()=>{}),n}async function c(){return a(async e=>{const t=e.read();if(void 0===t)return ge(void 0);const n=await e.query(t.id);return"error"in n?n.isRefusedAccess&&e.hasToken?e.createOnce(Ee(t.lines),[],t.id):{error:n.error,warnings:[]}:n.data.cart?ge(e.keep(Te(n.data.cart))):(e.drop(t.id),ge(void 0))})}const u={getCart:c,async addItem(e,t=1){const n=function(e){if("string"==typeof e)return we(e)?e:/^\d+$/v.test(e)?`gid://shopify/ProductVariant/${e}`:void 0}(e);if(void 0===n)return me("invalid_input",`Not a Shopify product variant id: ${e}.`);if(!Re(t,1))return me("invalid_input",`Not a quantity to add: ${t}.`);const r={merchandiseId:n,quantity:t},s=await a(async e=>{const t=e.read();return void 0===t?e.createOnce([r],[r]):e.change(t,{field:"cartLinesAdd",document:ue,variables:{lines:[r]}},{whenGone:[r],whenRefused:Ie(t.lines,r),added:[r]})}),i=function(e,t){if(void 0!==e.error||void 0===e.data)return;const{lines:n}=e.data;for(const r of e.warnings){const e="MERCHANDISE_OUT_OF_STOCK"===r.code?n.find(e=>0===e.quantity&&e.merchandise.id===t):void 0;if(void 0!==e)return{line:e,warning:r}}}(s,n);if(void 0===i)return s;return{data:(await u.removeItem(i.line.id)).data??s.data,error:{code:"refused",message:i.warning.message},warnings:s.warnings}},removeItem:async e=>pe(e)?a(async t=>{const n=t.read();return void 0===n?me("no_cart","There is no cart yet."):t.change(n,{field:"cartLinesRemove",document:le,variables:{lineIds:[e]}},{whenRefused:Ee(n.lines.filter(t=>t.id!==e))})}):me("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>pe(e)&&Re(t,0)?a(async n=>{const r=n.read();if(void 0===r)return me("no_cart","There is no cart yet.");const s=r.lines.map(n=>n.id===e?{...n,quantity:t}:n).filter(e=>e.quantity>0);return n.change(r,{field:"cartLinesUpdate",document:de,variables:{lines:[{id:e,quantity:t}]}},{whenRefused:Ee(s)})}):me("invalid_input",`Not a cart line and quantity: ${e} × ${t}.`),async checkout(){const e=await c();if(void 0!==e.error)return{error:e.error,warnings:e.warnings};const t=e.data;if(void 0===t||0===t.totalQuantity)return me("no_cart","The cart is empty.");if(!function(e){try{return"https:"===new URL(e).protocol}catch{return!1}}(t.checkoutUrl))return me("cart_unavailable","The store answered without a checkout link.");try{s(t.checkoutUrl)}catch(e){return me("cart_unavailable",Oe(e))}return ge(t.checkoutUrl,e.warnings)}};return u}const je=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ue=e=>"string"==typeof e&&""!==e.trim()?e.trim():void 0;function Le(e){const t=e?.trim()??"";if(""!==t)try{const{host:e}=new URL(/^https?:\/\//iv.test(t)?t:`https://${t}`);return""===e?void 0:e}catch{return}}const Ke=e=>void 0!==e&&/^[a-z]{2}$/iv.test(e)?e.toUpperCase():void 0;const ze=(e,t)=>Le(e?.storeDomain)??t;function Me(e,t){const n=Le(e?.domain??t?.storeDomain),r=e?.storefrontToken??Ue(t?.storefrontToken),s=e?.sourceName??void 0,i=Ke(t?.country);return{cartEnabled:e?.cartEnabled??!0,...void 0!==n&&{storeDomain:n,cartKey:ze(t,n)},...void 0!==r&&{storefrontToken:r},...void 0!==s&&{sourceName:s},countries:e?.countries??{},...void 0!==i&&{country:i}}}async function Be(e,t){try{const n="function"==typeof AbortSignal.timeout?AbortSignal.timeout(5e3):void 0,{data:r,response:s}=await e.get({url:"/shopify/storefront",...void 0!==n&&{signal:n}});return Me(200===s?.status?function(e){if(!je(e)||"boolean"!=typeof e.cartEnabled)return;const t=je(e.countries)?Object.fromEntries(Object.entries(e.countries).filter(e=>"string"==typeof e[1])):{};return{domain:Ue(e.domain)??null,storefrontToken:Ue(e.storefrontToken)??null,sourceName:Ue(e.sourceName)??null,countries:t,cartEnabled:e.cartEnabled}}(r):void 0,t)}catch{return Me(void 0,t)}}function Pe(e,t){const{countries:n,country:r,...s}=e,i=function(e,t){if(void 0===t||""===t)return;const n=t.toLowerCase(),[r]=n.split(/[\-_]/v,1),s=Object.entries(e),i=s.find(([e])=>e.toLowerCase()===n)??s.find(([e])=>e.toLowerCase()===r);return Ke(i?.[1])}(n,t)??r;return{...s,...void 0!==i&&{country:i}}}const Ve={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},He=Object.entries({$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"});function We(e,t){t||(t=new Map);for(const n of e)"in"in n?n.key&&t.set(n.key,{in:n.in,map:n.map}):"key"in n?t.set(n.key,{map:n.map}):n.args&&We(n.args,t);return t}function Ge(e,t){const n={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},r=We(t);function s(e,t,r){let s=n[e];void 0===s&&(s=Object.create(null),n[e]=s),s[t]=r}let i;for(const[o,a]of e.entries())if(t[o]&&(i=t[o]),i)if("in"in i)if(i.key){const e=r.get(i.key),t=e.map||i.key;e.in&&s(e.in,t,a)}else n.body=a;else for(const[e,t]of Object.entries(a??{})){const o=r.get(e);if(o)if(o.in){const n=o.map||e;s(o.in,n,t)}else n[o.map]=t;else{const n=He.find(([t])=>e.startsWith(t));if(n){const[r,i]=n;s(i,e.slice(r.length),t)}else if("allowExtra"in i&&i.allowExtra)for(const[n,r]of Object.entries(i.allowExtra))if(r){s(n,e,t);break}}}return function(e){for(const[t,n]of Object.entries(e))"body"!==t&&(!n||"object"!=typeof n||Array.isArray(n)||Object.keys(n).length||delete e[t])}(n),n}const Fe=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),o=s.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):Je({allowReserved:e,name:n,value:t})).join(i);return"label"===r||"matrix"===r?i+o:o},Je=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},Ye=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:i})=>{if(s instanceof Date)return i?s.toISOString():`${n}=${s.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(s).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const i=t.join(",");switch(r){case"form":return`${n}=${i}`;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return i}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(s).map(([t,s])=>Je({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+a:a},Qe=/\{[^{}]+\}/g,Ze=({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let i=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(i=(({path:e,url:t})=>{let n=t;const r=t.match(Qe);if(r)for(const t of r){let r=!1,s=t.substring(1,t.length-1),i="simple";s.endsWith("*")&&(r=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),i="label"):s.startsWith(";")&&(s=s.substring(1),i="matrix");const o=e[s];if(null==o)continue;if(Array.isArray(o)){n=n.replace(t,Fe({explode:r,name:s,style:i,value:o}));continue}if("object"==typeof o){n=n.replace(t,Ye({explode:r,name:s,style:i,value:o,valueOnly:!0}));continue}if("matrix"===i){n=n.replace(t,`;${Je({name:s,value:o})}`);continue}const a=encodeURIComponent("label"===i?`.${o}`:o);n=n.replace(t,a)}return n})({path:t,url:i}));let o=n?r(n):"";return o.startsWith("?")&&(o=o.substring(1)),o&&(i+=`?${o}`),i};function Xe(e){const t=void 0!==e.body;if(t&&e.bodySerializer){if("serializedBody"in e){return void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null}return""!==e.body?e.body:null}if(t)return e.body}const et=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},tt=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const s in n){const i=n[s];if(null==i)continue;const o=e[s]||t;if(Array.isArray(i)){const e=Fe({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:i,...o.array});e&&r.push(e)}else if("object"==typeof i){const e=Ye({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:i,...o.object});e&&r.push(e)}else{const e=Je({allowReserved:o.allowReserved,name:s,value:i});e&&r.push(e)}}return r.join("&")},nt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`));const rt=e=>Ze({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:tt(e.querySerializer),url:e.url}),st=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=ot(e.headers,t.headers),n},it=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},ot=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?it(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t};class at{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}}const ct=tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),ut={"Content-Type":"application/json"},dt=(e={})=>({...Ve,headers:ut,parseAs:"auto",querySerializer:ct,...e}),lt=(e={})=>{let t=st(dt(),e);const n=()=>({...t}),r={error:new at,request:new at,response:new at},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:ot(t.headers,e.headers),serializedBody:void 0};n.security&&await async function(e){for(const t of e.security??[]){if(nt(e,t.name))continue;const n=await et(t,e.auth);if(!n)continue;const r=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[r]=n;break;case"cookie":e.headers.append("Cookie",`${r}=${n}`);break;default:e.headers.set(r,n)}}}(n),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type");return{opts:n,url:rt(n)}},i=async e=>{const n=e.throwOnError??t.throwOnError,i=e.responseStyle??t.responseStyle;let o,a;try{const{opts:t,url:n}=await s(e),i={redirect:"follow",...t,body:Xe(t)};o=new Request(n,i);for(const e of r.request.fns)e&&(o=await e(o,t));const c=t.fetch;a=await c(o);for(const e of r.response.fns)e&&(a=await e(a,o,t));const u={request:o,response:a};if(a.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(a.headers.get("Content-Type")):t.parseAs)??"json";if(204===a.status||"0"===a.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await a[e]();break;case"formData":n=new FormData;break;case"stream":n=a.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...u}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"text":n=await a[e]();break;case"json":{const e=await a.text();n=e?JSON.parse(e):{};break}case"stream":return"data"===t.responseStyle?a.body:{data:a.body,...u}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...u}}const d=await a.text();let l;try{l=JSON.parse(d)}catch{}throw l??d}catch(t){let s=t;for(const t of r.error.fns)t&&(s=await t(s,a,o,e));if(s=s||{},n)throw s;return"data"===i?void 0:{error:s,request:o,response:a}}},o=e=>t=>i({...t,method:e}),a=e=>async t=>{const{opts:n,url:i}=await s(t);return function({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:i,sseMaxRetryAttempts:o,sseMaxRetryDelay:a,sseSleepFn:c,url:u,...d}){let l;const h=c??(e=>new Promise(t=>setTimeout(t,e))),y=async function*(){let c=i??3e3,y=0;const f=d.signal??(new AbortController).signal;for(;!f.aborted;){y++;const i=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==l&&i.set("Last-Event-ID",l);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:i,signal:f};let o=new Request(u,t);e&&(o=await e(u,t));const a=d.fetch??globalThis.fetch,h=await a(o);if(!h.ok)throw new Error(`SSE failed: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("No body in SSE response");const y=h.body.pipeThrough(new TextDecoderStream).getReader();let p="";const m=()=>{try{y.cancel()}catch{}};f.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await y.read();if(e)break;p+=t,p=p.replace(/\r\n?/g,"\n");const i=p.split("\n\n");p=i.pop()??"";for(const e of i){const t=e.split("\n"),i=[];let o,a;for(const e of t)if(e.startsWith("data:"))i.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))o=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))l=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let u=!1;if(i.length){const e=i.join("\n");try{a=JSON.parse(e),u=!0}catch{a=e}}u&&(s&&await s(a),r&&(a=await r(a))),n?.({data:a,event:o,id:l,retry:c}),i.length&&(yield a)}}}finally{f.removeEventListener("abort",m),y.releaseLock()}break}catch(e){if(t?.(e),void 0!==o&&y>=o)break;const n=Math.min(c*2**(y-1),a??3e4);await h(n)}}}();return{stream:y}}({...n,body:n.body,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of r.request.fns)e&&(s=await e(s,n));return s},serializedBody:Xe(n),url:i})};return{buildUrl:e=>rt({...t,...e}),connect:o("CONNECT"),delete:o("DELETE"),get:o("GET"),getConfig:n,head:o("HEAD"),interceptors:r,options:o("OPTIONS"),patch:o("PATCH"),post:o("POST"),put:o("PUT"),request:i,setConfig:e=>(t=st(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:o("TRACE")}};class ht{client;constructor(e){this.client=e.client}}class yt{defaultKey="default";instances=new Map;get(e){const t=this.instances.get(e??this.defaultKey);if(!t)throw new Error('No SDK client found. Create one with "new CallimacusApi()" to fix this error.');return t}set(e,t){this.instances.set(t??this.defaultKey,e)}}class ft extends ht{getPage(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/page/{language}/{id}",...t,...n})}listTopics(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}",...t,...n})}getTopicContents(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"idOrSlug"},{in:"query",key:"offset"},{in:"query",key:"limit"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}/{idOrSlug}",...t,...n})}getDocumentBySlug(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"slug"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/{language}/{slug}",...t,...n})}getDocumentByGroup(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"},{in:"path",key:"groupId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-group/{language}/{groupId}",...t,...n})}getDocumentByPath(e,t){const n=Ge([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-path",...t,...n})}listDocuments(e,t){const n=Ge([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/documents/{language}",...t,...n})}}class pt extends ht{getShared(e,t){const n=Ge([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}share(e,t){const n=Ge([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}}class mt extends ht{getSimilar(e,t){const n=Ge([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"topK"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/similar",...t,...n})}getRecommendations(e,t){const n=Ge([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/recommendations",...t,...n})}}class gt extends ht{getLast(e,t){const n=Ge([e],[{args:[{in:"query",key:"storyId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/whisper",...t,...n})}}class vt extends ht{trackEvent(e,t){const n=Ge([e],[{args:[{in:"body",key:"storyId"},{in:"body",key:"eventName"},{in:"body",key:"content"},{in:"body",key:"payload"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/track-event",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class bt extends ht{getCart(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart",...e})}addItemToCart(e,t){const n=Ge([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/add",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}removeItemFromCart(e,t){const n=Ge([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/remove",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}updateProductQuantity(e,t){const n=Ge([e],[{args:[{in:"body",key:"productId"},{in:"body",key:"quantity"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/update",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class kt extends ht{getStorefrontSettings(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/shopify/storefront",...e})}}class wt extends ht{similar(e,t){const n=Ge([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"topK"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/similar",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}related(e,t){const n=Ge([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/related",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}getItemByPath(e,t){const n=Ge([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/item/by-path",...t,...n})}}class Rt extends ht{static __registry=new yt;constructor(e){super(e),Rt.__registry.set(this,e.key)}_content;get content(){return this._content??=new ft({client:this.client})}_stories;get stories(){return this._stories??=new pt({client:this.client})}_products;get products(){return this._products??=new mt({client:this.client})}_whisper;get whisper(){return this._whisper??=new gt({client:this.client})}_analytics;get analytics(){return this._analytics??=new vt({client:this.client})}_cart;get cart(){return this._cart??=new bt({client:this.client})}_shopify;get shopify(){return this._shopify??=new kt({client:this.client})}_skesis;get skesis(){return this._skesis??=new wt({client:this.client})}}class Tt extends Error{status;body;response;request;constructor(e,t,n){const r=t?.status,s=n?`${n.method} ${n.url}`:"request";let i=`[thamyr] ${s} failed before a response arrived`;t&&(i=t.ok?`[thamyr] ${s} → ${t.status}, but the response could not be processed`:`[thamyr] ${s} → ${t.status}`),super(i,e instanceof Error?{cause:e}:void 0),this.name="ThamyrHttpError",this.status=r,this.body=e,this.response=t,this.request=n}}function St(e){const t=lt(dt({baseUrl:new URL("api/v3",e.endpoint).href,headers:{Authorization:`Bearer ${e.accessToken}`,"x-sl-access-token":e.accessToken},credentials:e.withCredentials?"include":"same-origin"}));return t.interceptors.error.use((e,n,r,s)=>{if(!(s.throwOnError??t.getConfig().throwOnError??!1)||!0===s.signal?.aborted)return e;return new Tt(""===e?{}:e??{},n,r)}),t}export{B as ACTION_TYPES,$ as ADD_TO_CART_RESULT_BLOCK,Rt as CallimacusApi,p as CallimacusEvent,S as CallimacusService,o as ChapterStatus,r as ClientEvents,Y as DELIVER_RESULT_BLOCK,i as GalleryMode,I as LANDING_VALUE_MAX_LENGTH,w as MAX_HANDSHAKE_RETRIES,s as SLInputEventType,ne as STOREFRONT_API_VERSION,n as ServerEvents,Tt as ThamyrHttpError,t as ThamyrResponseType,f as UserInteractionType,F as actionOf,N as addToCartResultOf,L as applyBlockPatch,x as blockKeyOf,E as callimacusService,Pe as cartSettingsFor,T as classifyConnectError,St as createContractClient,qe as createPageStorage,Ne as createShopifyCart,te as deliverResultOf,g as extractTtsAudio,J as fieldsOf,O as interactionRound,a as isCustomBlock,u as isMasterProduct,c as isSetProduct,we as isVariantGid,C as landingRound,l as logger,Me as mergeShopifySettings,k as parseConnectRejection,K as parseMapPath,y as randomUuid,Be as readShopifySettings,A as receptorsOf,M as resolveMapPage,R as shouldRetryHandshake,h as transformImageUrl};
9
9
  //# sourceMappingURL=index.js.map