@salla.sa/embedded-sdk 0.2.4 → 0.2.5
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/README.md +2 -2
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/index.js +300 -191
- package/dist/esm/index.js.map +1 -1
- package/dist/system/index.js +2 -2
- package/dist/system/index.js.map +1 -1
- package/dist/types/index.d.ts +111 -18
- package/dist/umd/index.js +2 -2
- package/dist/umd/index.js.map +1 -1
- package/package.json +18 -24
package/README.md
CHANGED
|
@@ -66,9 +66,9 @@ bootstrap();
|
|
|
66
66
|
The SDK provides modules for authentication, UI components, navigation, and page management:
|
|
67
67
|
|
|
68
68
|
- **Auth**: `getToken()`, `getAppId()`, `refresh()`, `introspect()`
|
|
69
|
-
- **UI**: `loading`, `toast`, `modal`, `confirm`
|
|
69
|
+
- **UI**: `loading`, `breadcrumbs`, `toast`, `modal`, `confirm`
|
|
70
70
|
- **Page**: `setTitle()`, `navigate()`, `redirect()`
|
|
71
|
-
- **Nav**: `setAction()`, `onActionClick()`, `clearAction()`
|
|
71
|
+
- **Nav**: `setAction()`, `onActionClick()`, `clearAction()`, `addNavItem()`, `updateNavItem()`, `removeNavItem()`, `onNavItemClick()`
|
|
72
72
|
- **Checkout**: `getAddons()`, `create()`, `onResult()`
|
|
73
73
|
|
|
74
74
|
## TypeScript
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o="embedded::",$={INIT:`${o}iframe.ready`,READY:`${o}ready`,DESTROY:`${o}destroy`},L={PROVIDE:`${o}context.provide`,THEME_CHANGE:`${o}theme.change`},g={LOADING:`${o}ui.loading`,TOAST:`${o}ui.toast`,CONFIRM:`${o}ui.confirm`,CONFIRM_RESPONSE:`${o}ui.confirm.response`},X={},V={REFRESH:`${o}auth.refresh`},p={NAVIGATE:`${o}page.navigate`,REDIRECT:`${o}page.redirect`,SET_TITLE:`${o}page.setTitle`},w={SET_ACTION:`${o}nav.setAction`,CLEAR_ACTION:`${o}nav.clearAction`,ACTION_CLICK:`${o}nav.actionClick`},m={CREATE:`${o}checkout.create`,RESPONSE:`${o}checkout.response`,GET_ADDONS:`${o}checkout.getAddons`,GET_ADDONS_RESPONSE:`${o}checkout.getAddons.response`},I=X.version||"",W=1e4,Y=["localhost","merchants.workers.dev","s.salla.sa",".salla.group",".salla.sa"];let S={showVersion:!0,debug:!1};function B(t){S={...S,...t}}function k(t){return`%c${t}`}function q(t,e="#fff"){return`background-color: ${t}; color: ${e}; padding: 2px 6px; border-radius: 3px; font-weight: 500; font-size: 11px;`}function b(t,...e){if(t==="debug"&&!S.debug)return;const r=[],i=[];r.push(k("EmbeddedSDK")),i.push(q("#10b981","#fff")),S.showVersion&&(r.push(k(`v${I}`)),i.push(q("#6b7280","#fff")));const n=r.join("").trim();(console[t]||console.log)(n,...i,...e)}const a={log:(...t)=>{b("log",...t)},warn:(...t)=>{b("warn",...t)},error:(...t)=>{b("error",...t)},info:(...t)=>{b("info",...t)},debug:(...t)=>{b("debug",...t)}};function Q(t){try{const r=new URL(t).hostname;return Y.some(i=>i.startsWith(".")?r.endsWith(i)||r===i.slice(1):r===i||r.startsWith(`${i}:`))}catch{return!1}}function J(){return typeof window>"u"||window.parent===window?null:window.parent}function c(t,e,r="*",i,n){const s=J();if(!s){a.warn("Not running in an iframe, cannot post to host");return}const u={event:t,payload:e||{},timestamp:Date.now(),source:"embedded-app",...i&&{requestId:i},metadata:{version:I}};s.postMessage(u,r)}const l=new Map;let A=!1;function j(t){if(process.env.NODE_ENV==="production"&&!Q(t.origin))return;const e=t.data;if(!e||typeof e.event!="string"||!e.payload||typeof e.timestamp!="number"||!e.source){a.warn("Invalid message structure received:",e);return}const r=l.get(e.event);r&&r.forEach(n=>{try{n(e)}catch(s){a.error("Error in message handler:",s)}});const i=l.get("*");i&&i.forEach(n=>{try{n(e)}catch(s){a.error("Error in wildcard handler:",s)}})}function Z(){A||typeof window>"u"||(window.addEventListener("message",j),A=!0)}function y(t,e){Z(),l.has(t)||l.set(t,new Set);const r=l.get(t);return r.add(e),()=>{r.delete(e),r.size===0&&l.delete(t)}}function ee(t,e=W){return new Promise((r,i)=>{const n=setTimeout(()=>{s(),i(new Error(`[EmbeddedSDK] Timeout waiting for "${t}" message`))},e),s=y(t,u=>{clearTimeout(n),s(),r(u)})})}function te(){l.clear(),A&&typeof window<"u"&&(window.removeEventListener("message",j),A=!1)}function re(){return typeof window>"u"?!1:window.parent!==window}function ie(t,e,r){const i={event:t,payload:e,timestamp:Date.now(),source:"merchant-dashboard",...r,metadata:{version:I,synthetic:!0}},n=l.get(t);n==null||n.forEach(s=>{try{s(i)}catch(u){a.error("Error in message handler:",u)}})}const f=new Map,ne=3e4;function F(){const t=Date.now(),e=Math.random().toString(36).slice(2,9);return`req_${t}_${e}`}function H(t,e={},r=ne){const i=F();return new Promise((n,s)=>{const u=setTimeout(()=>{f.get(i)&&(f.delete(i),s(new Error(`[EmbeddedSDK] Request "${t}" timed out after ${r}ms`)))},r);f.set(i,{resolve:n,reject:s,timeout:u,event:t}),c(t,e,"*",i)})}function G(t,e,r){const i=f.get(t);if(!i){a.warn(`Received response for unknown request: ${t}`);return}clearTimeout(i.timeout),f.delete(t),i.resolve(e)}function se(t="SDK cleanup"){f.forEach((e,r)=>{clearTimeout(e.timeout),e.reject(new Error(`[EmbeddedSDK] Request ${r} cancelled: ${t}`))}),f.clear()}function R(){const t=new Set;return{subscribe(e){return t.add(e),()=>{t.delete(e)}},notify(...e){t.forEach(r=>{try{r(...e)}catch(i){a.error("Error in subscription callback:",i)}})},clear(){t.clear()},size(){return t.size}}}const ae="https://api.salla.dev";class T extends Error{constructor(e,r,i){super(e),this.status=r,this.response=i,this.name="ApiError"}}async function oe(t,e={}){const{method:r="GET",headers:i={},body:n,timeout:s=3e4}=e,u=`${ae}${t}`,N=new AbortController,D=setTimeout(()=>{N.abort()},s);try{const d=await fetch(u,{method:r,headers:{"Content-Type":"application/json",...i},body:n?JSON.stringify(n):void 0,signal:N.signal});clearTimeout(D);let v;const C=d.headers.get("content-type");if(C!=null&&C.includes("application/json")?v=await d.json():v=await d.text(),!d.ok)throw new T(`API request failed: ${d.statusText}`,d.status,v);return v}catch(d){throw clearTimeout(D),d instanceof T?d:d instanceof Error?d.name==="AbortError"?new T(`Request timeout after ${s}ms`):new T(`Request failed: ${d.message}`):new T("Unknown error occurred")}}function O(t){return{isVerified:!1,isError:!0,error:t,data:null}}async function ue(t){const{token:e,appId:r,refreshOnError:i=!0}=t;if(!e){const n="Token is required. Provide it as a parameter or in URL as ?token=XXX";return a.error("Error in introspect:",n),O(n)}if(!r){const n="App ID is required. Provide it as a parameter or in URL as ?app_id=XXX";return a.error("Error in introspect:",n),O(n)}try{const n=await oe("/exchange-authority/v1/introspect",{method:"POST",headers:{"S-Source":r,"Content-Type":"application/json"},body:{env:"prod",token:e,iss:"merchant-dashboard",subject:"embedded-page"}}),s=n.success;return{isVerified:s,isError:!s,error:s?void 0:"API request failed",data:s?n.data:null}}catch(n){i&&(x().ui.toast.error((n==null?void 0:n.toString())??"Introspect error"),c(V.REFRESH,{})),a.error("Error in introspect:",n);const s=n instanceof Error?n.message:n;return O(s)}}function ce(t){return{getToken(){return new URLSearchParams(window.location.search).get("token")},getAppId(){return new URLSearchParams(window.location.search).get("app_id")},refresh(){c(V.REFRESH,{})},async introspect(e={}){const r=e.token??this.getToken()??"",i=e.appId??this.getAppId()??"";return ue({token:r,appId:i,refreshOnError:e.refreshOnError})}}}const M=["success","error","warning","info"];function de(t){const e=[];return t.type===void 0||t.type===null?e.push("Toast type is required"):(typeof t.type!="string"||!M.includes(t.type))&&e.push(`Invalid toast type "${t.type}". Expected: ${M.join(" | ")}`),t.message===void 0||t.message===null?e.push("Toast message is required"):typeof t.message!="string"?e.push("Toast message must be a string"):t.message.trim()===""&&e.push("Toast message cannot be empty"),t.duration!==void 0&&t.duration!==null&&(typeof t.duration!="number"?e.push("Toast duration must be a number"):t.duration<0&&e.push("Toast duration cannot be negative")),{valid:e.length===0,errors:e}}function z(t,e){const r=[];return typeof t!="object"||t===null?(r.push(`${e} must be an object`),r):((typeof t.type!="string"||t.type.trim()==="")&&r.push(`${e} must have a valid type`),(typeof t.slug!="string"||t.slug.trim()==="")&&r.push(`${e} must have a valid slug`),t.quantity!==void 0&&(typeof t.quantity!="number"||t.quantity<1)&&r.push(`${e} must have a quantity >= 1`),r)}function le(t){const e=[];if(typeof t!="object"||t===null)return e.push("Checkout options must be an object"),{valid:!1,errors:e};const r="item"in t,i="items"in t;if(!r&&!i)return e.push("Checkout requires either 'item' or 'items'"),{valid:!1,errors:e};if(r){const n=z(t.item,"Item");return e.push(...n),{valid:e.length===0,errors:e}}return Array.isArray(t.items)?t.items.length===0?(e.push("At least one item is required"),{valid:!1,errors:e}):(t.items.forEach((n,s)=>{const u=z(n,`Item at index ${s}`);e.push(...u)}),{valid:e.length===0,errors:e}):(e.push("Checkout items must be an array"),{valid:!1,errors:e})}function fe(t){const e=[];return t.path===void 0||t.path===null?e.push("Navigation path is required"):typeof t.path!="string"?e.push("Navigation path must be a string"):t.path.trim()===""&&e.push("Navigation path cannot be empty"),t.replace!==void 0&&typeof t.replace!="boolean"&&e.push("Navigation replace option must be a boolean"),{valid:e.length===0,errors:e}}function he(t){const e=[];if(t.url===void 0||t.url===null)e.push("Redirect URL is required");else if(typeof t.url!="string")e.push("Redirect URL must be a string");else if(t.url.trim()==="")e.push("Redirect URL cannot be empty");else try{new URL(t.url)}catch{e.push(`Invalid redirect URL: "${t.url}"`)}return{valid:e.length===0,errors:e}}function ge(t){const e=[];return t.title?typeof t.title!="string"&&e.push("Nav action title must be a string"):e.push("Nav action title is required"),t.value?typeof t.value!="string"&&e.push("Nav action value must be a string"):e.push("Nav action value is required"),t.subTitle!==void 0&&t.subTitle!==null&&typeof t.subTitle!="string"&&e.push("Nav action subTitle must be a string"),t.icon!==void 0&&t.icon!==null&&typeof t.icon!="string"&&e.push("Nav action icon must be a string"),t.disabled!==void 0&&t.disabled!==null&&typeof t.disabled!="boolean"&&e.push("Nav action disabled must be a boolean"),t.extendedActions!==void 0&&t.extendedActions!==null&&(Array.isArray(t.extendedActions)?t.extendedActions.forEach((r,i)=>{if(typeof r!="object"||r===null){e.push(`Extended action at index ${i} must be an object`);return}const n=r;(!n.title||typeof n.title!="string")&&e.push(`Extended action at index ${i} is missing required "title" property`),(!n.value||typeof n.value!="string")&&e.push(`Extended action at index ${i} is missing required "value" property`),n.subTitle!==void 0&&typeof n.subTitle!="string"&&e.push(`Extended action at index ${i} subTitle must be a string`),n.icon!==void 0&&typeof n.icon!="string"&&e.push(`Extended action at index ${i} icon must be a string`),n.disabled!==void 0&&typeof n.disabled!="boolean"&&e.push(`Extended action at index ${i} disabled must be a boolean`)}):e.push("Nav action extendedActions must be an array")),{valid:e.length===0,errors:e}}const P=["danger","warning","info"];function pe(t){const e=[];return t.title===void 0||t.title===null?e.push("Confirm dialog title is required"):typeof t.title!="string"?e.push("Confirm dialog title must be a string"):t.title.trim()===""&&e.push("Confirm dialog title cannot be empty"),t.message===void 0||t.message===null?e.push("Confirm dialog message is required"):typeof t.message!="string"?e.push("Confirm dialog message must be a string"):t.message.trim()===""&&e.push("Confirm dialog message cannot be empty"),t.confirmText!==void 0&&t.confirmText!==null&&typeof t.confirmText!="string"&&e.push("Confirm dialog confirmText must be a string"),t.cancelText!==void 0&&t.cancelText!==null&&typeof t.cancelText!="string"&&e.push("Confirm dialog cancelText must be a string"),t.variant!==void 0&&t.variant!==null&&(typeof t.variant!="string"||!P.includes(t.variant))&&e.push(`Invalid confirm variant "${t.variant}". Expected: ${P.join(" | ")}`),{valid:e.length===0,errors:e}}function h(t,e){a.error(`Validation failed for ${t}:
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o="embedded::",C={INIT:`${o}iframe.ready`,READY:`${o}ready`,DESTROY:`${o}destroy`},x={PROVIDE:`${o}context.provide`,THEME_CHANGE:`${o}theme.change`},h={LOADING:`${o}ui.loading`,BREADCRUMBS:`${o}ui.breadcrumbs`,TOAST:`${o}ui.toast`,CONFIRM:`${o}ui.confirm`,CONFIRM_RESPONSE:`${o}ui.confirm.response`},K={},j={REFRESH:`${o}auth.refresh`},E={NAVIGATE:`${o}page.navigate`,REDIRECT:`${o}page.redirect`,SET_TITLE:`${o}page.setTitle`},l={SET_ACTION:`${o}nav.setAction`,CLEAR_ACTION:`${o}nav.clearAction`,ACTION_CLICK:`${o}nav.actionClick`,ADD_ITEM:`${o}nav.addItem`,ADD_ITEM_RESPONSE:`${o}nav.addItem.response`,UPDATE_ITEM:`${o}nav.updateItem`,REMOVE_ITEM:`${o}nav.removeItem`,ITEM_CLICK:`${o}nav.itemClick`},g={CREATE:`${o}checkout.create`,RESPONSE:`${o}checkout.response`,GET_ADDONS:`${o}checkout.getAddons`,GET_ADDONS_RESPONSE:`${o}checkout.getAddons.response`,RESET_CACHE:`${o}checkout.resetCache`},R=K.version||"",B=1e4,X=["localhost","merchants.workers.dev","s.salla.sa",".salla.group",".salla.sa"],W=new Set(["ar","he","fa","ur","ps","sd","yi"]);function Y(t){const e=(t??"ar").toLowerCase().split(/[-_]/)[0];return W.has(e)?"rtl":"ltr"}let S={showVersion:!0,debug:!1};function Q(t){S={...S,...t}}function k(t){return`%c${t}`}function q(t,e="#fff"){return`background-color: ${t}; color: ${e}; padding: 2px 6px; border-radius: 3px; font-weight: 500; font-size: 11px;`}function y(t,...e){if(t==="debug"&&!S.debug)return;const r=[],i=[];r.push(k("EmbeddedSDK")),i.push(q("#10b981","#fff")),S.showVersion&&(r.push(k(`v${R}`)),i.push(q("#6b7280","#fff")));const n=r.join("").trim();(console[t]||console.log)(n,...i,...e)}const a={log:(...t)=>{y("log",...t)},warn:(...t)=>{y("warn",...t)},error:(...t)=>{y("error",...t)},info:(...t)=>{y("info",...t)},debug:(...t)=>{y("debug",...t)}};function J(t){try{const r=new URL(t).hostname;return X.some(i=>i.startsWith(".")?r.endsWith(i)||r===i.slice(1):r===i||r.startsWith(`${i}:`))}catch{return!1}}function Z(){return typeof window>"u"||window.parent===window?null:window.parent}function u(t,e,r="*",i,n){const s=Z();if(!s){a.warn("Not running in an iframe, cannot post to host");return}const d={event:t,payload:e||{},timestamp:Date.now(),source:"embedded-app",...i&&{requestId:i},metadata:{version:R}};s.postMessage(d,r)}const p=new Map;let A=!1;function F(t){if(process.env.NODE_ENV==="production"&&!J(t.origin))return;const e=t.data;if(!e||typeof e.event!="string"||!e.payload||typeof e.timestamp!="number"||!e.source){a.warn("Invalid message structure received:",e);return}const r=p.get(e.event);r&&r.forEach(n=>{try{n(e)}catch(s){a.error("Error in message handler:",s)}});const i=p.get("*");i&&i.forEach(n=>{try{n(e)}catch(s){a.error("Error in wildcard handler:",s)}})}function ee(){A||typeof window>"u"||(window.addEventListener("message",F),A=!0)}function m(t,e){ee(),p.has(t)||p.set(t,new Set);const r=p.get(t);return r.add(e),()=>{r.delete(e),r.size===0&&p.delete(t)}}function te(t,e=B){return new Promise((r,i)=>{const n=setTimeout(()=>{s(),i(new Error(`[EmbeddedSDK] Timeout waiting for "${t}" message`))},e),s=m(t,d=>{clearTimeout(n),s(),r(d)})})}function re(){p.clear(),A&&typeof window<"u"&&(window.removeEventListener("message",F),A=!1)}function ie(){return typeof window>"u"?!1:window.parent!==window}function ne(t,e,r){const i={event:t,payload:e,timestamp:Date.now(),source:"merchant-dashboard",...r,metadata:{version:R,synthetic:!0}};p.get(t)?.forEach(s=>{try{s(i)}catch(d){a.error("Error in message handler:",d)}})}const b=new Map,se=3e4;function H(){const t=Date.now(),e=Math.random().toString(36).slice(2,9);return`req_${t}_${e}`}function D(t,e={},r=se){const i=H();return new Promise((n,s)=>{const d=setTimeout(()=>{b.get(i)&&(b.delete(i),s(new Error(`[EmbeddedSDK] Request "${t}" timed out after ${r}ms`)))},r);b.set(i,{resolve:n,reject:s,timeout:d,event:t}),u(t,e,"*",i)})}function M(t,e,r){const i=b.get(t);if(!i){a.warn(`Received response for unknown request: ${t}`);return}clearTimeout(i.timeout),b.delete(t),i.resolve(e)}function ae(t="SDK cleanup"){b.forEach((e,r)=>{clearTimeout(e.timeout),e.reject(new Error(`[EmbeddedSDK] Request ${r} cancelled: ${t}`))}),b.clear()}function w(){const t=new Set;return{subscribe(e){return t.add(e),()=>{t.delete(e)}},notify(...e){t.forEach(r=>{try{r(...e)}catch(i){a.error("Error in subscription callback:",i)}})},clear(){t.clear()},size(){return t.size}}}const oe="https://api.salla.dev";class T extends Error{constructor(e,r,i){super(e),this.status=r,this.response=i,this.name="ApiError"}}async function ue(t,e={}){const{method:r="GET",headers:i={},body:n,timeout:s=3e4}=e,d=`${oe}${t}`,N=new AbortController,L=setTimeout(()=>{N.abort()},s);try{const c=await fetch(d,{method:r,headers:{"Content-Type":"application/json",...i},body:n?JSON.stringify(n):void 0,signal:N.signal});clearTimeout(L);let I;if(c.headers.get("content-type")?.includes("application/json")?I=await c.json():I=await c.text(),!c.ok)throw new T(`API request failed: ${c.statusText}`,c.status,I);return I}catch(c){throw clearTimeout(L),c instanceof T?c:c instanceof Error?c.name==="AbortError"?new T(`Request timeout after ${s}ms`):new T(`Request failed: ${c.message}`):new T("Unknown error occurred")}}function _(t){return{isVerified:!1,isError:!0,error:t,data:null}}async function de(t){const{token:e,appId:r,refreshOnError:i=!0}=t;if(!e){const n="Token is required. Provide it as a parameter or in URL as ?token=XXX";return a.error("Error in introspect:",n),_(n)}if(!r){const n="App ID is required. Provide it as a parameter or in URL as ?app_id=XXX";return a.error("Error in introspect:",n),_(n)}try{const n=await ue("/exchange-authority/v1/introspect",{method:"POST",headers:{"S-Source":r,"Content-Type":"application/json"},body:{env:"prod",token:e,iss:"merchant-dashboard",subject:"embedded-page"}}),s=n.success;return{isVerified:s,isError:!s,error:s?void 0:"API request failed",data:s?n.data:null}}catch(n){i&&(O().ui.toast.error(n?.toString()??"Introspect error"),u(j.REFRESH,{})),a.error("Error in introspect:",n);const s=n instanceof Error?n.message:n;return _(s)}}function ce(t){return{getToken(){return new URLSearchParams(window.location.search).get("token")},getAppId(){return new URLSearchParams(window.location.search).get("app_id")},refresh(){u(j.REFRESH,{})},async introspect(e={}){const r=e.token??this.getToken()??"",i=e.appId??this.getAppId()??"";return de({token:r,appId:i,refreshOnError:e.refreshOnError})}}}const P=["success","error","warning","info"];function le(t){const e=[];return t.type===void 0||t.type===null?e.push("Toast type is required"):(typeof t.type!="string"||!P.includes(t.type))&&e.push(`Invalid toast type "${t.type}". Expected: ${P.join(" | ")}`),t.message===void 0||t.message===null?e.push("Toast message is required"):typeof t.message!="string"?e.push("Toast message must be a string"):t.message.trim()===""&&e.push("Toast message cannot be empty"),t.duration!==void 0&&t.duration!==null&&(typeof t.duration!="number"?e.push("Toast duration must be a number"):t.duration<0&&e.push("Toast duration cannot be negative")),{valid:e.length===0,errors:e}}function z(t,e){const r=[];return typeof t!="object"||t===null?(r.push(`${e} must be an object`),r):((typeof t.type!="string"||t.type.trim()==="")&&r.push(`${e} must have a valid type`),(typeof t.slug!="string"||t.slug.trim()==="")&&r.push(`${e} must have a valid slug`),t.quantity!==void 0&&(typeof t.quantity!="number"||t.quantity<1)&&r.push(`${e} must have a quantity >= 1`),r)}function fe(t){const e=[];if(typeof t!="object"||t===null)return e.push("Checkout options must be an object"),{valid:!1,errors:e};const r="item"in t,i="items"in t;if(!r&&!i)return e.push("Checkout requires either 'item' or 'items'"),{valid:!1,errors:e};if(r){const n=z(t.item,"Item");return e.push(...n),{valid:e.length===0,errors:e}}return Array.isArray(t.items)?t.items.length===0?(e.push("At least one item is required"),{valid:!1,errors:e}):(t.items.forEach((n,s)=>{const d=z(n,`Item at index ${s}`);e.push(...d)}),{valid:e.length===0,errors:e}):(e.push("Checkout items must be an array"),{valid:!1,errors:e})}function he(t){const e=[];return t.path===void 0||t.path===null?e.push("Navigation path is required"):typeof t.path!="string"?e.push("Navigation path must be a string"):t.path.trim()===""&&e.push("Navigation path cannot be empty"),t.replace!==void 0&&typeof t.replace!="boolean"&&e.push("Navigation replace option must be a boolean"),{valid:e.length===0,errors:e}}function pe(t){const e=[];if(t.url===void 0||t.url===null)e.push("Redirect URL is required");else if(typeof t.url!="string")e.push("Redirect URL must be a string");else if(t.url.trim()==="")e.push("Redirect URL cannot be empty");else try{new URL(t.url)}catch{e.push(`Invalid redirect URL: "${t.url}"`)}return{valid:e.length===0,errors:e}}function me(t){const e=[];return t.title?typeof t.title!="string"&&e.push("Nav action title must be a string"):e.push("Nav action title is required"),t.value?typeof t.value!="string"&&e.push("Nav action value must be a string"):e.push("Nav action value is required"),t.subTitle!==void 0&&t.subTitle!==null&&typeof t.subTitle!="string"&&e.push("Nav action subTitle must be a string"),t.icon!==void 0&&t.icon!==null&&typeof t.icon!="string"&&e.push("Nav action icon must be a string"),t.disabled!==void 0&&t.disabled!==null&&typeof t.disabled!="boolean"&&e.push("Nav action disabled must be a boolean"),t.extendedActions!==void 0&&t.extendedActions!==null&&(Array.isArray(t.extendedActions)?t.extendedActions.forEach((r,i)=>{if(typeof r!="object"||r===null){e.push(`Extended action at index ${i} must be an object`);return}const n=r;(!n.title||typeof n.title!="string")&&e.push(`Extended action at index ${i} is missing required "title" property`),(!n.value||typeof n.value!="string")&&e.push(`Extended action at index ${i} is missing required "value" property`),n.subTitle!==void 0&&typeof n.subTitle!="string"&&e.push(`Extended action at index ${i} subTitle must be a string`),n.icon!==void 0&&typeof n.icon!="string"&&e.push(`Extended action at index ${i} icon must be a string`),n.disabled!==void 0&&typeof n.disabled!="boolean"&&e.push(`Extended action at index ${i} disabled must be a boolean`)}):e.push("Nav action extendedActions must be an array")),{valid:e.length===0,errors:e}}function ge(t){const e=[];if(typeof t!="object"||t===null)return e.push("Nav addItem expects an object item"),{valid:!1,errors:e};const r=t;return["title","value","url"].forEach(i=>{(typeof r[i]!="string"||!String(r[i]).trim())&&e.push(`Sub-nav addItem "${i}" must be non-empty string`)}),r.disabled!==void 0&&typeof r.disabled!="boolean"&&e.push('Sub-nav addItem "disabled" must be boolean'),r.active!==void 0&&typeof r.active!="boolean"&&e.push('Sub-nav addItem "active" must be boolean'),{valid:e.length===0,errors:e}}function be(t){const e=[];if(typeof t!="object"||t===null)return e.push("Nav updateItem expects an object item"),{valid:!1,errors:e};const r=t;if(typeof r.id!="string"||!r.id.trim())return e.push('Sub-nav updateItem requires string "id"'),{valid:!1,errors:e};let i=0;return r.title!==void 0&&i++,r.value!==void 0&&i++,r.url!==void 0&&i++,r.disabled!==void 0&&i++,r.active!==void 0&&i++,i===0?(e.push("Sub-nav updateItem must include at least one of title, value, url, disabled, active"),{valid:!1,errors:e}):(["title","value","url"].forEach(n=>{r[n]!==void 0&&(typeof r[n]!="string"||!r[n].trim())&&e.push(`Sub-nav updateItem "${n}" must be non-empty`)}),r.disabled!==void 0&&typeof r.disabled!="boolean"&&e.push('Sub-nav updateItem "disabled" must be boolean'),r.active!==void 0&&typeof r.active!="boolean"&&e.push('Sub-nav updateItem "active" must be boolean'),{valid:e.length===0,errors:e})}function Ee(t){const e=[];return(typeof t!="string"||!t.trim())&&e.push("Nav removeItem id must be non-empty string"),{valid:e.length===0,errors:e}}const U=["danger","warning","info"];function ve(t){const e=[];return t.title===void 0||t.title===null?e.push("Confirm dialog title is required"):typeof t.title!="string"?e.push("Confirm dialog title must be a string"):t.title.trim()===""&&e.push("Confirm dialog title cannot be empty"),t.message===void 0||t.message===null?e.push("Confirm dialog message is required"):typeof t.message!="string"?e.push("Confirm dialog message must be a string"):t.message.trim()===""&&e.push("Confirm dialog message cannot be empty"),t.confirmText!==void 0&&t.confirmText!==null&&typeof t.confirmText!="string"&&e.push("Confirm dialog confirmText must be a string"),t.cancelText!==void 0&&t.cancelText!==null&&typeof t.cancelText!="string"&&e.push("Confirm dialog cancelText must be a string"),t.variant!==void 0&&t.variant!==null&&(typeof t.variant!="string"||!U.includes(t.variant))&&e.push(`Invalid confirm variant "${t.variant}". Expected: ${U.join(" | ")}`),{valid:e.length===0,errors:e}}function f(t,e){a.error(`Validation failed for ${t}:
|
|
2
2
|
`+e.map(r=>` • ${r}`).join(`
|
|
3
|
-
`))}function
|
|
3
|
+
`))}function ye(){return{resize:i=>{},autoResize:()=>{},stopAutoResize:()=>{}}}function Te(){const{resize:t,autoResize:e,stopAutoResize:r}=ye();return{navigate(i,n){const s=he({path:i,...n});if(!s.valid){f(E.NAVIGATE,s.errors);return}u(E.NAVIGATE,{path:i,state:n?.state,replace:n?.replace})},redirect(i){const n=pe({url:i});if(!n.valid){f(E.REDIRECT,n.errors);return}u(E.REDIRECT,{url:i})},navTo(i,n){if(i.startsWith("http://")||i.startsWith("https://")){this.redirect(i);return}this.navigate(i,n)},setTitle(i){if(typeof i!="string"||!i.trim()){f(E.SET_TITLE,["Title must be a non-empty string"]);return}u(E.SET_TITLE,{title:i})},resize:t,autoResize:e,stopAutoResize:r}}function we(){const t=w(),e=w(),r=[];return r.push(m(l.ACTION_CLICK,i=>{t.notify(i.payload.value)})),r.push(m(l.ADD_ITEM_RESPONSE,i=>{const n=i.payload.item;i.requestId&&n&&typeof n.id=="string"&&typeof n.value=="string"&&M(i.requestId,n)})),r.push(m(l.ITEM_CLICK,i=>{e.notify(i.payload)})),{setAction(i){const n=me(i);if(!n.valid){f(l.SET_ACTION,n.errors);return}u(l.SET_ACTION,{title:i.title,value:i.value,subTitle:i.subTitle,icon:i.icon,disabled:i.disabled,extendedActions:i.extendedActions?.map(s=>({title:s.title,value:s.value,subTitle:s.subTitle,icon:s.icon,disabled:s.disabled}))})},clearAction(){u(l.CLEAR_ACTION,{})},onActionClick(i){return t.subscribe(i)},addNavItem(i){const n=ge(i);return n.valid?D(l.ADD_ITEM,{item:i},2e3):(f(l.ADD_ITEM,n.errors),Promise.reject(new Error(n.errors[0])))},updateNavItem(i){const n=be(i);if(!n.valid){f(l.UPDATE_ITEM,n.errors);return}u(l.UPDATE_ITEM,{item:i})},removeNavItem(i){const n=Ee(i);if(!n.valid){f(l.REMOVE_ITEM,n.errors);return}u(l.REMOVE_ITEM,{id:i})},onNavItemClick(i){return e.subscribe(i)},destroy(){r.forEach(i=>i()),r.length=0,t.clear(),e.clear()}}}function Ie(){return{show(){u(h.LOADING,{action:"show"})},hide(){u(h.LOADING,{action:"hide"})}}}function Se(){return{hide(){u(h.BREADCRUMBS,{action:"hide"})},show(){u(h.BREADCRUMBS,{action:"show"})}}}function Ae(){const t=e=>{const r=le(e);if(!r.valid){f(h.TOAST,r.errors);return}u(h.TOAST,{type:e.type,message:e.message,duration:e.duration})};return{show:t,success(e,r){t({type:"success",message:e,duration:r})},error(e,r){t({type:"error",message:e,duration:r})},warning(e,r){t({type:"warning",message:e,duration:r})},info(e,r){t({type:"info",message:e,duration:r})}}}function Re(){return async t=>{const e=ve(t);return e.valid?D(h.CONFIRM,{title:t.title,message:t.message,confirmText:t.confirmText??"Confirm",cancelText:t.cancelText??"Cancel",variant:t.variant??"info"}):(f(h.CONFIRM,e.errors),Promise.reject(new Error(e.errors.join(", "))))}}function Ne(){return{loading:Ie(),breadcrumbs:Se(),toast:Ae(),confirm:Re()}}function Ce(){const t=w(),e=[];return e.push(m(g.RESPONSE,r=>{t.notify({success:r.payload.success,order_id:r.payload.order_id,status:r.payload.status,error:r.payload.error,context:r.payload.context})})),e.push(m(g.GET_ADDONS_RESPONSE,r=>{r.requestId&&M(r.requestId,{success:r.payload.success,addons:r.payload.addons,error:r.payload.error})})),{create(r,i){const n=Array.isArray(r)?r:[r],s=fe({items:n});if(!s.valid)throw f(g.CREATE,s.errors),new Error(s.errors[0]);u(g.CREATE,{items:n.map(d=>({type:d.type,slug:d.slug,quantity:d.quantity??1})),...i?.context!==void 0&&{context:i.context}},"*",H())},onResult(r){return t.subscribe(r)},async getAddons(){try{return await D(g.GET_ADDONS,{},3e4)}catch(r){return{success:!1,error:{code:"REQUEST_FAILED",message:r instanceof Error?r.message:"Unknown error"}}}},resetCache(){u(g.RESET_CACHE,{},"*")},destroy(){e.forEach(r=>r()),e.length=0,t.clear()}}}const V={theme:"light",dir:"rtl",width:0,locale:"ar",currency:"SAR"};class G{constructor(){this.initialized=!1,this.initializing=!1,this.debugMode=!1,this.appReady=!1,this.layout={...V},this.postInitHooks=[],this.themeSubscription=w(),this.initSubscription=w(),this.auth=ce(),this.page=Te(),this.nav=we(),this.ui=Ne(),this.checkout=Ce(),this.registerPostInitHook(e=>{const r=e.payload.pendingCheckoutResult;r&&(a.debug("Dispatching pending checkout result:",r),queueMicrotask(()=>{ne(g.RESPONSE,{success:r.success,status:r.status,error:r.error,context:r.context})}))}),this.setupListeners()}registerPostInitHook(e){this.postInitHooks.push(e)}setupListeners(){m(x.THEME_CHANGE,e=>{this.layout.theme=e.payload.theme,a.debug("Theme changed:",e.payload.theme),this.themeSubscription.notify(e.payload.theme)}),m(h.CONFIRM_RESPONSE,e=>{a.debug("Received confirm response:",e),e.requestId&&M(e.requestId,{confirmed:e.payload.confirmed})})}getState(){return{ready:this.initialized,initializing:this.initializing,layout:{...this.layout}}}isReady(){return this.initialized}onThemeChange(e){return this.themeSubscription.subscribe(e)}onInit(e){if(this.initialized)try{e(this.getState())}catch(r){a.error("Error in init callback:",r)}return this.initSubscription.subscribe(e)}ready(){if(this.appReady){a.debug("App already signaled as ready");return}if(!this.initialized){a.warn("Cannot signal ready before init() is called");return}this.appReady=!0,u(C.READY,{}),a.debug("Sent ready signal to host")}async init(e={}){if(this.initialized)return a.debug("Already initialized, returning current layout"),{layout:{...this.layout}};if(this.initializing)return a.warn("Initialization already in progress"),new Promise(r=>{const i=this.onInit(n=>{i(),r({layout:{...n.layout}})})});this.initializing=!0,this.debugMode=e.debug??!1,Q({debug:this.debugMode}),ie()||a.warn("Not running in an iframe. Some features may not work."),a.debug("Initializing SDK...");try{u(C.INIT,{height:document.documentElement.scrollHeight}),a.debug("Sent iframe.ready message, waiting for context...");const r=await te(x.PROVIDE);a.debug("Received context from host:",r);const{layout:i}=r.payload;return this.layout={theme:i?.theme??"light",dir:i?.dir??Y(i?.locale),width:i?.width??0,locale:i?.locale??"ar",currency:i?.currency??"SAR"},this.postInitHooks.forEach(n=>{try{n(r)}catch(s){a.error("Error in post-init hook:",s)}}),this.initialized=!0,this.initializing=!1,a.debug("Initialization complete. Layout:",this.layout),this.initSubscription.notify(this.getState()),{layout:{...this.layout}}}catch(r){throw this.initializing=!1,r}}destroy(){a.debug("Destroying SDK instance"),this.initialized&&(u(C.DESTROY,{}),a.debug("Sent destroy event to host")),this.checkout.destroy(),this.nav.destroy(),ae("SDK destroyed"),re(),this.themeSubscription.clear(),this.initSubscription.clear(),this.postInitHooks=[],this.initialized=!1,this.initializing=!1,this.appReady=!1,this.layout={...V}}}let v=null;function O(){return v||(v=new G),v}function _e(){v&&(v.destroy(),v=null)}const $=O(),$e=R;typeof window<"u"&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla,window.salla.embedded||(window.salla.embedded=$),window.Salla.embedded||(window.Salla.embedded=$));exports.EmbeddedApp=G;exports.embedded=$;exports.getEmbeddedApp=O;exports.resetEmbeddedApp=_e;exports.version=$e;
|
|
4
4
|
//# sourceMappingURL=index.js.map
|