@salla.sa/embedded-sdk 0.1.0-beta.12 → 0.1.0-beta.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/README.md CHANGED
@@ -14,75 +14,283 @@ yarn add @salla.sa/embedded-sdk
14
14
 
15
15
  ## Quick Start
16
16
 
17
+ ### ES Modules (Recommended)
18
+
17
19
  ```typescript
18
20
  import { embedded } from "@salla.sa/embedded-sdk";
19
21
 
20
22
  async function bootstrap() {
21
23
  try {
22
- // Initialize SDK
24
+ // 1. Initialize SDK and get layout info
23
25
  const { layout } = await embedded.init({ debug: true });
26
+ console.log("Theme:", layout.theme);
27
+ console.log("Locale:", layout.locale);
24
28
 
25
- // Get token
29
+ // 2. Get token from URL and verify with your backend
26
30
  const token = embedded.auth.getToken();
27
- if (!token) throw new Error("No token found");
28
-
29
- // Verify token with your backend before signaling ready
30
- const isValid = await fetch("/api/verify-token", {
31
- method: "POST",
32
- headers: { "Content-Type": "application/json" },
33
- body: JSON.stringify({ token }),
34
- }).then((res) => res.ok);
31
+ if (!token) {
32
+ throw new Error("No token found");
33
+ }
35
34
 
36
- if (!isValid) throw new Error("Token is invalid");
35
+ const verified = await verifyWithBackend(token);
36
+ if (!verified) {
37
+ throw new Error("Token verification failed");
38
+ }
37
39
 
38
- // Signal app is ready only after successful verification
40
+ // 3. Signal that app is ready (removes host loading overlay)
39
41
  embedded.ready();
40
42
 
41
- // Set up your app
43
+ // 4. Set up your app
42
44
  embedded.page.setTitle("My App");
45
+
43
46
  } catch (err) {
44
- embedded.destroy();
47
+ // Signal auth error (redirects to apps page with error toast)
48
+ embedded.auth.error(err.message);
45
49
  }
46
50
  }
47
51
 
48
52
  bootstrap();
49
53
  ```
50
54
 
51
- ### Browser Global
55
+ ### UMD (Browser Global)
52
56
 
53
57
  ```html
54
- <script src="https://unpkg.com/@salla.sa/embedded-sdk/dist/umd/index.js"></script>
58
+ <script src="https://unpkg.com/@salla.sa/embedded-sdk/dist/index.umd.js"></script>
55
59
  <script>
56
- const embedded = Salla.embedded;
57
- embedded.init({ debug: true }).then((result) => {
58
- console.log("Layout:", result.layout);
59
- embedded.ready();
60
- });
60
+ const embedded = SallaEmbeddedSDK.embedded;
61
+
62
+ embedded.init({ debug: true })
63
+ .then(function(result) {
64
+ console.log("Layout:", result.layout);
65
+
66
+ const token = embedded.auth.getToken();
67
+ // ... verify token and call embedded.ready()
68
+ });
69
+ </script>
70
+ ```
71
+
72
+ ### Script Access via Salla Object
73
+
74
+ The SDK is also accessible via the global `Salla` object:
75
+
76
+ ```html
77
+ <script>
78
+ // Access SDK from Salla namespace
79
+ Salla.embedded.init({ debug: true });
61
80
  </script>
62
81
  ```
63
82
 
64
83
  ## API Overview
65
84
 
66
- The SDK provides modules for authentication, UI components, navigation, and page management:
85
+ ### Initialization
86
+
87
+ ```typescript
88
+ const { layout } = await embedded.init({
89
+ debug: false, // Optional: Enable debug logging
90
+ });
91
+ ```
92
+
93
+ Returns layout information from the host:
94
+
95
+ ```typescript
96
+ interface LayoutInfo {
97
+ theme: 'light' | 'dark';
98
+ width: number;
99
+ locale: string;
100
+ currency: string;
101
+ }
102
+ ```
103
+
104
+ ### Core Methods
105
+
106
+ ```typescript
107
+ // Signal app is ready (removes host loading overlay)
108
+ embedded.ready();
109
+
110
+ // Get current state
111
+ const state = embedded.getState();
112
+
113
+ // Check if initialized
114
+ const ready = embedded.isReady();
115
+
116
+ // Subscribe to initialization
117
+ embedded.onInit((state) => {
118
+ console.log('Initialized with layout:', state.layout);
119
+ });
120
+
121
+ // Send log message to host
122
+ embedded.log('error', 'Something failed', { context: 'data' });
123
+ ```
124
+
125
+ ### Auth Module
126
+
127
+ ```typescript
128
+ // Get token from URL (?token=XXX)
129
+ const token = embedded.auth.getToken();
130
+
131
+ // Request logout (navigates to apps page)
132
+ embedded.auth.logout();
133
+
134
+ // Request token refresh (re-renders iframe with new token)
135
+ embedded.auth.refresh();
136
+
137
+ // Signal auth error (navigates away with error toast)
138
+ embedded.auth.error("Token verification failed");
139
+ ```
140
+
141
+ ### UI Module
142
+
143
+ ```typescript
144
+ // Loading (in-app loading states)
145
+ embedded.ui.loading.show(); // Show loading
146
+ embedded.ui.loading.show("component"); // Component-level
147
+ embedded.ui.loading.hide(); // Hide loading
148
+
149
+ // Overlay (fullscreen mode)
150
+ embedded.ui.overlay.open();
151
+ embedded.ui.overlay.close();
152
+
153
+ // Toast Notifications
154
+ embedded.ui.toast.success("Product saved!");
155
+ embedded.ui.toast.error("Something went wrong");
156
+ embedded.ui.toast.warning("Please review input");
157
+ embedded.ui.toast.info("New features available");
158
+ embedded.ui.toast.success("Saved!", 5000); // Custom duration
159
+
160
+ // Generic toast
161
+ embedded.ui.toast.show({
162
+ type: "success",
163
+ message: "Done!",
164
+ duration: 3000,
165
+ });
166
+
167
+ // Modal
168
+ embedded.ui.modal.open("my-modal", { data: 123 });
169
+ embedded.ui.modal.close("my-modal");
170
+
171
+ // Confirm Dialog (async)
172
+ const result = await embedded.ui.confirm({
173
+ title: "Delete Product?",
174
+ message: "This action cannot be undone.",
175
+ confirmText: "Delete",
176
+ cancelText: "Cancel",
177
+ variant: "danger", // 'danger' | 'warning' | 'info'
178
+ });
67
179
 
68
- - **Auth**: `getToken()`, `getAppId()`, `refresh()`, `introspect()`
69
- - **UI**: `loading`, `toast`, `modal`, `confirm`
70
- - **Page**: `setTitle()`, `navigate()`, `redirect()`, `resize()`
71
- - **Nav**: `setAction()`, `onActionClick()`, `clearAction()`
180
+ if (result.confirmed) {
181
+ await deleteProduct();
182
+ }
183
+ ```
184
+
185
+ ### Page Module
186
+
187
+ ```typescript
188
+ // Set page title in host
189
+ embedded.page.setTitle("Product Details");
72
190
 
73
- ## TypeScript
191
+ // SPA Navigation (React Router)
192
+ embedded.page.navigate("/products");
193
+ embedded.page.navigate("/orders", { replace: true });
194
+ embedded.page.navigate("/item", { state: { id: 123 } });
74
195
 
75
- Full TypeScript support with exported types. See [documentation](#) for complete type reference.
196
+ // Full Page Redirect
197
+ embedded.page.redirect("https://external-site.com");
198
+
199
+ // Auto-detect (internal → navigate, external → redirect)
200
+ embedded.page.navTo("/products");
201
+ embedded.page.navTo("https://external.com");
202
+
203
+ // Iframe Resize
204
+ embedded.page.resize(800);
205
+ embedded.page.autoResize(); // Auto-detect content height
206
+ ```
207
+
208
+ ### Nav Module
209
+
210
+ ```typescript
211
+ // Set primary action button
212
+ embedded.nav.setAction({
213
+ title: "Create Product",
214
+ url: "/products/new",
215
+ });
216
+
217
+ // With dropdown actions
218
+ embedded.nav.setAction({
219
+ title: "Actions",
220
+ value: "main",
221
+ extendedActions: [
222
+ { title: "Import", url: "/import" },
223
+ { title: "Export", value: "export" },
224
+ ],
225
+ });
226
+
227
+ // Listen for action clicks
228
+ const unsubscribe = embedded.nav.onActionClick((url, value) => {
229
+ if (value === "export") {
230
+ handleExport();
231
+ }
232
+ });
233
+
234
+ // Clear action button
235
+ embedded.nav.clearAction();
236
+ ```
237
+
238
+ ### Checkout Module
239
+
240
+ ```typescript
241
+ embedded.checkout.create({
242
+ items: [{ productId: 123, quantity: 1 }],
243
+ amount: 99.99,
244
+ currency: "SAR",
245
+ });
246
+ ```
247
+
248
+ ### Theme Support
249
+
250
+ ```typescript
251
+ // Get current theme from state
252
+ const theme = embedded.getState().layout.theme;
253
+
254
+ // Listen for theme changes
255
+ const unsubscribe = embedded.onThemeChange((theme) => {
256
+ document.body.classList.toggle("dark", theme === "dark");
257
+ });
258
+ ```
259
+
260
+ ## TypeScript Support
261
+
262
+ Full TypeScript support with exported types:
263
+
264
+ ```typescript
265
+ import type {
266
+ EmbeddedState,
267
+ LayoutInfo,
268
+ InitOptions,
269
+ ToastOptions,
270
+ ToastType,
271
+ ConfirmOptions,
272
+ ConfirmResult,
273
+ PrimaryActionConfig,
274
+ ExtendedAction,
275
+ CheckoutPayload,
276
+ } from "@salla.sa/embedded-sdk";
277
+ ```
76
278
 
77
279
  ## Build Formats
78
280
 
79
- | Format | File |
80
- | -------- | ---------------------- |
81
- | ESM | `dist/esm/index.js` |
82
- | CommonJS | `dist/cjs/index.js` |
83
- | UMD | `dist/umd/index.js` |
84
- | SystemJS | `dist/system/index.js` |
281
+ | Format | File | Usage |
282
+ | -------- | ---------------------- | ---------------------------- |
283
+ | ESM | `dist/index.es.js` | Modern bundlers (Vite, etc.) |
284
+ | CommonJS | `dist/index.cjs.js` | Node.js |
285
+ | UMD | `dist/index.umd.js` | Browser global |
286
+ | SystemJS | `dist/index.system.js` | SystemJS/microfrontends |
85
287
 
86
- ## Documentation
288
+ ## Development
87
289
 
88
- For complete API documentation, examples, and advanced usage, see the [full documentation](#).
290
+ ```bash
291
+ pnpm install # Install dependencies
292
+ pnpm dev # Development build with watch
293
+ pnpm build # Production build
294
+ pnpm lint # Lint code
295
+ pnpm typecheck # Type check
296
+ ```
package/dist/cjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s="embedded::",y={INIT:`${s}iframe.ready`,RESIZE:`${s}iframe.resize`,READY:`${s}ready`,DESTROY:`${s}destroy`},O={PROVIDE:`${s}context.provide`,THEME_CHANGE:`${s}theme.change`},G={LOG:`${s}log`},d={LOADING:`${s}ui.loading`,TOAST:`${s}ui.toast`,MODAL:`${s}ui.modal`,CONFIRM:`${s}ui.confirm`,CONFIRM_RESPONSE:`${s}ui.confirm.response`,MODAL_RESPONSE:`${s}ui.modal.response`},H="0.1.0-beta.12",K={version:H},z={REFRESH:`${s}auth.refresh`},m={NAVIGATE:`${s}page.navigate`,REDIRECT:`${s}page.redirect`,SET_TITLE:`${s}page.setTitle`},w={SET_ACTION:`${s}nav.setAction`,ACTION_CLICK:`${s}nav.actionClick`},_={CREATE:`${s}checkout.create`},N=K.version,X=1e4,W=["localhost","merchants.workers.dev","s.salla.sa",".salla.group",".salla.sa"];let A={showVersion:!0,debug:!1};function Y(e){A={...A,...e}}function M(e){return`%c${e}`}function D(e,t="#fff"){return`background-color: ${e}; color: ${t}; padding: 2px 6px; border-radius: 3px; font-weight: 500; font-size: 11px;`}function b(e,...t){if(e==="debug"&&!A.debug)return;const i=[],r=[];i.push(M("EmbeddedSDK")),r.push(D("#10b981","#fff")),A.showVersion&&(i.push(M(`v${N}`)),r.push(D("#6b7280","#fff")));const n=i.join("").trim();(console[e]||console.log)(n,...r,...t)}const u={log:(...e)=>{b("log",...e)},warn:(...e)=>{b("warn",...e)},error:(...e)=>{b("error",...e)},info:(...e)=>{b("info",...e)},debug:(...e)=>{b("debug",...e)}};function B(e){try{const i=new URL(e).hostname;return W.some(r=>r.startsWith(".")?i.endsWith(r)||i===r.slice(1):i===r||i.startsWith(`${r}:`))}catch{return!1}}function Z(){return typeof window>"u"||window.parent===window?null:window.parent}function o(e,t,i="*",r,n){const a=Z();if(!a){u.warn("Not running in an iframe, cannot post to host");return}const l={event:e,payload:t||{},timestamp:Date.now(),source:"embedded-app",...r&&{requestId:r},metadata:{version:N}};a.postMessage(l,i)}const h=new Map;let S=!1;function F(e){if(process.env.NODE_ENV==="production"&&!B(e.origin))return;const t=e.data;if(!t||typeof t.event!="string"||!t.payload||typeof t.timestamp!="number"||!t.source){u.warn("Invalid message structure received:",t);return}const i=h.get(t.event);i&&i.forEach(n=>{try{n(t)}catch(a){u.error("Error in message handler:",a)}});const r=h.get("*");r&&r.forEach(n=>{try{n(t)}catch(a){u.error("Error in wildcard handler:",a)}})}function J(){S||typeof window>"u"||(window.addEventListener("message",F),S=!0)}function T(e,t){J(),h.has(e)||h.set(e,new Set);const i=h.get(e);return i.add(t),()=>{i.delete(t),i.size===0&&h.delete(e)}}function Q(e,t=X){return new Promise((i,r)=>{const n=setTimeout(()=>{a(),r(new Error(`[EmbeddedSDK] Timeout waiting for "${e}" message`))},t),a=T(e,l=>{clearTimeout(n),a(),i(l)})})}function ee(){h.clear(),S&&typeof window<"u"&&(window.removeEventListener("message",F),S=!1)}function te(){return typeof window>"u"?!1:window.parent!==window}const g=new Map,re=3e4;function ie(){const e=Date.now(),t=Math.random().toString(36).slice(2,9);return`req_${e}_${t}`}function ne(e,t={},i=re){const r=ie();return new Promise((n,a)=>{const l=setTimeout(()=>{g.get(r)&&(g.delete(r),a(new Error(`[EmbeddedSDK] Request "${e}" timed out after ${i}ms`)))},i);g.set(r,{resolve:n,reject:a,timeout:l,event:e}),o(e,t,"*",r)})}function x(e,t,i){const r=g.get(e);if(!r){u.warn(`Received response for unknown request: ${e}`);return}clearTimeout(r.timeout),g.delete(e),i?r.reject(new Error(i)):r.resolve(t)}function ae(e="SDK cleanup"){g.forEach((t,i)=>{clearTimeout(t.timeout),t.reject(new Error(`[EmbeddedSDK] Request ${i} cancelled: ${e}`))}),g.clear()}const se="https://api.salla.dev";class E extends Error{constructor(t,i,r){super(t),this.status=i,this.response=r,this.name="ApiError"}}async function oe(e,t={}){const{method:i="GET",headers:r={},body:n,timeout:a=3e4}=t,l=`${se}${e}`,R=new AbortController,$=setTimeout(()=>{R.abort()},a);try{const c=await fetch(l,{method:i,headers:{"Content-Type":"application/json",...r},body:n?JSON.stringify(n):void 0,signal:R.signal});clearTimeout($);let v;const C=c.headers.get("content-type");if(C!=null&&C.includes("application/json")?v=await c.json():v=await c.text(),!c.ok)throw new E(`API request failed: ${c.statusText}`,c.status,v);return v}catch(c){throw clearTimeout($),c instanceof E?c:c instanceof Error?c.name==="AbortError"?new E(`Request timeout after ${a}ms`):new E(`Request failed: ${c.message}`):new E("Unknown error occurred")}}function I(e){return{isVerified:!1,isError:!0,error:e,data:null}}async function le(e){const{token:t,appId:i,refreshOnError:r=!0}=e;if(!t){const n="Token is required. Provide it as a parameter or in URL as ?token=XXX";return u.error("Error in introspect:",n),I(n)}if(!i){const n="App ID is required. Provide it as a parameter or in URL as ?app_id=XXX";return u.error("Error in introspect:",n),I(n)}try{const n=await oe("/exchange-authority/v1/introspect",{method:"POST",headers:{"S-Source":i,"Content-Type":"application/json"},body:{env:"prod",token:t,iss:"merchant-dashboard",subject:"embedded-page"}}),a=n.success;return{isVerified:a,isError:!a,error:a?void 0:"API request failed",data:a?n.data:null}}catch(n){r&&(k().ui.toast.error((n==null?void 0:n.toString())??"Introspect error"),o(z.REFRESH,{})),u.error("Error in introspect:",n);const a=n instanceof Error?n.message:n;return I(a)}}function ue(e){return{getToken(){return new URLSearchParams(window.location.search).get("token")},getAppId(){return new URLSearchParams(window.location.search).get("app_id")},refresh(){o(z.REFRESH,{})},async introspect(t={}){const i=t.token??this.getToken()??"",r=t.appId??this.getAppId()??"";return le({token:i,appId:r,refreshOnError:t.refreshOnError})}}}const U=["success","error","warning","info"];function ce(e){const t=[];return e.type===void 0||e.type===null?t.push("Toast type is required"):(typeof e.type!="string"||!U.includes(e.type))&&t.push(`Invalid toast type "${e.type}". Expected: ${U.join(" | ")}`),e.message===void 0||e.message===null?t.push("Toast message is required"):typeof e.message!="string"?t.push("Toast message must be a string"):e.message.trim()===""&&t.push("Toast message cannot be empty"),e.duration!==void 0&&e.duration!==null&&(typeof e.duration!="number"?t.push("Toast duration must be a number"):e.duration<0&&t.push("Toast duration cannot be negative")),{valid:t.length===0,errors:t}}function de(e){const t=[];return typeof e!="object"||e===null?(t.push("Checkout payload must be an object"),{valid:!1,errors:t}):(e.amount!==void 0&&e.amount!==null&&(typeof e.amount!="number"?t.push("Checkout amount must be a number"):e.amount<0&&t.push("Checkout amount cannot be negative")),e.currency!==void 0&&e.currency!==null&&(typeof e.currency!="string"?t.push("Checkout currency must be a string"):e.currency.trim()===""&&t.push("Checkout currency cannot be empty")),e.items!==void 0&&e.items!==null&&(Array.isArray(e.items)||t.push("Checkout items must be an array")),{valid:t.length===0,errors:t})}function fe(e){const t=[];return e.path===void 0||e.path===null?t.push("Navigation path is required"):typeof e.path!="string"?t.push("Navigation path must be a string"):e.path.trim()===""&&t.push("Navigation path cannot be empty"),e.replace!==void 0&&typeof e.replace!="boolean"&&t.push("Navigation replace option must be a boolean"),{valid:t.length===0,errors:t}}function he(e){const t=[];if(e.url===void 0||e.url===null)t.push("Redirect URL is required");else if(typeof e.url!="string")t.push("Redirect URL must be a string");else if(e.url.trim()==="")t.push("Redirect URL cannot be empty");else try{new URL(e.url)}catch{t.push(`Invalid redirect URL: "${e.url}"`)}return{valid:t.length===0,errors:t}}function ge(e){const t=[];return e.title===void 0||e.title===null?t.push("Nav action title is required"):typeof e.title!="string"&&t.push("Nav action title must be a string"),e.onClick!==void 0&&e.onClick!==null&&typeof e.onClick!="function"&&t.push("Nav action onClick must be a function"),e.value!==void 0&&e.value!==null&&typeof e.value!="string"&&t.push("Nav action value must be a string"),e.subTitle!==void 0&&e.subTitle!==null&&typeof e.subTitle!="string"&&t.push("Nav action subTitle must be a string"),e.icon!==void 0&&e.icon!==null&&typeof e.icon!="string"&&t.push("Nav action icon must be a string"),e.disabled!==void 0&&e.disabled!==null&&typeof e.disabled!="boolean"&&t.push("Nav action disabled must be a boolean"),e.extendedActions!==void 0&&e.extendedActions!==null&&(Array.isArray(e.extendedActions)?e.extendedActions.forEach((i,r)=>{if(typeof i!="object"||i===null){t.push(`Extended action at index ${r} must be an object`);return}const n=i;(!n.title||typeof n.title!="string")&&t.push(`Extended action at index ${r} is missing required "title" property`),n.subTitle!==void 0&&typeof n.subTitle!="string"&&t.push(`Extended action at index ${r} subTitle must be a string`),n.url!==void 0&&typeof n.url!="string"&&t.push(`Extended action at index ${r} url must be a string`),n.value!==void 0&&typeof n.value!="string"&&t.push(`Extended action at index ${r} value must be a string`),n.icon!==void 0&&typeof n.icon!="string"&&t.push(`Extended action at index ${r} icon must be a string`),n.disabled!==void 0&&typeof n.disabled!="boolean"&&t.push(`Extended action at index ${r} disabled must be a boolean`)}):t.push("Nav action extendedActions must be an array")),{valid:t.length===0,errors:t}}const V=["danger","warning","info"];function me(e){const t=[];return e.title===void 0||e.title===null?t.push("Confirm dialog title is required"):typeof e.title!="string"?t.push("Confirm dialog title must be a string"):e.title.trim()===""&&t.push("Confirm dialog title cannot be empty"),e.message===void 0||e.message===null?t.push("Confirm dialog message is required"):typeof e.message!="string"?t.push("Confirm dialog message must be a string"):e.message.trim()===""&&t.push("Confirm dialog message cannot be empty"),e.confirmText!==void 0&&e.confirmText!==null&&typeof e.confirmText!="string"&&t.push("Confirm dialog confirmText must be a string"),e.cancelText!==void 0&&e.cancelText!==null&&typeof e.cancelText!="string"&&t.push("Confirm dialog cancelText must be a string"),e.variant!==void 0&&e.variant!==null&&(typeof e.variant!="string"||!V.includes(e.variant))&&t.push(`Invalid confirm variant "${e.variant}". Expected: ${V.join(" | ")}`),{valid:t.length===0,errors:t}}function f(e,t){u.error(`Validation failed for ${e}:
2
- `+t.map(i=>` • ${i}`).join(`
3
- `))}function pe(){return{navigate(e,t){const i=fe({path:e,...t});if(!i.valid){f(m.NAVIGATE,i.errors);return}o(m.NAVIGATE,{path:e,state:t==null?void 0:t.state,replace:t==null?void 0:t.replace})},redirect(e){const t=he({url:e});if(!t.valid){f(m.REDIRECT,t.errors);return}o(m.REDIRECT,{url:e})},navTo(e,t){if(e.startsWith("http://")||e.startsWith("https://")){this.redirect(e);return}this.navigate(e,t)},resize(e){if(typeof e!="number"||e<0){f(y.RESIZE,["Height must be a non-negative number"]);return}o(y.RESIZE,{height:e})},autoResize(){const e=document.documentElement.scrollHeight;this.resize(e)},setTitle(e){if(typeof e!="string"||!e.trim()){f(m.SET_TITLE,["Title must be a non-empty string"]);return}o(m.SET_TITLE,{title:e})}}}function be(){const e=new Set;let t=null;return T(w.ACTION_CLICK,r=>{if(t)try{t()}catch(n){u.error("Error in onClick callback:",n)}e.forEach(n=>{try{n(r.payload.url,r.payload.value)}catch(a){u.error("Error in action click callback:",a)}})}),{setAction(r){var a;const n=ge(r);if(!n.valid){f(w.SET_ACTION,n.errors);return}r.onClick?t=r.onClick:t=null,o(w.SET_ACTION,{title:r.title,onClick:r.onClick?!0:void 0,value:r.value,subTitle:r.subTitle,icon:r.icon,disabled:r.disabled,extendedActions:(a=r.extendedActions)==null?void 0:a.map(l=>({title:l.title,subTitle:l.subTitle,url:l.url,value:l.value,icon:l.icon,disabled:l.disabled}))})},clearAction(){t=null,o(w.SET_ACTION,{title:""})},onActionClick(r){return e.add(r),()=>{e.delete(r)}},primaryAction(r){this.setAction(r)},clearPrimaryAction(){this.clearAction()}}}function Ee(){return{show(){o(d.LOADING,{action:"show"})},hide(){o(d.LOADING,{action:"hide"})}}}function ye(){const e=t=>{const i=ce(t);if(!i.valid){f(d.TOAST,i.errors);return}o(d.TOAST,{type:t.type,message:t.message,duration:t.duration})};return{show:e,success(t,i){e({type:"success",message:t,duration:i})},error(t,i){e({type:"error",message:t,duration:i})},warning(t,i){e({type:"warning",message:t,duration:i})},info(t,i){e({type:"info",message:t,duration:i})}}}function Te(){return{open(e,t){o(d.MODAL,{action:"open",id:e,content:t})},close(e){o(d.MODAL,{action:"close",id:e})}}}function ve(){return async e=>{const t=me(e);return t.valid?ne(d.CONFIRM,{title:e.title,message:e.message,confirmText:e.confirmText??"Confirm",cancelText:e.cancelText??"Cancel",variant:e.variant??"info"}):(f(d.CONFIRM,t.errors),Promise.reject(new Error(t.errors.join(", "))))}}function we(){return{loading:Ee(),toast:ye(),modal:Te(),confirm:ve()}}function Ae(){return{create(e){const t=de(e);if(!t.valid){f(_.CREATE,t.errors);return}o(_.CREATE,e)}}}const q={debug:!1,initialized:!1},Se={theme:"light",width:0,locale:"ar",currency:"SAR"},P={ready:!1,initializing:!1,layout:{...Se}};class j{constructor(){this.config={...q},this.state={...P},this.themeCallbacks=new Set,this.initCallbacks=new Set,this.appReady=!1,this.auth=ue(),this.page=pe(),this.nav=be(),this.ui=we(),this.checkout=Ae(),this.setupThemeListener(),this.setupResponseListeners()}getState(){return{ready:this.state.ready,initializing:this.state.initializing,layout:{...this.state.layout}}}getConfig(){return{...this.config}}isReady(){return this.state.ready}internalLog(t,...i){switch(t){case"log":u.log(...i);break;case"warn":u.warn(...i);break;case"error":u.error(...i);break;case"info":u.info(...i);break;case"debug":u.debug(...i);break}}setupThemeListener(){T(O.THEME_CHANGE,t=>{this.state.layout.theme=t.payload.theme,this.internalLog("debug","Theme changed:",t.payload.theme),this.themeCallbacks.forEach(i=>{try{i(t.payload.theme)}catch(r){this.internalLog("error","Error in theme callback:",r)}})})}setupResponseListeners(){T(d.CONFIRM_RESPONSE,t=>{this.internalLog("debug","Received confirm response:",t),t.requestId&&x(t.requestId,{confirmed:t.payload.confirmed})}),T(d.MODAL_RESPONSE,t=>{this.internalLog("debug","Received modal response:",t),t.requestId&&x(t.requestId,t.payload.result,t.payload.error)})}onThemeChange(t){return this.themeCallbacks.add(t),()=>{this.themeCallbacks.delete(t)}}onInit(t){if(this.config.initialized)try{t(this.getState())}catch(i){this.internalLog("error","Error in init callback:",i)}return this.initCallbacks.add(t),()=>{this.initCallbacks.delete(t)}}log(t,i,r){o(G.LOG,{level:t,message:i,context:r})}ready(){if(this.appReady){this.internalLog("debug","App already signaled as ready");return}if(!this.config.initialized){this.internalLog("warn","Cannot signal ready before init() is called");return}this.appReady=!0,o(y.READY,{}),this.internalLog("debug","Sent ready signal to host")}async init(t={}){if(this.config.initialized)return this.internalLog("debug","Already initialized, returning current layout"),{layout:{...this.state.layout}};if(this.state.initializing)return this.internalLog("warn","Initialization already in progress"),this.waitForInit();te()||this.internalLog("warn","Not running in an iframe. Some features may not work."),this.config={debug:t.debug??!1,initialized:!1},Y({debug:this.config.debug}),this.state.initializing=!0,this.internalLog("debug","Initializing SDK...");try{o(y.INIT,{height:document.documentElement.scrollHeight}),this.internalLog("debug","Sent iframe.ready message, waiting for context...");const i=await Q(O.PROVIDE);this.internalLog("debug","Received context from host:",i);const r=i.payload.layout;this.state={ready:!0,initializing:!1,layout:{theme:(r==null?void 0:r.theme)??"light",width:(r==null?void 0:r.width)??0,locale:(r==null?void 0:r.locale)??"ar",currency:(r==null?void 0:r.currency)??"SAR"}},this.config.initialized=!0,this.internalLog("debug","Initialization complete. Layout:",this.state.layout);const n=this.getState();return this.initCallbacks.forEach(a=>{try{a(n)}catch(l){this.internalLog("error","Error in init callback:",l)}}),{layout:{...this.state.layout}}}catch(i){throw this.state.initializing=!1,this.state.ready=!1,i}}waitForInit(){return new Promise(t=>{const i=this.onInit(r=>{i(),t({layout:{...r.layout}})})})}destroy(){this.internalLog("debug","Destroying SDK instance"),this.config.initialized&&(o(y.DESTROY,{}),this.internalLog("debug","Sent destroy event to host")),ae("SDK destroyed"),ee(),this.themeCallbacks.clear(),this.initCallbacks.clear(),this.config={...q},this.state={...P},this.appReady=!1}}let p=null;function k(){return p||(p=new j),p}function Re(){p&&(p.destroy(),p=null)}const L=k(),Ce=N;typeof window<"u"&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla,window.salla.embedded||(window.salla.embedded=L),window.Salla.embedded||(window.Salla.embedded=L));exports.EmbeddedApp=j;exports.embedded=L;exports.getEmbeddedApp=k;exports.resetEmbeddedApp=Re;exports.version=Ce;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k="0.1.0-beta.2",x={version:k},n="embedded::",y={INIT:`${n}iframe.ready`,RESIZE:`${n}iframe.resize`,READY:`${n}ready`},A={PROVIDE:`${n}context.provide`,THEME_CHANGE:`${n}theme.change`},V={LOG:`${n}log`},b={LOGOUT:`${n}auth.logout`,REFRESH:`${n}auth.refresh`,ERROR:`${n}auth.error`},h={NAVIGATE:`${n}page.navigate`,REDIRECT:`${n}page.redirect`,SET_TITLE:`${n}page.setTitle`},E={SET_ACTION:`${n}nav.setAction`,ACTION_CLICK:`${n}nav.actionClick`},l={LOADING:`${n}ui.loading`,OVERLAY:`${n}ui.overlay`,TOAST:`${n}ui.toast`,MODAL:`${n}ui.modal`,CONFIRM:`${n}ui.confirm`,CONFIRM_RESPONSE:`${n}ui.confirm.response`,MODAL_RESPONSE:`${n}ui.modal.response`},S={CREATE:`${n}checkout.create`},v=x.version,U=1e4,z=["localhost","merchants.workers.dev","s.salla.sa",".salla.group",".salla.sa"];function K(t){try{const i=new URL(t).hostname;return z.some(r=>r.startsWith(".")?i.endsWith(r)||i===r.slice(1):i===r||i.startsWith(`${r}:`))}catch{return!1}}function F(){return typeof window>"u"||window.parent===window?null:window.parent}function s(t,e,i="*"){const r=F();if(!r){console.warn("[EmbeddedSDK] Not running in an iframe, cannot post to host");return}const a={event:t,...e};r.postMessage(a,i)}const d=new Map;let T=!1;function O(t){if(process.env.NODE_ENV==="production"&&!K(t.origin))return;const e=t.data;if(!e||typeof e.event!="string")return;const i=d.get(e.event);i&&i.forEach(a=>{try{a(e)}catch(o){console.error("[EmbeddedSDK] Error in message handler:",o)}});const r=d.get("*");r&&r.forEach(a=>{try{a(e)}catch(o){console.error("[EmbeddedSDK] Error in wildcard handler:",o)}})}function P(){T||typeof window>"u"||(window.addEventListener("message",O),T=!0)}function g(t,e){P(),d.has(t)||d.set(t,new Set);const i=d.get(t);return i.add(e),()=>{i.delete(e),i.size===0&&d.delete(t)}}function q(t,e=U){return new Promise((i,r)=>{const a=setTimeout(()=>{o(),r(new Error(`[EmbeddedSDK] Timeout waiting for "${t}" message`))},e),o=g(t,u=>{clearTimeout(a),o(),i(u)})})}function G(){d.clear(),T&&typeof window<"u"&&(window.removeEventListener("message",O),T=!1)}function H(){return typeof window>"u"?!1:window.parent!==window}const f=new Map,j=3e4;function Y(){const t=Date.now(),e=Math.random().toString(36).slice(2,9);return`req_${t}_${e}`}function W(t,e={},i=j){const r=Y();return new Promise((a,o)=>{const u=setTimeout(()=>{f.get(r)&&(f.delete(r),o(new Error(`[EmbeddedSDK] Request "${t}" timed out after ${i}ms`)))},i);f.set(r,{resolve:a,reject:o,timeout:u,event:t}),s(t,{...e,requestId:r})})}function R(t,e,i){const r=f.get(t);if(!r){console.warn(`[EmbeddedSDK] Received response for unknown request: ${t}`);return}clearTimeout(r.timeout),f.delete(t),i?r.reject(new Error(i)):r.resolve(e)}function Z(t="SDK cleanup"){f.forEach((e,i)=>{clearTimeout(e.timeout),e.reject(new Error(`[EmbeddedSDK] Request ${i} cancelled: ${t}`))}),f.clear()}function X(t){return{getToken(){return new URLSearchParams(window.location.search).get("token")},logout(){s(b.LOGOUT,{})},refresh(){s(b.REFRESH,{})},error(e){s(b.ERROR,{message:e})}}}const C=["success","error","warning","info"];function Q(t){const e=[];return t.type===void 0||t.type===null?e.push("Toast type is required"):(typeof t.type!="string"||!C.includes(t.type))&&e.push(`Invalid toast type "${t.type}". Expected: ${C.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 B(t){const e=[];return typeof t!="object"||t===null?(e.push("Checkout payload must be an object"),{valid:!1,errors:e}):(t.amount!==void 0&&t.amount!==null&&(typeof t.amount!="number"?e.push("Checkout amount must be a number"):t.amount<0&&e.push("Checkout amount cannot be negative")),t.currency!==void 0&&t.currency!==null&&(typeof t.currency!="string"?e.push("Checkout currency must be a string"):t.currency.trim()===""&&e.push("Checkout currency cannot be empty")),t.items!==void 0&&t.items!==null&&(Array.isArray(t.items)||e.push("Checkout items must be an array")),{valid:e.length===0,errors:e})}function J(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 ee(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 te(t){const e=[];return t.title===void 0||t.title===null?e.push("Nav action title is required"):typeof t.title!="string"&&e.push("Nav action title must be a string"),t.url!==void 0&&t.url!==null&&typeof t.url!="string"&&e.push("Nav action URL must be a string"),t.value!==void 0&&t.value!==null&&typeof t.value!="string"&&e.push("Nav action value must be a string"),t.extendedActions!==void 0&&t.extendedActions!==null&&(Array.isArray(t.extendedActions)?t.extendedActions.forEach((i,r)=>{if(typeof i!="object"||i===null){e.push(`Extended action at index ${r} must be an object`);return}const a=i;(!a.title||typeof a.title!="string")&&e.push(`Extended action at index ${r} is missing required "title" property`)}):e.push("Nav action extendedActions must be an array")),{valid:e.length===0,errors:e}}const L=["danger","warning","info"];function ie(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"||!L.includes(t.variant))&&e.push(`Invalid confirm variant "${t.variant}". Expected: ${L.join(" | ")}`),{valid:e.length===0,errors:e}}function c(t,e){console.error(`[EmbeddedSDK] Validation failed for ${t}:
2
+ `+e.map(i=>` • ${i}`).join(`
3
+ `))}function re(){return{navigate(t,e){const i=J({path:t,...e});if(!i.valid){c(h.NAVIGATE,i.errors);return}s(h.NAVIGATE,{path:t,state:e==null?void 0:e.state,replace:e==null?void 0:e.replace})},redirect(t){const e=ee({url:t});if(!e.valid){c(h.REDIRECT,e.errors);return}s(h.REDIRECT,{url:t})},navTo(t,e){if(t.startsWith("http://")||t.startsWith("https://")){this.redirect(t);return}this.navigate(t,e)},resize(t){if(typeof t!="number"||t<0){c(y.RESIZE,["Height must be a non-negative number"]);return}s(y.RESIZE,{height:t})},autoResize(){const t=document.documentElement.scrollHeight;this.resize(t)},setTitle(t){if(typeof t!="string"||!t.trim()){c(h.SET_TITLE,["Title must be a non-empty string"]);return}s(h.SET_TITLE,{title:t})}}}function ne(){const t=new Set;return g(E.ACTION_CLICK,e=>{t.forEach(i=>{try{i(e.url,e.value)}catch(r){console.error("[EmbeddedSDK] Error in action click callback:",r)}})}),{setAction(e){const i=te(e);if(!i.valid){c(E.SET_ACTION,i.errors);return}s(E.SET_ACTION,{title:e.title,url:e.url,value:e.value,extendedActions:e.extendedActions})},clearAction(){s(E.SET_ACTION,{title:""})},onActionClick(e){return t.add(e),()=>{t.delete(e)}},primaryAction(e){this.setAction(e)},clearPrimaryAction(){this.clearAction()}}}function se(){return{show(t="full"){s(l.LOADING,{status:!1,mode:t})},hide(){s(l.LOADING,{status:!0,mode:"full"})}}}function ae(){return{open(){s(l.OVERLAY,{action:"open"})},close(){s(l.OVERLAY,{action:"close"})}}}function oe(){const t=e=>{const i=Q(e);if(!i.valid){c(l.TOAST,i.errors);return}s(l.TOAST,{type:e.type,message:e.message,duration:e.duration})};return{show:t,success(e,i){t({type:"success",message:e,duration:i})},error(e,i){t({type:"error",message:e,duration:i})},warning(e,i){t({type:"warning",message:e,duration:i})},info(e,i){t({type:"info",message:e,duration:i})}}}function le(){return{open(t,e){s(l.MODAL,{action:"open",id:t,content:e})},close(t){s(l.MODAL,{action:"close",id:t})}}}function ue(){return async t=>{const e=ie(t);return e.valid?W(l.CONFIRM,{title:t.title,message:t.message,confirmText:t.confirmText??"Confirm",cancelText:t.cancelText??"Cancel",variant:t.variant??"info"}):(c(l.CONFIRM,e.errors),Promise.reject(new Error(e.errors.join(", "))))}}function ce(){return{loading:se(),overlay:ae(),toast:oe(),modal:le(),confirm:ue()}}function de(){return{create(t){const e=B(t);if(!e.valid){c(S.CREATE,e.errors);return}s(S.CREATE,{payload:t})}}}const I={debug:!1,initialized:!1},fe={theme:"light",width:0,locale:"ar",currency:"SAR"},N={ready:!1,initializing:!1,layout:{...fe}};class D{constructor(){this.config={...I},this.state={...N},this.themeCallbacks=new Set,this.initCallbacks=new Set,this.appReady=!1,this.auth=X(),this.page=re(),this.nav=ne(),this.ui=ce(),this.checkout=de(),this.setupThemeListener(),this.setupResponseListeners()}getState(){return{ready:this.state.ready,initializing:this.state.initializing,layout:{...this.state.layout}}}getConfig(){return{...this.config}}isReady(){return this.state.ready}debugLog(...e){this.config.debug&&console.log(`[EmbeddedSDK v${v}]`,...e)}warn(...e){console.warn(`[EmbeddedSDK v${v}]`,...e)}setupThemeListener(){g(A.THEME_CHANGE,e=>{this.state.layout.theme=e.theme,this.debugLog("Theme changed:",e.theme),this.themeCallbacks.forEach(i=>{try{i(e.theme)}catch(r){console.error("[EmbeddedSDK] Error in theme callback:",r)}})})}setupResponseListeners(){g(l.CONFIRM_RESPONSE,e=>{this.debugLog("Received confirm response:",e),R(e.requestId,{confirmed:e.confirmed})}),g(l.MODAL_RESPONSE,e=>{this.debugLog("Received modal response:",e),R(e.requestId,e.result,e.error)})}onThemeChange(e){return this.themeCallbacks.add(e),()=>{this.themeCallbacks.delete(e)}}onInit(e){if(this.config.initialized)try{e(this.getState())}catch(i){console.error("[EmbeddedSDK] Error in init callback:",i)}return this.initCallbacks.add(e),()=>{this.initCallbacks.delete(e)}}log(e,i,r){s(V.LOG,{level:e,message:i,context:r})}ready(){if(this.appReady){this.debugLog("App already signaled as ready");return}if(!this.config.initialized){this.warn("Cannot signal ready before init() is called");return}this.appReady=!0,s(y.READY,{}),this.debugLog("Sent ready signal to host")}async init(e={}){var i,r,a,o;if(this.config.initialized)return this.debugLog("Already initialized, returning current layout"),{layout:{...this.state.layout}};if(this.state.initializing)return this.warn("Initialization already in progress"),this.waitForInit();H()||this.warn("Not running in an iframe. Some features may not work."),this.config={debug:e.debug??!1,initialized:!1},this.state.initializing=!0,this.debugLog("Initializing SDK...");try{s(y.INIT,{height:document.documentElement.scrollHeight}),this.debugLog("Sent iframe.ready message, waiting for context...");const u=await q(A.PROVIDE);this.debugLog("Received context from host:",u),this.state={ready:!0,initializing:!1,layout:{theme:((i=u.layout)==null?void 0:i.theme)??"light",width:((r=u.layout)==null?void 0:r.width)??0,locale:((a=u.layout)==null?void 0:a.locale)??"ar",currency:((o=u.layout)==null?void 0:o.currency)??"SAR"}},this.config.initialized=!0,this.debugLog("Initialization complete. Layout:",this.state.layout);const p=this.getState();return this.initCallbacks.forEach(_=>{try{_(p)}catch(M){console.error("[EmbeddedSDK] Error in init callback:",M)}}),{layout:{...this.state.layout}}}catch(u){throw this.state.initializing=!1,this.state.ready=!1,u}}waitForInit(){return new Promise(e=>{const i=()=>{this.state.ready?e({layout:{...this.state.layout}}):setTimeout(i,100)};i()})}destroy(){this.debugLog("Destroying SDK instance"),Z("SDK destroyed"),G(),this.themeCallbacks.clear(),this.initCallbacks.clear(),this.config={...I},this.state={...N},this.appReady=!1}}let m=null;function $(){return m||(m=new D),m}function he(){m&&(m.destroy(),m=null)}const w=$(),me=v;typeof window<"u"&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla,window.salla.embedded||(window.salla.embedded=w),window.Salla.embedded||(window.Salla.embedded=w));exports.EmbeddedApp=D;exports.embedded=w;exports.getEmbeddedApp=$;exports.resetEmbeddedApp=he;exports.version=me;
4
4
  //# sourceMappingURL=index.js.map