@widgetic/ui-sdk 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONTRIBUTING.md CHANGED
@@ -14,3 +14,7 @@ Use `type(scope): summary` in the subject and a short body with the why. Stage e
14
14
  ## Locale work
15
15
 
16
16
  Master translation files are in `modules/locales/`. Run `npm run locales:export-english` when message keys change, `npm run locales:import-shopify` to refresh File Browser seeds from the Shopify app (read-only), and `npm run locales:coverage` to see per-module progress.
17
+
18
+ ## License
19
+
20
+ The package is under the Widgetic Integration License (`LICENSE`): a partner may use it to integrate Widgetic, and for nothing else. The text is the same in every Widgetic package, and `scripts/apply-package-license.ts` in `api-gateway-service` puts it there (run it with `--check` on this package). Change the text there, not by editing `LICENSE`, the `license` field of `package.json` or the README's License section here.
package/LICENSE CHANGED
@@ -1,15 +1,122 @@
1
- ISC License
1
+ Widgetic Integration License
2
+ Version 1.0
2
3
 
3
- Copyright (c) Widgetic
4
+ Copyright (c) Widgetic. All rights reserved.
4
5
 
5
- Permission to use, copy, modify, and/or distribute this software for any
6
- purpose with or without fee is hereby granted, provided that the above
7
- copyright notice and this permission notice appear in all copies.
6
+ This license covers the software package that it came with, in source and
7
+ compiled form, together with its documentation (the "Software"). By
8
+ installing, copying or using the Software you accept this license. If you do
9
+ not accept it, do not install or use the Software.
8
10
 
9
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
- PERFORMANCE OF THIS SOFTWARE.
11
+ In this license, "Widgetic" is the company that publishes the Software, "you"
12
+ is the person or organization that uses it, and "Your Application" is an
13
+ application, website, product or service that you build or operate, for
14
+ yourself or for a client. "Widgetic Services" are the services that Widgetic
15
+ operates: the Widgetic API, widgets, compositions, embeds, editors, file
16
+ browser, chat and AI creator, and the other services that can be reached from
17
+ widgetic.com or its API hosts.
18
+
19
+ 1. What you may do
20
+
21
+ Widgetic grants you a worldwide, non-exclusive, non-transferable and
22
+ non-sublicensable license to use the Software, unmodified, for one purpose: to
23
+ integrate the Widgetic Services into Your Application. Within that purpose you
24
+ may:
25
+
26
+ (a) install the Software and run it in Your Application, in development,
27
+ testing and production;
28
+
29
+ (b) use it to call the Widgetic API, to show Widgetic widgets and
30
+ compositions, and to open Widgetic's editors, file browser, chat and AI
31
+ creator inside Your Application;
32
+
33
+ (c) bundle, minify and tree-shake the Software with the build tools of Your
34
+ Application, deliver the result to the people who use Your Application as a
35
+ part of it, and let them run it there;
36
+
37
+ (d) keep the copies of the Software that (a), (b) and (c) need, including
38
+ copies in your version control, your build systems and your backups.
39
+
40
+ 2. What you may not do
41
+
42
+ You may not, and may not allow anyone else to:
43
+
44
+ (a) use the Software for any purpose other than the one in section 1;
45
+
46
+ (b) use the Software to build, run or improve a service that offers what the
47
+ Widgetic Services offer, or to connect Your Application to anything other than
48
+ the Widgetic Services (a proxy of yours that forwards calls to the Widgetic
49
+ Services is fine);
50
+
51
+ (c) copy, modify, translate, adapt or make derivative works of the Software,
52
+ except as section 1(c) allows;
53
+
54
+ (d) publish, sell, rent, lease, sublicense or distribute the Software on its
55
+ own, or inside a library, SDK, template or product that others could use for
56
+ anything other than integrating the Widgetic Services, including by
57
+ publishing it, or a copy of it, to a package registry or a public CDN;
58
+
59
+ (e) reverse engineer, decompile or disassemble the Software, or try to get at
60
+ its source code, except as far as the law lets you despite this restriction;
61
+
62
+ (f) remove or change a copyright, license or attribution notice in the
63
+ Software;
64
+
65
+ (g) bypass, disable or interfere with the authentication, rate limits, quotas,
66
+ credits, plan limits or other protections of the Widgetic Services, or help
67
+ anyone else to;
68
+
69
+ (h) use the name, logo or trademarks of Widgetic, except to say truthfully
70
+ that Your Application integrates Widgetic.
71
+
72
+ 3. The Widgetic Services are separate
73
+
74
+ This license is for the Software only. It does not give you the right to use
75
+ the Widgetic Services. That right comes from your account or agreement with
76
+ Widgetic and from Widgetic's Terms of Service (https://widgetic.com/terms),
77
+ which this license does not change.
78
+
79
+ 4. Ownership
80
+
81
+ The Software is licensed to you, not sold. Widgetic and its licensors keep all
82
+ rights in it. Any right that this license does not give you in plain words is
83
+ reserved to Widgetic.
84
+
85
+ 5. Third-party software
86
+
87
+ The Software may include or depend on software from others. That software is
88
+ under its own license, which applies to it instead of this one, and nothing in
89
+ this license limits your rights under it.
90
+
91
+ 6. How long it lasts
92
+
93
+ This license lasts while you follow it and while you are entitled to use the
94
+ Widgetic Services. It ends on its own if you break it or that entitlement
95
+ ends. When it ends, you stop using the Software and delete your copies of it,
96
+ except copies that the law requires you to keep. Sections 4, 8 and 9 still
97
+ apply after it has ended.
98
+
99
+ 7. Versions
100
+
101
+ This license applies to the version of the Software that it came with and to
102
+ later versions that carry it. A version that Widgetic published under another
103
+ license stays under that license, for the copies of it that you already have.
104
+
105
+ 8. No warranty
106
+
107
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
108
+ IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
109
+ PURPOSE AND NON-INFRINGEMENT.
110
+
111
+ 9. Limit of liability
112
+
113
+ TO THE EXTENT THE LAW ALLOWS, WIDGETIC IS NOT LIABLE FOR ANY INDIRECT,
114
+ INCIDENTAL, SPECIAL, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR FOR LOST PROFITS,
115
+ REVENUE, DATA OR GOODWILL, THAT ARISE FROM THE SOFTWARE OR FROM THIS LICENSE,
116
+ EVEN IF IT HAS BEEN TOLD THAT THEY ARE POSSIBLE. NOTHING IN THIS LICENSE
117
+ LIMITS A LIABILITY THAT THE LAW DOES NOT ALLOW TO BE LIMITED.
118
+
119
+ 10. Questions
120
+
121
+ If you need to do something that this license does not allow, ask first:
122
+ support@widgetic.com.
package/README.md CHANGED
@@ -6,7 +6,6 @@ the settings of a widget they own, beside a live preview) and the **widget creat
6
6
  draw, describe a widget to the AI, watch it being built and publish it).
7
7
 
8
8
  [![npm version](https://badge.fury.io/js/%40widgetic%2Fui-sdk.svg)](https://www.npmjs.com/package/@widgetic/ui-sdk)
9
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
9
 
11
10
  - **No API key in the browser.** Your server keeps the key and mints a short-lived *editor session* for one of your
12
11
  users. The page only ever holds that session's token.
@@ -839,6 +838,12 @@ npm run build:sdk # each part as its own IIFE and ES file in dist/brow
839
838
  # (REPLICABLE=1). Not part of the npm package, and it empties dist/ first: run `npm run build` after it
840
839
  ```
841
840
 
841
+ Nothing in this package reads a `.env`, so there is none to create (the template that used to sit here was removed for
842
+ that reason). Its build keeps an empty list of allowed `.env` keys on purpose (`scripts-sdk/load-env.js`), and
843
+ `scripts-sdk/check-no-secrets.js` fails on a gateway service key in anything that ships. If you keep a `.env` here
844
+ anyway (it is git-ignored), never put a Widgetic key in it: every `PUBLIC_*` and `VITE_*` value is copied into the
845
+ JavaScript that browsers download. The CDN publish settings live in `modules/.env`, a different file.
846
+
842
847
  The modules themselves (Svelte, the design system) live in [`modules/`](modules/README.md), a separate workspace so this
843
848
  package stays free of them. Its browser tests also exercise this SDK as built: `cd modules && npm run build:file-browser
844
849
  && PLAYWRIGHT_CHANNEL=chrome npm run test:e2e` loads `dist/` from a CDN on another origin, with the real File Browser.
@@ -850,7 +855,7 @@ itself — its built output, not its source. The link is made by hand rather tha
850
855
  dev-alias setup the adopting apps use, so a sibling edit stays invisible here until that package rebuilds its `dist/`.
851
856
  Setup is the install script this package ships: it reinstalls and then links the sibling, so `node_modules` keeps
852
857
  resolving the checkout rather than the published package. The dev-alias workflow these packages have not adopted, and
853
- the reasons the adopting apps use it, are described in the Widgetic monorepo's dev-tools package (not shipped inside this npm package).
858
+ the reasons the adopting apps use it, are described in [the dev-tools README](../dev-tools/README.md). That README is not shipped inside this npm package.
854
859
 
855
860
  The SDK itself no longer imports `@widgetic/api-sdk`; the one sibling linked here is the `api-sdk` checkout, for the
856
861
  local demo app in `demo/`. `npm run i` is the whole setup: it reinstalls `node_modules`, then re-links that checkout.
@@ -874,7 +879,7 @@ We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) and [mod
874
879
 
875
880
  ## License
876
881
 
877
- This project is licensed under the ISC License (see the `license` field in `package.json`).
882
+ This package is licensed under the Widgetic Integration License (see the `LICENSE` file in the package): you may use it to integrate Widgetic into your own application, and for nothing else. It is not open source. For any other use, write to support@widgetic.com.
878
883
 
879
884
  ## Support
880
885
 
package/dist/index.cjs CHANGED
@@ -2481,7 +2481,7 @@ function createSecureContext(allowedOrigins = []) {
2481
2481
  * `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
2482
2482
  * `tests/unit/version.test.ts` fails the same way in the suite.
2483
2483
  */
2484
- const SDK_VERSION = '0.1.6';
2484
+ const SDK_VERSION = '0.1.8';
2485
2485
  const SDK_NAME = '@widgetic/ui-sdk';
2486
2486
 
2487
2487
  /**
package/dist/index.esm.js CHANGED
@@ -2477,7 +2477,7 @@ function createSecureContext(allowedOrigins = []) {
2477
2477
  * `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
2478
2478
  * `tests/unit/version.test.ts` fails the same way in the suite.
2479
2479
  */
2480
- const SDK_VERSION = '0.1.6';
2480
+ const SDK_VERSION = '0.1.8';
2481
2481
  const SDK_NAME = '@widgetic/ui-sdk';
2482
2482
 
2483
2483
  /**
@@ -6,5 +6,5 @@
6
6
  * `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
7
7
  * `tests/unit/version.test.ts` fails the same way in the suite.
8
8
  */
9
- export declare const SDK_VERSION = "0.1.6";
9
+ export declare const SDK_VERSION = "0.1.8";
10
10
  export declare const SDK_NAME = "@widgetic/ui-sdk";
@@ -6,6 +6,6 @@
6
6
  * `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
7
7
  * `tests/unit/version.test.ts` fails the same way in the suite.
8
8
  */
9
- export declare const SDK_VERSION = "0.1.6";
9
+ export declare const SDK_VERSION = "0.1.8";
10
10
  export declare const SDK_NAME = "@widgetic/ui-sdk";
11
11
  //# sourceMappingURL=version.d.ts.map
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WidgeticUISDK={})}(this,function(e){"use strict";class t{static createError(e,t){const s=new Error(e);return s.code=t,s}static handleError(e,t){return e instanceof Error?e.code?e:this.createError(e.message,"UNKNOWN_ERROR"):"string"==typeof e?this.createError(e,"STRING_ERROR"):this.createError(`Unknown error in ${t}`,"UNKNOWN_ERROR")}static toSDKError(e){return{message:e.message,code:e.code||"UNKNOWN_ERROR",name:e.name,stack:e.stack,details:e}}}class s extends Error{constructor(e,t){super(e),this.field=t,this.name="ValidationError"}}class r extends Error{constructor(e,t){super(e),this.code=t,this.name="SecurityError"}}class n extends Error{constructor(e,t){super(e),this.componentId=t,this.name="ComponentError"}}class o{static validateId(e,s){if(!e||"string"!=typeof e||""===e.trim())throw t.createError(`Invalid ID provided in ${s}`,"INVALID_ID")}static validateContainer(e,s){if(o.requireBrowser(s),!e)throw t.createError(`Container is required in ${s}`,"MISSING_CONTAINER");if("string"==typeof e){const s=document.querySelector(e);if(!s)throw t.createError(`Container not found: ${e}`,"CONTAINER_NOT_FOUND");return s}if(!(e instanceof HTMLElement))throw t.createError(`Invalid container type in ${s}`,"INVALID_CONTAINER");return e}static requireBrowser(e){if("undefined"==typeof document)throw t.createError(`Widgetic modules can only be used in a browser (${e}). With server-side rendering, start them from an effect or an event handler, which only run on the client.`,"NOT_IN_BROWSER")}static rejectApiKey(e){const s=e??{},r=s.partner;if(void 0!==s.apiKey||void 0!==r?.apiKey)throw t.createError("The apiKey option is not accepted: an API key must never be in a browser. Mint an editor session on your server (POST /v1/managed-users/{id}/editor-sessions) and return its token from the getToken option.","API_KEY_NOT_ALLOWED")}static validateConfig(e,s,r){if(!e)throw t.createError(`Configuration is required in ${r}`,"MISSING_CONFIG");for(const n of s)if(!(n in e))throw t.createError(`Missing required field: ${String(n)} in ${r}`,"MISSING_REQUIRED_FIELD")}static validateEventType(e,s){if(!s.includes(e))throw t.createError(`Invalid event type: ${e}`,"INVALID_EVENT_TYPE")}static validateFileUpload(e,s,r){if(e.size>s)throw t.createError(`File size exceeds maximum allowed size of ${s} bytes`,"FILE_TOO_LARGE");if(!r.includes("*/*")&&!r.includes(e.type))throw t.createError(`File type ${e.type} is not allowed`,"INVALID_FILE_TYPE")}}const i=["mode","preset","colors","radius","font"],a=["light","dark","system"],c="(prefers-color-scheme: dark)";function h(e){return"string"==typeof e&&a.includes(e)}function d(e){const t="string"==typeof e?e:e?.mode;return h(t)?t:void 0}function l(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=Object.fromEntries(Object.entries(e).filter(([e,t])=>"mode"!==e&&void 0!==t));return Object.keys(t).length>0?t:void 0}function u(e){return"system"===e?"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(c).matches?"dark":"light":"dark"===e?"dark":"light"}function m(e,t){const s=d(e),r=s?u(s):t.mode,n=l(e)??t.settings;return n?{...n,mode:r}:r}class f extends Error{constructor(e,t){super(`The "${e}" module failed to start: ${t instanceof Error?t.message:String(t)}`),this.code="MOUNT_FAILED",this.name="ModuleMountError",this.moduleName=e,this.cause=t,Object.setPrototypeOf(this,f.prototype)}}class g{constructor(e,t){this.events=e,this.options=t,this.active=new Map}async mount(e,s){o.rejectApiKey(s);const r=o.validateContainer(s.container,"LifecycleManager.mount"),{version:n,theme:i,placeholder:a,loadingLabel:c,on:h,callbacks:d,signal:u,...g}=s,y=function(e){const t={...e};return delete t.container,t}(g),w=this.generateInstanceId(),E=!1===a?null:this.showPlaceholder(r,e,c);let M=null;const S=[];try{p(u,e);const t=await this.options.loader.load(e,{version:n});p(u,e);const{getToken:s,apiUrl:o,locale:a}=this.options.moduleDefaults;try{M=new t.Module(r,{apiUrl:o,locale:a,...s?{getToken:async e=>s(e)}:{},...y,theme:m(i,{mode:this.options.getThemeMode(),settings:this.options.getThemeSettings?.()})}),S.push(...this.connectEvents(w,M,{on:h,callbacks:d})),await M.mount()}catch(t){throw new f(e,t)}p(u,e);const c=this.createMountedModule(w,e,t.version,r,M);return this.active.set(w,{mounted:c,stopListening:S,hasOwnSettings:void 0!==l(i)}),c}catch(e){for(const e of S)e();throw await this.unmountQuietly(M),t.handleError(e,"LifecycleManager.mount")}finally{E?.remove()}}async unmount(e){const s=this.active.get(e);if(!s)throw t.createError(`No instance found for ID: ${e}`,"INSTANCE_NOT_FOUND");this.active.delete(e);try{await(s.mounted.module.unmount?.())}finally{for(const e of s.stopListening)e()}}get(e){return this.active.get(e)?.mounted}setThemeMode(e){for(const{mounted:t}of this.active.values())this.tellModule(t,e)}setDefaultTheme(e,t,s=!0){for(const{mounted:r,hasOwnSettings:n}of this.active.values())n?s&&this.tellModule(r,t):this.tellModule(r,{...e,mode:t})}tellModule(e,t){try{e.module.setTheme?.(t)}catch(s){console.error(`[widgetic-ui] The "${e.type}" module could not apply the theme ${JSON.stringify(t)}:`,s)}}async cleanup(){const e=await Promise.allSettled([...this.active.keys()].map(e=>this.unmount(e)));for(const t of e)"rejected"===t.status&&console.error("[widgetic-ui] A module failed to unmount during cleanup:",t.reason)}connectEvents(e,t,{on:s,callbacks:r}){const n=[];if("function"!=typeof t.on)return n;const o=(e,s)=>{n.push(t.on(e,s))};for(const[e,t]of Object.entries(s??{}))"function"==typeof t&&o(e,t);return o("ready",()=>{r?.onReady?.(),this.events.emit("ready",{componentId:e})}),o("error",t=>{const s=function(e){if(e instanceof Error)return e;const{message:t,code:s,fatal:r}=e??{},n=new Error("string"==typeof t?t:"The module reported an error");"string"==typeof s&&(n.code=s);"boolean"==typeof r&&(n.fatal=r);return n}(t);r?.onError?.(s),this.events.emit("error",{componentId:e,error:s})}),n}createMountedModule(e,t,s,r,n){return{id:e,type:t,version:s,container:r,module:n,on:(e,s)=>"function"!=typeof n.on?(console.warn(`[widgetic-ui] The "${t}" module does not report events.`),()=>{}):n.on(e,s),off:(e,t)=>n.off?.(e,t),setTheme:s=>{if("function"!=typeof n.setTheme)return void console.warn(`[widgetic-ui] The "${t}" module cannot change its look.`);n.setTheme(s);const r=this.active.get(e);r&&"object"==typeof s&&(r.hasOwnSettings=!0)},setLanguage:e=>{"function"==typeof n.setLanguage?n.setLanguage(e):console.warn(`[widgetic-ui] The "${t}" module has no words to translate yet.`)},unmount:()=>this.unmount(e)}}async unmountQuietly(e){try{await(e?.unmount?.())}catch(e){console.warn("[widgetic-ui] A module that failed to start also failed to clean up:",e)}}showPlaceholder(e,t,s){const r=document.createElement("div");r.setAttribute("data-widgetic-ui-loading",t),r.setAttribute("role","status"),r.setAttribute("aria-label","string"==typeof s&&""!==s.trim()?s:"Loading"),Object.assign(r.style,{display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",width:"100%",minHeight:this.getComponentMinHeight(t)});const n=document.createElement("div");return Object.assign(n.style,{width:"28px",height:"28px",border:"3px solid rgba(128, 128, 128, 0.25)",borderTopColor:"#3b82f6",borderRadius:"50%"}),"function"==typeof n.animate&&n.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:1e3,iterations:1/0}),r.appendChild(n),e.appendChild(r),r}getComponentMinHeight(e){switch(e){case"widget-creator":case"composition-editor":return"480px";case"embed-editor":case"file-browser":return"380px";default:return"280px"}}generateInstanceId(){return`widgetic-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}function p(e,s){if(e?.aborted){const e=t.createError(`Mounting the "${s}" module was cancelled.`,"MOUNT_ABORTED");throw e.name="AbortError",e}}class y{constructor(){this.handlers=new Map}on(e,t){const s=this.handlers.get(e)??new Set;return s.add(t),this.handlers.set(e,s),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){const s=this.handlers.get(e);if(!s)return;const r={type:e,...t,timestamp:Date.now()};for(const t of[...s])try{t(r)}catch(t){console.error(`[widgetic-ui] A handler for "${e}" threw:`,t)}}destroy(){this.handlers.clear()}}const w="https://api.widgetic.com",E="https://cdn.widgetic.com/modules",M={NODE_ENV:"production",API_URL:w,API_VERSION:"/v1",CLIENT_URL:"https://widgetic.com",PRODUCTION_URL:w,CDN_URL:"https://cdn.widgetic.com",EMBED_SDK_URL:"/sdks/browser/embed-sdk.js"};class S{constructor(){this.config={...M}}static getInstance(){return S.instance||(S.instance=new S),S.instance}initialize(e){this.config={...M,...e}}getApiUrl(){return(this.isProduction?this.config.PRODUCTION_URL:this.config.API_URL)+this.config.API_VERSION}getCdnUrl(){return this.config.CDN_URL}get isProduction(){return"production"===this.config.NODE_ENV}validateConfig(){if(!this.config.API_URL)throw new Error("API_URL is required");if(!this.config.API_VERSION)throw new Error("API_VERSION is required");if(!this.config.CLIENT_URL)throw new Error("CLIENT_URL is required")}}const v=S.getInstance();class I extends Error{constructor(e,t,s){super(t),this.name="ModuleLoadError",this.code=e,this.moduleName=s.moduleName,this.url=s.url,this.cause=s.cause,Object.setPrototypeOf(this,I.prototype)}}const T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,L=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$/,b=[300,900],_=e=>import(e);class N{constructor(e={}){this.loads=new Map,this.baseUrl=function(e){const t="undefined"!=typeof document?document.baseURI:"http://localhost/";let s;try{s=new URL(e,t)}catch(t){throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl is not an address: ${e}`,{moduleName:"",cause:t})}if("https:"!==s.protocol&&"http:"!==s.protocol)throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl must be an http(s) address, got ${s.protocol}`,{moduleName:""});s.pathname.endsWith("/")||(s.pathname+="/");return s}(e.moduleBaseUrl??E),this.fetchImpl=e.fetchImpl??((e,t)=>fetch(e,t)),this.importImpl=e.importImpl??_,this.retryDelaysMs=e.retryDelaysMs??b}async load(e,t={}){!function(e){if("string"!=typeof e||e.length>64||!T.test(e))throw new I("INVALID_MODULE_NAME",`"${String(e)}" is not a module name. Use lowercase letters, digits and dashes, like "file-browser".`,{moduleName:String(e)})}(e);const s=t.version;void 0!==s&&function(e,t){if("string"!=typeof t||!L.test(t))throw new I("INVALID_VERSION",`"${String(t)}" is not a version. Use an exact version like "1.2.0".`,{moduleName:e})}(e,s);const r=`${e}@${s??"latest"}`,n=this.loads.get(r);if(n)return n;const o=this.loadUncached(e,s).catch(e=>{throw this.loads.delete(r),e});return this.loads.set(r,o),o}async loadUncached(e,t){let s,r;if(void 0!==t)s=t,r=new URL(`${e}/${t}/index.js`,this.baseUrl);else{const t=await this.fetchManifest(e);s=t.version,r=this.resolveEntryUrl(e,t)}return{Module:await this.importModuleFile(e,r),name:e,version:s,url:r.href}}async fetchManifest(e){const t=new URL(`${e}/manifest.json`,this.baseUrl);try{return await this.withRetries(async()=>{const s=await this.fetchImpl(t.href,{credentials:"omit"});if(404===s.status||403===s.status)throw new I("MODULE_NOT_FOUND",`There is no "${e}" module at ${t.href} (HTTP ${s.status}).`,{moduleName:e,url:t.href});if(!s.ok)throw new Error(`HTTP ${s.status} for ${t.href}`);let r;try{r=await s.json()}catch(s){throw new I("MANIFEST_INVALID",`The manifest at ${t.href} is not JSON.`,{moduleName:e,url:t.href,cause:s})}return this.validateManifest(e,t,r)})}catch(s){if(s instanceof I)throw s;throw new I("MANIFEST_UNAVAILABLE",`Could not load the manifest of "${e}" from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}}validateManifest(e,t,s){const r=s=>{throw new I("MANIFEST_INVALID",`The manifest at ${t.href} ${s}.`,{moduleName:e,url:t.href})};if("object"!=typeof s||null===s)return r("is not a JSON object");const{name:n,version:o,entry:i}=s;return n!==e?r(`is for "${String(n)}", not "${e}"`):"string"==typeof o&&L.test(o)?"string"!=typeof i||0===i.length?r('has no "entry"'):{name:n,version:o,entry:i}:r(`has no valid "version" (found ${JSON.stringify(o)})`)}resolveEntryUrl(e,t){const s=new URL(`${e}/manifest.json`,this.baseUrl),r=new URL(`${e}/`,this.baseUrl);let n;try{n=new URL(t.entry,s)}catch(r){throw new I("MANIFEST_INVALID",`The manifest of "${e}" has an "entry" that is not an address: ${t.entry}`,{moduleName:e,url:s.href,cause:r})}const o=n.origin===r.origin&&n.pathname.startsWith(r.pathname),i=/\.m?js$/.test(n.pathname);if(!o||!i)throw new I("MANIFEST_INVALID",`The manifest of "${e}" points at ${n.href}, which is not a script inside ${r.href}.`,{moduleName:e,url:s.href});return n}async importModuleFile(e,t){let s;try{s=await this.withRetries(async e=>{const s=0===e?t.href:function(e,t){const s=new URL(e.href);return s.searchParams.set("retry",String(t)),s.href}(t,e);return this.importImpl(s)})}catch(s){throw new I("MODULE_LOAD_FAILED",`Could not load the "${e}" module from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}const r=s?.default;if("function"!=typeof r)throw new I("MODULE_INVALID",`The file at ${t.href} does not export a module class as its default export.`,{moduleName:e,url:t.href});return r}async withRetries(e){let t;for(let s=0;s<=this.retryDelaysMs.length;s++)try{return await e(s)}catch(e){if(e instanceof I)throw e;t=e;const r=this.retryDelaysMs[s];void 0!==r&&await new Promise(e=>setTimeout(e,r))}throw t}}function O(e){return e instanceof Error?e.message:String(e)}const U=new Map;class ${constructor(e={}){this.stopWatchingSystemTheme=null,function(e){o.rejectApiKey(e);const s=e?.getToken;if(void 0!==s&&"function"!=typeof s)throw t.createError("WidgeticUI: getToken must be a function that resolves an editor session token (or { token, expiresAt }) minted by your server.","INVALID_GET_TOKEN")}(e),this.events=new y,this.loader=e.moduleLoader??function(e){let t=U.get(e);return t||(t=new N({moduleBaseUrl:e}),U.set(e,t)),t}(e.moduleBaseUrl??E),this.themeMode=d(e.theme)??"light",this.themeSettings=l(e.theme),this.lifecycleManager=new g(this.events,{loader:this.loader,moduleDefaults:{apiUrl:e.apiUrl??w,getToken:e.getToken,locale:e.locale},getThemeMode:()=>u(this.themeMode),getThemeSettings:()=>this.themeSettings}),this.followSystemThemeWhenAsked()}async mount(e,t){try{return await this.lifecycleManager.mount(e,t)}catch(e){if("MOUNT_ABORTED"===e?.code)throw e;throw console.error("Error mounting component:",e),t.callbacks?.onError?.(e),e}}async mountComponent(e,t){return(await this.mount(e,t)).id}async unmountComponent(e){try{await this.lifecycleManager.unmount(e)}catch(e){throw console.error("Error unmounting component:",e),e}}getComponent(e){return this.lifecycleManager.get(e)}async preload(e,t={}){o.requireBrowser(`preloading "${e}"`),await this.loader.load(e,t)}updateTheme(e){if(!function(e){if("string"==typeof e)return h(e);if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e).filter(([,e])=>void 0!==e);if(0===t.length)return!1;if(!t.every(([e])=>i.includes(e)))return!1;const s=e.mode;return void 0===s||h(s)}(e))throw t.createError(`Unknown theme: ${JSON.stringify(e)}. Use 'light', 'dark', 'system', or an object with some of mode, preset, colors, radius, font.`,"INVALID_THEME");const s=d(e),r=l(e);s&&(this.themeMode=s),r&&(this.themeSettings=r),this.followSystemThemeWhenAsked();const n=u(this.themeMode);r?this.lifecycleManager.setDefaultTheme(r,n,void 0!==s):this.lifecycleManager.setThemeMode(n),this.events.emit("theme:update",{theme:r?{...r,mode:this.themeMode}:{mode:this.themeMode}})}getTheme(){return{mode:this.themeMode,...this.themeSettings}}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.events.emit(e,t)}async destroy(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,await this.lifecycleManager.cleanup(),this.events.destroy()}followSystemThemeWhenAsked(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,"system"===this.themeMode&&(this.stopWatchingSystemTheme=function(e){if("undefined"==typeof window||"function"!=typeof window.matchMedia)return()=>{};const t=window.matchMedia(c),s=t=>e(t.matches?"dark":"light");return t.addEventListener("change",s),()=>t.removeEventListener("change",s)}(e=>this.lifecycleManager.setThemeMode(e)))}}async function A(e,t){o.rejectApiKey(t);const{getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,...c}=t,h=new $({getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,theme:c.theme});let d;try{d=await h.mount(e,c)}catch(e){throw await h.destroy(),e}return{...d,unmount:async()=>{try{await d.unmount()}finally{await h.destroy()}}}}let D=null;function C(){if(!D)throw t.createError("Call HighLevelUIAPI.initialize({ getToken }) before mounting a component.","NOT_INITIALIZED");return D}const R={WidgeticUI:$,initialize:async e=>{const t=new $(e),s=D;return D=t,await(s?.destroy()),t},mountComponent:async(e,t,s={})=>C().mountComponent(e,{...s,container:t}),unmountComponent:async e=>{await C().unmountComponent(e)}};const P={mode:"light",colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",surface:"#f8f9fa",text:"#212529",border:"#dee2e6"},spacing:{unit:4,scale:[0,4,8,16,24,32,48,64]},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',scale:[12,14,16,18,20,24,30,36,48,60]}},k={colors:{primary:"#3b82f6",secondary:"#64748b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",border:"#334155"}};class j{validateDomain(e){if(!e||"string"!=typeof e)return!1;const t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();return!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||(!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||this.allowedOrigins.some(e=>{if("*"===e)return!0;const s=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(s.startsWith("*.")){const e=s.slice(2);return t===e||t.endsWith("."+e)}return t===s}))}constructor(e=[]){this.allowedOrigins=e,this.DEVELOPMENT_CSP={defaultSrc:["'self'","http://localhost:*"],scriptSrc:["'self'","'unsafe-eval'","http://localhost:*",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'","http://localhost:*"],imgSrc:["'self'","data:","https:","http://localhost:*"],connectSrc:["'self'","http://localhost:*","ws://localhost:*",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'","http://localhost:*"]},this.PRODUCTION_CSP={defaultSrc:["'self'"],scriptSrc:["'self'",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'"],imgSrc:["'self'","data:","https:"],connectSrc:["'self'",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'"]},this.ALLOWED_DEV_ORIGINS=["localhost","127.0.0.1",M.CLIENT_URL,"null"],this.setupCSP()}setupCSP(){}buildCSPString(){const e=v.isProduction?this.PRODUCTION_CSP:this.DEVELOPMENT_CSP,t=[];for(const[s,r]of Object.entries(e))if(r&&r.length){const e=s.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${e} ${r.join(" ")}`)}return t.join("; ")}validateOrigin(e){if(!e||"string"!=typeof e)return!1;if("null"===e)return!v.isProduction;let t;try{t=new URL(e.startsWith("http")?e:`https://${e}`).hostname.toLowerCase()}catch{t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase()}return!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||(!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||this.allowedOrigins.some(s=>{if("*"===s)return!0;const r=s.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(r.startsWith("*.")){const e=r.slice(2);return t===e||t.endsWith("."+e)}return t===r||e.toLowerCase()===s.toLowerCase()}))}validateRequest(e){const t=e.headers.get("origin");if(!t&&!v.isProduction)return!0;if(!t)return!1;if(!this.validateOrigin(t))return console.warn(`Invalid request origin: ${t}`),!1;if(!v.isProduction)return!0;const s=e.headers.get("x-csrf-token");return!(s&&!this.validateCSRFToken(s))||(console.warn("Invalid CSRF token"),!1)}validateCSRFToken(e){return!0}validateMessage(e){if(!e.data)return console.warn("Invalid message: missing data"),!1;const{type:t,data:s}=e.data;return t&&"string"==typeof t?!s||"object"==typeof s||(console.warn("Invalid message: data must be an object"),!1):(console.warn("Invalid message: missing or invalid type"),!1)}}function x(e){return"string"!=typeof e?"":e.replace(/[<>]/g,"").replace(/javascript:/gi,"").replace(/on\w+=/gi,"").trim()}const V="0.1.6",F="@widgetic/ui-sdk";var W={SDK_VERSION:V,SDK_NAME:F,WidgeticUI:$,mountModule:A,HighLevelUIAPI:R};e.ComponentError=n,e.ConfigManager=S,e.Core=class{constructor(){}},e.DEFAULT_API_URL=w,e.DEFAULT_CONFIG=M,e.DEFAULT_MODULE_BASE_URL=E,e.EventSystem=class{constructor(e,t){this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null,this.bridge=e||("undefined"!=typeof window?window.parent:{}),this.targetOrigin=t||("undefined"!=typeof window&&window.location?.origin?window.location.origin:"*"),this.setupMessageListener()}setupMessageListener(){this.messageListener=e=>{this.handleMessage(e)},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.targetOrigin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.HighLevelUIAPI=R,e.HostCommunication=class{constructor(e,t,s){this.origin=e,this.events=t,this.boundHandleMessage=e=>{this.handleMessage(e)},this.security=s,this.setupMessageHandling()}setupMessageHandling(){"undefined"!=typeof window&&window.addEventListener("message",this.boundHandleMessage)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data;this.events.emit(t,s)}catch(e){console.error("Error handling message:",e),this.events.emit("error",{componentId:"host-communication",error:e instanceof Error?e:new Error("Message handling failed")})}}validateMessage(e){return e.origin===this.origin&&!!this.security.validateMessage(e)}async createSecureChannel(){const e=new MessageChannel;window.parent.postMessage({type:"secure-channel-request"},this.origin,[e.port2]),this.channel=e.port1,this.channel.onmessage=this.boundHandleMessage}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.boundHandleMessage),this.channel?.close()}},e.LifecycleManager=g,e.MessagingSystem=class{constructor(e){this.config=e,this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null;try{o.validateConfig(e,["origin"],"MessagingSystem.constructor"),this.bridge="undefined"!=typeof window?window.parent:{},this.security=e.security,this.setupMessageListener()}catch(e){throw t.handleError(e,"MessagingSystem.constructor")}}setupMessageListener(){this.messageListener=e=>{try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.config.origin||window.location.origin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.ModuleLoadError=I,e.ModuleLoader=N,e.ModuleMountError=f,e.SDK_NAME=F,e.SDK_VERSION=V,e.SecurityError=r,e.StateManager=class{constructor(e={}){this.state=new Map,this.listeners=new Map,this.snapshots=new Map,this.maxSnapshots=e.maxSnapshots||10}setState(e,t,s,r={}){try{this.state.has(e)||this.state.set(e,new Map);const n=this.state.get(e),o=n.get(t);n.set(t,s),r.snapshot&&this.createSnapshot(e),r.silent||this.notifyStateChange(e,t,s,o)}catch(e){throw console.error("Error setting state:",e),e}}getState(e,t){return this.state.get(e)?.get(t)}getComponentState(e){return this.state.get(e)}subscribe(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){this.listeners.get(e)?.delete(t)}createSnapshot(e){this.snapshots.has(e)||this.snapshots.set(e,[]);const t={timestamp:Date.now(),state:new Map(this.state.get(e))},s=this.snapshots.get(e);s.push(t),s.length>this.maxSnapshots&&s.shift()}restoreSnapshot(e,t=-1){try{const s=this.snapshots.get(e);if(!s?.length)return!1;const r=s[t<0?s.length-1:t];return!!r&&(this.state.set(e,new Map(r.state)),this.notifyStateChange(e,"*",this.getComponentState(e)),!0)}catch(e){return console.error("Error restoring snapshot:",e),!1}}notifyStateChange(e,t,s,r){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n({componentId:e,key:t,newValue:s,oldValue:r})}catch(e){console.error("Error in state change listener:",e)}})}cleanup(e){e?(this.state.delete(e),this.listeners.delete(e),this.snapshots.delete(e)):(this.state.clear(),this.listeners.clear(),this.snapshots.clear())}},e.ThemeManager=class{constructor(e,t){this.events=e,this.activePreset="default",this.currentTheme=this.createDefaultTheme(),t&&this.updateTheme(t),this.setupSystemThemeListener()}getCurrentTheme(){return{...this.currentTheme}}updateTheme(e){try{const t=this.mergeThemes(this.currentTheme,e);this.validateTheme(t),this.currentTheme=t,this.applyTheme(),this.notifyThemeUpdate()}catch(e){throw console.error("Error updating theme:",e),new Error(`Theme update failed: ${e instanceof Error?e.message:"Unknown error"}`,{cause:e})}}setMode(e){this.updateTheme({mode:e}),this.applyColorScheme(e)}setupSystemThemeListener(){window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{"system"===this.currentTheme.mode&&this.applyColorScheme(e.matches?"dark":"light")})}createDefaultTheme(){return{...P}}mergeThemes(e,t){return{mode:t.mode??e.mode,colors:t.colors?{...e.colors,...t.colors}:e.colors,spacing:t.spacing?{...e.spacing,...t.spacing}:e.spacing,typography:t.typography?{...e.typography,...t.typography}:e.typography}}validateTheme(e){if(Object.entries(e.colors).forEach(([e,t])=>{if(!this.isValidColor(t))throw new Error(`Invalid color value for ${e}: ${t}`)}),e.spacing.unit<=0)throw new Error("Spacing unit must be positive");if(!e.typography.fontFamily)throw new Error("Font family is required")}isValidColor(e){return/^(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{8}|rgb\(.*\)|rgba\(.*\)|hsl\(.*\)|hsla\(.*\))$/.test(e)}applyColorScheme(e){const t="dark"===e?k:P;this.updateTheme({colors:t.colors})}applyTheme(){document.documentElement.style.setProperty("--theme-mode",this.currentTheme.mode),Object.entries(this.currentTheme.colors).forEach(([e,t])=>{document.documentElement.style.setProperty(`--color-${e}`,t)}),document.documentElement.style.setProperty("--spacing-unit",`${this.currentTheme.spacing.unit}px`),this.currentTheme.spacing.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--spacing-${t}`,`${e}px`)}),document.documentElement.style.setProperty("--font-family",this.currentTheme.typography.fontFamily),this.currentTheme.typography.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--font-size-${t}`,`${e}px`)})}notifyThemeUpdate(){this.events.emit("theme:update",{theme:this.currentTheme})}},e.UILoader=$,e.ValidationError=s,e.WidgeticComponent=class{constructor(e,t){this.container=e,this.config=t,this.shadow=this.initializeShadowDOM(),this.state={status:"initializing",error:null},this.events=t.events,this.id=t.id,t.theme&&this.applyTheme(t.theme),this.events&&this.events.on("theme:update",e=>{const t=e?.theme||e;t&&"object"==typeof t&&this.applyTheme(t)})}initializeShadowDOM(){try{return this.container.attachShadow({mode:"closed"})}catch(e){throw console.error("Error initializing shadow DOM:",e),new Error("Failed to initialize component shadow DOM",{cause:e})}}setState(e){this.state={...this.state,...e},this.events.emit("state:update",{componentId:this.id,state:this.state})}handleError(e){console.error(`Error in ${this.constructor.name}:`,e),this.setState({status:"error",error:e}),this.events.emit("error",{componentId:this.id,error:e})}applyTheme(e){this.container.style.setProperty("--theme-mode",e.mode);const t=`\n :host {\n --theme-mode: ${e.mode};\n ${Object.entries(e.colors).map(([e,t])=>`--color-${e}: ${t};`).join("\n")}\n --spacing-unit: ${e.spacing.unit}px;\n ${e.spacing.scale.map((e,t)=>`--spacing-${t}: ${e}px;`).join("\n")}\n --font-family: ${e.typography.fontFamily};\n ${e.typography.scale.map((e,t)=>`--font-size-${t}: ${e}px;`).join("\n")}\n }\n `;if("undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype&&this.shadow&&"adoptedStyleSheets"in this.shadow)try{return this.themeStyleSheet||(this.themeStyleSheet=new CSSStyleSheet,this.shadow.adoptedStyleSheets=[...this.shadow.adoptedStyleSheets,this.themeStyleSheet]),void this.themeStyleSheet.replaceSync(t)}catch{}let s=this.shadow.querySelector("style[data-widgetic-theme]");s||(s=document.createElement("style"),s.setAttribute("data-widgetic-theme","true"),this.shadow.appendChild(s)),s.textContent=t}},e.WidgeticUI=$,e.config=v,e.createSecureContext=function(e=[]){const t=new j(e);return{validateMessage:e=>t.validateMessage(e),validateOrigin:e=>t.validateOrigin(e),sanitizeInput:x}},e.createSecureRequest=function(e,t={}){const s=new Headers(t.headers);return s.set("X-Requested-With","XMLHttpRequest"),new Request(e,{...t,headers:s,credentials:"same-origin"})},e.default=W,e.mountModule=A,e.sanitizeInput=x,e.validateOrigin=function(e,t=[]){return new j(t).validateOrigin(e)},e.validateResponse=function(e){if(!e.ok)return!1;const t=e.headers.get("content-type");return t&&!t.includes("application/json")&&console.warn("Unexpected content type:",t),!0},Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WidgeticUISDK={})}(this,function(e){"use strict";class t{static createError(e,t){const s=new Error(e);return s.code=t,s}static handleError(e,t){return e instanceof Error?e.code?e:this.createError(e.message,"UNKNOWN_ERROR"):"string"==typeof e?this.createError(e,"STRING_ERROR"):this.createError(`Unknown error in ${t}`,"UNKNOWN_ERROR")}static toSDKError(e){return{message:e.message,code:e.code||"UNKNOWN_ERROR",name:e.name,stack:e.stack,details:e}}}class s extends Error{constructor(e,t){super(e),this.field=t,this.name="ValidationError"}}class r extends Error{constructor(e,t){super(e),this.code=t,this.name="SecurityError"}}class n extends Error{constructor(e,t){super(e),this.componentId=t,this.name="ComponentError"}}class o{static validateId(e,s){if(!e||"string"!=typeof e||""===e.trim())throw t.createError(`Invalid ID provided in ${s}`,"INVALID_ID")}static validateContainer(e,s){if(o.requireBrowser(s),!e)throw t.createError(`Container is required in ${s}`,"MISSING_CONTAINER");if("string"==typeof e){const s=document.querySelector(e);if(!s)throw t.createError(`Container not found: ${e}`,"CONTAINER_NOT_FOUND");return s}if(!(e instanceof HTMLElement))throw t.createError(`Invalid container type in ${s}`,"INVALID_CONTAINER");return e}static requireBrowser(e){if("undefined"==typeof document)throw t.createError(`Widgetic modules can only be used in a browser (${e}). With server-side rendering, start them from an effect or an event handler, which only run on the client.`,"NOT_IN_BROWSER")}static rejectApiKey(e){const s=e??{},r=s.partner;if(void 0!==s.apiKey||void 0!==r?.apiKey)throw t.createError("The apiKey option is not accepted: an API key must never be in a browser. Mint an editor session on your server (POST /v1/managed-users/{id}/editor-sessions) and return its token from the getToken option.","API_KEY_NOT_ALLOWED")}static validateConfig(e,s,r){if(!e)throw t.createError(`Configuration is required in ${r}`,"MISSING_CONFIG");for(const n of s)if(!(n in e))throw t.createError(`Missing required field: ${String(n)} in ${r}`,"MISSING_REQUIRED_FIELD")}static validateEventType(e,s){if(!s.includes(e))throw t.createError(`Invalid event type: ${e}`,"INVALID_EVENT_TYPE")}static validateFileUpload(e,s,r){if(e.size>s)throw t.createError(`File size exceeds maximum allowed size of ${s} bytes`,"FILE_TOO_LARGE");if(!r.includes("*/*")&&!r.includes(e.type))throw t.createError(`File type ${e.type} is not allowed`,"INVALID_FILE_TYPE")}}const i=["mode","preset","colors","radius","font"],a=["light","dark","system"],c="(prefers-color-scheme: dark)";function h(e){return"string"==typeof e&&a.includes(e)}function d(e){const t="string"==typeof e?e:e?.mode;return h(t)?t:void 0}function l(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=Object.fromEntries(Object.entries(e).filter(([e,t])=>"mode"!==e&&void 0!==t));return Object.keys(t).length>0?t:void 0}function u(e){return"system"===e?"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(c).matches?"dark":"light":"dark"===e?"dark":"light"}function m(e,t){const s=d(e),r=s?u(s):t.mode,n=l(e)??t.settings;return n?{...n,mode:r}:r}class f extends Error{constructor(e,t){super(`The "${e}" module failed to start: ${t instanceof Error?t.message:String(t)}`),this.code="MOUNT_FAILED",this.name="ModuleMountError",this.moduleName=e,this.cause=t,Object.setPrototypeOf(this,f.prototype)}}class g{constructor(e,t){this.events=e,this.options=t,this.active=new Map}async mount(e,s){o.rejectApiKey(s);const r=o.validateContainer(s.container,"LifecycleManager.mount"),{version:n,theme:i,placeholder:a,loadingLabel:c,on:h,callbacks:d,signal:u,...g}=s,y=function(e){const t={...e};return delete t.container,t}(g),w=this.generateInstanceId(),E=!1===a?null:this.showPlaceholder(r,e,c);let M=null;const S=[];try{p(u,e);const t=await this.options.loader.load(e,{version:n});p(u,e);const{getToken:s,apiUrl:o,locale:a}=this.options.moduleDefaults;try{M=new t.Module(r,{apiUrl:o,locale:a,...s?{getToken:async e=>s(e)}:{},...y,theme:m(i,{mode:this.options.getThemeMode(),settings:this.options.getThemeSettings?.()})}),S.push(...this.connectEvents(w,M,{on:h,callbacks:d})),await M.mount()}catch(t){throw new f(e,t)}p(u,e);const c=this.createMountedModule(w,e,t.version,r,M);return this.active.set(w,{mounted:c,stopListening:S,hasOwnSettings:void 0!==l(i)}),c}catch(e){for(const e of S)e();throw await this.unmountQuietly(M),t.handleError(e,"LifecycleManager.mount")}finally{E?.remove()}}async unmount(e){const s=this.active.get(e);if(!s)throw t.createError(`No instance found for ID: ${e}`,"INSTANCE_NOT_FOUND");this.active.delete(e);try{await(s.mounted.module.unmount?.())}finally{for(const e of s.stopListening)e()}}get(e){return this.active.get(e)?.mounted}setThemeMode(e){for(const{mounted:t}of this.active.values())this.tellModule(t,e)}setDefaultTheme(e,t,s=!0){for(const{mounted:r,hasOwnSettings:n}of this.active.values())n?s&&this.tellModule(r,t):this.tellModule(r,{...e,mode:t})}tellModule(e,t){try{e.module.setTheme?.(t)}catch(s){console.error(`[widgetic-ui] The "${e.type}" module could not apply the theme ${JSON.stringify(t)}:`,s)}}async cleanup(){const e=await Promise.allSettled([...this.active.keys()].map(e=>this.unmount(e)));for(const t of e)"rejected"===t.status&&console.error("[widgetic-ui] A module failed to unmount during cleanup:",t.reason)}connectEvents(e,t,{on:s,callbacks:r}){const n=[];if("function"!=typeof t.on)return n;const o=(e,s)=>{n.push(t.on(e,s))};for(const[e,t]of Object.entries(s??{}))"function"==typeof t&&o(e,t);return o("ready",()=>{r?.onReady?.(),this.events.emit("ready",{componentId:e})}),o("error",t=>{const s=function(e){if(e instanceof Error)return e;const{message:t,code:s,fatal:r}=e??{},n=new Error("string"==typeof t?t:"The module reported an error");"string"==typeof s&&(n.code=s);"boolean"==typeof r&&(n.fatal=r);return n}(t);r?.onError?.(s),this.events.emit("error",{componentId:e,error:s})}),n}createMountedModule(e,t,s,r,n){return{id:e,type:t,version:s,container:r,module:n,on:(e,s)=>"function"!=typeof n.on?(console.warn(`[widgetic-ui] The "${t}" module does not report events.`),()=>{}):n.on(e,s),off:(e,t)=>n.off?.(e,t),setTheme:s=>{if("function"!=typeof n.setTheme)return void console.warn(`[widgetic-ui] The "${t}" module cannot change its look.`);n.setTheme(s);const r=this.active.get(e);r&&"object"==typeof s&&(r.hasOwnSettings=!0)},setLanguage:e=>{"function"==typeof n.setLanguage?n.setLanguage(e):console.warn(`[widgetic-ui] The "${t}" module has no words to translate yet.`)},unmount:()=>this.unmount(e)}}async unmountQuietly(e){try{await(e?.unmount?.())}catch(e){console.warn("[widgetic-ui] A module that failed to start also failed to clean up:",e)}}showPlaceholder(e,t,s){const r=document.createElement("div");r.setAttribute("data-widgetic-ui-loading",t),r.setAttribute("role","status"),r.setAttribute("aria-label","string"==typeof s&&""!==s.trim()?s:"Loading"),Object.assign(r.style,{display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",width:"100%",minHeight:this.getComponentMinHeight(t)});const n=document.createElement("div");return Object.assign(n.style,{width:"28px",height:"28px",border:"3px solid rgba(128, 128, 128, 0.25)",borderTopColor:"#3b82f6",borderRadius:"50%"}),"function"==typeof n.animate&&n.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:1e3,iterations:1/0}),r.appendChild(n),e.appendChild(r),r}getComponentMinHeight(e){switch(e){case"widget-creator":case"composition-editor":return"480px";case"embed-editor":case"file-browser":return"380px";default:return"280px"}}generateInstanceId(){return`widgetic-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}function p(e,s){if(e?.aborted){const e=t.createError(`Mounting the "${s}" module was cancelled.`,"MOUNT_ABORTED");throw e.name="AbortError",e}}class y{constructor(){this.handlers=new Map}on(e,t){const s=this.handlers.get(e)??new Set;return s.add(t),this.handlers.set(e,s),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){const s=this.handlers.get(e);if(!s)return;const r={type:e,...t,timestamp:Date.now()};for(const t of[...s])try{t(r)}catch(t){console.error(`[widgetic-ui] A handler for "${e}" threw:`,t)}}destroy(){this.handlers.clear()}}const w="https://api.widgetic.com",E="https://cdn.widgetic.com/modules",M={NODE_ENV:"production",API_URL:w,API_VERSION:"/v1",CLIENT_URL:"https://widgetic.com",PRODUCTION_URL:w,CDN_URL:"https://cdn.widgetic.com",EMBED_SDK_URL:"/sdks/browser/embed-sdk.js"};class S{constructor(){this.config={...M}}static getInstance(){return S.instance||(S.instance=new S),S.instance}initialize(e){this.config={...M,...e}}getApiUrl(){return(this.isProduction?this.config.PRODUCTION_URL:this.config.API_URL)+this.config.API_VERSION}getCdnUrl(){return this.config.CDN_URL}get isProduction(){return"production"===this.config.NODE_ENV}validateConfig(){if(!this.config.API_URL)throw new Error("API_URL is required");if(!this.config.API_VERSION)throw new Error("API_VERSION is required");if(!this.config.CLIENT_URL)throw new Error("CLIENT_URL is required")}}const v=S.getInstance();class I extends Error{constructor(e,t,s){super(t),this.name="ModuleLoadError",this.code=e,this.moduleName=s.moduleName,this.url=s.url,this.cause=s.cause,Object.setPrototypeOf(this,I.prototype)}}const T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,L=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$/,b=[300,900],_=e=>import(e);class N{constructor(e={}){this.loads=new Map,this.baseUrl=function(e){const t="undefined"!=typeof document?document.baseURI:"http://localhost/";let s;try{s=new URL(e,t)}catch(t){throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl is not an address: ${e}`,{moduleName:"",cause:t})}if("https:"!==s.protocol&&"http:"!==s.protocol)throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl must be an http(s) address, got ${s.protocol}`,{moduleName:""});s.pathname.endsWith("/")||(s.pathname+="/");return s}(e.moduleBaseUrl??E),this.fetchImpl=e.fetchImpl??((e,t)=>fetch(e,t)),this.importImpl=e.importImpl??_,this.retryDelaysMs=e.retryDelaysMs??b}async load(e,t={}){!function(e){if("string"!=typeof e||e.length>64||!T.test(e))throw new I("INVALID_MODULE_NAME",`"${String(e)}" is not a module name. Use lowercase letters, digits and dashes, like "file-browser".`,{moduleName:String(e)})}(e);const s=t.version;void 0!==s&&function(e,t){if("string"!=typeof t||!L.test(t))throw new I("INVALID_VERSION",`"${String(t)}" is not a version. Use an exact version like "1.2.0".`,{moduleName:e})}(e,s);const r=`${e}@${s??"latest"}`,n=this.loads.get(r);if(n)return n;const o=this.loadUncached(e,s).catch(e=>{throw this.loads.delete(r),e});return this.loads.set(r,o),o}async loadUncached(e,t){let s,r;if(void 0!==t)s=t,r=new URL(`${e}/${t}/index.js`,this.baseUrl);else{const t=await this.fetchManifest(e);s=t.version,r=this.resolveEntryUrl(e,t)}return{Module:await this.importModuleFile(e,r),name:e,version:s,url:r.href}}async fetchManifest(e){const t=new URL(`${e}/manifest.json`,this.baseUrl);try{return await this.withRetries(async()=>{const s=await this.fetchImpl(t.href,{credentials:"omit"});if(404===s.status||403===s.status)throw new I("MODULE_NOT_FOUND",`There is no "${e}" module at ${t.href} (HTTP ${s.status}).`,{moduleName:e,url:t.href});if(!s.ok)throw new Error(`HTTP ${s.status} for ${t.href}`);let r;try{r=await s.json()}catch(s){throw new I("MANIFEST_INVALID",`The manifest at ${t.href} is not JSON.`,{moduleName:e,url:t.href,cause:s})}return this.validateManifest(e,t,r)})}catch(s){if(s instanceof I)throw s;throw new I("MANIFEST_UNAVAILABLE",`Could not load the manifest of "${e}" from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}}validateManifest(e,t,s){const r=s=>{throw new I("MANIFEST_INVALID",`The manifest at ${t.href} ${s}.`,{moduleName:e,url:t.href})};if("object"!=typeof s||null===s)return r("is not a JSON object");const{name:n,version:o,entry:i}=s;return n!==e?r(`is for "${String(n)}", not "${e}"`):"string"==typeof o&&L.test(o)?"string"!=typeof i||0===i.length?r('has no "entry"'):{name:n,version:o,entry:i}:r(`has no valid "version" (found ${JSON.stringify(o)})`)}resolveEntryUrl(e,t){const s=new URL(`${e}/manifest.json`,this.baseUrl),r=new URL(`${e}/`,this.baseUrl);let n;try{n=new URL(t.entry,s)}catch(r){throw new I("MANIFEST_INVALID",`The manifest of "${e}" has an "entry" that is not an address: ${t.entry}`,{moduleName:e,url:s.href,cause:r})}const o=n.origin===r.origin&&n.pathname.startsWith(r.pathname),i=/\.m?js$/.test(n.pathname);if(!o||!i)throw new I("MANIFEST_INVALID",`The manifest of "${e}" points at ${n.href}, which is not a script inside ${r.href}.`,{moduleName:e,url:s.href});return n}async importModuleFile(e,t){let s;try{s=await this.withRetries(async e=>{const s=0===e?t.href:function(e,t){const s=new URL(e.href);return s.searchParams.set("retry",String(t)),s.href}(t,e);return this.importImpl(s)})}catch(s){throw new I("MODULE_LOAD_FAILED",`Could not load the "${e}" module from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}const r=s?.default;if("function"!=typeof r)throw new I("MODULE_INVALID",`The file at ${t.href} does not export a module class as its default export.`,{moduleName:e,url:t.href});return r}async withRetries(e){let t;for(let s=0;s<=this.retryDelaysMs.length;s++)try{return await e(s)}catch(e){if(e instanceof I)throw e;t=e;const r=this.retryDelaysMs[s];void 0!==r&&await new Promise(e=>setTimeout(e,r))}throw t}}function O(e){return e instanceof Error?e.message:String(e)}const U=new Map;class ${constructor(e={}){this.stopWatchingSystemTheme=null,function(e){o.rejectApiKey(e);const s=e?.getToken;if(void 0!==s&&"function"!=typeof s)throw t.createError("WidgeticUI: getToken must be a function that resolves an editor session token (or { token, expiresAt }) minted by your server.","INVALID_GET_TOKEN")}(e),this.events=new y,this.loader=e.moduleLoader??function(e){let t=U.get(e);return t||(t=new N({moduleBaseUrl:e}),U.set(e,t)),t}(e.moduleBaseUrl??E),this.themeMode=d(e.theme)??"light",this.themeSettings=l(e.theme),this.lifecycleManager=new g(this.events,{loader:this.loader,moduleDefaults:{apiUrl:e.apiUrl??w,getToken:e.getToken,locale:e.locale},getThemeMode:()=>u(this.themeMode),getThemeSettings:()=>this.themeSettings}),this.followSystemThemeWhenAsked()}async mount(e,t){try{return await this.lifecycleManager.mount(e,t)}catch(e){if("MOUNT_ABORTED"===e?.code)throw e;throw console.error("Error mounting component:",e),t.callbacks?.onError?.(e),e}}async mountComponent(e,t){return(await this.mount(e,t)).id}async unmountComponent(e){try{await this.lifecycleManager.unmount(e)}catch(e){throw console.error("Error unmounting component:",e),e}}getComponent(e){return this.lifecycleManager.get(e)}async preload(e,t={}){o.requireBrowser(`preloading "${e}"`),await this.loader.load(e,t)}updateTheme(e){if(!function(e){if("string"==typeof e)return h(e);if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e).filter(([,e])=>void 0!==e);if(0===t.length)return!1;if(!t.every(([e])=>i.includes(e)))return!1;const s=e.mode;return void 0===s||h(s)}(e))throw t.createError(`Unknown theme: ${JSON.stringify(e)}. Use 'light', 'dark', 'system', or an object with some of mode, preset, colors, radius, font.`,"INVALID_THEME");const s=d(e),r=l(e);s&&(this.themeMode=s),r&&(this.themeSettings=r),this.followSystemThemeWhenAsked();const n=u(this.themeMode);r?this.lifecycleManager.setDefaultTheme(r,n,void 0!==s):this.lifecycleManager.setThemeMode(n),this.events.emit("theme:update",{theme:r?{...r,mode:this.themeMode}:{mode:this.themeMode}})}getTheme(){return{mode:this.themeMode,...this.themeSettings}}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.events.emit(e,t)}async destroy(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,await this.lifecycleManager.cleanup(),this.events.destroy()}followSystemThemeWhenAsked(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,"system"===this.themeMode&&(this.stopWatchingSystemTheme=function(e){if("undefined"==typeof window||"function"!=typeof window.matchMedia)return()=>{};const t=window.matchMedia(c),s=t=>e(t.matches?"dark":"light");return t.addEventListener("change",s),()=>t.removeEventListener("change",s)}(e=>this.lifecycleManager.setThemeMode(e)))}}async function A(e,t){o.rejectApiKey(t);const{getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,...c}=t,h=new $({getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,theme:c.theme});let d;try{d=await h.mount(e,c)}catch(e){throw await h.destroy(),e}return{...d,unmount:async()=>{try{await d.unmount()}finally{await h.destroy()}}}}let D=null;function C(){if(!D)throw t.createError("Call HighLevelUIAPI.initialize({ getToken }) before mounting a component.","NOT_INITIALIZED");return D}const R={WidgeticUI:$,initialize:async e=>{const t=new $(e),s=D;return D=t,await(s?.destroy()),t},mountComponent:async(e,t,s={})=>C().mountComponent(e,{...s,container:t}),unmountComponent:async e=>{await C().unmountComponent(e)}};const P={mode:"light",colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",surface:"#f8f9fa",text:"#212529",border:"#dee2e6"},spacing:{unit:4,scale:[0,4,8,16,24,32,48,64]},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',scale:[12,14,16,18,20,24,30,36,48,60]}},k={colors:{primary:"#3b82f6",secondary:"#64748b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",border:"#334155"}};class j{validateDomain(e){if(!e||"string"!=typeof e)return!1;const t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();return!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||(!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||this.allowedOrigins.some(e=>{if("*"===e)return!0;const s=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(s.startsWith("*.")){const e=s.slice(2);return t===e||t.endsWith("."+e)}return t===s}))}constructor(e=[]){this.allowedOrigins=e,this.DEVELOPMENT_CSP={defaultSrc:["'self'","http://localhost:*"],scriptSrc:["'self'","'unsafe-eval'","http://localhost:*",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'","http://localhost:*"],imgSrc:["'self'","data:","https:","http://localhost:*"],connectSrc:["'self'","http://localhost:*","ws://localhost:*",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'","http://localhost:*"]},this.PRODUCTION_CSP={defaultSrc:["'self'"],scriptSrc:["'self'",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'"],imgSrc:["'self'","data:","https:"],connectSrc:["'self'",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'"]},this.ALLOWED_DEV_ORIGINS=["localhost","127.0.0.1",M.CLIENT_URL,"null"],this.setupCSP()}setupCSP(){}buildCSPString(){const e=v.isProduction?this.PRODUCTION_CSP:this.DEVELOPMENT_CSP,t=[];for(const[s,r]of Object.entries(e))if(r&&r.length){const e=s.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${e} ${r.join(" ")}`)}return t.join("; ")}validateOrigin(e){if(!e||"string"!=typeof e)return!1;if("null"===e)return!v.isProduction;let t;try{t=new URL(e.startsWith("http")?e:`https://${e}`).hostname.toLowerCase()}catch{t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase()}return!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||(!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||this.allowedOrigins.some(s=>{if("*"===s)return!0;const r=s.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(r.startsWith("*.")){const e=r.slice(2);return t===e||t.endsWith("."+e)}return t===r||e.toLowerCase()===s.toLowerCase()}))}validateRequest(e){const t=e.headers.get("origin");if(!t&&!v.isProduction)return!0;if(!t)return!1;if(!this.validateOrigin(t))return console.warn(`Invalid request origin: ${t}`),!1;if(!v.isProduction)return!0;const s=e.headers.get("x-csrf-token");return!(s&&!this.validateCSRFToken(s))||(console.warn("Invalid CSRF token"),!1)}validateCSRFToken(e){return!0}validateMessage(e){if(!e.data)return console.warn("Invalid message: missing data"),!1;const{type:t,data:s}=e.data;return t&&"string"==typeof t?!s||"object"==typeof s||(console.warn("Invalid message: data must be an object"),!1):(console.warn("Invalid message: missing or invalid type"),!1)}}function x(e){return"string"!=typeof e?"":e.replace(/[<>]/g,"").replace(/javascript:/gi,"").replace(/on\w+=/gi,"").trim()}const V="0.1.8",F="@widgetic/ui-sdk";var W={SDK_VERSION:V,SDK_NAME:F,WidgeticUI:$,mountModule:A,HighLevelUIAPI:R};e.ComponentError=n,e.ConfigManager=S,e.Core=class{constructor(){}},e.DEFAULT_API_URL=w,e.DEFAULT_CONFIG=M,e.DEFAULT_MODULE_BASE_URL=E,e.EventSystem=class{constructor(e,t){this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null,this.bridge=e||("undefined"!=typeof window?window.parent:{}),this.targetOrigin=t||("undefined"!=typeof window&&window.location?.origin?window.location.origin:"*"),this.setupMessageListener()}setupMessageListener(){this.messageListener=e=>{this.handleMessage(e)},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.targetOrigin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.HighLevelUIAPI=R,e.HostCommunication=class{constructor(e,t,s){this.origin=e,this.events=t,this.boundHandleMessage=e=>{this.handleMessage(e)},this.security=s,this.setupMessageHandling()}setupMessageHandling(){"undefined"!=typeof window&&window.addEventListener("message",this.boundHandleMessage)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data;this.events.emit(t,s)}catch(e){console.error("Error handling message:",e),this.events.emit("error",{componentId:"host-communication",error:e instanceof Error?e:new Error("Message handling failed")})}}validateMessage(e){return e.origin===this.origin&&!!this.security.validateMessage(e)}async createSecureChannel(){const e=new MessageChannel;window.parent.postMessage({type:"secure-channel-request"},this.origin,[e.port2]),this.channel=e.port1,this.channel.onmessage=this.boundHandleMessage}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.boundHandleMessage),this.channel?.close()}},e.LifecycleManager=g,e.MessagingSystem=class{constructor(e){this.config=e,this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null;try{o.validateConfig(e,["origin"],"MessagingSystem.constructor"),this.bridge="undefined"!=typeof window?window.parent:{},this.security=e.security,this.setupMessageListener()}catch(e){throw t.handleError(e,"MessagingSystem.constructor")}}setupMessageListener(){this.messageListener=e=>{try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.config.origin||window.location.origin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.ModuleLoadError=I,e.ModuleLoader=N,e.ModuleMountError=f,e.SDK_NAME=F,e.SDK_VERSION=V,e.SecurityError=r,e.StateManager=class{constructor(e={}){this.state=new Map,this.listeners=new Map,this.snapshots=new Map,this.maxSnapshots=e.maxSnapshots||10}setState(e,t,s,r={}){try{this.state.has(e)||this.state.set(e,new Map);const n=this.state.get(e),o=n.get(t);n.set(t,s),r.snapshot&&this.createSnapshot(e),r.silent||this.notifyStateChange(e,t,s,o)}catch(e){throw console.error("Error setting state:",e),e}}getState(e,t){return this.state.get(e)?.get(t)}getComponentState(e){return this.state.get(e)}subscribe(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){this.listeners.get(e)?.delete(t)}createSnapshot(e){this.snapshots.has(e)||this.snapshots.set(e,[]);const t={timestamp:Date.now(),state:new Map(this.state.get(e))},s=this.snapshots.get(e);s.push(t),s.length>this.maxSnapshots&&s.shift()}restoreSnapshot(e,t=-1){try{const s=this.snapshots.get(e);if(!s?.length)return!1;const r=s[t<0?s.length-1:t];return!!r&&(this.state.set(e,new Map(r.state)),this.notifyStateChange(e,"*",this.getComponentState(e)),!0)}catch(e){return console.error("Error restoring snapshot:",e),!1}}notifyStateChange(e,t,s,r){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n({componentId:e,key:t,newValue:s,oldValue:r})}catch(e){console.error("Error in state change listener:",e)}})}cleanup(e){e?(this.state.delete(e),this.listeners.delete(e),this.snapshots.delete(e)):(this.state.clear(),this.listeners.clear(),this.snapshots.clear())}},e.ThemeManager=class{constructor(e,t){this.events=e,this.activePreset="default",this.currentTheme=this.createDefaultTheme(),t&&this.updateTheme(t),this.setupSystemThemeListener()}getCurrentTheme(){return{...this.currentTheme}}updateTheme(e){try{const t=this.mergeThemes(this.currentTheme,e);this.validateTheme(t),this.currentTheme=t,this.applyTheme(),this.notifyThemeUpdate()}catch(e){throw console.error("Error updating theme:",e),new Error(`Theme update failed: ${e instanceof Error?e.message:"Unknown error"}`,{cause:e})}}setMode(e){this.updateTheme({mode:e}),this.applyColorScheme(e)}setupSystemThemeListener(){window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{"system"===this.currentTheme.mode&&this.applyColorScheme(e.matches?"dark":"light")})}createDefaultTheme(){return{...P}}mergeThemes(e,t){return{mode:t.mode??e.mode,colors:t.colors?{...e.colors,...t.colors}:e.colors,spacing:t.spacing?{...e.spacing,...t.spacing}:e.spacing,typography:t.typography?{...e.typography,...t.typography}:e.typography}}validateTheme(e){if(Object.entries(e.colors).forEach(([e,t])=>{if(!this.isValidColor(t))throw new Error(`Invalid color value for ${e}: ${t}`)}),e.spacing.unit<=0)throw new Error("Spacing unit must be positive");if(!e.typography.fontFamily)throw new Error("Font family is required")}isValidColor(e){return/^(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{8}|rgb\(.*\)|rgba\(.*\)|hsl\(.*\)|hsla\(.*\))$/.test(e)}applyColorScheme(e){const t="dark"===e?k:P;this.updateTheme({colors:t.colors})}applyTheme(){document.documentElement.style.setProperty("--theme-mode",this.currentTheme.mode),Object.entries(this.currentTheme.colors).forEach(([e,t])=>{document.documentElement.style.setProperty(`--color-${e}`,t)}),document.documentElement.style.setProperty("--spacing-unit",`${this.currentTheme.spacing.unit}px`),this.currentTheme.spacing.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--spacing-${t}`,`${e}px`)}),document.documentElement.style.setProperty("--font-family",this.currentTheme.typography.fontFamily),this.currentTheme.typography.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--font-size-${t}`,`${e}px`)})}notifyThemeUpdate(){this.events.emit("theme:update",{theme:this.currentTheme})}},e.UILoader=$,e.ValidationError=s,e.WidgeticComponent=class{constructor(e,t){this.container=e,this.config=t,this.shadow=this.initializeShadowDOM(),this.state={status:"initializing",error:null},this.events=t.events,this.id=t.id,t.theme&&this.applyTheme(t.theme),this.events&&this.events.on("theme:update",e=>{const t=e?.theme||e;t&&"object"==typeof t&&this.applyTheme(t)})}initializeShadowDOM(){try{return this.container.attachShadow({mode:"closed"})}catch(e){throw console.error("Error initializing shadow DOM:",e),new Error("Failed to initialize component shadow DOM",{cause:e})}}setState(e){this.state={...this.state,...e},this.events.emit("state:update",{componentId:this.id,state:this.state})}handleError(e){console.error(`Error in ${this.constructor.name}:`,e),this.setState({status:"error",error:e}),this.events.emit("error",{componentId:this.id,error:e})}applyTheme(e){this.container.style.setProperty("--theme-mode",e.mode);const t=`\n :host {\n --theme-mode: ${e.mode};\n ${Object.entries(e.colors).map(([e,t])=>`--color-${e}: ${t};`).join("\n")}\n --spacing-unit: ${e.spacing.unit}px;\n ${e.spacing.scale.map((e,t)=>`--spacing-${t}: ${e}px;`).join("\n")}\n --font-family: ${e.typography.fontFamily};\n ${e.typography.scale.map((e,t)=>`--font-size-${t}: ${e}px;`).join("\n")}\n }\n `;if("undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype&&this.shadow&&"adoptedStyleSheets"in this.shadow)try{return this.themeStyleSheet||(this.themeStyleSheet=new CSSStyleSheet,this.shadow.adoptedStyleSheets=[...this.shadow.adoptedStyleSheets,this.themeStyleSheet]),void this.themeStyleSheet.replaceSync(t)}catch{}let s=this.shadow.querySelector("style[data-widgetic-theme]");s||(s=document.createElement("style"),s.setAttribute("data-widgetic-theme","true"),this.shadow.appendChild(s)),s.textContent=t}},e.WidgeticUI=$,e.config=v,e.createSecureContext=function(e=[]){const t=new j(e);return{validateMessage:e=>t.validateMessage(e),validateOrigin:e=>t.validateOrigin(e),sanitizeInput:x}},e.createSecureRequest=function(e,t={}){const s=new Headers(t.headers);return s.set("X-Requested-With","XMLHttpRequest"),new Request(e,{...t,headers:s,credentials:"same-origin"})},e.default=W,e.mountModule=A,e.sanitizeInput=x,e.validateOrigin=function(e,t=[]){return new j(t).validateOrigin(e)},e.validateResponse=function(e){if(!e.ok)return!1;const t=e.headers.get("content-type");return t&&!t.includes("application/json")&&console.warn("Unexpected content type:",t),!0},Object.defineProperty(e,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=ui-sdk.js.map
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@widgetic/ui-sdk",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Framework-agnostic UI components for building Widgetic integrations",
5
+ "license": "SEE LICENSE IN LICENSE",
5
6
  "main": "dist/index.cjs",
6
7
  "module": "dist/index.esm.js",
7
8
  "types": "dist/index.d.ts",
@@ -65,7 +66,7 @@
65
66
  "lint": "eslint .",
66
67
  "build:sdk:local": "NODE_ENV=production rollup -c ./scripts-sdk/rollup.config.js",
67
68
  "prepublishOnly": "npm run build:publish && node scripts-sdk/check-no-secrets.js",
68
- "publish-to-npm": "npm version patch --no-git-tag-version && node -e \"const fs=require('fs'); const v=require('./package.json').version; const p='src/sdk/version.ts'; fs.writeFileSync(p, fs.readFileSync(p,'utf8').replace(/SDK_VERSION = '[^']+'/, \\\"SDK_VERSION = '\\\"+v+\\\"'\\\"))\"; npm run build:publish && node scripts-sdk/check-no-secrets.js && npm publish --ignore-scripts --access public && node modules/scripts/advance-module-version.mjs && cd modules && ver=$(node -p \"require('./package.json').version\") && npm run release:check -- --tag modules-v$ver && NODE_OPTIONS=--max-old-space-size=8192 npm run build && npm run release:publish -- --tag modules-v$ver"
69
+ "publish-to-npm": "node ../dev-tools/bin/publish-package.mjs"
69
70
  },
70
71
  "devDependencies": {
71
72
  "@eslint/js": "^10.0.1",