@topol.io/editor 1.0.0-alpha.0 → 1.0.0-alpha.10

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.
Files changed (41) hide show
  1. package/README.md +150 -101
  2. package/dist/topol-plugin.es.js +131 -190
  3. package/dist/topol-plugin.umd.cjs +1 -0
  4. package/dist/types/src/core/script-loader.d.ts +15 -0
  5. package/dist/types/src/email-editor/constants.d.ts +3 -3
  6. package/dist/types/src/email-editor/index.d.ts +15 -90
  7. package/dist/types/src/landing-page-editor/index.d.ts +18 -6
  8. package/dist/types/src/landing-page-editor/schemas/contentBlock/contentBlockScheme.d.ts +1 -1
  9. package/dist/types/src/landing-page-editor/schemas/openAI/openAISchema.d.ts +1 -2
  10. package/dist/types/src/landing-page-editor/schemas/pluginOptions/pluginOptionsSchema.d.ts +89 -0
  11. package/dist/types/src/landing-page-editor/schemas/premadeBlock/premadeBlockSchema.d.ts +816 -816
  12. package/dist/types/src/landing-page-editor/schemas/savedBlock/savedBlockApiSchema.d.ts +612 -612
  13. package/dist/types/src/landing-page-editor/schemas/savedBlock/savedBlockSchema.d.ts +816 -816
  14. package/dist/types/src/landing-page-editor/schemas/template/blocks/buttonBlockSchema.d.ts +2 -2
  15. package/dist/types/src/landing-page-editor/schemas/template/blocks/dividerBlockSchema.d.ts +2 -2
  16. package/dist/types/src/landing-page-editor/schemas/template/blocks/imageAnGifBlockSchema.d.ts +6 -6
  17. package/dist/types/src/landing-page-editor/schemas/template/blocks/socialBlockSchema.d.ts +2 -2
  18. package/dist/types/src/landing-page-editor/schemas/template/blocks/spacerBlockSchema.d.ts +2 -2
  19. package/dist/types/src/landing-page-editor/schemas/template/structure/blockSchema.d.ts +92 -92
  20. package/dist/types/src/landing-page-editor/schemas/template/structure/columnSchema.d.ts +94 -94
  21. package/dist/types/src/landing-page-editor/schemas/template/structure/sectionSchema.d.ts +204 -204
  22. package/dist/types/src/landing-page-editor/schemas/templateSchema.d.ts +804 -804
  23. package/dist/types/src/main.d.ts +14 -68
  24. package/dist/types/types/API/API.d.ts +8 -7
  25. package/dist/types/types/Auth/INonceAuthCallbacks.d.ts +9 -0
  26. package/dist/types/types/Callbacks/ICallbackPayloads.d.ts +20 -17
  27. package/dist/types/types/Callbacks/IEmailCallbacks.d.ts +65 -104
  28. package/dist/types/types/Cloud/ICloudOptions.d.ts +32 -0
  29. package/dist/types/types/ContentBlock/IContentBlockOptions.d.ts +1 -1
  30. package/dist/types/types/Countdown/ICountdownOptions.d.ts +48 -0
  31. package/dist/types/types/IEmailConfig.d.ts +199 -0
  32. package/dist/types/types/IEmailEditorInstance.d.ts +54 -0
  33. package/dist/types/types/ITopolOptions.d.ts +4 -120
  34. package/dist/types/types/ITopolPlugin.d.ts +2 -37
  35. package/dist/types/types/Language/Language.d.ts +6 -1
  36. package/dist/types/types/SavedBlock/ISavedBlock.d.ts +2 -6
  37. package/dist/types/types/Sections/ISections.d.ts +30 -0
  38. package/dist/types/types/landing-page/ILandingPageEditorInstance.d.ts +12 -4
  39. package/dist/types/types/landing-page/ILandingPageOptions.d.ts +96 -58
  40. package/package.json +10 -13
  41. package/dist/topol-plugin.umd.js +0 -1
package/README.md CHANGED
@@ -1,121 +1,170 @@
1
- <a href="https://topol.io" target="_blank">
2
- <img src="https://storage.googleapis.com/topolio17326/plugin-assets/6320/17326/topol-with-bg.png" alt="Tailwind CSS" width="400" height="120">
3
- </a>
1
+ # @topol.io/editor — 1.x alpha
4
2
 
5
- ---
3
+ The 1.x alpha line targets **Email Editor v4** from `1.0.0-alpha.10`. Earlier 1.x
4
+ alphas targeted v3; see [Migration from earlier 1.x alphas](#migration-from-earlier-1x-alphas).
6
5
 
7
- Easy and quick! Drag and drop HTML editor and builder for beautiful responsive email templates.
8
-
9
- # Documentation
10
-
11
- ## Installation
12
-
13
- Install Editor from NPM using:
14
-
15
- ```sh
16
- npm install @topol.io/editor
17
-
18
- //or
6
+ ```ts
7
+ import { EmailEditor } from "@topol.io/editor";
19
8
 
20
- yarn add @topol.io/editor
9
+ const editor = await EmailEditor.init({
10
+ config: {
11
+ authorize: { apiKey: "your-api-key", userId: "user-123" },
12
+ },
13
+ async onSave({ json, html, mutations, syncedSections }) {
14
+ // Await your own backend's persistence here. A rejection shows a save error.
15
+ console.log(json, html, mutations, syncedSections);
16
+ },
17
+ onEditorError({ source, message, detail }) {
18
+ console.error(source, message, detail);
19
+ },
20
+ });
21
+ await editor.render("#editor"); // Container must exist and have a height.
22
+ // onInit reports successful editor authentication; render only mounts the iframe.
23
+ await editor.load(templateJson);
24
+ await editor.save({ langCode: "en" });
25
+ await editor.destroy(); // When closing/unmounting, not immediately after render.
21
26
  ```
22
27
 
23
- ## Usage
28
+ Every `init` creates an independent instance. Host methods return promises, including
29
+ `getMutations()`, which resolves to `{ code, primary }[]`. Use instance methods for
30
+ `setSavedSections`, `refreshSyncedSections`, `setMergeTags`, `translateLanguage(code,
31
+ sourceCode?)`, `translateAllLanguages`, and other editor actions.
24
32
 
25
- Add HTML element Editor will load to
33
+ ## Nonce authentication
26
34
 
27
- ```html
28
- <div id="app" style="position: absolute; width: 100%; height: 100%"></div>
29
- ```
35
+ Passing a `getNonce` callback switches authentication from the public key alone to
36
+ short-lived `nc_` nonces minted on your backend from the `sk_` secret. Nothing else
37
+ changes: templates, autosaves, images, comments and sections keep using your own
38
+ `api.*` endpoints and callbacks. There is no separate option; the presence of the
39
+ callback enables it. Topol Cloud is built on top of it and requires the callback.
30
40
 
31
- In your JS or TS file import TopolPlugin, initialize the editor, as an ID provide the id you defined the HTML, in this example its `app`
41
+ ```ts
42
+ const editor = await EmailEditor.init({
43
+ config: { authorize: { apiKey: "pk_your-public-key", userId: "user-123" } },
44
+ async getNonce() {
45
+ // Your backend calls Topol's POST /auth/nonce with the sk_ secret and this userId.
46
+ const response = await fetch("/api/topol/nonce", { method: "POST" });
47
+ if (!response.ok) throw new Error("Could not mint a Topol nonce");
48
+ return (await response.json()).nonce; // A fresh nc_ token.
49
+ },
50
+ });
51
+ ```
32
52
 
33
- For more options see the docs for [TopolOptions configuration](https://docs.topol.io/reference/topol-options.html)
53
+ The editor refreshes the nonce before it expires and retries once on a rejected
54
+ nonce. A first nonce that cannot be obtained, or `cloud.enabled` without `getNonce`,
55
+ reports `onEditorError` with `source: "authorize"`; a later refresh failure reports
56
+ `source: "nonceAuth"` while the editor keeps working on the last valid nonce.
34
57
 
35
- ```js
36
- import TopolPlugin from "@topol.io/editor";
58
+ ## Topol Cloud
37
59
 
38
- const TOPOL_OPTIONS = {
39
- id: "#app",
40
- authorize: {
41
- apiKey: "YOUR_API_TOKEN",
42
- userId: "some-user-id",
60
+ ```ts
61
+ const editor = await EmailEditor.init({
62
+ config: {
63
+ authorize: { apiKey: "pk_your-public-key", userId: "user-123" },
64
+ cloud: { enabled: true, templateId: 123, features: { images: false } },
43
65
  },
44
- callbacks: {
45
- onSave(json, html) {},
66
+ async getNonce() {
67
+ // Your authenticated backend mints a nonce for this public key and user.
68
+ const response = await fetch("/api/topol/nonce", { method: "POST" });
69
+ if (!response.ok) throw new Error("Could not authorize Topol Cloud");
70
+ const { nonce } = await response.json();
71
+ return nonce; // A fresh nc_ token. Keep sk_ secrets on the server.
46
72
  },
47
- };
48
-
49
- TopolPlugin.init(TOPOL_OPTIONS);
73
+ onCloudSave({ templateId, name, langCode }) {
74
+ console.log("Stored in Cloud:", templateId, name, langCode);
75
+ },
76
+ onCloudTemplateChange({ type, templateId, name, folderId }) {
77
+ console.log(type, templateId, name, folderId);
78
+ },
79
+ });
80
+ await editor.render("#editor");
50
81
  ```
51
82
 
52
- ## Call Topol Plugin actions
83
+ Enabling Cloud activates templates, autosaves, images, comments, sections,
84
+ multilanguage, and test-send. Set a feature to `false` to use external behavior.
85
+ Omit `cloud.templateId` to start in the Cloud template browser. Cloud requires the
86
+ `getNonce` callback from nonce authentication above; `init` rejects without it. The
87
+ editor handles nonce refresh, persistence, and its Cloud recovery UI; this package
88
+ supplies the host bridge.
53
89
 
54
- To call actions to the editor import:
90
+ ## Countdown block
55
91
 
56
- ```js
57
- import { TopolPlugin } from "@topol.io/editor";
58
-
59
- TopolPlugin.save();
60
- ```
61
-
62
- ### List of all available TopolPlugin actions:
63
-
64
- | Action | Description |
65
- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
66
- | `TopolPlugin.save()` | Saves the content of the editor [more info](https://docs.topol.io/guide/how-to-use-custom-topbar.html#save-and-saveandclose) |
67
- | `TopolPlugin.load(template)` | Loads the provided template [more info](https://docs.topol.io/guide/how-to-load-and-save-template.html#loading-template) |
68
- | `TopolPlugin.togglePreview()` | Toggles editor preview [more info](https://docs.topol.io/guide/how-to-use-custom-topbar.html#changing-preview-mode) |
69
- | `TopolPlugin.togglePreviewSize()` | Toggles editor preview size [more info](https://docs.topol.io/guide/how-to-use-custom-topbar.html#changing-preview-mode) |
70
- | `TopolPlugin.undo()` | Undo change in editor [more info](https://docs.topol.io/guide/how-to-use-custom-topbar.html#undo-and-redo) |
71
- | `TopolPlugin.redo()` | Redo change in editor [more info](https://docs.topol.io/guide/how-to-use-custom-topbar.html#undo-and-redo) |
72
- | `TopolPlugin.setSavedBlocks(savedblock: ISavedBlock[])` | Sets the saved blocks [more info](https://docs.topol.io/guide/saved-blocks.html) |
73
- | `TopolPlugin.createNotification(notification: INotification)` | Creates editor's notification [more info](https://docs.topol.io/guide/custom-notifications.html) |
74
- | `TopolPlugin.changeEmailToMobile()` | Change email to mobile view [more info](https://docs.topol.io/guide/mobile-first.html#mobile-first-email-template) |
75
- | `TopolPlugin.changeEmailToDesktop()` | Change email to desktop view [more info](https://docs.topol.io/guide/mobile-first.html#mobile-first-email-template) |
76
- | `TopolPlugin.toggleBlocksAndStructuresVisibility()` | Toggle hidden structures visibility for blocks and structures [more info](https://docs.topol.io/guide/mobile-first.html#mobile-first-email-template) |
77
- | `TopolPlugin.destroy()` | Destroys the editor initialization |
78
- | `TopolPlugin.chooseFile()` | Chooses the file if image block is active [more info](https://docs.topol.io/guide/custom-filemanager.html#choosefile) |
79
- | `TopolPlugin.openPremadeTemplatesSelection()` | Opens the premade templates modal pick [more info](https://docs.topol.io/guide/premade-templates-in-editor.html) |
80
- | `TopolPlugin.refreshComments(key: string)` | Refreshes the conversation [more info](https://docs.topol.io/guide/comments.html#refreshcomments) |
81
- | `TopolPlugin.setActiveMembers(activeMemers: string[])` | Sets the active members |
82
- | `TopolPlugin.setTemplateName(name: string)` | Sets the name of template [more info](https://docs.topol.io/guide/rename-template.html) |
83
- | `TopolPlugin.updateApiAuthorizationHeader(newHeader: string \| Record<string, string>)` | Refreshes the authorization tokens [more info](https://docs.topol.io/guide/security.html#refresh-token) |
84
- | `TopolPlugin.updateCustomBlockContent(content: string)` | Refreshes the authorization tokens [more info](https://docs.topol.io/guide/custom-block.html#inserting-custom-html-in-custom-dialog-component) |
85
- | `TopolPlugin.setMergeTags(mergeTags: Array<IMergeTagGroup \| IMergeTag>)` | Sets new array of merge tags. [more info](https://docs.topol.io/guide/merge-tags.html#update-merge-tags) |
86
-
87
- <br>
88
-
89
- ### List of all editor callbacks
90
-
91
- | Event | Description |
92
- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
93
- | `onSave` | Returns object which contains html and json of the template [more info](https://docs.topol.io/guide/callbacks.html#on-save) |
94
- | `onSaveAndClose` | Returns object which contains html and json of the template [more info](https://docs.topol.io/guide/callbacks.html#on-save-and-close) |
95
- | `onTestSend` | Returns object which contains email, html and json of the template [more info](https://docs.topol.io/guide/callbacks.html#on-test-email-send) |
96
- | `onOpenFileManager` | When user clicks file manager open [more info](https://docs.topol.io/guide/custom-filemanager.html#onopenfilemanager) |
97
- | `onLoaded` | After editor template is loaded using `TopolPlugin.load()` [more info](https://docs.topol.io/guide/callbacks.html#on-loaded) |
98
- | `onInit` | When editor inits [more info](https://docs.topol.io/guide/callbacks.html#on-init) |
99
- | `onBlockSave` | When user saves block in editor, returns object of type ISavedBlock [more info](https://docs.topol.io/guide/callbacks.html#on-block-save) |
100
- | `onBlockRemove` | When user removes saved block, returns id of saved block to be removed [more info](https://docs.topol.io/guide/callbacks.html#on-block-remove) |
101
- | `onBlockEdit` | When user edits saved block, returns id of saved block to be updated [more info](https://docs.topol.io/guide/callbacks.html#on-block-edit) |
102
- | `onUndoChange` | When user clicks undo button, retunrs number of steps user undone [more info](https://docs.topol.io/guide/callbacks.html#on-undo-change) |
103
- | `onRedoChange` | When user clicks redo button, retunrs number of steps user redone [more info](https://docs.topol.io/guide/callbacks.html#on-redo-change) |
104
- | `onPreview` | When user switches to preview [more info](https://docs.topol.io/guide/callbacks.html#on-preview) |
105
- | `onAlert` | When alert appears in editor [more info](https://docs.topol.io/guide/callbacks.html#on-alert) |
106
- | `onClose` | When close is click inside WindowBar [more info](https://docs.topol.io/guide/top-bar.html#window-bar) |
107
- | `onEdittedWithoutSaveChanged` | When user is about to leave an editor with unsaved changes [more info](https://docs.topol.io/guide/disable-before-leaving-modal.html#before-exit-modal-when-user-has-unsaved-changes) |
108
- | `onOpenCustomBlockDialog` | When user clicks on the open dialog in custom block [more info](https://docs.topol.io/guide/custom-block.html#inserting-custom-html-in-custom-dialog-component) |
109
- | `onTemplateRename` | When user clicks on the pencil icon next to the template name [more info](https://docs.topol.io/guide/rename-template.html#rename-template) |
110
- | `updateTestingEmailAddresses` | When user edits the email list in preview [more info](https://docs.topol.io/guide/sending-a-test-email.html#managing-saving-emails-yourself) |
111
- | `onError` | When an error that cannot be handled happened in the editor [more info](https://docs.topol.io/guide/callbacks.html#onerror) |
112
-
113
- <br>
114
-
115
- ## TypeScript
116
-
117
- Topol Editor provides full TypeScript integration and exports all necessary types.
92
+ The Countdown block is a paid add-on rolled out per user. It appears only when the
93
+ add-on flag your backend put into the editor nonce is set **and** `enableCountdown`
94
+ is `true`, and it needs `templateId`. The optional `countdown` object adapts the block
95
+ to your email service provider:
118
96
 
119
97
  ```ts
120
- import { ITopolOptions, INotification, ISavedBlock } from "@topol.io/editor";
98
+ const editor = await EmailEditor.init({
99
+ config: {
100
+ authorize: { apiKey: "pk_your-public-key", userId: "user-123" },
101
+ templateId: 123,
102
+ enableCountdown: true,
103
+ countdown: {
104
+ defaultColors: { background: "#ffffff", digits: "#000000", accent: "#2b66b3" },
105
+ styleThumbnailBase: "https://cdn.example.com/countdown-styles",
106
+ mergeTag: "*|CONTACT_ID|*",
107
+ dateMergeTags: [{ label: "From send", value: "*|SEND_DATE+{seconds}|*" }],
108
+ },
109
+ },
110
+ async getNonce() {
111
+ /* ... */
112
+ },
113
+ });
121
114
  ```
115
+
116
+ - `defaultColors` — palette of newly created countdowns; any subset of `background`,
117
+ `digits`, `labels`, `accent` as hex colors (`#RGB`, `#RRGGBB`, `#RRGGBBAA`). Unset
118
+ colors keep the editor defaults.
119
+ - `styleThumbnailBase` — base URL of your own style thumbnails; the editor loads
120
+ `{base}/{style}.gif` for each of the ten styles.
121
+ - `mergeTag` — merge tag identifying the recipient of an evergreen countdown, stored
122
+ in the template as part of the countdown image URL (`?key={tag}`). Prefer a stable
123
+ contact ID over the email address. At most 100 characters, no quotes. Unset = the
124
+ recipient's email address in the syntax of `emailServiceProvider`.
125
+ - `dateMergeTags` — merge tags that can supply the end date of a dynamic countdown
126
+ (for automations); without them the editor does not offer the dynamic type.
127
+ `{seconds}` in a `value` is replaced with the countdown length the user sets. The
128
+ value goes into the URL verbatim: at most 200 characters, no quotes, `<`, `>` or `&`.
129
+
130
+ The types are exported as `ICountdownOptions`, `ICountdownDefaultColors` and
131
+ `ICountdownDateMergeTag`. Details and the ESP requirements are in the
132
+ [option reference](https://docs.topol.io/email-editor/reference/topol-options#countdown).
133
+
134
+ ## Loader selection
135
+
136
+ The default is `https://v4.email-assets.topol.io/loader/build.js`.
137
+ Build-time overrides use `VITE_TOPOL_V4_URL`, `VITE_TOPOL_V4_DEV_URL`, and
138
+ `VITE_TOPOL_V4_STAGING_URL`; old `VITE_TOPOL_URL` values are ignored to prevent
139
+ accidentally bundling a v3 loader.
140
+ Pass `{ loaderUrl: 'https://your-preview/loader/build.js' }` as the second argument
141
+ to `init` to select a local or preview v4 loader. Explicit URLs never fall back.
142
+ Numeric stages still select PR previews; loader failures fall back to v4 production
143
+ only before a runtime has been initialized. Each page supports one loader URL;
144
+ switching environments requires a page reload, even after destroying all instances.
145
+ Let `EmailEditor.init` insert custom loader scripts. Host-inserted scripts with unknown
146
+ lifecycle are rejected immediately; an already available production runtime can be reused.
147
+ These runtime conflicts reject without falling back to another environment.
148
+ `dev` and `staging` use the v4 release loader unless their build-time
149
+ `VITE_TOPOL_V4_DEV_URL` / `VITE_TOPOL_V4_STAGING_URL` overrides are configured.
150
+ The upstream local loader uses its host page's origin for the iframe: serve/proxy
151
+ the editor at that origin, or build a loader with an explicit iframe URL.
152
+
153
+ ## Migration from earlier 1.x alphas
154
+
155
+ - `init({ id, authorize, callbacks })` → `init({ config: { authorize }, ...callbacks })`, then `instance.render(container)`.
156
+ - Singleton methods → methods on the returned instance. `save('en')` → `save({ langCode: 'en' })`.
157
+ - All callbacks receive zero arguments or one object. `onSave(json, html)` → `onSave({ json, html })`.
158
+ - `onClose` → `onEditorClose`; `onError(type, message, responseBody)` → `onEditorError({ source, message, detail })`.
159
+ - `savedBlocks` / `setSavedBlocks` → `savedSections` / `setSavedSections`.
160
+ - `onBlockSave/Remove/Edit` → `onSavedSectionSave/Remove/Edit` with `{ section }` / `{ id }` payloads.
161
+ - `premadeBlocks` → `premadeSections`; replace `premadeBlocksNoOverwrite` with `{ blocks, override }`.
162
+ - `syncedRowsEnable` / `refreshSyncedRows` → `syncedSectionsEnabled` / `refreshSyncedSections`.
163
+ - `api.SAVED_BLOCKS` → `api.SAVED_SECTIONS`; `api.SYNCED_ROWS` is removed. Legacy SAVE/LOAD/PREVIEW and singular autosave endpoints are removed.
164
+ - Language mutations and `defaultTemplateSettings.langs` use `code`, not `key`.
165
+ - `topBarOptions` → `hideTopbarControls` (a list of controls to hide).
166
+ - `authorize.userId` must be a non-negative integer or match `[A-Za-z0-9_-]+`.
167
+
168
+ `TopolPlugin` remains a naming alias for the new EmailEditor API, not a v3 adapter.
169
+ `LandingPageEditor` retains its existing API and loader. Its Cloud integration is
170
+ not enabled by these email-specific changes.
@@ -1,195 +1,139 @@
1
- function s(e) {
1
+ function I(e) {
2
2
  return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
3
3
  }
4
- var c = function(n, o, i) {
5
- var l = document.head || document.getElementsByTagName("head")[0], t = document.createElement("script");
6
- typeof o == "function" && (i = o, o = {}), o = o || {}, i = i || function() {
7
- }, t.type = o.type || "text/javascript", t.charset = o.charset || "utf8", t.async = "async" in o ? !!o.async : !0, t.src = n, o.attrs && w(t, o.attrs), o.text && (t.text = "" + o.text);
8
- var r = "onload" in t ? g : p;
9
- r(t, i), t.onload || g(t, i), l.appendChild(t);
4
+ var P = function(o, t, r) {
5
+ var n = document.head || document.getElementsByTagName("head")[0], i = document.createElement("script");
6
+ typeof t == "function" && (r = t, t = {}), t = t || {}, r = r || function() {
7
+ }, i.type = t.type || "text/javascript", i.charset = t.charset || "utf8", i.async = "async" in t ? !!t.async : !0, i.src = o, t.attrs && T(i, t.attrs), t.text && (i.text = "" + t.text);
8
+ var a = "onload" in i ? p : b;
9
+ a(i, r), i.onload || p(i, r), n.appendChild(i);
10
10
  };
11
- function w(e, n) {
12
- for (var o in n)
13
- e.setAttribute(o, n[o]);
11
+ function T(e, o) {
12
+ for (var t in o)
13
+ e.setAttribute(t, o[t]);
14
14
  }
15
- function g(e, n) {
15
+ function p(e, o) {
16
16
  e.onload = function() {
17
- this.onerror = this.onload = null, n(null, e);
17
+ this.onerror = this.onload = null, o(null, e);
18
18
  }, e.onerror = function() {
19
- this.onerror = this.onload = null, n(new Error("Failed to load " + this.src), e);
19
+ this.onerror = this.onload = null, o(new Error("Failed to load " + this.src), e);
20
20
  };
21
21
  }
22
- function p(e, n) {
22
+ function b(e, o) {
23
23
  e.onreadystatechange = function() {
24
- this.readyState != "complete" && this.readyState != "loaded" || (this.onreadystatechange = null, n(null, e));
24
+ this.readyState != "complete" && this.readyState != "loaded" || (this.onreadystatechange = null, o(null, e));
25
25
  };
26
26
  }
27
- const d = /* @__PURE__ */ s(c);
28
- var u = { BASE_URL: "/", MODE: "production", DEV: !1, PROD: !0, SSR: !1 };
29
- const a = {
30
- production: u.VITE_TOPOL_URL,
31
- dev: u.VITE_TOPOL_DEV_URL,
32
- staging: u.VITE_TOPOL_STAGING_URL
33
- }, P = "https://d10h8ga60f7b91.cloudfront.net/preview-app-{stage}/loader/build.js";
34
- function T(e = "production") {
35
- switch (e) {
36
- case "dev":
37
- return a.dev;
38
- case "staging":
39
- return a.staging;
40
- case "production":
41
- return a.production;
42
- default:
43
- return P.replace("{stage}", String(e));
27
+ const _ = /* @__PURE__ */ I(P), f = /* @__PURE__ */ new Map();
28
+ function U(e, o) {
29
+ if (o())
30
+ return Promise.resolve();
31
+ const t = f.get(e);
32
+ if (t)
33
+ return t;
34
+ const r = new Promise((n, i) => {
35
+ const a = typeof document < "u" ? g(e) : null;
36
+ if (a) {
37
+ const l = () => {
38
+ c(), n();
39
+ }, d = () => {
40
+ c(), a.remove(), i(new Error(`Failed to load script: ${e}`));
41
+ }, c = () => {
42
+ a.removeEventListener("load", l), a.removeEventListener("error", d);
43
+ };
44
+ a.addEventListener("load", l), a.addEventListener("error", d);
45
+ return;
46
+ }
47
+ _(e, (l) => {
48
+ var d;
49
+ l !== null ? ((d = g(e)) == null || d.remove(), i(l)) : n();
50
+ });
51
+ }).finally(() => {
52
+ f.delete(e);
53
+ });
54
+ return f.set(e, r), r;
55
+ }
56
+ function g(e) {
57
+ const o = document.getElementsByTagName("script");
58
+ for (let t = 0; t < o.length; t++)
59
+ if (o[t].src === new URL(e, document.baseURI).href)
60
+ return o[t];
61
+ return null;
62
+ }
63
+ const w = "https://v4.email-assets.topol.io/loader/build.js", u = {
64
+ production: w,
65
+ dev: w,
66
+ staging: w
67
+ }, A = "https://d10h8ga60f7b91.cloudfront.net/preview-app-{stage}/loader/build.js";
68
+ class h extends Error {
69
+ }
70
+ let s, y = Promise.resolve();
71
+ function O(e) {
72
+ if ((e == null ? void 0 : e.loaderUrl) !== void 0) {
73
+ if (!e.loaderUrl.trim())
74
+ throw new Error("[@topol.io/editor] loaderUrl must not be empty.");
75
+ return e.loaderUrl;
44
76
  }
77
+ const o = (e == null ? void 0 : e.stage) ?? "production", r = typeof o == "number" || /^\d+$/.test(o) ? A.replace("{stage}", String(o)) : u[o];
78
+ if (!r)
79
+ throw new Error(`[@topol.io/editor] Unsupported stage "${o}". Use a supported stage or loaderUrl.`);
80
+ return r;
45
81
  }
46
- async function f(e) {
47
- return new Promise((n, o) => {
48
- d(a.production, (i) => {
49
- if (i !== null) {
50
- o(i);
51
- return;
52
- }
53
- window.TopolPlugin.init(e), n(!0);
54
- });
82
+ function S(e, o) {
83
+ const t = y.then(async () => {
84
+ try {
85
+ return await v(e);
86
+ } catch (r) {
87
+ if (r instanceof h || o === void 0)
88
+ throw r;
89
+ const n = await v(o);
90
+ return s == null || s.urls.add(new URL(e, document.baseURI).href), n;
91
+ }
55
92
  });
93
+ return y = t.catch(() => {
94
+ }), t;
56
95
  }
57
- const m = {
58
- /**
59
- * Initialize the Email Editor.
60
- * @param topolOptions - Configuration options for the editor
61
- * @param options - Plugin options including stage selection
62
- * @returns Promise that resolves to true when the editor is ready
63
- */
64
- init: (e, n) => new Promise((o, i) => {
65
- const l = T(n == null ? void 0 : n.stage);
66
- d(l, async (t) => {
67
- if (t !== null) {
68
- if (l !== a.production)
69
- try {
70
- return await f(e), o(!0);
71
- } catch (r) {
72
- i(r);
73
- }
74
- i(t);
75
- return;
76
- }
77
- window.TopolPlugin.init(e), o(!0);
96
+ async function v(e) {
97
+ const o = new URL(e, document.baseURI).href;
98
+ if (s) {
99
+ if (s.urls.has(o))
100
+ return s.factory;
101
+ throw new h("[@topol.io/editor] Editor v4 supports one loader URL per page. Reload the page to switch environments.");
102
+ }
103
+ const t = o === new URL(u.production, document.baseURI).href && typeof window.TopolEmailEditor == "function";
104
+ if (!t && (typeof window.TopolEmailEditor == "function" || Array.from(document.scripts).some((n) => n.src === o)))
105
+ throw new h("[@topol.io/editor] Cannot initialize from a host-provided loader with unknown lifecycle. Remove the script, reload the page, and let EmailEditor.init load the requested URL.");
106
+ if (await U(e, () => t), typeof window.TopolEmailEditor != "function") {
107
+ for (const n of Array.from(document.scripts))
108
+ n.src === o && n.remove();
109
+ throw new Error("[@topol.io/editor] The loader did not define window.TopolEmailEditor. Use an editor v4 loader.");
110
+ }
111
+ const r = window.TopolEmailEditor;
112
+ return s = { urls: /* @__PURE__ */ new Set([o]), factory: r }, r;
113
+ }
114
+ const N = {
115
+ async init(e, o) {
116
+ var E, m;
117
+ if (typeof window > "u" || typeof document > "u")
118
+ throw new Error("[@topol.io/editor] EmailEditor.init requires a browser. Call it after mounting.");
119
+ if (!((E = e == null ? void 0 : e.config) != null && E.authorize))
120
+ throw new Error("[@topol.io/editor] Editor v4 requires { config: { authorize, ... }, onSave, ... }. See docs/MIGRATION-editor-v4.md.");
121
+ const t = e.config.authorize.userId;
122
+ if (typeof t == "string" ? !/^[A-Za-z0-9_-]+$/.test(t) : !Number.isInteger(t) || t < 0)
123
+ throw new Error("[@topol.io/editor] authorize.userId must be a URL-safe string or a non-negative integer.");
124
+ if ((m = e.config.cloud) != null && m.enabled && typeof e.getNonce != "function")
125
+ throw new Error("[@topol.io/editor] cloud.enabled requires nonce authentication: pass a top-level getNonce callback returning Promise<string>.");
126
+ const r = O(o), n = (o == null ? void 0 : o.loaderUrl) === void 0 && r !== u.production ? u.production : void 0, i = await S(r, n), { onClose: a, onError: l, ...d } = e, c = i(d);
127
+ let L;
128
+ return Object.assign(c, {
129
+ destroy: () => L ?? (L = Promise.resolve().then(() => c.close()))
78
130
  });
79
- }),
80
- /** Trigger the save callback with current editor content */
81
- save: () => {
82
- window.TopolPlugin.save();
83
- },
84
- /** Load a template JSON into the editor */
85
- load: (e) => {
86
- window.TopolPlugin.load(e);
87
- },
88
- /** Toggle the preview mode */
89
- togglePreview: () => {
90
- window.TopolPlugin.togglePreview();
91
- },
92
- /** Toggle between desktop and mobile preview sizes */
93
- togglePreviewSize: () => {
94
- window.TopolPlugin.togglePreviewSize();
95
- },
96
- /** Select a file from the custom file manager */
97
- chooseFile: (e) => {
98
- window.TopolPlugin.chooseFile(e);
99
- },
100
- /** Undo the last action */
101
- undo: () => {
102
- window.TopolPlugin.undo();
103
- },
104
- /** Redo the last undone action */
105
- redo: () => {
106
- window.TopolPlugin.redo();
107
- },
108
- /** Destroy the editor instance and clean up resources */
109
- destroy: () => {
110
- window.TopolPlugin.destroy();
111
- },
112
- /** Update the list of saved/reusable blocks */
113
- setSavedBlocks: (e) => {
114
- window.TopolPlugin.setSavedBlocks(e);
115
- },
116
- /** Set custom HTML for the preview */
117
- setPreviewHTML: (e) => {
118
- window.TopolPlugin.setPreviewHTML(e);
119
- },
120
- /** Display a notification in the editor */
121
- createNotification: (e) => {
122
- window.TopolPlugin.createNotification(e);
123
- },
124
- /** Set the list of active collaboration members */
125
- setActiveMembers: (e) => {
126
- window.TopolPlugin.setActiveMembers(e);
127
- },
128
- /** Switch to mobile view */
129
- changeEmailToMobile: () => {
130
- window.TopolPlugin.changeEmailToMobile();
131
- },
132
- /** Switch to desktop view */
133
- changeEmailToDesktop: () => {
134
- window.TopolPlugin.changeEmailToDesktop();
135
- },
136
- /** Toggle visibility of hidden blocks and structures */
137
- toggleBlocksAndStructuresVisibility: () => {
138
- window.TopolPlugin.toggleBlocksAndStructuresVisibility();
139
- },
140
- /** Update the content of a custom block */
141
- updateCustomBlockContent: (e) => {
142
- window.TopolPlugin.updateCustomBlockContent(e);
143
- },
144
- /** Refresh comments/conversations */
145
- refreshComments: (e) => {
146
- window.TopolPlugin.refreshComments(e);
147
- },
148
- /** Refresh synced rows */
149
- refreshSyncedRows: () => {
150
- window.TopolPlugin.refreshSyncedRows();
151
- },
152
- /** Open the premade templates selection modal */
153
- openPremadeTemplatesSelection: () => {
154
- window.TopolPlugin.openPremadeTemplatesSelection();
155
- },
156
- /** Update the API authorization header */
157
- updateApiAuthorizationHeader: (e) => {
158
- window.TopolPlugin.updateApiAuthorizationHeader(e);
159
- },
160
- /** Set the template name/title */
161
- setTemplateName: (e) => {
162
- window.TopolPlugin.setTemplateName(e);
163
- },
164
- /** Toggle the AI chat feature */
165
- toggleChatAI: () => {
166
- window.TopolPlugin.toggleChatAI();
167
- },
168
- /** Toggle the autosaves feature */
169
- toggleAutosaves: () => {
170
- window.TopolPlugin.toggleAutosaves();
171
- },
172
- /** Toggle the comments panel */
173
- toggleComments: () => {
174
- window.TopolPlugin.toggleComments();
175
- },
176
- /** Create a new language variant */
177
- createLanguage: (e) => {
178
- window.TopolPlugin.createLanguage(e);
179
- },
180
- /** Set the primary language */
181
- setPrimaryLanguage: (e) => {
182
- window.TopolPlugin.setPrimaryLanguage(e);
183
- },
184
- /** Delete a language variant */
185
- deleteLanguage: (e) => {
186
- window.TopolPlugin.deleteLanguage(e);
187
- },
188
- /** Select/switch to a language */
189
- selectLanguage: (e) => {
190
- window.TopolPlugin.selectLanguage(e);
191
131
  }
192
- }, h = "https://v1.page-assets.topol.io/topol-lpe.js", E = {
132
+ }, C = "https://v1.page-assets.topol.io/topol-lpe.js";
133
+ function R() {
134
+ return typeof window < "u" && typeof window.LandingPageEditor == "function";
135
+ }
136
+ const j = {
193
137
  /**
194
138
  * Inits Landing Page Editor.
195
139
  *
@@ -197,20 +141,17 @@ const m = {
197
141
  * @param pluginOptions - Plugin options (reserved for future staging/dev URL support)
198
142
  * @returns Promise that resolves with the editor instance
199
143
  */
200
- init: (e, n) => new Promise((o, i) => {
201
- d(h, (l) => {
202
- if (l !== null) {
203
- i(l);
204
- return;
205
- }
206
- const t = window.LandingPageEditor(e);
207
- o(t);
208
- });
209
- })
210
- }, v = m;
144
+ init: async (e, o) => {
145
+ var a;
146
+ if (await U(C, R), !R())
147
+ throw new Error("[@topol.io/editor] topol-lpe.js loaded but window.LandingPageEditor is not defined.");
148
+ const { onClose: t, ...r } = e, n = window.LandingPageEditor(r), i = ((a = n.destroy) == null ? void 0 : a.bind(n)) ?? (() => n.close());
149
+ return n.destroy = () => i(), n;
150
+ }
151
+ }, D = N;
211
152
  export {
212
- m as EmailEditor,
213
- E as LandingPageEditor,
214
- v as TopolPlugin,
215
- v as default
153
+ N as EmailEditor,
154
+ j as LandingPageEditor,
155
+ D as TopolPlugin,
156
+ D as default
216
157
  };
@@ -0,0 +1 @@
1
+ (function(a,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(a=typeof globalThis<"u"?globalThis:a||self,u(a.TopolPlugin={}))})(this,function(a){"use strict";function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var I=function(o,t,n){var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("script");typeof t=="function"&&(n=t,t={}),t=t||{},n=n||function(){},i.type=t.type||"text/javascript",i.charset=t.charset||"utf8",i.async="async"in t?!!t.async:!0,i.src=o,t.attrs&&_(i,t.attrs),t.text&&(i.text=""+t.text);var d="onload"in i?g:S;d(i,n),i.onload||g(i,n),r.appendChild(i)};function _(e,o){for(var t in o)e.setAttribute(t,o[t])}function g(e,o){e.onload=function(){this.onerror=this.onload=null,o(null,e)},e.onerror=function(){this.onerror=this.onload=null,o(new Error("Failed to load "+this.src),e)}}function S(e,o){e.onreadystatechange=function(){this.readyState!="complete"&&this.readyState!="loaded"||(this.onreadystatechange=null,o(null,e))}}const A=u(I),h=new Map;function p(e,o){if(o())return Promise.resolve();const t=h.get(e);if(t)return t;const n=new Promise((r,i)=>{const d=typeof document<"u"?y(e):null;if(d){const c=()=>{f(),r()},l=()=>{f(),d.remove(),i(new Error(`Failed to load script: ${e}`))},f=()=>{d.removeEventListener("load",c),d.removeEventListener("error",l)};d.addEventListener("load",c),d.addEventListener("error",l);return}A(e,c=>{var l;c!==null?((l=y(e))==null||l.remove(),i(c)):r()})}).finally(()=>{h.delete(e)});return h.set(e,n),n}function y(e){const o=document.getElementsByTagName("script");for(let t=0;t<o.length;t++)if(o[t].src===new URL(e,document.baseURI).href)return o[t];return null}const m="https://v4.email-assets.topol.io/loader/build.js",w={production:m,dev:m,staging:m},O="https://d10h8ga60f7b91.cloudfront.net/preview-app-{stage}/loader/build.js";class E extends Error{}let s,v=Promise.resolve();function N(e){if((e==null?void 0:e.loaderUrl)!==void 0){if(!e.loaderUrl.trim())throw new Error("[@topol.io/editor] loaderUrl must not be empty.");return e.loaderUrl}const o=(e==null?void 0:e.stage)??"production",n=typeof o=="number"||/^\d+$/.test(o)?O.replace("{stage}",String(o)):w[o];if(!n)throw new Error(`[@topol.io/editor] Unsupported stage "${o}". Use a supported stage or loaderUrl.`);return n}function j(e,o){const t=v.then(async()=>{try{return await R(e)}catch(n){if(n instanceof E||o===void 0)throw n;const r=await R(o);return s==null||s.urls.add(new URL(e,document.baseURI).href),r}});return v=t.catch(()=>{}),t}async function R(e){const o=new URL(e,document.baseURI).href;if(s){if(s.urls.has(o))return s.factory;throw new E("[@topol.io/editor] Editor v4 supports one loader URL per page. Reload the page to switch environments.")}const t=o===new URL(w.production,document.baseURI).href&&typeof window.TopolEmailEditor=="function";if(!t&&(typeof window.TopolEmailEditor=="function"||Array.from(document.scripts).some(r=>r.src===o)))throw new E("[@topol.io/editor] Cannot initialize from a host-provided loader with unknown lifecycle. Remove the script, reload the page, and let EmailEditor.init load the requested URL.");if(await p(e,()=>t),typeof window.TopolEmailEditor!="function"){for(const r of Array.from(document.scripts))r.src===o&&r.remove();throw new Error("[@topol.io/editor] The loader did not define window.TopolEmailEditor. Use an editor v4 loader.")}const n=window.TopolEmailEditor;return s={urls:new Set([o]),factory:n},n}const U={async init(e,o){var P,b;if(typeof window>"u"||typeof document>"u")throw new Error("[@topol.io/editor] EmailEditor.init requires a browser. Call it after mounting.");if(!((P=e==null?void 0:e.config)!=null&&P.authorize))throw new Error("[@topol.io/editor] Editor v4 requires { config: { authorize, ... }, onSave, ... }. See docs/MIGRATION-editor-v4.md.");const t=e.config.authorize.userId;if(typeof t=="string"?!/^[A-Za-z0-9_-]+$/.test(t):!Number.isInteger(t)||t<0)throw new Error("[@topol.io/editor] authorize.userId must be a URL-safe string or a non-negative integer.");if((b=e.config.cloud)!=null&&b.enabled&&typeof e.getNonce!="function")throw new Error("[@topol.io/editor] cloud.enabled requires nonce authentication: pass a top-level getNonce callback returning Promise<string>.");const n=N(o),r=(o==null?void 0:o.loaderUrl)===void 0&&n!==w.production?w.production:void 0,i=await j(n,r),{onClose:d,onError:c,...l}=e,f=i(l);let M;return Object.assign(f,{destroy:()=>M??(M=Promise.resolve().then(()=>f.close()))})}},C="https://v1.page-assets.topol.io/topol-lpe.js";function L(){return typeof window<"u"&&typeof window.LandingPageEditor=="function"}const D={init:async(e,o)=>{var d;if(await p(C,L),!L())throw new Error("[@topol.io/editor] topol-lpe.js loaded but window.LandingPageEditor is not defined.");const{onClose:t,...n}=e,r=window.LandingPageEditor(n),i=((d=r.destroy)==null?void 0:d.bind(r))??(()=>r.close());return r.destroy=()=>i(),r}},T=U;a.EmailEditor=U,a.LandingPageEditor=D,a.TopolPlugin=T,a.default=T,Object.defineProperties(a,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});