@widgetic/ui-sdk 0.1.14 → 0.1.15
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 +19 -3
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/sdk/types/module-events.d.cts +22 -0
- package/dist/sdk/types/module-events.d.ts +22 -0
- package/dist/sdk/types/module-events.d.ts.map +1 -1
- package/dist/sdk/version.d.cts +1 -1
- package/dist/sdk/version.d.ts +1 -1
- package/dist/umd/ui-sdk.js +1 -1
- package/modules/README.md +95 -16
- package/package.json +1 -1
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`, `presence`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl
|
|
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`, `allowSelecting` (`false` for a library page: no ticking, no confirm button), `allowResumableUploads`. Composition editor: `compositionId`, `mediaLibrary`, `pickFile`, `lockPreviewSize`, `googleFontsApiKey`, `autosaveDelayMs`, `presence`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl`, and for a page that draws its own header around it `toolbarPosition`, `showSaveButton`, `limitNotices`, `initialMessage` (see [The widget creator](#the-widget-creator)). 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
|
|
|
@@ -351,6 +351,20 @@ await creator.unmount();
|
|
|
351
351
|
points for a visitor who has made nothing yet".
|
|
352
352
|
- **Publishing** saves a version of the widget (the user can go back to an earlier one) and you hear `widgetPublished`.
|
|
353
353
|
A session can never make a widget public in Widgetic's catalogue: what a user builds stays private to your account.
|
|
354
|
+
- **Your own header around the creator.** A page that draws its own bar (a Back arrow, the name of the widget, a Publish
|
|
355
|
+
button) is given what it needs: `publishStateChanged` `{ widgetId, canPublish, publishing, label, unpublished }` says
|
|
356
|
+
what Publish would do now (`creator.module.getPublishState()` gives the last state to a button drawn later),
|
|
357
|
+
`await creator.module.publish()` presses it for the user, `await creator.module.flush()` puts what the user changed on
|
|
358
|
+
the server before your page takes them away, and `creator.module.setWidgetName(name, widgetId?)` renames a widget from
|
|
359
|
+
your own header (the creator shows and saves the name, and says `widgetRenamed`). The options that go with it:
|
|
360
|
+
`toolbarPosition: 'BL' | 'BC' | 'BR'` puts the drawing toolbar bottom left, bottom centre (the default) or bottom right,
|
|
361
|
+
for a page that has something of its own over the middle of the bottom edge; `showSaveButton: false` takes away the
|
|
362
|
+
canvas's Save button and its dot (the creator saves by itself, five seconds after the last change, at the latest fifteen
|
|
363
|
+
seconds into continuous work, and when the page is hidden or closed); `limitNotices: 'chat'` tells a refusal because of a
|
|
364
|
+
limit in the chat only, not also in a toast; `initialMessage: { text, send: true, attachments? }` puts words in the chat
|
|
365
|
+
of a new widget, with the photos you give it as `File`s, and sends them as the first message. A creator older than these ignores the options, and `publish()` and
|
|
366
|
+
`setWidgetName()` reject while `flush()` resolves at once. Details: `modules/README.md`, "A header of your own around
|
|
367
|
+
the creator".
|
|
354
368
|
- **Credits and limits are yours.** The AI is paid for by your account, as your own calls are. When your credits run out
|
|
355
369
|
(or a plan limit or the storage limit is reached), the creator tells the user in plain words ("This is not available
|
|
356
370
|
right now. Please try again later.") and keeps working; it never shows what your account holds. Your page hears
|
|
@@ -442,7 +456,7 @@ await workflows.unmount();
|
|
|
442
456
|
[Speaking your visitors' language](#speaking-your-visitors-language)) and speaks the twelve languages of the other
|
|
443
457
|
modules from lazy packs (provisional until a native speaker has read them): a `locale` that has a pack shows its words
|
|
444
458
|
from the first paint, any other `locale` keeps the English, and your `messages` win over the pack, key by key.
|
|
445
|
-
`workflows.module.defaultMessages` lists the
|
|
459
|
+
`workflows.module.defaultMessages` lists the 439 messages with their English text, and
|
|
446
460
|
`workflows.module.checkMessages(messages)` reports mistakes in yours without mounting anything. A language written right
|
|
447
461
|
to left (Arabic, Hebrew, Persian, Urdu) turns the screen around, except the canvas, which is read from its first block
|
|
448
462
|
forward and is drawn left to right in every language.
|
|
@@ -600,7 +614,7 @@ files.setLanguage({ locale: '', messages: {} }); // back to Englis
|
|
|
600
614
|
saved into the chat stay English in the API and are translated on screen when the table knows them.
|
|
601
615
|
[The modules' README](modules/README.md#speaking-your-visitors-language) has the list.
|
|
602
616
|
- **Workflows** takes the same `locale`, `messages` and `setLanguage`, with **one** `messages` object for all of it: its
|
|
603
|
-
`workflows.` keys,
|
|
617
|
+
`workflows.` keys, 439 today (`workflows.module.defaultMessages` lists them). It has packs for the same twelve
|
|
604
618
|
languages as the other modules (`workflows.module.supportedLocales` lists them, every one provisional): a `locale` that
|
|
605
619
|
has a pack shows its words, one that has not keeps the English, and in both it sets the plural rules your messages use
|
|
606
620
|
and which way the screen reads. Your `messages` win over the pack, key by key. The `message` of its `error` events stays
|
|
@@ -622,6 +636,7 @@ files.setLanguage({ locale: '', messages: {} }); // back to Englis
|
|
|
622
636
|
| `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. |
|
|
623
637
|
| `widgetRenamed` | `{ widgetId, name }` | Widget creator: the main widget has this name (said when the canvas opens and each time the user renames it). |
|
|
624
638
|
| `widgetPublished` | `{ widgetId, version? }` | Widget creator: the user published a version of a widget. |
|
|
639
|
+
| `publishStateChanged` | `{ widgetId, canPublish, publishing, label, unpublished }` | Widget creator: what Publish would do now, for a page that draws its own Publish button (`creator.module.publish()` presses it). Said when the creator first knows and at every change, never twice with the same state. |
|
|
625
640
|
| `limitReached` | `{ message, code? }` | Widget creator: the user ran into a limit (credits, plan, storage, allowance). The creator has told them already. |
|
|
626
641
|
| `reloadRequested` | | Widget creator: it would have reloaded the page to recover. Unmount it and mount a new one. |
|
|
627
642
|
| `openWorkflow` | `{ workflowId }` | Workflows: the person opened a workflow, or went back to the list (`workflowId: null`). Keep your address in step; the screen has moved itself. |
|
|
@@ -651,6 +666,7 @@ const reportError = (error: CompositionEditorEvents['error']) => report(error.co
|
|
|
651
666
|
```
|
|
652
667
|
|
|
653
668
|
The types are exported: `FileBrowserEvents`, `CompositionEditorEvents`, `WidgetCreatorEvents` and `WorkflowsEvents` (one property per event);
|
|
669
|
+
`WidgetCreatorPublishState` (what `publishStateChanged` carries);
|
|
654
670
|
`PickedFile` and `LibraryAction` (what `select` and the File Browser's `error` carry); `ModuleErrorEvent` (what every
|
|
655
671
|
`error` carries), with `FileBrowserErrorEvent`, `CompositionEditorErrorEvent` and `WidgetCreatorErrorEvent` for what each
|
|
656
672
|
module adds, and `CompositionEditorErrorDuring` and `WidgetCreatorErrorDuring` for the values of `during`;
|
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.
|
|
2485
|
+
const SDK_VERSION = '0.1.15';
|
|
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.
|
|
2481
|
+
const SDK_VERSION = '0.1.15';
|
|
2482
2482
|
const SDK_NAME = '@widgetic/ui-sdk';
|
|
2483
2483
|
|
|
2484
2484
|
/**
|
|
@@ -200,6 +200,19 @@ export interface CompositionEditorEvents {
|
|
|
200
200
|
presence: CompositionEditorPresenceEvent;
|
|
201
201
|
error: CompositionEditorErrorEvent;
|
|
202
202
|
}
|
|
203
|
+
/** What Publish would do now: the payload of the widget creator's `publishStateChanged` event and `getPublishState()`. */
|
|
204
|
+
export interface WidgetCreatorPublishState {
|
|
205
|
+
/** The widget `publish()` would publish; `null` while there is none yet. */
|
|
206
|
+
widgetId: string | null;
|
|
207
|
+
/** Publish can be pressed now: the widget has something to publish and nothing is running. */
|
|
208
|
+
canPublish: boolean;
|
|
209
|
+
/** A publish of that widget is running. */
|
|
210
|
+
publishing: boolean;
|
|
211
|
+
/** The words the creator's own Publish button would carry ("Publish", "Publish changes"). */
|
|
212
|
+
label: string;
|
|
213
|
+
/** The widget has changes that no published version has. */
|
|
214
|
+
unpublished: boolean;
|
|
215
|
+
}
|
|
203
216
|
/** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
|
|
204
217
|
export interface WidgetCreatorEvents {
|
|
205
218
|
/** The first canvas has loaded and the creator is ready to be used. `canvasId` is the one that is open. */
|
|
@@ -243,6 +256,15 @@ export interface WidgetCreatorEvents {
|
|
|
243
256
|
widgetId: string;
|
|
244
257
|
name: string;
|
|
245
258
|
};
|
|
259
|
+
/**
|
|
260
|
+
* What Publish would do now, for a page that draws its own Publish button next to the creator: `canPublish` (the
|
|
261
|
+
* widget has something to publish and nothing is running), `publishing` (a publish of that widget is running), `label`
|
|
262
|
+
* (the words the creator's own button would carry, "Publish" or "Publish changes", in your page's language) and
|
|
263
|
+
* `unpublished` (the widget has changes no published version has), for `widgetId`, the widget `publish()` would
|
|
264
|
+
* publish (`null` while there is none). Said when the creator first knows, then at every change and never twice with
|
|
265
|
+
* the same state; `getPublishState()` gives the last one to a page that draws its button later.
|
|
266
|
+
*/
|
|
267
|
+
publishStateChanged: WidgetCreatorPublishState;
|
|
246
268
|
/**
|
|
247
269
|
* The user ran into a limit (credits used up, a cap reached, the storage full). The creator tells the user itself, in
|
|
248
270
|
* plain words; this is for your page, for instance to offer more. `code` is what the API answered
|
|
@@ -200,6 +200,19 @@ export interface CompositionEditorEvents {
|
|
|
200
200
|
presence: CompositionEditorPresenceEvent;
|
|
201
201
|
error: CompositionEditorErrorEvent;
|
|
202
202
|
}
|
|
203
|
+
/** What Publish would do now: the payload of the widget creator's `publishStateChanged` event and `getPublishState()`. */
|
|
204
|
+
export interface WidgetCreatorPublishState {
|
|
205
|
+
/** The widget `publish()` would publish; `null` while there is none yet. */
|
|
206
|
+
widgetId: string | null;
|
|
207
|
+
/** Publish can be pressed now: the widget has something to publish and nothing is running. */
|
|
208
|
+
canPublish: boolean;
|
|
209
|
+
/** A publish of that widget is running. */
|
|
210
|
+
publishing: boolean;
|
|
211
|
+
/** The words the creator's own Publish button would carry ("Publish", "Publish changes"). */
|
|
212
|
+
label: string;
|
|
213
|
+
/** The widget has changes that no published version has. */
|
|
214
|
+
unpublished: boolean;
|
|
215
|
+
}
|
|
203
216
|
/** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
|
|
204
217
|
export interface WidgetCreatorEvents {
|
|
205
218
|
/** The first canvas has loaded and the creator is ready to be used. `canvasId` is the one that is open. */
|
|
@@ -243,6 +256,15 @@ export interface WidgetCreatorEvents {
|
|
|
243
256
|
widgetId: string;
|
|
244
257
|
name: string;
|
|
245
258
|
};
|
|
259
|
+
/**
|
|
260
|
+
* What Publish would do now, for a page that draws its own Publish button next to the creator: `canPublish` (the
|
|
261
|
+
* widget has something to publish and nothing is running), `publishing` (a publish of that widget is running), `label`
|
|
262
|
+
* (the words the creator's own button would carry, "Publish" or "Publish changes", in your page's language) and
|
|
263
|
+
* `unpublished` (the widget has changes no published version has), for `widgetId`, the widget `publish()` would
|
|
264
|
+
* publish (`null` while there is none). Said when the creator first knows, then at every change and never twice with
|
|
265
|
+
* the same state; `getPublishState()` gives the last one to a page that draws its button later.
|
|
266
|
+
*/
|
|
267
|
+
publishStateChanged: WidgetCreatorPublishState;
|
|
246
268
|
/**
|
|
247
269
|
* The user ran into a limit (credits used up, a cap reached, the storage full). The creator tells the user itself, in
|
|
248
270
|
* plain words; this is for your page, for instance to offer more. `code` is what the API answered
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module-events.d.ts","sourceRoot":"","sources":["../../../src/sdk/types/module-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,uDAAuD;AACvD,MAAM,WAAW,UAAU;IACvB,gGAAgG;IAChG,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,0CAA0C;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iCAAiC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wDAAwD;IACxD,SAAS,CAAC,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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.
|
|
9
|
+
export declare const SDK_VERSION = "0.1.15";
|
|
10
10
|
export declare const SDK_NAME = "@widgetic/ui-sdk";
|
package/dist/sdk/version.d.ts
CHANGED
|
@@ -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.
|
|
9
|
+
export declare const SDK_VERSION = "0.1.15";
|
|
10
10
|
export declare const SDK_NAME = "@widgetic/ui-sdk";
|
|
11
11
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/umd/ui-sdk.js
CHANGED
|
@@ -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.14",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.15",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
|
@@ -56,6 +56,11 @@ shows the API's message with "Try again" and the module emits a non-fatal `error
|
|
|
56
56
|
Only **one File Browser can be mounted per page** for now (see "Known gaps"). Its words can be your visitors' own: pass
|
|
57
57
|
`locale` and `messages` (see "Speaking your visitors' language").
|
|
58
58
|
|
|
59
|
+
The File Browser is a picker unless the page says otherwise: the visitor ticks files, and the confirm button hands them to
|
|
60
|
+
your page (`select`). A page that only manages files, such as a media library of its own, passes `allowSelecting: false`
|
|
61
|
+
(default `true`): nothing can be ticked, there is no confirm button, and the header that only says "Uploads" is left out.
|
|
62
|
+
The visitor still adds and edits files.
|
|
63
|
+
|
|
59
64
|
## Showing your own media library
|
|
60
65
|
|
|
61
66
|
A platform that keeps its files itself (a CMS, an S3 bucket, a DAM) passes `mediaLibrary` instead of `getToken`: an object
|
|
@@ -322,6 +327,10 @@ mount()`, `await unmount()`), imported from `https://cdn.widgetic.com/modules/wi
|
|
|
322
327
|
| `presetsOnly` | When `true`, hides "Start from scratch" and offers only your presets. If you have none, the visitor sees a clear empty state (not a blank screen) and the module logs one warning. Default: `false`. |
|
|
323
328
|
| `startFromPreset` | The key of one of your presets. A visitor who has made nothing yet gets a copy of it without being asked, and the creator opens on it. |
|
|
324
329
|
| `presetLabels` | The words of the picker, for a tone of your own: `{ heading, intro, startFromScratch, startFromScratchHint, copying, copyFailed, presetGone, checking }`. A shortcut for the eight `presetPicker.` messages (see "Speaking your visitors' language"): a word that `messages` also says is `messages`'s. Any word neither says stays English. |
|
|
330
|
+
| `toolbarPosition` | Where the drawing toolbar (and the element selector) stands along the bottom edge of the canvas: `'BL'` bottom left, `'BC'` bottom centre (the default) or `'BR'` bottom right. For a page that puts something of its own over the middle of the bottom edge (an assistant, a chat bubble). Anything else throws a `TypeError` that names the option. See "A header of your own around the creator". |
|
|
331
|
+
| `showSaveButton` | `false` takes away the canvas's Save button and the dot that says the board has changes the server does not have. Default `true`. The creator saves by itself either way (five seconds after the last change, at the latest fifteen seconds into continuous work, and when the page is hidden or closed). A value that is not `true` or `false` is ignored, with one warning in the console. |
|
|
332
|
+
| `limitNotices` | `'all'` (the default) or `'chat'`. When a limit refuses the user (credits used up), `'all'` tells them in a toast and in the chat; `'chat'` in the chat alone, for a page that draws its own notice (see `limitReached`). Other failures keep their toast. Anything else throws a `TypeError` that names the option. |
|
|
333
|
+
| `initialMessage` | Words for the chat of a new widget, and the pictures that go with them: `{ text: 'Replicate this design: https://…', send: true }`, or `{ text: 'Replicate this photo', send: true, attachments: [file] }`. `text` is words, not empty, at most 4000 characters. `attachments` is a list of at most 5 `File`s of your page's own (a photo the user chose on your page, not a link: the builder looks at a picture that is attached, not at an address in the text), each a PNG, JPEG, WebP or GIF of at most 10 MB. With `send: true` the creator sends it as the first message when the chat is ready, exactly as if the user had typed it, attached the pictures and pressed Enter; without `send` the words and the pictures wait in the chat's input. Used once, for a new widget (`startWithNewWidget: true`); a widget that already has a draft keeps its own. A wrong shape throws a `TypeError` that names the option (and the picture, by its place in the list). |
|
|
325
334
|
| `locale`, `messages` | The creator's language: the plural rules, numbers and dates, and the words as ONE flat object of message keys and texts for the whole creator (its own words, the chat's, the canvas's, the picker's). See "Speaking your visitors' language"; `setLanguage({ locale?, messages? })` changes them while it is on screen. |
|
|
326
335
|
| `mediaLibrary` | Your own media library for the settings panel file pickers (see "Showing your own media library"). When `upload` is given, chat attachments and canvas/prompt images use it too (`purpose`: `chat`, `canvas`, or `field` for pickers), with Widgetic upload as fallback. |
|
|
327
336
|
| `pickFile` | Your own file picker for file fields (see "Partner file picker (`pickFile`)"). Without it the built-in File Browser is used. |
|
|
@@ -336,6 +345,8 @@ shown the picker it comes after they chose), `presetChosen` `{ key, canvasId, wi
|
|
|
336
345
|
`{ canvasId }` (the creator opened a canvas or made one: keep the id and give it back next time), `widgetRenamed`
|
|
337
346
|
`{ widgetId, name }` (the main widget has this name: said when the canvas opens and each time the user renames it, never
|
|
338
347
|
twice in a row for the same name, so you can keep a title for the user's work), `widgetPublished` `{ widgetId, version? }`,
|
|
348
|
+
`publishStateChanged` `{ widgetId, canPublish, publishing, label, unpublished }` (what Publish would do now, for a page that
|
|
349
|
+
draws its own Publish button: see "A header of your own around the creator"),
|
|
339
350
|
`limitReached` `{ message, code? }` (the visitor ran into a limit; the creator tells them in plain words, this is for your
|
|
340
351
|
page: see "When a limit is reached"), `reloadRequested` (the creator would have reloaded the page to recover: unmount it and mount a new one),
|
|
341
352
|
and `error` `{ message, code?, fatal, during?, sessionEnded? }`. `fatal: false` with `during: 'presets'` is the starting points
|
|
@@ -346,7 +357,58 @@ again without it). Either way, no `ready` comes, and the creator stops asking th
|
|
|
346
357
|
|
|
347
358
|
Methods: `getCanvasId()` (the canvas that is open now, or `null`), `setTheme(theme)` (see "Looking like your product"),
|
|
348
359
|
`setLanguage({ locale?, messages? })` and, to hand to a translator, `defaultMessages` and `checkMessages(messages)` (see
|
|
349
|
-
"Speaking your visitors' language"), `
|
|
360
|
+
"Speaking your visitors' language"), `getPublishState()`, `publish()`, `flush()` and `setWidgetName(name, widgetId?)` (see
|
|
361
|
+
"A header of your own around the creator"), `unmount()`.
|
|
362
|
+
|
|
363
|
+
**A header of your own around the creator.** A page that draws its own bar above the creator (a Back arrow, the name of the
|
|
364
|
+
widget the user is on, a Publish button) is given what it needs, and the creator's own controls for the same things can
|
|
365
|
+
be put aside:
|
|
366
|
+
|
|
367
|
+
```js
|
|
368
|
+
creator.on('publishStateChanged', ({ canPublish, publishing, label }) => drawPublishButton({ enabled: canPublish && !publishing, label }));
|
|
369
|
+
publishButton.onclick = async () => {
|
|
370
|
+
try {
|
|
371
|
+
await creator.publish(); // resolves after `widgetPublished`
|
|
372
|
+
goBackToMyDashboard();
|
|
373
|
+
} catch (error) {
|
|
374
|
+
// the creator has told the user why it could not (nothing to publish yet, a limit, a failed publish); this is for you
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
backButton.onclick = async () => {
|
|
378
|
+
await creator.flush(); // the last change is on the server before the page leaves
|
|
379
|
+
goBackToMyDashboard();
|
|
380
|
+
};
|
|
381
|
+
nameField.onchange = () => creator.setWidgetName(nameField.value); // the widget the user is on; pass a widgetId for another one
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
- **`publishStateChanged`** `{ widgetId, canPublish, publishing, label, unpublished }`: `widgetId` is the widget `publish()`
|
|
385
|
+
would publish (the one the user is on, the main widget of the canvas while no other is open; `null` while there is none);
|
|
386
|
+
`canPublish` is `true` when it has something to publish and nothing is running; `publishing` is `true` while a publish
|
|
387
|
+
of it runs; `label` is the creator's own button's words ("Publish" or "Publish changes", in your page's language);
|
|
388
|
+
`unpublished` is `true` when the widget has changes no published version has. It is said when the creator first knows,
|
|
389
|
+
then at every change and never twice with the same state. `getPublishState()` gives the last one (a copy, `null` before the
|
|
390
|
+
creator said any) to a page that draws its button after the creator reported.
|
|
391
|
+
- **`publish()`** does what the creator's own Publish button does and resolves when it is done, after `widgetPublished`
|
|
392
|
+
(the creator now says `widgetPublished` for a session too). It rejects, and does nothing, when the creator is not on
|
|
393
|
+
screen (call it after `mount()` has finished and before `unmount()`), when the creator is one that cannot be told to
|
|
394
|
+
publish, or with the creator's own reason when it cannot publish now; the creator shows that reason to the user as it
|
|
395
|
+
does when its own button is pressed.
|
|
396
|
+
- **`flush()`** puts what the user changed in the canvas on the server now and resolves when that is done. Wait for it
|
|
397
|
+
before your page takes the user away from the creator. It never rejects: with nothing on screen nothing is unsaved, and
|
|
398
|
+
a save that fails is the creator's to say (the problem is written to the console, once).
|
|
399
|
+
- **`setWidgetName(name, widgetId?)`** renames the widget the page names, or the one the user is on without a `widgetId`.
|
|
400
|
+
The creator shows the new name at once and saves it, and says `widgetRenamed` (your page sees its own change come back, so
|
|
401
|
+
ignore an old name while your own rename is on its way). It rejects, and renames nothing, for a name that is not text or
|
|
402
|
+
is empty, when the creator is not on screen, or when the creator is one that cannot be renamed from the page.
|
|
403
|
+
- **`showSaveButton: false`** removes the canvas's Save button and the dot next to it; **`toolbarPosition`** moves the
|
|
404
|
+
drawing toolbar out of the way of something of your own along the bottom edge; **`limitNotices: 'chat'`** keeps the
|
|
405
|
+
refusal because of a limit to the line in the chat; **`initialMessage`** starts a new widget with words in the chat
|
|
406
|
+
(a link and an instruction, say, or a photo the user chose on your page, as `attachments`) and, with `send: true`, sends
|
|
407
|
+
them for the user, which makes the widget and starts the build.
|
|
408
|
+
- **A creator older than these.** A module that is newer than the creator it carries ignores the options the creator does not
|
|
409
|
+
know, `publish()` and `setWidgetName()` reject with a message that says so, and `flush()` resolves at once with one
|
|
410
|
+
warning in the console. A page that wants to know checks `typeof creator.publish === 'function'` on the module it
|
|
411
|
+
loaded from the CDN: an older module lacks the methods altogether.
|
|
350
412
|
|
|
351
413
|
**What it keeps.** It does not touch your page's `localStorage`, `sessionStorage`, cookies or address bar, and never
|
|
352
414
|
opens a window, reloads or navigates your page: what it remembers (the user's settings, colour presets, the canvas that
|
|
@@ -355,7 +417,8 @@ it follows a generation over the API's event stream.
|
|
|
355
417
|
|
|
356
418
|
**When a limit is reached.** Your credits, your plan and your storage are yours: a visitor is never told what they hold.
|
|
357
419
|
The API refuses a session with one plain sentence ("This is not available right now. Please try again later.") and the
|
|
358
|
-
creator shows exactly that, in the chat with a *Retry* button and in a toast
|
|
420
|
+
creator shows exactly that, in the chat with a *Retry* button and in a toast (`limitNotices: 'chat'` leaves the toast out,
|
|
421
|
+
for a page that draws its own notice), and keeps working: the canvas, the chat and
|
|
359
422
|
the other widgets are still there. It also tells *your page*, with
|
|
360
423
|
`limitReached` `{ message: 'The visitor reached a limit.', code }`, where `code` is what the API answered:
|
|
361
424
|
|
|
@@ -440,7 +503,9 @@ module gives it a shadow root, a theme, a language, a session and a way to tell
|
|
|
440
503
|
name, date created, last published or visitors, new workflow, duplicate, delete) and, when one is opened, the editor: a
|
|
441
504
|
canvas of Composition, Trigger and Condition blocks that go forward only (up to 25), a side panel for the selected block,
|
|
442
505
|
a draft that is saved while you work, publish and discard, a history of versions that never change, a Test run that plays a
|
|
443
|
-
visitor through the draft, a Runs tab
|
|
506
|
+
visitor through the draft, a Runs tab that draws how far visitors came as a funnel (a Sankey diagram: a bar for each
|
|
507
|
+
composition, a band for each way between two of them, as wide as the visitors who went that way, and a red part under a bar for the
|
|
508
|
+
times that composition could not be shown), and a Settings tab (time zone, embed
|
|
444
509
|
code, pause, archive, duplicate, delete). A trigger is enabled for a composition only when its widget can supply it (values a
|
|
445
510
|
visitor adds need a Pro widget that keeps data); the reason is told next to the choice. *New workflow* asks for a name and for
|
|
446
511
|
where to start: a blank workflow, or a starting point (a preset) the workspace is offered, which is Widgetic's for a person with a
|
|
@@ -477,7 +542,7 @@ window.addEventListener('popstate', () => workflows.module.setWorkflow(workflowO
|
|
|
477
542
|
| `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 }`. Two kinds work: 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, or an **editor session** your server minted for one of your customers with `surfaces: ['workflows']` ("Showing it to your customers"). 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). |
|
|
478
543
|
| `apiUrl` | The API origin (`https://api.widgetic.com` unless you run your own). |
|
|
479
544
|
| `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. |
|
|
480
|
-
| `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. |
|
|
545
|
+
| `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). The list says it too: a row shows "Anna is editing" under the name of a workflow a teammate has open ("Someone is editing" when the API gives no name). The list asks the API once for the whole page of rows, again every twenty seconds or so while the tab can be seen (never while it is hidden), and a look takes and renews nothing, so a person who only looks at the list does not become an editor of anything. 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. |
|
|
481
546
|
| `theme`, `themeFromHost` | The colours, the corners and the typeface ("Looking like your product"). |
|
|
482
547
|
| `locale`, `messages` | The language ("Speaking your visitors' language"). |
|
|
483
548
|
|
|
@@ -719,7 +784,7 @@ files.setLanguage({ locale: 'de', messages: germanMessages }); // later, while i
|
|
|
719
784
|
| `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. |
|
|
720
785
|
| `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. |
|
|
721
786
|
|
|
722
|
-
**Translation packs (shipped languages).** Each pack is one lazy file next to `index.js` (gzip budget per pack: File Browser **5 kB**, composition editor **
|
|
787
|
+
**Translation packs (shipped languages).** Each pack is one lazy file next to `index.js` (gzip budget per pack: File Browser **5 kB**, composition editor **10 kB**, widget creator **28 kB**, Workflows **10 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 439 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.
|
|
723
788
|
|
|
724
789
|
**`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).
|
|
725
790
|
|
|
@@ -783,8 +848,7 @@ await mountModule('file-browser', { container: '#media', getToken, locale: 'ar'
|
|
|
783
848
|
Browser above, turned around with it.
|
|
784
849
|
- **The widget creator:** the tools of the toolbar run from the start of the line, the properties panel is docked at the
|
|
785
850
|
end of it, the context menu, the list of shapes, the publish history and the starting-point picker are laid out from the
|
|
786
|
-
start, the title of a widget in its panel keeps the room it needs
|
|
787
|
-
start edge of its button. The composition editor and the File Browser inside the creator are turned around the same
|
|
851
|
+
start, and the title of a widget in its panel keeps the room it needs. The composition editor and the File Browser inside the creator are turned around the same
|
|
788
852
|
way.
|
|
789
853
|
- **Workflows:** everything is placed by the start and the end of the line (the package's `tests/workflows-direction.test.mjs`
|
|
790
854
|
fails on a physical side), so the list, the top bar of the editor, the tabs, the side panel, the menus and the dialogs
|
|
@@ -887,8 +951,8 @@ editor.setLanguage({ locale: 'pl', messages: polishMessages }); // labels and bu
|
|
|
887
951
|
takes **one flat `messages` object for all of it**. The creator is made of parts that each have their own words, and it
|
|
888
952
|
splits what you give between them, so you never need to know which part says a word:
|
|
889
953
|
|
|
890
|
-
- the creator's own words, the `creator.` keys: the widget's panel, publishing and versions,
|
|
891
|
-
|
|
954
|
+
- the creator's own words, the `creator.` keys: the widget's panel, publishing and versions, chat generation options
|
|
955
|
+
(language and custom libraries in debug), the limits it explains, the lines of its status bar; the preset **Libraries** toggle and its
|
|
892
956
|
add-library control are drawn only in creator debug mode (`showPresetLibraries`), which the widget creator module does
|
|
893
957
|
not turn on, but their messages stay in the catalog for hosts that do;
|
|
894
958
|
- the chat's words (`chat.` keys) and the canvas's (`canvas.` keys: the toolbar, the zoom controls, the context menu, the
|
|
@@ -942,14 +1006,14 @@ creator.setLanguage({ locale: 'de', messages: germanMessages }); // every screen
|
|
|
942
1006
|
code stay left to right.
|
|
943
1007
|
|
|
944
1008
|
**Workflows.** It takes the same `locale`, `messages`, `setLanguage`, `defaultMessages` and `checkMessages`, with **one**
|
|
945
|
-
`messages` object for all of it: its
|
|
1009
|
+
`messages` object for all of it: its 439 `workflows.` keys (the list, the editor and its panels, the names of blocks,
|
|
946
1010
|
operators and units, what the engine finds wrong with a workflow, what a failed request means, and the words of the screen
|
|
947
|
-
that says a part could not be drawn). The words of a block are made of parts the screen puts together (`{field} {value}`,
|
|
1011
|
+
that says a part could not be drawn and why). The words of a block are made of parts the screen puts together (`{field} {value}`,
|
|
948
1012
|
`{count, plural, ...}`), so a language that puts them in another order can say so in its own message.
|
|
949
1013
|
|
|
950
1014
|
- **It speaks the twelve languages of the other modules.** `Workflows.supportedLocales` lists them (`fr`, `de`, `es`,
|
|
951
1015
|
`pt-BR`, `nl`, `da`, `sv`, `zh-CN`, `ar`, `he`, `fa`, `ur`) and `Workflows.localePackStatus(tag)` is `'provisional'` for
|
|
952
|
-
each: a `locale` that has a pack fetches one lazy file of
|
|
1016
|
+
each: a `locale` that has a pack fetches one lazy file of 439 messages (30 to 44 kB, 8.0 to 9.3 kB gzipped; the budget is
|
|
953
1017
|
10 kB gzipped), and `mount()` waits for it, so the first paint is already in that language. A `locale` with no pack
|
|
954
1018
|
(English, `zh-TW`, an unknown tag) downloads nothing and says nothing in the console: the words stay English, while the
|
|
955
1019
|
plural rules and the direction follow `locale` either way. Your `messages` win over the pack, key by key. The packs are
|
|
@@ -1085,8 +1149,7 @@ a wrong shape.
|
|
|
1085
1149
|
every message of `WidgetCreatorModule.defaultMessages` wrapped in marks). It walks the canvas with a widget's shape selected
|
|
1086
1150
|
(the toolbar, the zoom controls, the properties panel and the pop-up region), the details of the widget (the chat, what it
|
|
1087
1151
|
sends, the version menu with its dates), the canvas's context menu with a shape selected and with nothing selected, More
|
|
1088
|
-
Shapes, the question before a shape is removed (a sentence made of three pieces), the
|
|
1089
|
-
(not the preset **Libraries** section, which debug mode alone draws), a refusal and the pop-up it brings with its close
|
|
1152
|
+
Shapes, the question before a shape is removed (a sentence made of three pieces), a refusal and the pop-up it brings with its close
|
|
1090
1153
|
button, the moment before the picker, the picker and
|
|
1091
1154
|
a copy that fails, and fails on any text, label, hint or picture description a visitor can read or hear and that has no
|
|
1092
1155
|
marks. A short list of things that belong to the page (a hot key, the code of a colour, the name of a version, a unit, the
|
|
@@ -1201,6 +1264,22 @@ scripts/build-module.mjs the Vite build; scripts/plugins/* the CSS and packag
|
|
|
1201
1264
|
`module.css` is compiled once by Tailwind and the build exports it as two strings: `shadowCss` (goes into the shadow
|
|
1202
1265
|
root) and `documentCss` (the few rules that must live in the page: `@font-face`).
|
|
1203
1266
|
|
|
1267
|
+
### Building from the checkout
|
|
1268
|
+
|
|
1269
|
+
`node scripts/build-module.mjs <name> --from-source` compiles that module from the sibling packages' `src`
|
|
1270
|
+
(file-browser, design-system, editor, canvas, chat, creator, workflows, and the rest) instead of from the copies in
|
|
1271
|
+
`node_modules`. `--watch` rebuilds when one of those files is saved. A package that is not cloned stays the
|
|
1272
|
+
installed copy, and a bare import that the clone has not installed (`kaykay`, for example) is taken from this
|
|
1273
|
+
workspace. A SvelteKit `tsconfig` that extends a generated file is not read. `npm run build` and `publish:cdn`
|
|
1274
|
+
do not pass `--from-source`, so a published module is still built from the registry packages.
|
|
1275
|
+
|
|
1276
|
+
The Tailwind entry stays the installed `@widgetic/design-system` stylesheet. Pointing that import at the
|
|
1277
|
+
checkout's `global.css` pulls in that package's own Tailwind config and the module loses its layout. The
|
|
1278
|
+
`@source` lines in `module.css` are rewritten to the sibling `src` for the build, so the classes in the
|
|
1279
|
+
checkout are the ones that end up in the script.
|
|
1280
|
+
|
|
1281
|
+
The Shopify dev app is the one that serves the result. It is not a second way to publish.
|
|
1282
|
+
|
|
1204
1283
|
### One file, and the parts that are not in it
|
|
1205
1284
|
|
|
1206
1285
|
A module is `index.js`, which has everything the module needs to appear and to work, and the **lazy files** in `chunks/`:
|
|
@@ -1407,8 +1486,8 @@ What is left:
|
|
|
1407
1486
|
- **The fixes are released.** They were in branches of those packages (`feat/embed-in-shadow-root` of the canvas and the
|
|
1408
1487
|
chat, `feat/partner-host-mode` of the creator); `package.json` now asks for `@widgetic/canvas` ^0.5.19,
|
|
1409
1488
|
`@widgetic/chat` ^0.1.18 and `@widgetic/creator` ^0.4.0, which are on npm, and the lockfile pins them.
|
|
1410
|
-
- **Size.** 6.
|
|
1411
|
-
the creator itself (
|
|
1489
|
+
- **Size.** 6.3 MB (1.5 MB gzip) to open, which is 98% of its 6.45 MB budget, and 9.3 MB (2.3 MB gzip) in all, with the PDF viewer
|
|
1490
|
+
and the twelve language packs (a page downloads the one of its own language): the creator itself (573 kB), the whole canvas with fabric (370 kB), the chat, the editor's controls and their libraries. The canvas and the details panel
|
|
1412
1491
|
stay in `index.js` on purpose: the creator asks for the canvas as soon as it starts, and they share the Svelte runtime
|
|
1413
1492
|
and most of the creator, which a lazy file cannot (see "One file, and the parts that are not in it").
|
|
1414
1493
|
- **Stop only stops the creator waiting.** The Stop button ends the creator's wait for a generation. The gateway's cancel
|