@useinsider/guido 3.24.0-beta.b9ec78b → 3.24.0-beta.bf47c23

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 (24) hide show
  1. package/dist/composables/useActionsApi.js +2 -2
  2. package/dist/composables/useEditorTrackingIds.js +49 -0
  3. package/dist/config/migrator/recommendation/inferLegacyConfig.js +133 -0
  4. package/dist/config/migrator/recommendationMigrator.js +78 -64
  5. package/dist/config/migrator/unsubscribeMigrator.js +98 -94
  6. package/dist/extensions/Blocks/Recommendation/controls/main/index.js +10 -8
  7. package/dist/extensions/Blocks/Recommendation/store/recommendation.js +28 -24
  8. package/dist/extensions/Blocks/Recommendation/utils/nodeConfigWriter.js +23 -22
  9. package/dist/extensions/Blocks/Unsubscribe/block.js +96 -104
  10. package/dist/extensions/Blocks/Unsubscribe/utils/constants.js +3 -4
  11. package/dist/package.json.js +2 -2
  12. package/dist/services/templateLibraryApi.js +39 -36
  13. package/dist/src/composables/useEditorTrackingIds.d.ts +7 -0
  14. package/dist/src/config/migrator/recommendation/inferLegacyConfig.d.ts +6 -0
  15. package/dist/src/config/migrator/recommendation/parseLegacyConfig.d.ts +1 -1
  16. package/dist/src/config/migrator/recommendationMigrator.d.ts +1 -5
  17. package/dist/src/extensions/Blocks/Recommendation/store/recommendation.d.ts +2 -0
  18. package/dist/src/extensions/Blocks/Unsubscribe/utils/constants.d.ts +0 -1
  19. package/dist/src/utils/linkTrackingIds.d.ts +19 -0
  20. package/dist/utils/linkTrackingIds.js +82 -48
  21. package/dist/utils/templatePreparation.js +30 -33
  22. package/package.json +1 -1
  23. package/dist/extensions/Blocks/Unsubscribe/utils/swapMergeTagInHref.js +0 -5
  24. package/dist/src/extensions/Blocks/Unsubscribe/utils/swapMergeTagInHref.d.ts +0 -1
@@ -111,8 +111,8 @@ const H = 1e4, T = 3e4, m = (n, l, A) => new Promise((C, p) => {
111
111
  }),
112
112
  updateHtmlAndCss: (t, e) => {
113
113
  const { actionsApi: i } = r();
114
- return m("updateHtmlAndCss", H, (a) => {
115
- i.updateHtmlAndCss(t, e, () => a());
114
+ return m("updateHtmlAndCss", H, (a, o) => {
115
+ i.updateHtmlAndCss(t, e, () => a(), o);
116
116
  });
117
117
  },
118
118
  editorSave: () => m(
@@ -0,0 +1,49 @@
1
+ import { TRACK_ID_ATTRIBUTE as u, writeAnchorTrackIds as I, TRACK_SEQ_ATTRIBUTE as f, planTrackingIds as h, parseTrackSeq as w, readAnchorTrackIds as k } from "../utils/linkTrackingIds.js";
2
+ import { getEditorApi as A } from "../utils/stripoEditorApi.js";
3
+ import { ModificationDescription as x } from "../node_modules/@stripoinc/ui-editor-extensions/dist/esm/index.js";
4
+ function T(t, r = []) {
5
+ const o = t.getType();
6
+ if (o === "comment") {
7
+ const e = t.getTextContent() ?? "", i = k(e);
8
+ return i.length && r.push({ kind: "comment", node: t, text: e, rawIds: i }), r;
9
+ }
10
+ if (o === "element") {
11
+ const e = t;
12
+ e.getTagName().toLowerCase() === "a" && r.push({ kind: "element", node: e, rawIds: [e.getAttribute(u) ?? ""] });
13
+ }
14
+ return t.childNodes().forEach((e) => T(e, r)), r;
15
+ }
16
+ function y(t, r) {
17
+ if (!t)
18
+ throw new Error("The editor exposes no editorCopilotApi.");
19
+ const o = t.getDocumentRootHtmlNode(), e = o.querySelector("body");
20
+ if (!e)
21
+ throw new Error("The editor document has no <body> to record tracking ids on.");
22
+ const i = T(o), s = h(
23
+ i.flatMap((d) => d.rawIds),
24
+ w(e.getAttribute(f)),
25
+ r
26
+ );
27
+ return { api: t, seqHost: e, hosts: i, plan: s };
28
+ }
29
+ const H = () => ({ writeTrackingIds: (r) => {
30
+ const { editorCopilotApi: o } = A();
31
+ let e;
32
+ try {
33
+ e = y(o, r);
34
+ } catch (n) {
35
+ return console.warn("Tracking ids skipped for this save:", n), { changed: !1, nextSeq: r };
36
+ }
37
+ const { api: i, seqHost: s, hosts: d, plan: c } = e;
38
+ if (!c.changed)
39
+ return { changed: !1, nextSeq: c.nextSeq };
40
+ const a = i.getTemplateModifier();
41
+ let l = 0;
42
+ return d.forEach((n) => {
43
+ const m = n.rawIds.map((p, g) => c.reassigned[l + g] ? c.ids[l + g] : null);
44
+ l += n.rawIds.length, !m.every((p) => p === null) && (n.kind === "element" ? a.modifyHtml(n.node).setAttribute(u, String(m[0])) : a.modifyHtml(n.node).replaceWith(`<!--${I(n.text, m)}-->`));
45
+ }), a.modifyHtml(s).setAttribute(f, String(c.nextSeq)), a.apply(new x("Updated Insider tracking IDs").asHidden()), { changed: !0, nextSeq: c.nextSeq };
46
+ } });
47
+ export {
48
+ H as useEditorTrackingIds
49
+ };
@@ -0,0 +1,133 @@
1
+ import { MAX_PRODUCTS_PER_ROW as _ } from "../../../extensions/Blocks/Recommendation/constants/layout.js";
2
+ const T = "td.product-card", x = '[class*="ext-product-"]', d = ".ext-ins-attr p[product-attr]", y = ".ext-ins-attr", S = ["font-family", "font-size", "font-weight", "font-style"], a = [
3
+ ["p_image", ".ext-product-image"],
4
+ ["p_name", ".ext-product-name"],
5
+ ["p_price", ".ext-product-price"],
6
+ ["p_original_price", ".ext-product-original-price"],
7
+ ["p_omnibus_price", ".ext-product-omnibus-price", !0],
8
+ ["p_omnibus_discount", ".ext-product-omnibus-discount", !0],
9
+ ["p_button", ".ext-product-button"]
10
+ ], l = a.map(([, t]) => t).join(", ");
11
+ function s(t, e) {
12
+ const n = new RegExp(`(?:^|;)\\s*${e}\\s*:\\s*([^;]+)`, "i"), r = ((t == null ? void 0 : t.getAttribute("style")) ?? "").match(n);
13
+ return (r == null ? void 0 : r[1].trim()) || void 0;
14
+ }
15
+ function p(t) {
16
+ return /^none\b/.test(s(t, "display") ?? "");
17
+ }
18
+ function h(t) {
19
+ return p(t) || p(t.closest("tr"));
20
+ }
21
+ function f(t) {
22
+ const e = {};
23
+ return S.forEach((n) => {
24
+ const r = s(t, n);
25
+ r && (e[n] = r);
26
+ }), Object.keys(e).length > 0 ? e : void 0;
27
+ }
28
+ function g(t) {
29
+ return Object.keys(t).length > 0 ? t : void 0;
30
+ }
31
+ function m(t) {
32
+ const e = t.querySelector("p") ?? t, n = f(e), r = s(e, "color"), i = t.getAttribute("align") ?? s(e, "text-align"), o = s(e, "line-height");
33
+ return g({
34
+ ...n ? { textStyle: n } : {},
35
+ ...r ? { textColor: { color: r } } : {},
36
+ ...i ? { textAlign: { align: i } } : {},
37
+ ...o ? { textLineSpacing: { lineSpacing: o } } : {}
38
+ });
39
+ }
40
+ function A(t) {
41
+ var u;
42
+ const e = t.querySelector("a") ?? t, n = (u = e.textContent) == null ? void 0 : u.trim(), r = s(e, "background-color") ?? s(e, "background"), i = s(e, "color"), o = f(e), c = t.getAttribute("align");
43
+ return g({
44
+ ...n ? { buttonText: { text: n } } : {},
45
+ ...r ? { buttonColor: { color: r } } : {},
46
+ ...i ? { textButtonColor: { color: i } } : {},
47
+ ...o ? { buttonStyle: o } : {},
48
+ ...c ? { buttonAlign: { align: c } } : {}
49
+ });
50
+ }
51
+ function C(t) {
52
+ const e = t.querySelector("img"), n = Number(e == null ? void 0 : e.getAttribute("width")), r = Number(e == null ? void 0 : e.getAttribute("height")), i = { ...n > 0 ? { width: n } : {}, ...r > 0 ? { height: r } : {} };
53
+ return Object.keys(i).length > 0 ? { imageSize: i } : void 0;
54
+ }
55
+ function R(t, e) {
56
+ switch (t) {
57
+ case "p_image":
58
+ return C(e);
59
+ case "p_button":
60
+ return A(e);
61
+ default:
62
+ return m(e);
63
+ }
64
+ }
65
+ function L(t, e) {
66
+ const n = Array.from(t.querySelectorAll(`[class*="show-recommendation-${e}-"]`));
67
+ return n.length > 0 ? n : Array.from(t.querySelectorAll(T));
68
+ }
69
+ function w(t, e) {
70
+ const n = (o) => e.filter((c) => o.contains(c)).length;
71
+ let r = e[0].parentElement;
72
+ for (; r && r !== t && n(r) < 2; )
73
+ r = r.parentElement;
74
+ if (!r || r === t)
75
+ return e.length === 1 ? 1 : void 0;
76
+ const i = r.tagName === "TBODY" || r.tagName === "TABLE" ? 1 : n(r);
77
+ return Math.min(i, _);
78
+ }
79
+ function v(t) {
80
+ const e = Array.from(t.querySelectorAll(x)).filter((n) => !n.matches(l) && !n.querySelector(l)).flatMap((n) => Array.from(n.classList).filter((r) => r.startsWith("ext-product-")));
81
+ return [...new Set(e)];
82
+ }
83
+ function O(t, e, n) {
84
+ const r = t.closest(y) ?? t, i = m(r);
85
+ return {
86
+ variable: `p_attribute_${e}`,
87
+ variableType: "p_attribute",
88
+ value: t.getAttribute("product-attr") ?? "",
89
+ positionIdx: n,
90
+ hidden: h(r),
91
+ ...i ? { theme: i } : {}
92
+ };
93
+ }
94
+ function N(t) {
95
+ const e = /* @__PURE__ */ new Set(), n = [];
96
+ let r = 0;
97
+ t.querySelectorAll(`${l}, ${d}`).forEach((o) => {
98
+ if (o.matches(d)) {
99
+ n.push(O(o, r, n.length)), r += 1;
100
+ return;
101
+ }
102
+ const c = a.find(
103
+ ([b, E]) => !e.has(b) && o.matches(E)
104
+ );
105
+ if (!c)
106
+ return;
107
+ const u = R(c[0], o);
108
+ e.add(c[0]), n.push({
109
+ variable: c[0],
110
+ positionIdx: n.length,
111
+ hidden: h(o),
112
+ ...u ? { theme: u } : {}
113
+ });
114
+ });
115
+ const i = a.filter(([o, , c]) => !c && !e.has(o)).map(([o]) => ({ variable: o, hidden: !0 }));
116
+ return [...n, ...i];
117
+ }
118
+ function q(t, e) {
119
+ const n = L(t, e);
120
+ if (n.length === 0)
121
+ return null;
122
+ const r = v(n[0]);
123
+ return r.length > 0 ? (console.warn(
124
+ `[RecommendationMigrator] Block id=${e} — legacy card cells the rebuild cannot map: ${r.join(", ")}`
125
+ ), null) : {
126
+ totalCount: n.length,
127
+ rowCount: w(t, n),
128
+ composition: { variables: N(n[0]) }
129
+ };
130
+ }
131
+ export {
132
+ q as inferLegacyConfig
133
+ };
@@ -1,59 +1,71 @@
1
1
  import { BlockId as b } from "../../enums/block.js";
2
- import { DEFAULT_NODE_CONFIG as C } from "../../extensions/Blocks/Recommendation/constants/defaultConfig.js";
3
- import { ATTR_RECOMMENDATION_TITLE as f } from "../../extensions/Blocks/Recommendation/constants/selectors.js";
4
- import { useTemplateStore as M } from "../../stores/template.js";
5
- import { mapComposition as x } from "./recommendation/compositionMapper.js";
6
- import { isPriceOnNextLine as R, extractCurrencyFromBlock as h, isOldPriceFirst as S, withRenderedTextTheme as w, extractTitleText as E, hasEmptyTitle as L, hasVisibleTitle as B, extractCardBgColor as P, isPartnerManagedBlock as A, extractRenderedBlockPadding as H } from "./recommendation/extractors.js";
7
- import { buildBlockHtml as N } from "./recommendation/htmlBuilder.js";
8
- import { parseRecommendationId as O, parseLegacyConfig as F } from "./recommendation/parseLegacyConfig.js";
9
- import { mapSettings as I } from "./recommendation/settingsMapper.js";
10
- import { mapBlockPadding as _ } from "./recommendation/themeMapper.js";
11
- const k = 'td[esd-dev-product-config][class*="ins-recommendation-v3-block-"]:not(.recommendation-block-v2), td.product-block[esd-handler-name*="EmailRecommendationV3"][esd-dev-product-config]:not(.recommendation-block-v2)';
12
- function $(c, e, m) {
13
- var l, g, p;
14
- const t = O(e);
2
+ import { DEFAULT_NODE_CONFIG as h } from "../../extensions/Blocks/Recommendation/constants/defaultConfig.js";
3
+ import { ATTR_RECOMMENDATION_TITLE as y } from "../../extensions/Blocks/Recommendation/constants/selectors.js";
4
+ import { useTemplateStore as x } from "../../stores/template.js";
5
+ import { mapComposition as S } from "./recommendation/compositionMapper.js";
6
+ import { isPriceOnNextLine as L, extractCurrencyFromBlock as A, isOldPriceFirst as B, withRenderedTextTheme as E, extractTitleText as w, hasEmptyTitle as O, hasVisibleTitle as N, extractCardBgColor as P, isPartnerManagedBlock as H, extractRenderedBlockPadding as I } from "./recommendation/extractors.js";
7
+ import { buildBlockHtml as _ } from "./recommendation/htmlBuilder.js";
8
+ import { inferLegacyConfig as F } from "./recommendation/inferLegacyConfig.js";
9
+ import { parseRecommendationId as $, parseLegacyConfig as k } from "./recommendation/parseLegacyConfig.js";
10
+ import { mapSettings as D } from "./recommendation/settingsMapper.js";
11
+ import { mapBlockPadding as G } from "./recommendation/themeMapper.js";
12
+ const T = ":not(.recommendation-block-v2):not([esd-ext-config])", U = `td[class*="ins-recommendation-v3-block-"]${T}, td.product-block[esd-handler-name*="EmailRecommendationV3"]${T}`, V = "esd-dev-product-config";
13
+ function q(o) {
14
+ return !!(o != null && o.strategy);
15
+ }
16
+ function K(o, e, c) {
17
+ var g, f, u;
18
+ const t = $(e);
15
19
  if (t === null)
16
20
  return console.warn(
17
21
  "[RecommendationMigrator] Skipping block — missing/invalid `ins-recommendation-v3-campaign-id`"
18
22
  ), !1;
19
- const r = F(e);
20
- if (!r)
23
+ const s = e.hasAttribute(V), m = c[String(t)];
24
+ if (!s && !q(m))
25
+ return console.warn(
26
+ `[RecommendationMigrator] Skipping block id=${t} — no \`esd-dev-product-config\` and no recommendationConfigs strategy to rebuild from`
27
+ ), !1;
28
+ const i = s ? k(e) : F(e, t);
29
+ if (!i)
21
30
  return console.warn(
22
- `[RecommendationMigrator] Aborting block id=${t} — \`esd-dev-product-config\` missing or unable to be parsed`
31
+ `[RecommendationMigrator] Aborting block id=${t} — \`esd-dev-product-config\` empty or unparsable, or the rendered markup could not be inferred`
23
32
  ), !1;
24
- const o = m[String(t)] ?? {}, n = {
25
- ...o,
26
- currencySettings: o.currencySettings ?? h(e),
27
- isPriceMovedToNextLine: o.isPriceMovedToNextLine ?? R(e)
28
- }, a = I(n, r, t), i = x(
29
- w((l = r.composition) == null ? void 0 : l.variables, e),
30
- { oldPriceFirst: S(e) }
31
- ), u = E(e);
32
- L(e) ? i.visibility[f] = !1 : i.titleVariable || (i.visibility[f] = B(e));
33
- const y = P(e), T = {
34
- ...a,
33
+ s || console.info(
34
+ `[RecommendationMigrator] Block id=${t} has no \`esd-dev-product-config\` — rebuilt from its rendered markup`
35
+ );
36
+ const r = m ?? {}, n = {
37
+ ...r,
38
+ currencySettings: r.currencySettings ?? A(e),
39
+ isPriceMovedToNextLine: r.isPriceMovedToNextLine ?? L(e)
40
+ }, d = D(n, i, t), a = S(
41
+ E((g = i.composition) == null ? void 0 : g.variables, e),
42
+ { oldPriceFirst: B(e) }
43
+ ), C = w(e);
44
+ O(e) ? a.visibility[y] = !1 : a.titleVariable || (a.visibility[y] = N(e));
45
+ const v = P(e), M = {
46
+ ...d,
35
47
  strategyId: "",
36
- composition: i.composition,
37
- visibility: i.visibility,
38
- previousTitleHtml: C.previousTitleHtml,
39
- textTrimming: i.anyTextTrimming
40
- }, s = A(e), v = `
48
+ composition: a.composition,
49
+ visibility: a.visibility,
50
+ previousTitleHtml: h.previousTitleHtml,
51
+ textTrimming: a.anyTextTrimming
52
+ }, l = H(e), R = `
41
53
  <table>
42
54
  <tbody>
43
55
  <tr>
44
56
  <td class="esd-structure" align="left">
45
57
  <table width="100%" cellpadding="0" cellspacing="0">
46
58
  <tbody>
47
- <tr>${N({
48
- nodeConfig: T,
49
- composition: i,
50
- cardBg: y,
51
- titleText: u,
59
+ <tr>${_({
60
+ nodeConfig: M,
61
+ composition: a,
62
+ cardBg: v,
63
+ titleText: C,
52
64
  legacyId: e.getAttribute("id") ?? void 0,
53
65
  legacyBgColor: e.getAttribute("bgcolor") ?? void 0,
54
- preserveInnerHtml: s ? e.innerHTML : void 0,
55
- skipCompile: s,
56
- blockPadding: _(((p = (g = r.theme) == null ? void 0 : g.blockPadding) == null ? void 0 : p.desktop) ?? H(e))
66
+ preserveInnerHtml: l ? e.innerHTML : void 0,
67
+ skipCompile: l,
68
+ blockPadding: G(((u = (f = i.theme) == null ? void 0 : f.blockPadding) == null ? void 0 : u.desktop) ?? I(e))
57
69
  })}</tr>
58
70
  </tbody>
59
71
  </table>
@@ -61,40 +73,42 @@ function $(c, e, m) {
61
73
  </tr>
62
74
  </tbody>
63
75
  </table>
64
- `, d = c.parseFromString(v, "text/html").querySelector("td.esd-structure");
65
- return !d || !e.parentNode ? (console.warn(
76
+ `, p = o.parseFromString(R, "text/html").querySelector("td.esd-structure");
77
+ return !p || !e.parentNode ? (console.warn(
66
78
  `[RecommendationMigrator] Aborting block id=${t} — failed to construct new HTML element`
67
- ), !1) : (e.parentNode.replaceChild(d, e), !0);
79
+ ), !1) : (e.parentNode.replaceChild(p, e), !0);
68
80
  }
69
- function X(c, e = {}) {
70
- const m = new DOMParser();
81
+ function ne(o, e = {}) {
82
+ const c = new DOMParser();
71
83
  let t;
72
84
  try {
73
- t = m.parseFromString(c, "text/html");
74
- } catch (n) {
75
- return console.error("[RecommendationMigrator] Failed to parse template:", n), c;
85
+ t = c.parseFromString(o, "text/html");
86
+ } catch (r) {
87
+ return console.error("[RecommendationMigrator] Failed to parse template:", r), o;
76
88
  }
77
- const r = Array.from(t.querySelectorAll(k));
89
+ const s = Array.from(t.querySelectorAll(U)), m = s.filter((r) => {
90
+ var n;
91
+ return !((n = r.parentElement) != null && n.closest(".recommendation-block-v2")) && !s.some((d) => d !== r && d.contains(r));
92
+ });
93
+ let i = 0;
94
+ m.forEach((r) => {
95
+ try {
96
+ K(c, r, e) && (i += 1);
97
+ } catch (n) {
98
+ console.error("[RecommendationMigrator] Unexpected error migrating block:", n);
99
+ }
100
+ });
78
101
  try {
79
- M().$patch((a) => {
80
- a.migrations = {
81
- ...a.migrations,
82
- [b.Recommendation]: r.length
102
+ x().$patch((n) => {
103
+ n.migrations = {
104
+ ...n.migrations,
105
+ [b.Recommendation]: i
83
106
  };
84
107
  });
85
108
  } catch {
86
109
  }
87
- if (r.length === 0)
88
- return c;
89
- let o = 0;
90
- return r.forEach((n) => {
91
- try {
92
- $(m, n, e) && (o += 1);
93
- } catch (a) {
94
- console.error("[RecommendationMigrator] Unexpected error migrating block:", a);
95
- }
96
- }), o > 0 && console.info(`[RecommendationMigrator] Migrated ${o} legacy Recommendation block(s)`), t.documentElement.outerHTML;
110
+ return i === 0 ? o : (console.info(`[RecommendationMigrator] Migrated ${i} legacy Recommendation block(s)`), t.documentElement.outerHTML);
97
111
  }
98
112
  export {
99
- X as migrateRecommendation
113
+ ne as migrateRecommendation
100
114
  };
@@ -1,142 +1,146 @@
1
- var $ = Object.defineProperty;
2
- var _ = (f, e, t) => e in f ? $(f, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : f[e] = t;
3
- var y = (f, e, t) => _(f, typeof e != "symbol" ? e + "" : e, t);
4
- import { MERGE_TAGS as l, PAGE_TYPES as p } from "../../enums/unsubscribe.js";
5
- import { UNSUBSCRIBE_BLOCK_SELECTOR as A, DATA_ATTRIBUTES as T, UNSUBSCRIBE_MERGE_TAG_REGEX as E } from "../../extensions/Blocks/Unsubscribe/utils/constants.js";
6
- import { swapMergeTagInHref as B } from "../../extensions/Blocks/Unsubscribe/utils/swapMergeTagInHref.js";
7
- import { useUnsubscribeStore as N } from "../../stores/unsubscribe.js";
8
- import { escapeHtml as h } from "../../utils/htmlEscape.js";
9
- const S = "unsubscribe", R = "You can ", M = " from our emails, if you need to.", C = "{-{-UNSUBSCRIBE-LINK-}-}";
10
- class P {
1
+ var x = Object.defineProperty;
2
+ var B = (c, e, r) => e in c ? x(c, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : c[e] = r;
3
+ var A = (c, e, r) => B(c, typeof e != "symbol" ? e + "" : e, r);
4
+ import { MERGE_TAGS as f, PAGE_TYPES as p } from "../../enums/unsubscribe.js";
5
+ import { UNSUBSCRIBE_BLOCK_SELECTOR as h, DATA_ATTRIBUTES as k } from "../../extensions/Blocks/Unsubscribe/utils/constants.js";
6
+ import { useUnsubscribeStore as C } from "../../stores/unsubscribe.js";
7
+ class $ {
11
8
  constructor() {
12
- y(this, "parser");
9
+ A(this, "parser");
13
10
  this.parser = new DOMParser();
14
11
  }
15
12
  async migrate(e) {
16
13
  try {
17
- const t = this.parser.parseFromString(e, "text/html"), r = t.querySelectorAll("td.unsubscribe-block");
18
- if (r.length) {
19
- const s = N();
20
- await s.fetchTemplates(), this.migrateLegacyBlocks(r, s, this.collectBlockTags(t));
14
+ const r = this.parser.parseFromString(e, "text/html"), t = r.querySelectorAll("td.unsubscribe-block");
15
+ if (t.length) {
16
+ const s = C();
17
+ await s.fetchTemplates(), this.migrateLegacyBlocks(t, s);
21
18
  }
22
- const n = this.repairUnsubscribeLinks(t);
23
- return !r.length && !n ? e : t.documentElement.outerHTML;
24
- } catch (t) {
25
- return console.error("UnsubscribeMigrator failed:", t), e;
19
+ const n = this.repairUnsubscribeLinks(r);
20
+ return !t.length && !n ? e : r.documentElement.outerHTML;
21
+ } catch (r) {
22
+ return console.error("UnsubscribeMigrator failed:", r), e;
26
23
  }
27
24
  }
28
- migrateLegacyBlocks(e, t, r) {
29
- e.forEach((n) => {
30
- const s = n.getAttribute("id"), i = this.extractPaddingClass(n), c = n.getAttribute("bgcolor") || "", a = this.extractUnsubscribeContent(n, r), b = this.getCollectionTypeFromMergeTag(a.linkHref), u = t.getSelectedUnsubscribePagesByCollection(b);
25
+ migrateLegacyBlocks(e, r) {
26
+ e.forEach((t) => {
27
+ const n = t.getAttribute("id"), s = this.extractPaddingClass(t), l = t.getAttribute("bgcolor") || "", a = this.extractUnsubscribeContent(t), o = this.getCollectionTypeFromMergeTag(a.linkHref), b = r.getSelectedUnsubscribePagesByCollection(o);
31
28
  console.debug("[UnsubscribeMigrator]", {
32
29
  mergeTag: a.linkHref,
33
- collectionType: b,
34
- pageIds: u,
35
- paddingClass: i,
36
- bgColor: c
30
+ collectionType: o,
31
+ pageIds: b,
32
+ paddingClass: s,
33
+ bgColor: l
37
34
  });
38
- const o = this.buildUnsubscribeBlock(
35
+ const u = this.buildUnsubscribeBlock(
39
36
  a,
37
+ o,
40
38
  b,
41
- u,
42
- i,
43
- c
44
- ), g = this.parser.parseFromString(
45
- `<table id="tempDoc"><tbody><tr>${o}</tr></tbody></table>`,
39
+ s,
40
+ l
41
+ ), i = this.parser.parseFromString(
42
+ `<table id="tempDoc"><tbody><tr>${u}</tr></tbody></table>`,
46
43
  "text/html"
47
- ).querySelector(A);
48
- g && n.parentNode && (g.setAttribute("id", s || ""), n.parentNode.replaceChild(g, n));
44
+ ).querySelector(h);
45
+ i && t.parentNode && (i.setAttribute("id", n || ""), t.parentNode.replaceChild(i, t));
49
46
  });
50
47
  }
51
- collectBlockTags(e) {
52
- const t = e.querySelectorAll(`td.unsubscribe-block, ${A}`), r = /* @__PURE__ */ new Set();
53
- return t.forEach((n) => {
54
- var a, b, u;
55
- const s = Number(n.getAttribute(T.PAGE_TYPE)), i = l[s], c = (u = (b = (a = this.findLinkCandidates(n).primary) == null ? void 0 : a.getAttribute("href")) == null ? void 0 : b.match(E)) == null ? void 0 : u[0];
56
- i ? r.add(i) : c && r.add(l[this.getCollectionTypeFromMergeTag(c)]);
57
- }), r;
58
- }
59
48
  // Re-derives the typed merge tag from data-unsubscribe-page-type for any v2
60
49
  // block whose anchor href is missing or the legacy default. Returns true when
61
50
  // at least one href was rewritten. Typed tags and custom URLs are left intact.
62
51
  repairUnsubscribeLinks(e) {
63
- const t = e.querySelectorAll(`${A}[${T.PAGE_TYPE}]`);
64
- let r = !1;
65
- return t.forEach((n) => {
52
+ const r = e.querySelectorAll(`${h}[${k.PAGE_TYPE}]`);
53
+ let t = !1;
54
+ return r.forEach((n) => {
66
55
  const s = n.querySelector('a[data-unsubscribe-link="true"], a.unsubscribe-link');
67
56
  if (!s)
68
57
  return;
69
- const i = s.getAttribute("href") || "";
70
- if (i && i !== l.default)
58
+ const l = s.getAttribute("href") || "";
59
+ if (l && l !== f.default)
71
60
  return;
72
- const c = Number(n.getAttribute(T.PAGE_TYPE)), a = l[c];
73
- a && (s.setAttribute("href", a), r = !0);
74
- }), r;
61
+ const a = Number(n.getAttribute(k.PAGE_TYPE)), o = f[a];
62
+ o && (s.setAttribute("href", o), t = !0);
63
+ }), t;
75
64
  }
76
65
  extractPaddingClass(e) {
77
- const r = (e.getAttribute("class") || "").match(/\bes-p\d+\b/);
78
- return r ? r[0] : "";
79
- }
80
- hasVisibleContent(e) {
81
- var t;
82
- return !!((t = e.textContent) != null && t.trim() || e.querySelector("img"));
66
+ const t = (e.getAttribute("class") || "").match(/\bes-p\d+\b/);
67
+ return t ? t[0] : "";
83
68
  }
84
- findLinkCandidates(e) {
85
- const t = Array.from(/* @__PURE__ */ new Set([
86
- ...Array.from(e.querySelectorAll("a.unsubscribe-link")),
87
- ...Array.from(e.querySelectorAll('a[href*="unsubscribe"]'))
88
- ])), r = (i) => E.test(i.getAttribute("href") || ""), n = (i) => this.hasVisibleContent(i), s = t.find((i) => n(i) && r(i)) ?? t.find((i) => n(i) && i.classList.contains("unsubscribe-link")) ?? t.find(r) ?? t.find(n) ?? t[0];
89
- return { candidates: t, primary: s };
90
- }
91
- extractUnsubscribeContent(e, t) {
92
- const r = e.cloneNode(!0), { candidates: n, primary: s } = this.findLinkCandidates(r), i = (s == null ? void 0 : s.closest("p")) ?? null, c = i || r.querySelector("p"), a = {
93
- footerHtml: "",
94
- linkText: S,
95
- linkHref: l.default,
96
- linkStyle: "",
97
- align: "center",
98
- paragraphStyle: ""
69
+ extractUnsubscribeContent(e) {
70
+ var d;
71
+ const r = e.querySelector("a.unsubscribe-link") || e.querySelector('a[href*="unsubscribe"]'), t = (r == null ? void 0 : r.closest("p")) || e.querySelector("p");
72
+ if (!t)
73
+ return {
74
+ textBefore: "You can ",
75
+ linkText: "unsubscribe",
76
+ linkHref: "{{ins-unsubscribe-link}}",
77
+ linkStyle: "",
78
+ textAfter: " from our emails, if you need to.",
79
+ isBold: !1,
80
+ isItalic: !1,
81
+ align: "center",
82
+ paragraphStyle: ""
83
+ };
84
+ const n = e.getAttribute("align") || t.getAttribute("align") || "center", s = t.getAttribute("style") || "";
85
+ if (!r)
86
+ return {
87
+ textBefore: "You can ",
88
+ linkText: "unsubscribe",
89
+ linkHref: "{{ins-unsubscribe-link}}",
90
+ linkStyle: "",
91
+ textAfter: " from our emails, if you need to.",
92
+ isBold: !1,
93
+ isItalic: !1,
94
+ align: n,
95
+ paragraphStyle: s
96
+ };
97
+ const l = ((d = r.textContent) == null ? void 0 : d.trim()) || "unsubscribe", a = r.getAttribute("href") || "{{ins-unsubscribe-link}}", o = r.getAttribute("style") || "", b = t.textContent || "", u = b.indexOf(l), g = u >= 0 ? b.substring(0, u).trim() : "You can ", i = u >= 0 ? b.substring(u + l.length).trim() : " from our emails, if you need to.", m = !!t.querySelector("b, strong"), y = !!t.querySelector("i, em");
98
+ return {
99
+ textBefore: g,
100
+ linkText: l,
101
+ linkHref: this.normalizeUnsubscribeHref(a),
102
+ linkStyle: o,
103
+ textAfter: i,
104
+ isBold: m,
105
+ isItalic: y,
106
+ align: n,
107
+ paragraphStyle: s
99
108
  };
100
- if (!c || (a.align = e.getAttribute("align") || c.getAttribute("align") || "center", i || (a.paragraphStyle = c.getAttribute("style") || ""), !s))
101
- return a;
102
- if (a.linkText = this.hasVisibleContent(s) ? s.innerHTML.trim() : S, a.linkHref = this.normalizeUnsubscribeHref(s.getAttribute("href") || l.default), a.linkStyle = s.getAttribute("style") || "", i) {
103
- const b = this.getCollectionTypeFromMergeTag(a.linkHref), u = l[b];
104
- r.querySelectorAll("a[href]").forEach((o) => {
105
- var m;
106
- const d = o.getAttribute("href") || "", g = (m = d.match(E)) == null ? void 0 : m[0];
107
- g && o.setAttribute("href", B(d, t.has(g) ? g : u));
108
- }), n.filter((o) => o !== s && !this.hasVisibleContent(o)).forEach((o) => o.replaceWith(...Array.from(o.childNodes))), s.replaceWith(r.ownerDocument.createTextNode(C)), a.footerHtml = r.innerHTML.trim();
109
- }
110
- return a;
111
109
  }
112
- buildUnsubscribeBlock(e, t, r, n, s) {
113
- const i = e.linkStyle ? ` style="${h(e.linkStyle)}"` : "", a = Object.values(l).includes(e.linkHref) ? l[t] : e.linkHref, u = `<a ${`href="${h(a)}" class="unsubscribe-link" target="_blank" data-unsubscribe-link="true"`}${i}>${e.linkText}</a>`, o = e.paragraphStyle ? ` style="${h(e.paragraphStyle)}"` : "", d = e.footerHtml ? e.footerHtml.replace(C, () => u) : `<p path="1"${o}>${R}${u}${M}</p>`, g = e.align ? ` align="${e.align}"` : "", m = s ? ` bgcolor="${s}"` : "", U = r.length > 0 ? ` ${T.PAGE_LIST}="${r.join(",")}"` : "", L = ` ${T.PAGE_TYPE}="${t}"`, k = "esd-block-text unsubscribe-block-v2 esd-block-unsubscribe esd-unsubscribe-block esd-extension-block";
110
+ buildUnsubscribeBlock(e, r, t, n, s) {
111
+ const l = e.linkStyle ? ` style="${e.linkStyle}"` : "", u = `<a ${`href="${Object.values(f).includes(e.linkHref) ? f[r] : e.linkHref}" class="unsubscribe-link" target="_blank" data-unsubscribe-link="true"`}${l}>${e.linkText}</a>`, g = [];
112
+ e.textBefore && g.push(e.textBefore), g.push(u), e.textAfter && g.push(e.textAfter);
113
+ let i = g.join(" ");
114
+ e.isBold && e.isItalic ? i = `<strong path="1,0"><em path="1,0,0">${i}</em></strong>` : e.isBold ? i = `<strong path="1,0">${i}</strong>` : e.isItalic && (i = `<em path="1,0">${i}</em>`);
115
+ const m = e.align ? ` align="${e.align}"` : "", y = s ? ` bgcolor="${s}"` : "", d = e.paragraphStyle ? ` style="${e.paragraphStyle}"` : "", T = t.length > 0 ? ` ${k.PAGE_LIST}="${t.join(",")}"` : "", E = ` ${k.PAGE_TYPE}="${r}"`, S = "esd-block-text unsubscribe-block-v2 esd-block-unsubscribe esd-unsubscribe-block esd-extension-block";
114
116
  return `
115
117
  <td
116
118
  data-migration="true"
117
119
  esd-extension-block-id="unsubscribe-block"
118
- class="${n ? `${k} ${n}` : k}"
119
- ${g}${m}${L}${U}
120
+ class="${n ? `${S} ${n}` : S}"
121
+ ${m}${y}${E}${T}
120
122
  >
121
- ${d}
123
+ <p path="1"${d}>
124
+ ${i}
125
+ </p>
122
126
  </td>
123
127
  `;
124
128
  }
125
129
  getCollectionTypeFromMergeTag(e) {
126
- return e === l[p.SUBSCRIPTION_PREFERENCE_CENTER] ? p.SUBSCRIPTION_PREFERENCE_CENTER : e === l[p.GLOBAL_UNSUBSCRIBE] ? p.GLOBAL_UNSUBSCRIBE : p.GLOBAL_UNSUBSCRIBE;
130
+ return e === f[p.SUBSCRIPTION_PREFERENCE_CENTER] ? p.SUBSCRIPTION_PREFERENCE_CENTER : e === f[p.GLOBAL_UNSUBSCRIBE] ? p.GLOBAL_UNSUBSCRIBE : p.GLOBAL_UNSUBSCRIBE;
127
131
  }
128
132
  normalizeUnsubscribeHref(e) {
129
- if (Object.values(l).includes(e))
133
+ if (Object.values(f).includes(e))
130
134
  return e;
131
- const r = e.match(/{{ins-(?:global-)?(?:preferences-)?unsubscribe-link}}/);
132
- return r ? r[0] : e.includes("unsubscribe") || e.includes("unsub") ? (console.warn(
135
+ const t = e.match(/{{ins-(?:global-)?(?:preferences-)?unsubscribe-link}}/);
136
+ return t ? t[0] : e.includes("unsubscribe") || e.includes("unsub") ? (console.warn(
133
137
  `[UnsubscribeMigrator] Unrecognized unsubscribe href format: "${e}". Defaulting to {{ins-unsubscribe-link}}`
134
138
  ), "{{ins-unsubscribe-link}}") : e;
135
139
  }
136
140
  }
137
- async function q(f) {
138
- return new P().migrate(f);
141
+ async function M(c) {
142
+ return new $().migrate(c);
139
143
  }
140
144
  export {
141
- q as migrateUnsubscribe
145
+ M as migrateUnsubscribe
142
146
  };