@widgetic/ui-sdk 0.1.11 → 0.1.12

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
@@ -108,7 +108,7 @@ Mounts one module and resolves with a handle once it is on screen.
108
108
  | `signal` | `AbortSignal` | Cancels the mount. See [Cancelling](#cancelling-a-mount). |
109
109
  | `placeholder` | `boolean` | `false` skips the loading spinner shown while the module downloads. |
110
110
  | `loadingLabel` | `string` | What a screen reader says for that spinner. Default `Loading`: give it in your visitors' language. |
111
- | *anything else* | | Handed to the module. Every module: `themeFromHost` (see [Looking like your product](#looking-like-your-product)). File Browser: `maxSelections`, `initialFilter`, `selectLabel`, `messages`, `mediaLibrary`. Composition editor: `compositionId`, `mediaLibrary`, `pickFile`, `lockPreviewSize`, `googleFontsApiKey`, `autosaveDelayMs`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl`. Workflows: `workspaceId` (required), `workflowId`, `messages`. The types of your library, your picker and the files they handle are exported (see [Your own files, typed](#your-own-files-typed)). |
111
+ | *anything else* | | Handed to the module. Every module: `themeFromHost` (see [Looking like your product](#looking-like-your-product)). File Browser: `maxSelections`, `initialFilter`, `selectLabel`, `messages`, `mediaLibrary`. Composition editor: `compositionId`, `mediaLibrary`, `pickFile`, `lockPreviewSize`, `googleFontsApiKey`, `autosaveDelayMs`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl`. Workflows: `workspaceId` (required), `workflowId`, `presence`, `messages`. The types of your library, your picker and the files they handle are exported (see [Your own files, typed](#your-own-files-typed)). |
112
112
 
113
113
  The handle:
114
114
 
@@ -278,6 +278,16 @@ await editor.unmount();
278
278
  - **Problems** are shown to the visitor by the editor itself, with "Try again" where that helps; `error` is for your page.
279
279
  `fatal: true` means the editor cannot go on by itself: the composition cannot be opened, or the session is over
280
280
  (`sessionEnded: true`), so mint a new session or take the editor away. Quote `correlationId` to Widgetic's support.
281
+ - **Somebody else saved first.** Every save carries the version the editor loaded. When another tab, another person or
282
+ your own server saved the composition in the meantime, the save is refused: nothing is overwritten and nothing more is
283
+ sent. The editor keeps the visitor's edits and shows a card with *Keep my changes* (saved on top of the newer version, a
284
+ deliberate overwrite) and *Use the latest version* (the edits are dropped). Your page hears it as `conflict`
285
+ (`{ currentVersion, lastEditedBy, lastEditedAt, correlationId? }`; the API names who saved only to a member of a team, so
286
+ for an editor session `lastEditedBy` and `lastEditedAt` are `null`) and, once somebody chose, as `conflictResolved`
287
+ (`{ resolution: 'keepMine' | 'loadLatest' }`). It is not an `error`. A page with buttons of its own can call
288
+ `editor.module.keepMyChanges()` (resolves `true` when nothing is left unsaved) or `editor.module.loadLatestVersion()`
289
+ instead of leaving the choice to the card. The "Anna is editing" notice of Widgetic's own site is not part of the module:
290
+ it needs a signed-in member of a team, which an editor session is not.
281
291
  - **Your own files.** Pass `mediaLibrary` (above) and the editor's file pickers show your files instead of the user's
282
292
  Widgetic uploads, or pass [`pickFile`](#your-own-file-picker-for-file-fields-pickfile) to open your own picker.
283
293
  - **Fonts.** `googleFontsApiKey` is a Google Fonts Web Fonts API key for the font picker's list; without one the picker
@@ -399,6 +409,11 @@ await workflows.unmount();
399
409
  appears (a `getToken` that fails fails the mount) and again when the token runs out. An *editor session* minted for one
400
410
  of a partner's customers is refused on the workflow routes: it may call only what its allow-list names, and workflows
401
411
  are not on it. See [Tokens](#tokens).
412
+ - **Two people, one workflow.** A save that finds the draft changed by somebody else is never silent: the screen says so
413
+ and offers *Keep my changes as a copy* (a new workflow that holds what the person did) before *Load the latest
414
+ version*. Pass `presence: true` for an organization's workspace and the screen also tells who has the workflow open
415
+ ("Anna is editing"), with a choice to take over or to only look. It is presence, never a lock, it is off unless you ask,
416
+ and for `personal`, or a token the API refuses the edit-lease routes, the screen carries on as if it were off.
402
417
  - **Opening and closing a workflow** belong to your page: the screen tells it (`openWorkflow`, with `workflowId: null` for
403
418
  the list) so it can keep its address in step, and `workflows.module.setWorkflow(id)` moves the screen when your page
404
419
  moves. The embed code is shown by your page too: the screen has its button only when something listens for
@@ -410,7 +425,7 @@ await workflows.unmount();
410
425
  [Speaking your visitors' language](#speaking-your-visitors-language)) and speaks the twelve languages of the other
411
426
  modules from lazy packs (provisional until a native speaker has read them): a `locale` that has a pack shows its words
412
427
  from the first paint, any other `locale` keeps the English, and your `messages` win over the pack, key by key.
413
- `workflows.module.defaultMessages` lists the 390 messages with their English text, and
428
+ `workflows.module.defaultMessages` lists the 416 messages with their English text, and
414
429
  `workflows.module.checkMessages(messages)` reports mistakes in yours without mounting anything. A language written right
415
430
  to left (Arabic, Hebrew, Persian, Urdu) turns the screen around, except the canvas, which is read from its first block
416
431
  forward and is drawn left to right in every language.
@@ -568,7 +583,7 @@ files.setLanguage({ locale: '', messages: {} }); // back to Englis
568
583
  saved into the chat stay English in the API and are translated on screen when the table knows them.
569
584
  [The modules' README](modules/README.md#speaking-your-visitors-language) has the list.
570
585
  - **Workflows** takes the same `locale`, `messages` and `setLanguage`, with **one** `messages` object for all of it: its
571
- `workflows.` keys, 390 today (`workflows.module.defaultMessages` lists them). It has packs for the same twelve
586
+ `workflows.` keys, 416 today (`workflows.module.defaultMessages` lists them). It has packs for the same twelve
572
587
  languages as the other modules (`workflows.module.supportedLocales` lists them, every one provisional): a `locale` that
573
588
  has a pack shows its words, one that has not keeps the English, and in both it sets the plural rules your messages use
574
589
  and which way the screen reads. Your `messages` win over the pack, key by key. The `message` of its `error` events stays
@@ -583,6 +598,8 @@ files.setLanguage({ locale: '', messages: {} }); // back to Englis
583
598
  | `select` | `{ files: PickedFile[] }` | File Browser: the visitor confirmed a pick. |
584
599
  | `dirty` | `{ dirty: boolean }` | Composition editor: there is, or is no longer, work that is not saved. |
585
600
  | `saved` | `{ composition, savedAt }` | Composition editor: a save went through. |
601
+ | `conflict` | `{ currentVersion, lastEditedBy, lastEditedAt, correlationId? }` | Composition editor: a save was refused because somebody else saved the composition after the editor loaded it. Nothing is lost: the editor keeps the visitor's edits and asks which version stays. Not an `error`. `lastEditedBy` and `lastEditedAt` are `null` for an editor session. |
602
+ | `conflictResolved` | `{ resolution }` | Composition editor: the visitor (or your page, with `editor.module.keepMyChanges()` or `editor.module.loadLatestVersion()`) chose: `'keepMine'` (the edits are saved on top of the newer version) or `'loadLatest'` (the edits are gone). |
586
603
  | `canvasChanged` | `{ canvasId }` | Widget creator: it opened a canvas or made one. Keep the id and give it back as `canvasId` next time. |
587
604
  | `presetChosen` | `{ key, canvasId, widgetId, widgetName, warnings, automatic }` | Widget creator: a starting point was chosen, before the creator opens on the copy. `key`, `canvasId`, `widgetId` and `widgetName` are `null` when the visitor chose *Start from scratch*; `automatic` is `true` when your `startFromPreset` was copied for them; `warnings` are sentences for you, not the visitor (usually empty). The creator then says `canvasChanged` for the copy. |
588
605
  | `widgetRenamed` | `{ widgetId, name }` | Widget creator: the main widget has this name (said when the canvas opens and each time the user renames it). |
@@ -619,7 +636,8 @@ const reportError = (error: CompositionEditorEvents['error']) => report(error.co
619
636
  The types are exported: `FileBrowserEvents`, `CompositionEditorEvents` and `WidgetCreatorEvents` (one property per event);
620
637
  `PickedFile` and `LibraryAction` (what `select` and the File Browser's `error` carry); `ModuleErrorEvent` (what every
621
638
  `error` carries), with `FileBrowserErrorEvent`, `CompositionEditorErrorEvent` and `WidgetCreatorErrorEvent` for what each
622
- module adds, and `CompositionEditorErrorDuring` and `WidgetCreatorErrorDuring` for the values of `during`; and, for code
639
+ module adds, and `CompositionEditorErrorDuring` and `WidgetCreatorErrorDuring` for the values of `during`;
640
+ `CompositionEditorConflictEvent` (what `conflict` carries); and, for code
623
641
  that handles any module, `ModuleEventMap`, `KnownModuleName`, `ModuleEvents`, `ModuleEventHandlers`, `ModuleEventName`
624
642
  and `ModuleEventPayload`.
625
643
 
@@ -931,7 +949,8 @@ Nothing in this package reads a `.env`, so there is none to create (the template
931
949
  that reason). Its build keeps an empty list of allowed `.env` keys on purpose (`scripts-sdk/load-env.js`), and
932
950
  `scripts-sdk/check-no-secrets.js` fails on a gateway service key in anything that ships. If you keep a `.env` here
933
951
  anyway (it is git-ignored), never put a Widgetic key in it: every `PUBLIC_*` and `VITE_*` value is copied into the
934
- JavaScript that browsers download. The CDN publish settings live in `modules/.env`, a different file.
952
+ JavaScript that browsers download. The CDN publish settings are not in a file at all: `modules/` reads them from Doppler (the
953
+ API gateway's production config) every time it releases, see its [README](modules/README.md), "Publishing".
935
954
 
936
955
  The modules themselves (Svelte, the design system) live in [`modules/`](modules/README.md), a separate workspace so this
937
956
  package stays free of them. Its browser tests also exercise this SDK as built: `cd modules && npm run build:file-browser
package/dist/index.cjs CHANGED
@@ -2482,7 +2482,7 @@ function createSecureContext(allowedOrigins = []) {
2482
2482
  * `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
2483
2483
  * `tests/unit/version.test.ts` fails the same way in the suite.
2484
2484
  */
2485
- const SDK_VERSION = '0.1.11';
2485
+ const SDK_VERSION = '0.1.12';
2486
2486
  const SDK_NAME = '@widgetic/ui-sdk';
2487
2487
 
2488
2488
  /**
package/dist/index.esm.js CHANGED
@@ -2478,7 +2478,7 @@ function createSecureContext(allowedOrigins = []) {
2478
2478
  * `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
2479
2479
  * `tests/unit/version.test.ts` fails the same way in the suite.
2480
2480
  */
2481
- const SDK_VERSION = '0.1.11';
2481
+ const SDK_VERSION = '0.1.12';
2482
2482
  const SDK_NAME = '@widgetic/ui-sdk';
2483
2483
 
2484
2484
  /**
@@ -83,6 +83,24 @@ export interface CompositionEditorErrorEvent extends ModuleErrorEvent {
83
83
  /** Quote it to Widgetic's support: it finds the request in the logs. */
84
84
  correlationId?: string;
85
85
  }
86
+ /**
87
+ * The `conflict` event of the composition editor: a save was refused because somebody else saved the composition after the
88
+ * editor loaded it (another tab, another person, your own server). Nothing is lost: the editor keeps the visitor's edits,
89
+ * stops saving by itself and asks which version stays, in a card of its own. It is not an `error`.
90
+ */
91
+ export interface CompositionEditorConflictEvent {
92
+ /** The content version the API holds now, when the refusal said so; `null` when it did not. */
93
+ currentVersion: number | null;
94
+ /** Who saved the newer version (`{ id, name }`), when the API said and this session may be told; `null` otherwise. */
95
+ lastEditedBy: {
96
+ id?: string;
97
+ name?: string;
98
+ } | null;
99
+ /** When they saved it (the date as the API wrote it), when the API said; `null` otherwise. */
100
+ lastEditedAt: string | null;
101
+ /** Quote it to Widgetic's support: it finds the request in the logs. */
102
+ correlationId?: string;
103
+ }
86
104
  /** What the widget creator was doing when something went wrong. `presets` is the lookup and copy of starting points. */
87
105
  export type WidgetCreatorErrorDuring = 'start' | 'token' | 'session' | 'canvas' | 'presets';
88
106
  /**
@@ -122,6 +140,20 @@ export interface CompositionEditorEvents {
122
140
  composition: Record<string, unknown>;
123
141
  savedAt: number;
124
142
  };
143
+ /**
144
+ * A save was refused because somebody else saved the composition after the editor loaded it. The editor keeps the
145
+ * visitor's edits and asks which version stays; a page with buttons of its own answers with
146
+ * `editor.module.keepMyChanges()` (save the edits on top, a deliberate overwrite) or `editor.module.loadLatestVersion()`
147
+ * (drop them).
148
+ */
149
+ conflict: CompositionEditorConflictEvent;
150
+ /**
151
+ * The visitor (or your page) chose. `keepMine`: the edits are saved on top of the newer version (a `saved`, another
152
+ * `conflict` or an `error` follows). `loadLatest`: the composition was read again and the edits are gone.
153
+ */
154
+ conflictResolved: {
155
+ resolution: 'keepMine' | 'loadLatest';
156
+ };
125
157
  error: CompositionEditorErrorEvent;
126
158
  }
127
159
  /** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
@@ -83,6 +83,24 @@ export interface CompositionEditorErrorEvent extends ModuleErrorEvent {
83
83
  /** Quote it to Widgetic's support: it finds the request in the logs. */
84
84
  correlationId?: string;
85
85
  }
86
+ /**
87
+ * The `conflict` event of the composition editor: a save was refused because somebody else saved the composition after the
88
+ * editor loaded it (another tab, another person, your own server). Nothing is lost: the editor keeps the visitor's edits,
89
+ * stops saving by itself and asks which version stays, in a card of its own. It is not an `error`.
90
+ */
91
+ export interface CompositionEditorConflictEvent {
92
+ /** The content version the API holds now, when the refusal said so; `null` when it did not. */
93
+ currentVersion: number | null;
94
+ /** Who saved the newer version (`{ id, name }`), when the API said and this session may be told; `null` otherwise. */
95
+ lastEditedBy: {
96
+ id?: string;
97
+ name?: string;
98
+ } | null;
99
+ /** When they saved it (the date as the API wrote it), when the API said; `null` otherwise. */
100
+ lastEditedAt: string | null;
101
+ /** Quote it to Widgetic's support: it finds the request in the logs. */
102
+ correlationId?: string;
103
+ }
86
104
  /** What the widget creator was doing when something went wrong. `presets` is the lookup and copy of starting points. */
87
105
  export type WidgetCreatorErrorDuring = 'start' | 'token' | 'session' | 'canvas' | 'presets';
88
106
  /**
@@ -122,6 +140,20 @@ export interface CompositionEditorEvents {
122
140
  composition: Record<string, unknown>;
123
141
  savedAt: number;
124
142
  };
143
+ /**
144
+ * A save was refused because somebody else saved the composition after the editor loaded it. The editor keeps the
145
+ * visitor's edits and asks which version stays; a page with buttons of its own answers with
146
+ * `editor.module.keepMyChanges()` (save the edits on top, a deliberate overwrite) or `editor.module.loadLatestVersion()`
147
+ * (drop them).
148
+ */
149
+ conflict: CompositionEditorConflictEvent;
150
+ /**
151
+ * The visitor (or your page) chose. `keepMine`: the edits are saved on top of the newer version (a `saved`, another
152
+ * `conflict` or an `error` follows). `loadLatest`: the composition was read again and the edits are gone.
153
+ */
154
+ conflictResolved: {
155
+ resolution: 'keepMine' | 'loadLatest';
156
+ };
125
157
  error: CompositionEditorErrorEvent;
126
158
  }
127
159
  /** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
@@ -1 +1 @@
1
- {"version":3,"file":"module-events.d.ts","sourceRoot":"","sources":["../../../src/sdk/types/module-events.ts"],"names":[],"mappings":"AAAA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M,MAAM,kBAAkB,CAAC,IAAI,SAAS,MAAM,EAAE,KAAK,SAAS,eAAe,CAAC,IAAI,CAAC,IACnF,YAAY,CAAC,IAAI,CAAC,CAAC,KAAK,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC"}
@@ -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.11";
9
+ export declare const SDK_VERSION = "0.1.12";
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.11";
9
+ export declare const SDK_VERSION = "0.1.12";
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":case"workflows":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.11",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":case"workflows":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.12",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/modules/README.md CHANGED
@@ -205,17 +205,35 @@ Without the SDK it is the same class as the File Browser's (`new CompositionEdit
205
205
  | `apiUrl` | As for the File Browser. |
206
206
 
207
207
  Events: `ready` `{ name, widgetId }` (the composition has loaded and is on screen), `dirty` `{ dirty }` (there is, or is
208
- no longer, work that is not saved), `saved` `{ composition, savedAt }` (a save went through), and `error`
208
+ no longer, work that is not saved), `saved` `{ composition, savedAt }` (a save went through), `conflict`
209
+ `{ currentVersion, lastEditedBy, lastEditedAt, correlationId? }` and `conflictResolved` `{ resolution }` (see "When somebody
210
+ else saved first" below), and `error`
209
211
  `{ message, code?, fatal, during?, status?, retryable?, sessionEnded?, correlationId? }`. The editor shows a problem to the
210
212
  visitor itself (with "Try again" where that helps); `error` is for your page. `fatal: true` means the editor cannot go on
211
213
  by itself: the composition cannot be opened, or the session is over (`sessionEnded`), so give it a new session or take it
212
214
  away. `correlationId` is what Widgetic's support needs to find the request.
213
215
 
216
+ **When somebody else saved first.** Every save carries the version of the content the editor loaded (an `If-Match` header
217
+ of the composition's `contentVersion`). When another tab, another person or your own server saved the composition in the
218
+ meantime, the API refuses the save (412 `CONTENT_VERSION_MISMATCH`): nothing is overwritten and nothing more is sent. The
219
+ editor stops saving by itself, keeps the visitor's
220
+ edits and shows a card with two choices: *Keep my changes* (it reads the newer version again and saves the edits on top,
221
+ a deliberate overwrite; when somebody saved a third time meanwhile it asks again instead of replacing that unseen) and
222
+ *Use the latest version* (the composition is read again and the edits are dropped). Your page hears `conflict` when the
223
+ save is refused and `conflictResolved` (`{ resolution: 'keepMine' | 'loadLatest' }`) once somebody chose. It is not an
224
+ `error`, so `error` is not sent for it. A page that wants its own buttons calls `keepMyChanges()` or `loadLatestVersion()`
225
+ on the module. The API names who saved only to a member of a team (it never tells an editor session), so `lastEditedBy`
226
+ and `lastEditedAt` are `null` here; `currentVersion` is the version the API holds now, when the refusal said so. The
227
+ editor's *presence* notice ("Anna is editing", take over, read only) is not offered by the module: it runs on routes an
228
+ editor session may not call, and the module keeps the `presence` option of the editor off.
229
+
214
230
  Methods (on `editor.module` when you mounted it with the SDK): `save()` saves what is unsaved now, `flush()` saves
215
231
  everything and waits, both resolving `true` when nothing is left unsaved; `isDirty()`; `reload()` loads the composition
216
232
  again (unsaved edits are lost); `adoptEmbedSettings(settings)` for a page that saves the composition's `embedSettings` itself
217
233
  (call it after `await flush()`, with the settings the API now holds, so a later save of the editor does not put the old ones
218
- back; nothing becomes unsaved); `adoptName(name)` for a page that renames the composition itself (same use); `setTheme(theme)` (see "Looking like your product"); `setLanguage({ locale?, messages? })`, and
234
+ back; nothing becomes unsaved); `adoptName(name)` for a page that renames the composition itself (same use); `keepMyChanges()`
235
+ (resolves `true` when nothing is left unsaved) and `loadLatestVersion()`, the two answers to a `conflict` for a page with buttons of its own (both do nothing, and
236
+ `keepMyChanges()` resolves `false`, when there is no conflict); `setTheme(theme)` (see "Looking like your product"); `setLanguage({ locale?, messages? })`, and
219
237
  `CompositionEditorModule.defaultMessages` and `checkMessages(messages)`, which are also on the instance (see "Speaking your
220
238
  visitors' language").
221
239
 
@@ -426,6 +444,7 @@ window.addEventListener('popstate', () => workflows.module.setWorkflow(workflowO
426
444
  | `getToken` | **Required**, and the same as for the other modules: `getToken({ reason })` resolves with a token the API accepts for the workspace's workflows, bare or as `{ token, expiresAt }`. It must be the token of a **signed-in person who may work in that workspace** (a member of the team, or the partner's own account), the way the Widgetic site calls the API: an *editor session* minted for one of a partner's customers is refused on these routes (`403`), because an editor session may call only what its allow-list names and workflows are not on it. It is called once before the screen appears (a `getToken` that fails fails the mount), and again when the token is about to run out or the API refuses it (`reason: 'expired'`, once per refusal). |
427
445
  | `apiUrl` | The API origin (`https://api.widgetic.com` unless you run your own). |
428
446
  | `workflowId` | The workflow to open first. Leave it out for the list. After mounting the screen moves by itself (and says so with `openWorkflow`); `setWorkflow` moves it from the page. |
447
+ | `presence` | `true` tells the people of a team who else has the workflow open: "Anna is editing", with a choice to take over or to only look (default `false`, read once when the module mounts). It is for an organization's workspace and a person who may change the workflow; for `personal`, or for a token the edit-lease routes refuse (an editor session), the screen carries on as if it were off, without asking again. It is presence, never a lock: nobody is shut out, and a save that finds the draft changed by somebody else asks the person what to do (*Keep my changes as a copy* first, if they like, then *Load the latest version*) whether `presence` is on or not. A value that is not `true` or `false` is ignored, with one warning in the console. |
429
448
  | `theme`, `themeFromHost` | The colours, the corners and the typeface ("Looking like your product"). |
430
449
  | `locale`, `messages` | The language ("Speaking your visitors' language"). |
431
450
 
@@ -628,7 +647,7 @@ files.setLanguage({ locale: 'de', messages: germanMessages }); // later, while i
628
647
  | `selectLabel` | The text of the button that hands the pick to your page, for a page that only wants to rename that one button (default "Select"). `messages['action.addToEditor']` does the same and wins when both are given. |
629
648
  | `setLanguage({ locale?, messages? })` | On the handle (`files.setLanguage`) and on a module you made yourself. Changes the language at once, while the module is on screen or before `mount()`. A value the call leaves out keeps what it was. `messages` it gives **replace** all the earlier ones: a page that switches from German to French passes the French only, and `setLanguage({ locale: '', messages: {} })` goes back to English. `null` counts as "not said". When `locale` changes, the module loads the matching pack (if any) and applies it in one step; two quick calls end in the language of the last call. |
630
649
 
631
- **Translation packs (shipped languages).** Each pack is one lazy file next to `index.js` (gzip budget per pack: File Browser **5 kB**, composition editor **9 kB**, widget creator **28 kB**, Workflows **9 kB**; the build fails when a pack grows past its module's budget). **Twelve** languages ship today as lazy JSON packs on the CDN: the eight left-to-right ones (`fr`, `de`, `es`, `pt-BR`, `nl`, `da`, `sv`, `zh-CN`) and four right-to-left ones (`ar`, `he`, `fa`, `ur`; Hebrew also answers to the legacy tag `iw`). Every pack is **provisional** until a native speaker has reviewed it. Each module exposes `Module.supportedLocales` (the list above) and `Module.localePackStatus(tag)` (`'provisional' | 'reviewed' | null`). Master files for translators live in `modules/locales/<tag>.json` (union of all keys, with the 390 of Workflows); the build splits them into one pack per module. Missing keys in a pack fall back to English. **Merge order:** pack → module English shortcuts (`selectLabel`, `presetLabels`, the File Browser's "Select" / "Files selected" toasts) → your `messages` (your page always wins). **Fallback examples:** `pt-PT` and `pt` → `pt-BR` pack; `fr-CA` → `fr`; `zh` / `zh-Hans` / `zh-SG` → `zh-CN`; `zh-TW` / `zh-Hant` → no pack (English words, Simplified is not used); `ar-SA`, `ar-EG` → `ar`; `he-IL` and `iw` → `he`; `fa-IR`, `fa-AF` → `fa`; `ur-PK`, `ur-IN` → `ur`; `en*` → no pack; unknown tag → English (no console line). A pack file that fails to load is reported once in the console; the module keeps working in English. On `mount()`, the module waits for the pack in parallel with its session token so the first paint can be in the pack language when the file arrives in time (Workflows waits for the token and the pack both before it draws anything, so its first paint is always in the language). Commands: `npm run locales:export-english`, `locales:import-shopify`, `locales:coverage`. Report a wrong translation to Widgetic support with the module name, `locale`, message key and what you expected.
650
+ **Translation packs (shipped languages).** Each pack is one lazy file next to `index.js` (gzip budget per pack: File Browser **5 kB**, composition editor **9 kB**, widget creator **28 kB**, Workflows **9 kB**; the build fails when a pack grows past its module's budget). **Twelve** languages ship today as lazy JSON packs on the CDN: the eight left-to-right ones (`fr`, `de`, `es`, `pt-BR`, `nl`, `da`, `sv`, `zh-CN`) and four right-to-left ones (`ar`, `he`, `fa`, `ur`; Hebrew also answers to the legacy tag `iw`). Every pack is **provisional** until a native speaker has reviewed it. Each module exposes `Module.supportedLocales` (the list above) and `Module.localePackStatus(tag)` (`'provisional' | 'reviewed' | null`). Master files for translators live in `modules/locales/<tag>.json` (union of all keys, with the 416 of Workflows); the build splits them into one pack per module. Missing keys in a pack fall back to English. **Merge order:** pack → module English shortcuts (`selectLabel`, `presetLabels`, the File Browser's "Select" / "Files selected" toasts) → your `messages` (your page always wins). **Fallback examples:** `pt-PT` and `pt` → `pt-BR` pack; `fr-CA` → `fr`; `zh` / `zh-Hans` / `zh-SG` → `zh-CN`; `zh-TW` / `zh-Hant` → no pack (English words, Simplified is not used); `ar-SA`, `ar-EG` → `ar`; `he-IL` and `iw` → `he`; `fa-IR`, `fa-AF` → `fa`; `ur-PK`, `ur-IN` → `ur`; `en*` → no pack; unknown tag → English (no console line). A pack file that fails to load is reported once in the console; the module keeps working in English. On `mount()`, the module waits for the pack in parallel with its session token so the first paint can be in the pack language when the file arrives in time (Workflows waits for the token and the pack both before it draws anything, so its first paint is always in the language). Commands: `npm run locales:export-english`, `locales:import-shopify`, `locales:coverage`. Report a wrong translation to Widgetic support with the module name, `locale`, message key and what you expected.
632
651
 
633
652
  **`action.addToEditor` vs Shopify.** The confirm button of the file picker is the message `action.addToEditor`. In these modules its English text is **Select** (`selectLabel` is a shortcut for the same key; `messages` wins over both). Packs seeded from the Shopify app's File Browser used Shopify's wording ("Add to Editor") for that key; the import script replaces it with Select in each language. There is no separate `action.select` key in the module catalogs (Shopify's JSON may list `action.select` for another button).
634
653
 
@@ -750,6 +769,11 @@ and it splits what you give between them, so you never need to know which part s
750
769
  - the rich text editor of its text fields, the `shadEditor.` keys. The editor draws its own text toolbar (`editor.` keys),
751
770
  so these words are not on screen today, and a translation can leave them out.
752
771
 
772
+ Among the `editor.` keys, the nineteen `editor.presence.` ones ("Anna is editing", take over, look only) are on no screen
773
+ either: the module keeps the editor's `presence` off, because it runs on routes an editor session may not use. The language
774
+ packs leave them out (`npm run locales:coverage` counts them as missing for that reason); the nine `editor.conflict.` ones,
775
+ which the card of a refused save shows, are translated.
776
+
753
777
  `CompositionEditorModule.defaultMessages` lists all of them, with their English text: more than 500. A key that is in none
754
778
  of the three parts is said once in the console as `[Editor] ...`, with the nearest real key, and ignored.
755
779
 
@@ -847,14 +871,14 @@ creator.setLanguage({ locale: 'de', messages: germanMessages }); // every screen
847
871
  code stay left to right.
848
872
 
849
873
  **Workflows.** It takes the same `locale`, `messages`, `setLanguage`, `defaultMessages` and `checkMessages`, with **one**
850
- `messages` object for all of it: its 390 `workflows.` keys (the list, the editor and its panels, the names of blocks,
874
+ `messages` object for all of it: its 416 `workflows.` keys (the list, the editor and its panels, the names of blocks,
851
875
  operators and units, what the engine finds wrong with a workflow, what a failed request means, and the words of the screen
852
876
  that says a part could not be drawn). The words of a block are made of parts the screen puts together (`{field} {value}`,
853
877
  `{count, plural, ...}`), so a language that puts them in another order can say so in its own message.
854
878
 
855
879
  - **It speaks the twelve languages of the other modules.** `Workflows.supportedLocales` lists them (`fr`, `de`, `es`,
856
880
  `pt-BR`, `nl`, `da`, `sv`, `zh-CN`, `ar`, `he`, `fa`, `ur`) and `Workflows.localePackStatus(tag)` is `'provisional'` for
857
- each: a `locale` that has a pack fetches one lazy file of 390 messages (26 to 37 kB, 7 to 8 kB gzipped; the budget is
881
+ each: a `locale` that has a pack fetches one lazy file of 416 messages (27 to 39 kB, 7 to 8 kB gzipped; the budget is
858
882
  9 kB gzipped), and `mount()` waits for it, so the first paint is already in that language. A `locale` with no pack
859
883
  (English, `zh-TW`, an unknown tag) downloads nothing and says nothing in the console: the words stay English, while the
860
884
  plural rules and the direction follow `locale` either way. Your `messages` win over the pack, key by key. The packs are
@@ -889,7 +913,8 @@ itself, which no `messages` could ever translate. The same trick works on your o
889
913
  | `npm run check:creator-routes` | Reads the packages the creator is made of and checks that every route they can call is on the gateway's list for a creator session, or is listed with the reason a visitor can never reach it (`-- --inventory` prints it as JSON, see "What the end-to-end tests check") |
890
914
  | `npm run publish:cdn -- <module> [options]` | Releases a module to the CDN: see "Publishing". `--help` lists every option |
891
915
  | `npm run release:check -- --tag modules-v<x.y.z>` | The checks a release starts with (the tag against `package.json`, a lockfile the pipeline can install), on your machine: no keys, nothing written, no package needed |
892
- | `npm run release:publish` | Releases every built module from the tag in `CI_COMMIT_TAG` (or `-- --tag modules-v<x.y.z>`), in three passes. This is what the pipeline's `publish` job runs; it needs the R2 settings. See "Releasing from a tag" |
916
+ | `npm run release:publish` | Releases every built module from the tag in `CI_COMMIT_TAG` (or `-- --tag modules-v<x.y.z>`), in three passes. This is what the pipeline's `publish` job runs; it needs the R2 settings (read from Doppler once, when you run it). See "Releasing from a tag" |
917
+ | `npm run release:settings` | Checks that a release can reach the CDN's bucket: reads the R2 settings (from Doppler, or the environment), reads one object that is not there, writes nothing, prints no key. `npm run publish-to-npm` in `Frontend/ui-sdk` runs it before it raises the version |
893
918
  | `npm run typecheck` | `tsc --noEmit` over `src`, `tests`, `e2e` |
894
919
 
895
920
  Run `npm run build` (or the `build:<module>` of the one you test) before `npm run harness` / `npm run test:e2e`: the
@@ -1501,20 +1526,23 @@ module that needs a first release.
1501
1526
 
1502
1527
  1. **Put the work on `main`.** `publish:cdn` refuses a `modules/` with uncommitted changes, and a release has to come
1503
1528
  from a commit that is on the default branch.
1504
- 2. **Give the command the R2 keys.** The four names are the API gateway's own, so the values are in its Doppler config.
1505
- Use an R2 token of its own, limited to the `widgets` bucket with object read and write, and keep the file out of git
1506
- (`modules/.env` is ignored):
1529
+ 2. **Check that the command can reach the R2 keys.** The four names are the API gateway's own (`CLOUDFLARE_PUBLIC_ENDPOINT`,
1530
+ `R2_WIDGETS_NAME`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`), and the command reads them **from Doppler, every time it
1531
+ runs**: the gateway's production config (project `api-gateway-service`, config `prd`), with the Doppler CLI you are
1532
+ logged in to (`brew install dopplerhq/cli/doppler`, then `doppler login`). There is no `.env` file to make, copy or keep
1533
+ in step, and a key rotated in Doppler is the key the next release uses. This reads one object that is not there, writes
1534
+ nothing and prints no key:
1507
1535
 
1508
1536
  ```bash
1509
1537
  cd Frontend/ui-sdk/modules
1510
- cat > .env <<'EOF'
1511
- CLOUDFLARE_PUBLIC_ENDPOINT=...
1512
- R2_WIDGETS_NAME=...
1513
- R2_ACCESS_KEY_ID=...
1514
- R2_SECRET_ACCESS_KEY=...
1515
- EOF
1538
+ npm run release:settings
1516
1539
  ```
1517
1540
 
1541
+ It prints `R2 settings from Doppler (project api-gateway-service, config prd); the bucket "widgets" answers a read.` When it
1542
+ stops instead, it says why: the CLI is not installed, you are not logged in, you cannot read the project, or the bucket
1543
+ refuses the key. To release with a token of its own (limited to the `widgets` bucket, object read and write) put it in
1544
+ Doppler under the same four names and change `R2_SETTINGS_DOPPLER` in `scripts/lib/publishModule.mjs`.
1545
+
1518
1546
  3. **Look at CORS before you write anything.** A page on another origin `import()`s the module and `fetch`es its manifest,
1519
1547
  so the CDN must answer `Access-Control-Allow-Origin: *` for `modules/*`. On 2026-10-09 it already does, even for the
1520
1548
  404 of a manifest that does not exist yet, and for `sdks/browser/embed-sdk.js`:
@@ -1577,15 +1605,15 @@ module that needs a first release.
1577
1605
  export PROJECT='widgeticai%2FFrontend%2Fui-sdk'
1578
1606
  curl --request POST --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
1579
1607
  "https://gitlab.com/api/v4/projects/$PROJECT/protected_tags" --form 'name=modules-v*' --form 'create_access_level=40'
1580
- set -a; . ./.env; set +a
1581
1608
  for name in CLOUDFLARE_PUBLIC_ENDPOINT R2_WIDGETS_NAME R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY; do
1609
+ value=$(doppler secrets get "$name" --plain --project api-gateway-service --config prd --no-check-version)
1582
1610
  masked=false; case "$name" in R2_ACCESS_KEY_ID|R2_SECRET_ACCESS_KEY) masked=true;; esac
1583
1611
  curl --request POST --header "PRIVATE-TOKEN: $GITLAB_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT/variables" \
1584
- --form "key=$name" --form "value=${!name}" --form 'protected=true' --form "masked=$masked" --form 'environment_scope=cdn'
1612
+ --form "key=$name" --form "value=$value" --form 'protected=true' --form "masked=$masked" --form 'environment_scope=cdn'
1585
1613
  done
1586
1614
  ```
1587
1615
 
1588
- (`${!name}` is bash. In zsh write `${(P)name}`.)
1616
+ (The values are read from Doppler into the loop and never printed. This works in bash and zsh alike.)
1589
1617
 
1590
1618
  8. **The next release goes by tag and proves the pipeline:** `npm version 0.1.1 --no-git-tag-version`, commit, merge,
1591
1619
  `git tag modules-v0.1.1 && git push origin modules-v0.1.1`.
@@ -1671,9 +1699,16 @@ stays until the next release.) `build-module.mjs` refuses a build in which any f
1671
1699
  still publishes the maps, but nothing points at them, so whoever wants one loads it by its address in DevTools. A map
1672
1700
  carries the text of every source file it was made from, so publishing it is a decision about who may read the code.
1673
1701
 
1674
- The settings are the API gateway's own names, so the same values work: `CLOUDFLARE_PUBLIC_ENDPOINT`, `R2_WIDGETS_NAME`,
1675
- `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` (and `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ZONE_ID` for `--purge`). The real
1676
- environment wins over `modules/.env` (git-ignored, or `--env-file <path>`). Nothing prints them.
1702
+ The settings are the API gateway's own, with its names: `CLOUDFLARE_PUBLIC_ENDPOINT`, `R2_WIDGETS_NAME`,
1703
+ `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` (and `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ZONE_ID` for `--purge`, asked for only
1704
+ then). **They are read from Doppler every time the command runs**: the gateway's production config (project
1705
+ `api-gateway-service`, config `prd`, named once, as `R2_SETTINGS_DOPPLER` in `scripts/lib/publishModule.mjs`), with the
1706
+ Doppler CLI you are logged in to, asking for exactly those names and nothing else of the config. There is no `.env` for
1707
+ them and no `--env-file`. One exception: an environment that already holds all of them (the pipeline's runner, where they
1708
+ are variables of the `cdn` environment, or a shell started with `doppler run`) is used as it is, and Doppler is not asked;
1709
+ an environment that holds only some is not mixed with Doppler's, all of them come from the one place. `npm run
1710
+ release:settings` checks the settings and the bucket without publishing anything. Nothing prints a value: when Doppler
1711
+ cannot be read, the message says what the CLI said (not logged in, not installed, no access) and never a key.
1677
1712
 
1678
1713
  | I want to | Run (after `npm run publish:cdn --`) |
1679
1714
  | --- | --- |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/ui-sdk",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Framework-agnostic UI components for building Widgetic integrations",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "main": "dist/index.cjs",