@joryio/web-sdk 1.4.0-beta.7 → 1.4.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"joryio-editor.min.js","sources":["../node_modules/tslib/tslib.es6.js","../src/core/page-edits.ts","../src/core/sdk-host-files.ts","../src/core/editor-gate.ts","../src/editor/editor-strings.ts","../src/editor/editor-model.ts","../src/editor/editor-ui.ts","../src/editor/liquid-field.ts","../src/editor/visual-editor.ts","../src/editor/index.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\r\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nvar ownKeys = function(o) {\r\n ownKeys = Object.getOwnPropertyNames || function (o) {\r\n var ar = [];\r\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\r\n return ar;\r\n };\r\n return ownKeys(o);\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose, inner;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n if (async) inner = dispose;\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n var r, s = 0;\r\n function next() {\r\n while (r = env.stack.pop()) {\r\n try {\r\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\r\n if (r.dispose) {\r\n var result = r.dispose.call(r.value);\r\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n else s |= 1;\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\r\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\r\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\r\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\r\n });\r\n }\r\n return path;\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __esDecorate: __esDecorate,\r\n __runInitializers: __runInitializers,\r\n __propKey: __propKey,\r\n __setFunctionName: __setFunctionName,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,\r\n};\r\n","/**\n * Page edits on web (BACKLOG D444 Phase 4, docs/PLACEMENTS_WEBSITE_LAYER.md 2).\n *\n * A page-edit campaign changes elements of the site's own page, found by CSS\n * selector: replace a text, an image, a link, hide an element, or insert a\n * placement next to it. Nothing else - no HTML, no script, no free-form DOM.\n *\n * - Text is set with `textContent` (never parsed as HTML); image and link\n * addresses must be absolute http(s); a selector that could escape the\n * anti-flicker style rule is refused. The server checks the same and this\n * SDK checks again: an edit it does not trust is skipped, never half-applied.\n * - Site settings first (`GET /v1/in-app/site-settings?sdkKey=`, public,\n * the same for every visitor; asked once per SDK session and refreshed at\n * most every SITE_SETTINGS_SESSION_REFRESH_SECONDS, kept in sessionStorage\n * so the session's later page loads do not wait for it): page edits off\n * for this site, or no live page-edit campaign, = nothing is asked or\n * applied on this page view. Otherwise the per-visitor answer.\n * - Anti-flicker: only edited elements are hidden (opacity, so the layout\n * does not move), for at most PAGE_EDIT_ANTI_FLICKER_MS from the start of\n * the page, never the whole body: the ones edited on this page last time,\n * or - on a first view, when there are none - the site's list from the site\n * settings (selectors only).\n * - Static edits from the last answer for this page apply at once, as each\n * element appears (MutationObserver); personalized edits apply when the\n * answer arrives and are never stored.\n * - A route change undoes this page's edits and applies the next page's.\n * - Exposure: `in_app.displayed` once an edit of the experience landed on an\n * element; a control visitor reports `in_app.control_viewed` once one of\n * the control's selectors is on the page.\n * - Server-applied edits (D450): a store plugin may already have written the\n * edits that are the same for every visitor into the page's HTML. Its\n * marker - a JSON block `#joryio-server-page-edits` and\n * `data-joryio-applied=\"<campaignId>:<editId>\"` on each changed element -\n * says which. The SDK never applies those again (no double insert, no\n * flicker), counts them as landed for the exposure (once, with its own\n * answer's token), keeps them out of the anti-flicker rule, and undoes one\n * (from `data-joryio-orig` and the element's `<template data-joryio-orig>`)\n * when the definitive answer for this visitor no longer carries it -\n * paused, edited, the visitor suppressed or in a control, page edits\n * switched off - or on a route change to another page.\n */\nimport { bucketHash } from '../utils/bucket-hash';\nimport type { IdentityManager } from './identity';\nimport type { SessionManager } from './session';\nimport type { Logger } from '../utils/logger';\nimport type { InAppAuthProvider } from './inapp';\nimport type { PlacementConsent } from './placements';\nimport { sdkIdentityHeaders } from './config';\nimport { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';\n\nexport const PAGE_EDIT_OPERATIONS = ['replace_text', 'replace_image', 'replace_link', 'hide', 'insert_placement'] as const;\n/** `replace` (\"Instead of it\"): the element is hidden and the spot takes its place, right after it. */\nexport const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append', 'replace'] as const;\nexport const PAGE_EDITS_CAPABILITY = 'page_edits';\n/** The longest edited elements stay hidden while the SDK waits. Never the whole body. */\nexport const PAGE_EDIT_ANTI_FLICKER_MS = 300;\n\nconst MAX_SELECTOR_LENGTH = 500;\nconst MAX_TEXT_LENGTH = 2000;\nconst MAX_URL_LENGTH = 2048;\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\nconst STYLE_ID = 'joryio-page-edits-anti-flicker';\n/**\n * Both stores are per workspace: the names carry a hash of the SDK key (the\n * flags cache's scheme), so two workspaces on one origin never share edits\n * or anti-flicker selectors. The unscoped names of earlier builds are never\n * read; they are removed on the first load.\n */\nconst LEGACY_ANSWER_STORE = 'jry_page_edits';\nconst LEGACY_SELECTOR_STORE = 'jry_page_edit_selectors';\nexport const pageEditsStorageKeys = (sdkKey: string): { answers: string; selectors: string; site: string } => {\n const h = bucketHash(sdkKey).toString(36);\n return { answers: `jry_page_edits_${h}`, selectors: `jry_page_edit_selectors_${h}`, site: `jry_page_edit_site_${h}` };\n};\nconst MAX_REMEMBERED_PAGES = 50;\nconst DEFAULT_TTL_SECONDS = 300;\n/**\n * The site settings are asked once per SDK session and then at most every\n * this many seconds within it (sessionStorage, per workspace, tied to the\n * session id: a new session asks again). The server's `ttlSeconds` (60) is\n * the HTTP cache lifetime for browsers and the CDN and no longer shortens\n * this: on a multi-page store every full page load used to re-ask, and the\n * answer is the same for every visitor and changes only when a page-edit\n * campaign is launched or page edits are switched on or off. The cost, by\n * design: a newly launched page-edit campaign reaches a visitor already on\n * the site within this time. Pausing is not delayed - `/page-edits` checks\n * every campaign's liveness itself on every page.\n */\nexport const SITE_SETTINGS_SESSION_REFRESH_SECONDS = 600;\n/** At most this many selectors of the site list go into the style rule (the server sends at most 200). */\nconst MAX_SITE_SELECTORS = 200;\n\n/**\n * The marker a store plugin writes with the edits it applied in the HTML\n * (backend common/web-experience/server-page-edits.ts, the plugins' shared\n * core; pinned by server-page-edits-parity.spec.ts).\n */\nexport const SERVER_PAGE_EDITS_MARKER_ID = 'joryio-server-page-edits';\nexport const SERVER_APPLIED_ATTR = 'data-joryio-applied';\nexport const SERVER_ORIG_ATTR = 'data-joryio-orig';\nexport const SERVER_SPOT_ATTR = 'data-joryio-server-spot';\nconst SERVER_MARKER_VERSION = 1;\n\ninterface ServerEdit {\n experienceId: string;\n variantId: string | null;\n edit: PageEditWire;\n}\n\nconst sameEdit = (a: PageEditWire, b: PageEditWire): boolean =>\n a.id === b.id &&\n a.selector === b.selector &&\n a.operation === b.operation &&\n (a.value ?? null) === (b.value ?? null) &&\n (a.placementKey ?? null) === (b.placementKey ?? null) &&\n (a.position ?? null) === (b.position ?? null) &&\n !b.personalized;\n\nfunction serverMarkerElement(): HTMLScriptElement | null {\n const head = document.head;\n if (!head) return null;\n for (const c of Array.from(head.children)) {\n if (c.id === SERVER_PAGE_EDITS_MARKER_ID) {\n return c.tagName === 'SCRIPT' && (c.getAttribute('type') || '').trim().toLowerCase() === 'application/json' ? (c as HTMLScriptElement) : null;\n }\n }\n return null;\n}\n\n/** An address the undo may write back: absolute http(s) or relative (no scheme). Anything else is dropped. */\nfunction safeRestoredUrl(v: unknown): string | null {\n if (typeof v !== 'string' || v.length > MAX_URL_LENGTH) return null;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(v)) return null;\n const t = v.trim();\n if (/^https?:\\/\\//i.test(t)) return v;\n // A scheme is letters before a ':' that comes before any '/', '?' or '#'.\n return /^[a-z][a-z0-9+.-]*:/i.test(t) ? null : v;\n}\n\nconst safeRestoredSrcset = (v: unknown): string | null =>\n typeof v === 'string' && v.split(',').every((c) => !c.trim() || safeRestoredUrl(c.trim().split(/\\s+/)[0]) !== null) ? v : null;\n\nconst HIDE_DECLARATION = 'display:none !important';\n\n/** Hide one element (display:none !important); returns how to show it again as it was. */\nfunction hideElement(h: HTMLElement): () => void {\n const display = h.style.getPropertyValue('display');\n const priority = h.style.getPropertyPriority('display');\n h.style.setProperty('display', 'none', 'important');\n return () => (display ? h.style.setProperty('display', display, priority) : h.style.removeProperty('display'));\n}\n\n/**\n * Undo a hide the server wrote (`hide`, and `insert_placement` at `replace`).\n * Never a style string from the marker: the original is put back only when\n * the attribute is exactly it plus the server's one declaration; otherwise\n * that one declaration is removed.\n */\nfunction undoServerHide(el: Element, orig: Record<string, any>): void {\n const current = el.getAttribute('style') || '';\n const before = typeof orig.style === 'string' ? orig.style : null;\n const base = before === null ? '' : before.trim().replace(/;+$/, '');\n if (current === (base ? base + ';' : '') + HIDE_DECLARATION) {\n if (before === null) el.removeAttribute('style');\n else el.setAttribute('style', before);\n } else if ((el as HTMLElement).style?.getPropertyValue('display') === 'none') {\n (el as HTMLElement).style.removeProperty('display');\n }\n}\n\n/**\n * Inline text markup a replaced element's original content may come back with.\n * Everything else is unwrapped to its text (its children are kept, checked the same way):\n * no script, frame, object, embed, meta, base, link, style, form, svg or math element is\n * ever created, and no attribute outside RESTORE_ATTRIBUTES (no on*, style, srcdoc, data).\n */\nconst RESTORE_ELEMENTS = new Set(['A', 'ABBR', 'B', 'BDI', 'BDO', 'BR', 'CITE', 'CODE', 'DATA', 'DEL', 'DFN', 'EM', 'I', 'IMG', 'INS', 'KBD', 'MARK', 'Q', 'S', 'SAMP', 'SMALL', 'SPAN', 'STRONG', 'SUB', 'SUP', 'TIME', 'U', 'VAR', 'WBR']);\nconst RESTORE_ATTRIBUTES = new Set(['class', 'id', 'title', 'lang', 'dir', 'alt', 'width', 'height', 'datetime', 'href', 'src', 'srcset', 'rel', 'target']);\nconst MAX_RESTORE_NODES = 500;\n\nfunction restoreInline(from: DocumentFragment): DocumentFragment {\n const out = document.createDocumentFragment();\n let budget = MAX_RESTORE_NODES;\n const copy = (src: Node, into: Node): void => {\n for (const n of Array.from(src.childNodes)) {\n if (budget-- <= 0) return;\n if (n.nodeType === 3) {\n into.appendChild(document.createTextNode(n.nodeValue || ''));\n } else if (n.nodeType === 1) {\n const e = n as Element;\n if (e.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !RESTORE_ELEMENTS.has(e.tagName)) {\n // Not allowed: only its text and allowed descendants, never the element.\n if (!/^(SCRIPT|STYLE|TEMPLATE|IFRAME|OBJECT|EMBED|NOSCRIPT|TEXTAREA|TITLE)$/.test(e.tagName)) copy(e, into);\n continue;\n }\n const made = document.createElement(e.tagName.toLowerCase());\n for (const a of Array.from(e.attributes)) {\n const name = a.name.toLowerCase();\n if (!RESTORE_ATTRIBUTES.has(name)) continue;\n if (name === 'href' || name === 'src') {\n const v = safeRestoredUrl(a.value);\n if (v !== null) made.setAttribute(name, v);\n } else if (name === 'srcset') {\n const v = safeRestoredSrcset(a.value);\n if (v !== null) made.setAttribute(name, v);\n } else {\n made.setAttribute(name, a.value);\n }\n }\n into.appendChild(made);\n copy(e, made);\n }\n }\n };\n copy(from, out);\n return out;\n}\n\nconst tokensOf = (el: Element): string[] => (el.getAttribute(SERVER_APPLIED_ATTR) || '').split(/\\s+/).filter(Boolean);\n\n/** `GET /v1/in-app/site-settings` (backend common/web-experience/page-edit-site.ts). */\nexport interface SiteSettingsResponse {\n success?: boolean;\n ttlSeconds?: number;\n pageEdits?: { enabled?: boolean; active?: boolean; antiFlickerSelectors?: string[] };\n}\nexport interface PageEditSite {\n enabled: boolean;\n active: boolean;\n antiFlickerSelectors: string[];\n}\n\nexport type PageEditOperation = (typeof PAGE_EDIT_OPERATIONS)[number];\nexport type PageEditPosition = (typeof PAGE_EDIT_POSITIONS)[number];\n\nexport interface PageEditWire {\n id: string;\n selector: string;\n operation: PageEditOperation;\n value?: string;\n placementKey?: string;\n position?: PageEditPosition;\n personalized?: true;\n}\n\nexport interface PageEditExperienceWire {\n id: string;\n variantId: string | null;\n deliveryId: string | null;\n deliveryToken: string | null;\n isControl: boolean;\n controlToken: string | null;\n selectors: string[];\n edits: PageEditWire[];\n}\n\nexport interface PageEditsResponse {\n success?: boolean;\n ttlSeconds?: number;\n experiences?: PageEditExperienceWire[];\n}\n\nexport interface PageEditRuntime {\n /** As placements: null = send nothing; `granted` = personal serving and reporting. */\n consent: () => PlacementConsent | null;\n requestTimeoutMs?: number;\n noteStatus?: (status: number, data: any) => void;\n}\n\n/** Same rule as the server: nothing that could close the style rule, no comment, no control character. */\nexport function isSafeSelector(selector: unknown): selector is string {\n if (typeof selector !== 'string') return false;\n const s = selector.trim();\n if (!s || s.length > MAX_SELECTOR_LENGTH) return false;\n if (/[{};<@]/.test(s) || s.includes('/*') || s.includes('*/')) return false;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(s)) return false;\n try {\n if (typeof document !== 'undefined') document.createDocumentFragment().querySelector(s);\n } catch {\n return false; // not a selector this browser parses\n }\n return true;\n}\n\nexport function isSafeEditUrl(url: unknown): url is string {\n if (typeof url !== 'string') return false;\n const u = url.trim();\n if (!u || u.length > MAX_URL_LENGTH) return false;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f\\s]/.test(u)) return false;\n return /^https?:\\/\\/[^/?#\\s]+/i.test(u);\n}\n\n/** The edit as this SDK will apply it, or null - an edit it does not trust is skipped whole. */\nexport function trustedEdit(e: any): PageEditWire | null {\n if (!e || typeof e !== 'object' || typeof e.id !== 'string' || !isSafeSelector(e.selector)) return null;\n const base = { id: e.id, selector: e.selector.trim(), ...(e.personalized === true ? { personalized: true as const } : {}) };\n switch (e.operation) {\n case 'hide':\n return { ...base, operation: 'hide' };\n case 'replace_text':\n return typeof e.value === 'string' && e.value.length <= MAX_TEXT_LENGTH ? { ...base, operation: 'replace_text', value: e.value } : null;\n case 'replace_image':\n case 'replace_link':\n return isSafeEditUrl(e.value) ? { ...base, operation: e.operation, value: e.value.trim() } : null;\n case 'insert_placement':\n return typeof e.placementKey === 'string' && PLACEMENT_KEY_PATTERN.test(e.placementKey)\n ? { ...base, operation: 'insert_placement', placementKey: e.placementKey, position: (PAGE_EDIT_POSITIONS as readonly string[]).includes(e.position) ? e.position : 'after' }\n : null;\n default:\n return null;\n }\n}\n\ninterface Applied {\n el: Element;\n editId: string;\n undo: () => void;\n}\n\ninterface Experience {\n wire: PageEditExperienceWire;\n edits: PageEditWire[];\n}\n\n/** The site settings as stored for one SDK session (`sid`), answered at `at`. */\ninterface StoredSite {\n sid: string;\n at: number;\n value: PageEditSite;\n}\n\nexport class PageEditManager {\n private page: PageContextTracker | null = null;\n private pageUnsubscribe: (() => void) | null = null;\n private experiences: Experience[] = [];\n private applied: Applied[] = [];\n private reported = new Set<string>();\n private observer: MutationObserver | null = null;\n private scheduled = false;\n private flickerTimer: ReturnType<typeof setTimeout> | null = null;\n /** When the current page started: the anti-flicker never lasts past this + PAGE_EDIT_ANTI_FLICKER_MS. */\n private pageStartedAt = 0;\n /** The last site settings answer, for its session id (mirrors the sessionStorage entry). */\n private site: StoredSite | null = null;\n private siteRequest: Promise<PageEditSite | null> | null = null;\n private readonly stores: { answers: string; selectors: string; site: string };\n /** Edits the page's HTML arrived with (token -> edit); null until the marker was read. */\n private server: Map<string, ServerEdit> | null = null;\n /** The page those were written for: a route change elsewhere undoes them. */\n private serverUrl: string | null = null;\n private generation = 0;\n private started = false;\n private destroyed = false;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private identity: IdentityManager,\n private session: SessionManager,\n private logger: Logger,\n private runtime: PageEditRuntime,\n private auth?: InAppAuthProvider,\n ) {\n this.stores = pageEditsStorageKeys(sdkKey);\n try {\n // Not workspace-scoped: another workspace on this origin may have written them.\n localStorage.removeItem(LEGACY_SELECTOR_STORE);\n sessionStorage.removeItem(LEGACY_ANSWER_STORE);\n } catch {\n /* storage blocked */\n }\n }\n\n setPageContext(tracker: PageContextTracker | null): void {\n this.pageUnsubscribe?.();\n this.pageUnsubscribe = null;\n this.page = tracker;\n if (tracker) {\n this.pageUnsubscribe = tracker.onSignal((s) => {\n if (s.type === 'page_change' && this.started) this.loadPage();\n });\n }\n }\n\n /** Hide what was edited here last time, apply what is known, observe the DOM, ask the server. */\n start(): void {\n if (this.started || this.destroyed || typeof document === 'undefined') return;\n this.started = true;\n if (typeof MutationObserver !== 'undefined' && document.documentElement) {\n this.observer = new MutationObserver(() => this.schedule());\n this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n this.loadPage();\n }\n\n /**\n * The audience changed (identify, reset, consent): forget this visitor's\n * answers and ask again. `siteSettings: true` (reset, wipeData, a consent\n * change) forgets the stored site settings too; identify keeps them - they\n * are the same for every visitor of the site.\n */\n invalidate(opts: { siteSettings?: boolean } = {}): void {\n this.generation++;\n this.reported.clear();\n if (opts.siteSettings) this.forgetSite();\n try {\n sessionStorage.removeItem(this.stores.answers);\n } catch {\n /* ignore */\n }\n if (this.started) this.loadPage();\n }\n\n destroy(): void {\n this.destroyed = true;\n this.pageUnsubscribe?.();\n this.observer?.disconnect();\n this.observer = null;\n this.revertAll();\n this.showAll();\n }\n\n /** Currently applied edits, for tests and debugging. */\n appliedCount(): number {\n return this.applied.length;\n }\n\n /** Edits the page arrived with from the server and still carries, for tests and debugging. */\n serverAppliedCount(): number {\n return this.serverEdits().size;\n }\n\n // ── one page ─────────────────────────────────────────────────────────────\n\n private url(): string | null {\n return this.page ? this.page.current().url : currentPageUrl();\n }\n\n private loadPage(): void {\n const generation = ++this.generation;\n this.revertAll();\n const url = this.url();\n if (!url) {\n this.experiences = [];\n return;\n }\n this.pageStartedAt = Date.now();\n // The server's edits belong to the page they were written for.\n const server = this.serverEdits();\n if (this.serverUrl === null) this.serverUrl = url;\n else if (url !== this.serverUrl && server.size) this.reconcileServer([]);\n // 1. Anti-flicker: the elements edited on this page last time, at most 300 ms.\n const remembered = this.rememberedSelectors(url);\n this.hide(remembered);\n // 2. Static edits from the last answer for this page, applied as elements appear.\n this.experiences = this.cachedExperiences(url);\n this.applyAll();\n // 3. The site settings (cached), then the answer for this page and visitor.\n void this.siteThenFetch(url, generation, remembered.length > 0);\n }\n\n private async siteThenFetch(url: string, generation: number, rememberedAny: boolean): Promise<void> {\n // A stored answer for this session is used at once - no wait before the\n // per-visitor request - and refreshed in the background when it is older\n // than SITE_SETTINGS_SESSION_REFRESH_SECONDS. Only without one (first\n // page of a session) does the page wait for the site settings.\n const stored = this.storedSite();\n let site: PageEditSite | null;\n if (stored) {\n site = stored.value;\n if (Date.now() - stored.at >= SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) {\n void this.requestSite().then((fresh) => {\n // Was off or idle and is live now: this page asks after all.\n if (fresh && fresh.enabled && fresh.active && !(site!.enabled && site!.active) && generation === this.generation && !this.destroyed) {\n void this.fetch(url, generation);\n }\n });\n }\n } else {\n site = await this.siteSettings();\n }\n if (generation !== this.generation || this.destroyed) return;\n if (site && (!site.enabled || !site.active)) {\n // Off for this site, or nothing live: undo what the cache (or the server) applied, ask nothing.\n this.revertAll();\n this.reconcileServer([]);\n this.experiences = [];\n this.showAll();\n return;\n }\n // First view on this page: hold back the site's edited elements, inside the same 300 ms.\n if (site && !rememberedAny && site.antiFlickerSelectors.length) this.hide(site.antiFlickerSelectors);\n await this.fetch(url, generation);\n }\n\n /**\n * The site settings: one GET per SDK session, then at most one per\n * SITE_SETTINGS_SESSION_REFRESH_SECONDS within it, kept in sessionStorage\n * per workspace across the session's page loads. A CORS-simple request (no\n * custom header, the key in the query string - the server refuses a key in\n * a header there, the URL being the cache key), so no preflight. Null when\n * unknown (network error, an HTTP error, an answer it cannot read): then\n * the SDK asks /page-edits as it always did, and nothing is stored.\n */\n siteSettings(): Promise<PageEditSite | null> {\n const stored = this.storedSite();\n if (stored && Date.now() - stored.at < SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) return Promise.resolve(stored.value);\n return this.requestSite();\n }\n\n /** The stored answer for the current session id (any age), or null. */\n private storedSite(): StoredSite | null {\n const sid = this.session.getSessionId();\n if (!sid) return null; // no session (after wipeData): nothing to tie it to\n if (this.site && this.site.sid === sid) return this.site;\n this.site = null;\n try {\n const raw = JSON.parse(sessionStorage.getItem(this.stores.site) || 'null');\n const v = raw?.value;\n if (raw && raw.sid === sid && typeof raw.at === 'number' && raw.at <= Date.now() && v && typeof v === 'object') {\n this.site = {\n sid,\n at: raw.at,\n value: {\n enabled: v.enabled !== false,\n active: v.active !== false,\n antiFlickerSelectors: (Array.isArray(v.antiFlickerSelectors) ? v.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),\n },\n };\n } else if (raw) {\n sessionStorage.removeItem(this.stores.site); // another session's answer\n }\n } catch {\n /* storage blocked or unreadable: ask */\n }\n return this.site;\n }\n\n private forgetSite(): void {\n this.site = null;\n try {\n sessionStorage.removeItem(this.stores.site);\n } catch {\n /* ignore */\n }\n }\n\n private requestSite(): Promise<PageEditSite | null> {\n if (this.siteRequest) return this.siteRequest;\n const request = (async (): Promise<PageEditSite | null> => {\n const sid = this.session.getSessionId();\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/site-settings?sdkKey=${encodeURIComponent(this.sdkKey)}`, { method: 'GET', credentials: 'omit' });\n if (!res.ok) {\n this.runtime.noteStatus?.(res.status, null);\n this.forgetSite();\n return null;\n }\n const data: SiteSettingsResponse = await res.json();\n const pe = data?.pageEdits;\n if (!pe || typeof pe !== 'object') {\n this.forgetSite();\n return null;\n }\n const value: PageEditSite = {\n enabled: pe.enabled !== false,\n active: pe.active !== false,\n antiFlickerSelectors: (Array.isArray(pe.antiFlickerSelectors) ? pe.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),\n };\n // data.ttlSeconds is the HTTP cache lifetime; the SDK keeps the\n // answer for the session (SITE_SETTINGS_SESSION_REFRESH_SECONDS).\n if (sid) {\n this.site = { sid, at: Date.now(), value };\n try {\n sessionStorage.setItem(this.stores.site, JSON.stringify(this.site));\n } catch {\n /* storage full or blocked: kept in memory for this page */\n }\n }\n return value;\n } catch (error) {\n this.logger.debug('Site settings request failed', error);\n // Unknown: a stale stored answer is not trusted past its refresh time.\n this.forgetSite();\n return null;\n } finally {\n this.siteRequest = null;\n }\n })();\n this.siteRequest = request;\n return request;\n }\n\n private async fetch(url: string, generation: number): Promise<void> {\n const consent = this.runtime.consent();\n if (consent === null || this.destroyed) {\n this.showAll();\n return;\n }\n const personal = consent === 'granted';\n const userId = personal ? this.identity.getUserId() : null;\n const anonymousId = personal ? this.identity.getAnonymousId() : null;\n const body = {\n ...(userId ? { userId } : {}),\n ...(anonymousId ? { anonymousId } : {}),\n ...(personal ? { sessionId: this.session.getSessionId() } : {}),\n deviceType: 'web',\n locale: typeof navigator !== 'undefined' ? navigator.language : undefined,\n capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY],\n trackingConsent: consent,\n context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} },\n };\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/page-edits`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(personal ? this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {} : {}),\n },\n body: JSON.stringify(body),\n ...(controller ? { signal: controller.signal } : {}),\n });\n if (generation !== this.generation) return;\n if (!res.ok) {\n // 429 and every other failure: keep what is applied (the cached static edits).\n this.runtime.noteStatus?.(res.status, null);\n return;\n }\n const data: PageEditsResponse = await res.json();\n if (generation !== this.generation || !data || data.success === false || !Array.isArray(data.experiences)) return;\n const experiences = data.experiences\n .filter((x) => x && typeof x.id === 'string')\n .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e): e is PageEditWire => !!e) }));\n this.revertAll();\n this.experiences = experiences;\n // The definitive answer: a server-applied edit it no longer carries is undone first.\n this.reconcileServer(experiences);\n this.remember(url, experiences, data.ttlSeconds);\n this.applyAll();\n } catch (error) {\n this.logger.debug('Page edits request failed', error);\n } finally {\n clearTimeout(timeout);\n if (generation === this.generation) this.showAll();\n }\n }\n\n // ── applying ─────────────────────────────────────────────────────────────\n\n private schedule(): void {\n if (this.scheduled || this.destroyed) return;\n this.scheduled = true;\n const run = () => {\n this.scheduled = false;\n this.applyAll();\n };\n if (typeof queueMicrotask === 'function') queueMicrotask(run);\n else void Promise.resolve().then(run);\n }\n\n private applyAll(): void {\n if (this.destroyed || typeof document === 'undefined') return;\n // Our own DOM writes would wake the observer; it is paused while we write.\n this.observer?.disconnect();\n try {\n for (const x of this.experiences) {\n if (x.wire.isControl) {\n const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);\n if (seen) this.reportControl(x.wire);\n continue;\n }\n let landed = false;\n for (const edit of x.edits) {\n const token = `${x.wire.id}:${edit.id}`;\n const server = this.serverEdits().get(token);\n const byServer = !!server && server.variantId === (x.wire.variantId ?? null) && sameEdit(server.edit, edit);\n for (const el of this.query(edit.selector)) {\n if (this.applied.some((a) => a.el === el && a.editId === edit.id)) {\n landed = true;\n continue;\n }\n // Already in the HTML the server sent: never applied a second time.\n if (byServer && tokensOf(el).includes(token)) {\n landed = true;\n continue;\n }\n const undo = this.applyOne(el, edit);\n if (undo) {\n this.applied.push({ el, editId: edit.id, undo });\n landed = true;\n }\n }\n }\n if (landed) this.reportDisplayed(x.wire);\n }\n } finally {\n if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n\n private query(selector: string): Element[] {\n try {\n return Array.from(document.querySelectorAll(selector)).filter((el) => !(el as HTMLElement).closest?.('[data-joryio-editor]'));\n } catch {\n return [];\n }\n }\n\n /** One edit on one element; returns how to undo it, or null when it does not fit the element. */\n private applyOne(el: Element, edit: PageEditWire): (() => void) | null {\n const h = el as HTMLElement;\n switch (edit.operation) {\n case 'replace_text': {\n const before = Array.from(el.childNodes);\n el.textContent = edit.value ?? '';\n return () => {\n el.textContent = '';\n before.forEach((n) => el.appendChild(n));\n };\n }\n case 'replace_image': {\n if (el.tagName !== 'IMG') return null;\n const src = el.getAttribute('src');\n const srcset = el.getAttribute('srcset');\n el.setAttribute('src', edit.value!);\n // A srcset would win over the new src in every browser.\n el.removeAttribute('srcset');\n return () => {\n if (src === null) el.removeAttribute('src');\n else el.setAttribute('src', src);\n if (srcset !== null) el.setAttribute('srcset', srcset);\n };\n }\n case 'replace_link': {\n if (el.tagName !== 'A') return null;\n const href = el.getAttribute('href');\n el.setAttribute('href', edit.value!);\n return () => (href === null ? el.removeAttribute('href') : el.setAttribute('href', href));\n }\n case 'hide':\n return hideElement(h);\n case 'insert_placement': {\n const spot = document.createElement('div');\n spot.setAttribute('data-joryio-placement', edit.placementKey!);\n spot.setAttribute('data-joryio-edit', edit.id);\n const where: InsertPosition =\n edit.position === 'before' ? 'beforebegin' : edit.position === 'prepend' ? 'afterbegin' : edit.position === 'append' ? 'beforeend' : 'afterend';\n el.insertAdjacentElement(where, spot);\n if (edit.position !== 'replace') return () => spot.remove();\n // \"Instead of it\": the spot sits where the element was, the element is hidden.\n const show = hideElement(h);\n return () => {\n spot.remove();\n show();\n };\n }\n default:\n return null;\n }\n }\n\n private revertAll(): void {\n const applied = this.applied.splice(0).reverse();\n if (!applied.length) return;\n this.observer?.disconnect();\n try {\n for (const a of applied) {\n try {\n a.undo();\n } catch {\n /* the element may be gone */\n }\n }\n } finally {\n if (this.observer && typeof document !== 'undefined' && document.documentElement) {\n this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n }\n\n // ── anti-flicker ─────────────────────────────────────────────────────────\n\n private hide(selectors: string[]): void {\n const safe = selectors.filter(isSafeSelector);\n if (!safe.length || typeof document === 'undefined') return;\n // Never past PAGE_EDIT_ANTI_FLICKER_MS from the start of this page, however late the list arrived.\n const left = PAGE_EDIT_ANTI_FLICKER_MS - (Date.now() - (this.pageStartedAt || Date.now()));\n if (left <= 0) return;\n let style = document.getElementById(STYLE_ID) as HTMLStyleElement | null;\n if (!style) {\n style = document.createElement('style');\n style.id = STYLE_ID;\n (document.head || document.documentElement).appendChild(style);\n }\n // Only these elements, never the body; opacity, so the layout does not move.\n // Elements the server already edited are never held back.\n style.textContent = this.serverEdits().size\n ? `:is(${safe.join(',')}):not([${SERVER_APPLIED_ATTR}]){opacity:0 !important}`\n : `${safe.join(',')}{opacity:0 !important}`;\n if (this.flickerTimer) clearTimeout(this.flickerTimer);\n this.flickerTimer = setTimeout(() => this.showAll(), left);\n }\n\n private showAll(): void {\n if (this.flickerTimer) clearTimeout(this.flickerTimer);\n this.flickerTimer = null;\n try {\n document.getElementById(STYLE_ID)?.remove();\n } catch {\n /* ignore */\n }\n }\n\n // ── what is remembered (selectors and static edits only, never a personalized value) ──\n\n private subjectKey(): string {\n return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;\n }\n\n private remember(url: string, experiences: Experience[], ttlSeconds?: number): void {\n const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.map((e) => e.selector))))];\n try {\n const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};\n delete all[url];\n if (selectors.length) all[url] = selectors.slice(0, 50);\n const keys = Object.keys(all);\n for (const k of keys.slice(0, Math.max(0, keys.length - MAX_REMEMBERED_PAGES))) delete all[k];\n localStorage.setItem(this.stores.selectors, JSON.stringify(all));\n } catch {\n /* storage blocked: no anti-flicker next time, nothing else */\n }\n try {\n const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};\n const pages = stored.subject === this.subjectKey() && stored.pages ? stored.pages : {};\n pages[url] = {\n at: Date.now(),\n ttl: (ttlSeconds && ttlSeconds > 0 ? ttlSeconds : DEFAULT_TTL_SECONDS) * 1000,\n experiences: experiences\n .filter((x) => !x.wire.isControl)\n .map((x) => ({ ...x.wire, deliveryToken: null, edits: x.edits.filter((e) => !e.personalized) }))\n .filter((x) => x.edits.length),\n };\n sessionStorage.setItem(this.stores.answers, JSON.stringify({ subject: this.subjectKey(), pages }));\n } catch {\n /* ignore */\n }\n }\n\n private rememberedSelectors(url: string): string[] {\n try {\n const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};\n return Array.isArray(all[url]) ? all[url].filter((s: unknown) => typeof s === 'string') : [];\n } catch {\n return [];\n }\n }\n\n private cachedExperiences(url: string): Experience[] {\n try {\n const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};\n if (stored.subject !== this.subjectKey()) return [];\n const entry = stored.pages?.[url];\n if (!entry || Date.now() - entry.at > entry.ttl) return [];\n // Applied, never reported: the exposure belongs to the answer with a token.\n return (entry.experiences || []).map((wire: PageEditExperienceWire) => ({\n wire: { ...wire, isControl: false, deliveryToken: null },\n edits: (wire.edits || []).map(trustedEdit).filter((e): e is PageEditWire => !!e && !e.personalized),\n }));\n } catch {\n return [];\n }\n }\n\n // ── edits the server applied (D450) ──────────────────────────────────────\n\n /** The marker, read once it is in the DOM (it sits right after <head>). */\n private serverEdits(): Map<string, ServerEdit> {\n if (this.server) return this.server;\n const found = new Map<string, ServerEdit>();\n if (typeof document === 'undefined') return found;\n // Trusted only where the plugin writes it: a JSON <script> directly in <head>\n // (the plugin inserts it right after <head>, before any page script). An\n // element with that id anywhere else - user content in the body, DOM\n // clobbering - is ignored.\n const el = serverMarkerElement();\n if (!el) {\n // Not (yet) in the DOM: asked again on the next call while the page is still loading.\n if (document.readyState !== 'loading') this.server = found;\n return found;\n }\n try {\n const data = JSON.parse(el.textContent || '{}');\n if (data && data.v === SERVER_MARKER_VERSION && Array.isArray(data.experiences)) {\n for (const x of data.experiences) {\n if (!x || typeof x.id !== 'string' || !Array.isArray(x.edits)) continue;\n for (const raw of x.edits) {\n const edit = trustedEdit(raw);\n if (edit && !edit.personalized) found.set(`${x.id}:${edit.id}`, { experienceId: x.id, variantId: typeof x.variantId === 'string' ? x.variantId : null, edit });\n }\n }\n }\n } catch {\n /* a marker this SDK cannot read: treated as none; the edits it lists stay as the page has them */\n }\n this.server = found;\n return found;\n }\n\n /**\n * Keep the server-applied edits the definitive answer still carries for this\n * visitor (same campaign, variant and edit); undo every other one.\n */\n private reconcileServer(experiences: Experience[]): void {\n const server = this.serverEdits();\n if (!server.size || typeof document === 'undefined') return;\n const keep = new Set<string>();\n for (const x of experiences) {\n if (x.wire.isControl) continue;\n for (const e of x.edits) {\n const token = `${x.wire.id}:${e.id}`;\n const s = server.get(token);\n if (s && s.variantId === (x.wire.variantId ?? null) && sameEdit(s.edit, e)) keep.add(token);\n }\n }\n const undo = [...server.keys()].filter((t) => !keep.has(t));\n if (!undo.length) return;\n this.observer?.disconnect();\n try {\n for (const token of undo) {\n this.undoServerEdit(token, server.get(token)!.edit);\n server.delete(token);\n }\n } finally {\n if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n\n /** Put back what the server changed for one edit, from the undo data it left on each element. */\n private undoServerEdit(token: string, edit: PageEditWire): void {\n for (const el of Array.from(document.querySelectorAll(`[${SERVER_APPLIED_ATTR}]`))) {\n const tokens = tokensOf(el);\n if (!tokens.includes(token)) continue;\n let all: Record<string, any> = {};\n try {\n all = JSON.parse(el.getAttribute(SERVER_ORIG_ATTR) || '{}') || {};\n } catch {\n all = {};\n }\n const orig = all[token] || {};\n // Only an element that still shows exactly what the server applied is put back,\n // and only with values that pass the same checks as an edit.\n try {\n switch (edit.operation) {\n case 'replace_text': {\n const tpl = Array.from(el.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute(SERVER_ORIG_ATTR) === token) as HTMLTemplateElement | undefined;\n if (tpl && tpl.content && el.textContent === edit.value) {\n // Rebuilt node by node through an allowlist - never the template's markup made live.\n const restored = restoreInline(tpl.content);\n el.textContent = '';\n el.appendChild(restored);\n }\n break;\n }\n case 'replace_image':\n if (el.tagName === 'IMG' && el.getAttribute('src') === edit.value) {\n const src = safeRestoredUrl(orig.src);\n const srcset = safeRestoredSrcset(orig.srcset);\n if (src === null) el.removeAttribute('src');\n else el.setAttribute('src', src);\n if (srcset !== null) el.setAttribute('srcset', srcset);\n }\n break;\n case 'replace_link':\n if (el.tagName === 'A' && el.getAttribute('href') === edit.value) {\n const href = safeRestoredUrl(orig.href);\n if (href === null) el.removeAttribute('href');\n else el.setAttribute('href', href);\n }\n break;\n case 'hide':\n undoServerHide(el, orig);\n break;\n case 'insert_placement':\n // \"Instead of it\" also hid the element (the spot itself is removed below).\n if (edit.position === 'replace') undoServerHide(el, orig);\n break;\n default:\n break;\n }\n } catch {\n /* the element changed since: leave it */\n }\n const left = tokens.filter((t) => t !== token);\n if (left.length) el.setAttribute(SERVER_APPLIED_ATTR, left.join(' '));\n else el.removeAttribute(SERVER_APPLIED_ATTR);\n delete all[token];\n if (Object.keys(all).length) el.setAttribute(SERVER_ORIG_ATTR, JSON.stringify(all));\n else el.removeAttribute(SERVER_ORIG_ATTR);\n }\n if (edit.operation === 'insert_placement') {\n for (const spot of Array.from(document.querySelectorAll(`div[${SERVER_SPOT_ATTR}][data-joryio-placement]`))) {\n if (spot.getAttribute(SERVER_SPOT_ATTR) === token && spot.getAttribute('data-joryio-placement') === edit.placementKey) spot.remove();\n }\n }\n }\n\n // ── reporting ────────────────────────────────────────────────────────────\n\n private reportDisplayed(x: PageEditExperienceWire): void {\n if (!x.deliveryToken || this.runtime.consent() !== 'granted') return;\n const once = `displayed:${x.deliveryId || x.deliveryToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post({\n campaignId: x.id,\n ...(x.variantId ? { variantId: x.variantId } : {}),\n deliveryToken: x.deliveryToken,\n action: 'displayed',\n displayedAt: new Date().toISOString(),\n });\n }\n\n private reportControl(x: PageEditExperienceWire): void {\n if (!x.controlToken || this.runtime.consent() !== 'granted') return;\n const once = `control:${x.controlToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post({ action: 'control_viewed', controlToken: x.controlToken, viewedAt: new Date().toISOString() });\n }\n\n private post(body: Record<string, any>): void {\n const userId = this.identity.getUserId();\n const full = { ...body, ...(userId ? { userId } : {}), anonymousId: this.identity.getAnonymousId(), sessionId: this.session.getSessionId(), deviceType: 'web' };\n fetch(`${this.apiEndpoint}/v1/in-app/track`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : this.identity.getAnonymousId()) || {}),\n },\n body: JSON.stringify(full),\n keepalive: true,\n })\n .then((r) => {\n if (!r.ok) this.runtime.noteStatus?.(r.status, null);\n })\n .catch((error) => this.logger.debug('Page edit report failed', error));\n }\n}\n","/**\n * The files the core loads on demand from the SDK host, next to\n * `joryio.min.js`: the point-and-click editor (`joryio-editor.min.js`,\n * src/core/editor-gate.ts) and the default card feed (`joryio-cards-ui.min.js`,\n * src/core/cards.ts). Kept out of the core so that a visitor who never needs\n * them never downloads them (BACKLOG D444).\n */\nimport { SDK_VERSION } from './config';\n\nexport const SDK_HOST = 'https://sdk.joryio.com';\n\n/** A core bundle's own file name: what a script tag loads (sdk.joryio.com, the npm package's dist/). */\nconst CORE_FILE = /\\/joryio(?:\\.umd)?(?:\\.min)?\\.js$/;\n\n/**\n * The folder the running core was loaded from (with a trailing slash), when\n * it was loaded by a script tag as `joryio.min.js` over https - for example\n * `https://sdk.joryio.com/web/1.4.0-beta.4/`. Null when bundled into the\n * site's own code (the script is then the site's file), or not over https.\n */\nexport function coreFolderOf(src: string | null | undefined): string | null {\n if (!src || typeof src !== 'string') return null;\n let u: URL;\n try {\n u = new URL(src);\n } catch {\n return null;\n }\n if (u.protocol !== 'https:' || !CORE_FILE.test(u.pathname)) return null;\n return `${u.origin}${u.pathname.replace(/[^/]*$/, '')}`;\n}\n\n/**\n * Read while this module is evaluated, i.e. while the core's script runs:\n * `document.currentScript` is null afterwards (and for a module script),\n * then the last `<script src=\".../joryio.min.js\">` on the page is used.\n */\nfunction readOwnFolder(): string | null {\n if (typeof document === 'undefined') return null;\n try {\n const current = document.currentScript as HTMLScriptElement | null;\n const fromCurrent = coreFolderOf(current && current.src);\n if (fromCurrent || (current && current.src)) return fromCurrent;\n const tags = document.querySelectorAll('script[src]');\n for (let i = tags.length - 1; i >= 0; i--) {\n const folder = coreFolderOf((tags[i] as HTMLScriptElement).src);\n if (folder) return folder;\n }\n } catch {\n /* no DOM access */\n }\n return null;\n}\nconst OWN_FOLDER = readOwnFolder();\n\n/**\n * Where a lazily loaded file comes from, in order:\n * 1. the folder the core itself was loaded from (`coreFolderOf`), so a core\n * from `sdk.joryio.com/web/1.4.0-beta.6/` or from the npm package's\n * `dist/` on a CDN loads the side files of the same build - unless that\n * folder is the major channel `sdk.joryio.com/web/<major>/`, which moves:\n * then 2 goes first;\n * 2. the exact SDK version's folder on the SDK host (immutable, the same\n * build as this core). A beta's SDK_VERSION is the beta's own version\n * (from 1.4.0-beta.6 the release build stamps it), so this is\n * `web/1.4.0-beta.6/`, the only folder a beta is published to;\n * 3. the major channel, as a fallback (a version not on the CDN, such as a\n * local build) - never for a pre-release: the channel carries finals\n * only, so a beta would get the previous final's side files.\n * An init option (`editorScriptUrl`, `cardsUiScriptUrl`) replaces all of\n * them, for a self-hosted SDK.\n */\nexport function sdkHostFileUrls(file: string, override?: string, ownFolder: string | null = OWN_FOLDER, version: string = SDK_VERSION): string[] {\n if (override) return [override];\n const major = version.split('.')[0];\n const exact = `${SDK_HOST}/web/${version}/${file}`;\n const channel = `${SDK_HOST}/web/${major}/${file}`;\n const prerelease = version.includes('-');\n let urls = ownFolder && ownFolder !== `${SDK_HOST}/web/${major}/` ? [`${ownFolder}${file}`, exact, channel] : [exact, channel];\n if (prerelease) urls = urls.filter((u) => u !== channel);\n return urls.filter((u, i) => urls.indexOf(u) === i);\n}\n\n/** Inject one script tag; resolves when it ran (onload), rejects on an error (a 404, a blocking CSP). */\nexport function loadSdkScript(src: string, marker: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const s = document.createElement('script');\n s.src = src;\n s.async = true;\n s.setAttribute(marker, 'bundle');\n s.onload = () => resolve();\n s.onerror = () => {\n s.remove();\n reject(new Error(`could not load ${src}`));\n };\n (document.head || document.documentElement).appendChild(s);\n });\n}\n","/**\n * The point-and-click editor's door in the core bundle (BACKLOG D444 Phase 4,\n * docs/PLACEMENTS_WEBSITE_LAYER.md 3).\n *\n * The visual editor itself (highlight, panel, selector computation) is a\n * separate file, `joryio-editor.min.js`, served from the same SDK host next to\n * `joryio.min.js`, so the ~every-visitor bundle carries only this handshake:\n *\n * 1. only when the tab was opened with `?joryio_editor=1` AND by another\n * window (`window.opener`) AND page edits are not switched off in the\n * site's code (`pageEdits: false`), post `joryio:editor-ready` to the\n * opener (no secret in it);\n * 2. accept `joryio:editor-token` only from that opener window, and check\n * the token with `POST /v1/in-app/editor/verify`, which answers the\n * dashboard origin it was minted for (bound to this site's origin and\n * this SDK key's workspace; refused when page edits are off);\n * 3. only then load the editor bundle and hand it the verified dashboard\n * origin and the opener. Nothing is loaded for any other visitor.\n */\nimport type { Logger } from '../utils/logger';\nimport { sdkIdentityHeaders } from './config';\nimport { loadSdkScript, sdkHostFileUrls } from './sdk-host-files';\n\nexport const EDITOR_QUERY_FLAG = 'joryio_editor';\nexport const EDITOR_MESSAGES = {\n READY: 'joryio:editor-ready',\n TOKEN: 'joryio:editor-token',\n ACTIVE: 'joryio:editor-active',\n PICK: 'joryio:editor-pick',\n CLOSE: 'joryio:editor-close',\n CLOSED: 'joryio:editor-closed',\n} as const;\n\n/** The global the editor bundle registers itself under, and the contract version between the two files. */\nexport const EDITOR_GLOBAL = '__joryioEditor';\nexport const EDITOR_API_VERSION = 1;\n/** The file next to joryio.min.js on the SDK host. */\nexport const EDITOR_BUNDLE_FILE = 'joryio-editor.min.js';\n\nexport interface EditorBundleApi {\n version: number;\n start(ctx: { dashboardOrigin: string; opener: Window; logger: Logger; onStop: () => void }): { stop(): void };\n}\n\n/**\n * Where the editor bundle is loaded from: the exact SDK version's folder on\n * the SDK host, then the major channel (see sdkHostFileUrls).\n * `editorScriptUrl` (init) replaces both, for a self-hosted SDK.\n */\nexport function editorBundleUrls(override?: string): string[] {\n return sdkHostFileUrls(EDITOR_BUNDLE_FILE, override);\n}\n\n/** True when this tab was opened by the dashboard's editor (the flag and an opener). */\nexport function editorRequested(): boolean {\n try {\n return typeof window !== 'undefined' && !!window.opener && new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) === '1';\n } catch {\n return false;\n }\n}\n\nfunction loadScript(src: string): Promise<void> {\n return loadSdkScript(src, 'data-joryio-editor');\n}\n\nexport class EditorGate {\n private opener: Window | null = null;\n private dashboardOrigin: string | null = null;\n private verifying = false;\n private session: { stop(): void } | null = null;\n private off: (() => void) | null = null;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private logger: Logger,\n private options: { scriptUrl?: string; load?: (src: string) => Promise<void> } = {},\n ) {}\n\n /** Step 1. Does nothing unless the dashboard's editor opened this tab. */\n start(): void {\n if (!editorRequested() || this.opener) return;\n this.opener = window.opener as Window;\n const onMessage = (e: MessageEvent) => void this.onMessage(e);\n window.addEventListener('message', onMessage);\n this.off = () => window.removeEventListener('message', onMessage);\n try {\n // No secret in it, so any target origin: the dashboard checks it came from the tab it opened.\n this.opener.postMessage({ type: EDITOR_MESSAGES.READY }, '*');\n } catch {\n /* the opener went away */\n }\n }\n\n isActive(): boolean {\n return !!this.session;\n }\n\n stop(): void {\n const session = this.session;\n this.session = null;\n session?.stop();\n this.off?.();\n this.off = null;\n this.dashboardOrigin = null;\n this.opener = null;\n }\n\n private async onMessage(e: MessageEvent): Promise<void> {\n const data = e.data as { type?: string; token?: string } | null;\n if (!data || typeof data.type !== 'string' || this.dashboardOrigin) return;\n if (data.type !== EDITOR_MESSAGES.TOKEN || e.source !== this.opener || typeof data.token !== 'string' || this.verifying) return;\n this.verifying = true;\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/editor/verify`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey, ...sdkIdentityHeaders() },\n body: JSON.stringify({ token: data.token }),\n });\n const answer = res.ok ? await res.json() : null;\n // The token says which dashboard may talk to this tab; the message must have come from it.\n if (!answer?.valid || typeof answer.dashboardOrigin !== 'string' || answer.dashboardOrigin !== e.origin) {\n this.logger.warn('Joryio editor: the editor token was not accepted for this site');\n return;\n }\n this.dashboardOrigin = answer.dashboardOrigin;\n // The message listener of the handshake is done; the editor installs its own.\n this.off?.();\n this.off = null;\n await this.loadAndStart(answer.dashboardOrigin);\n } catch (error) {\n this.logger.debug('Joryio editor verification failed', error);\n } finally {\n this.verifying = false;\n }\n }\n\n /** Step 3: the bundle, only now. */\n private async loadAndStart(dashboardOrigin: string): Promise<void> {\n const load = this.options.load ?? loadScript;\n let api: EditorBundleApi | undefined = (window as any)[EDITOR_GLOBAL];\n for (const src of api ? [] : editorBundleUrls(this.options.scriptUrl)) {\n try {\n await load(src);\n api = (window as any)[EDITOR_GLOBAL];\n if (api) break;\n } catch (error) {\n this.logger.debug('Joryio editor bundle failed to load', error);\n }\n }\n if (!api || api.version !== EDITOR_API_VERSION || typeof api.start !== 'function' || !this.opener) {\n this.logger.warn('Joryio editor: the editor could not be loaded (check that your Content-Security-Policy allows sdk.joryio.com)');\n return;\n }\n this.session = api.start({ dashboardOrigin, opener: this.opener, logger: this.logger, onStop: () => this.stop() });\n }\n}\n","/**\n * The editor's words. English is built in; the dashboard sends the same keys\n * in the marketer's language with `joryio:editor-context` (`strings`, plus\n * `dir` for Hebrew and Arabic), so the five dashboard locales reach the\n * editor without shipping every translation to the customer's site. A key\n * the dashboard does not send stays English. `{name}` placeholders are\n * filled with text, never parsed as HTML.\n */\nexport const EDITOR_STRINGS = {\n title: 'Joryio editor',\n variant: 'Variant {name}',\n hintPoint: 'Point at anything on the page',\n hintEditing: 'Editing · changes show live',\n editsOne: '1 edit',\n editsMany: '{n} edits',\n noEdits: 'No edits yet.',\n undo: 'Undo last edit',\n undoOffline: 'Undo is available once the Joryio dashboard is connected',\n saveReturn: 'Save & return to Joryio',\n clickToEdit: 'click to edit',\n helpTitle: 'Not the right box?',\n helpUp: 'Select the section around it',\n helpDown: 'Select something inside it',\n helpClickKey: 'Click',\n helpClick: 'Edit this one',\n dismiss: 'Dismiss',\n page: 'Page',\n up: 'Select the element around it',\n down: 'Select the first element inside it',\n matchOne: '1 match on page',\n matchMany: 'Matches {n} - all will change',\n matchNone: 'Not found',\n whatToDo: 'What do you want to do?',\n actText: 'Change text',\n actLink: 'Change link',\n actImage: 'Change image',\n actHide: 'Hide it',\n actSlot: 'Add content slot',\n noText: 'No text here',\n notLink: 'Not a link',\n notImage: 'Not an image',\n newText: 'New text',\n was: 'Was: \"{value}\"',\n insert: 'Insert',\n fallbackFor: 'If {name} is missing',\n fallbackHelp: \"Shown to visitors we don't know yet.\",\n fallbackBad: 'Plain text only - no Liquid here.',\n fallbackDone: 'Done',\n liquid: 'Liquid code',\n more: 'More…',\n search: 'Search fields',\n noMatch: 'No matching fields',\n rawNote: 'Shown as code: this text uses Liquid beyond profile fields and fallbacks.',\n newLink: 'New link address',\n newImage: 'New image address',\n urlBad: 'Enter an address starting with https:// (or http://).',\n hideNote: \"The {kind} is removed for people in this campaign's audience. Everyone else still sees it.\",\n hiddenFor: 'Hidden for this audience',\n slotName: 'Slot name',\n savedAs: 'Saved as',\n slotHelp: 'Filled by a Placement campaign or a journey step.',\n slotEmpty: 'Enter a name for the slot.',\n slotCreate: 'Create content for this slot →',\n slotIn: 'In this slot:',\n slotAddAnother: '+ Add another campaign',\n where: 'Where',\n posBefore: 'Above it',\n posAfter: 'Below it',\n posReplace: 'Instead of it',\n posPrepend: 'Inside, at the start',\n posAppend: 'Inside, at the end',\n slotPreview: 'Content slot',\n css: 'CSS selector',\n cssHelp: 'For developers. Matches {n} on this page.',\n cssBad: 'Not a selector this page can use.',\n cancel: 'Cancel',\n save: 'Save · {action}',\n noSelector: 'This element has no stable selector. Choose the element around it (arrow up) or another one.',\n kHeading: 'Heading',\n kText: 'Text',\n kLink: 'Link',\n kButton: 'Button',\n kImage: 'Image',\n kList: 'List',\n kSection: 'Section',\n kMain: 'Main',\n kHeader: 'Header',\n kFooter: 'Footer',\n kNav: 'Navigation',\n kForm: 'Form',\n kElement: 'Element',\n};\n\nexport type EditorStringKey = keyof typeof EDITOR_STRINGS;\nexport type EditorStrings = Record<EditorStringKey, string>;\n\n/** The built-in English, with the dashboard's translations over it (strings only, at most 500 characters each). */\nexport function mergeStrings(over: unknown): EditorStrings {\n const out: EditorStrings = { ...EDITOR_STRINGS };\n if (over && typeof over === 'object') {\n for (const k of Object.keys(EDITOR_STRINGS) as EditorStringKey[]) {\n const v = (over as Record<string, unknown>)[k];\n if (typeof v === 'string' && v.trim() && v.length <= 500) out[k] = v;\n }\n }\n return out;\n}\n\n/** `{name}` placeholders filled in; the result is only ever set as text. */\nexport function fill(text: string, vars: Record<string, string | number> = {}): string {\n return text.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));\n}\n","/**\n * The editor's pure parts: the Liquid of a personalized text (the same\n * `{{ user.<field> | default: \"...\" }}` the dashboard writes, packages/frontend\n * src/lib/web-experience.ts), the slot-name slug, the friendly element kind,\n * and the live-preview rendering of an edit's text.\n */\nimport type { EditorStringKey } from './editor-strings';\n\nconst OUTPUT_TAG = /\\{\\{-?([\\s\\S]*?)-?\\}\\}/g;\nconst DEFAULT_FILTER = /\\|\\s*default\\s*:\\s*(\"[^\"]*\"|'[^']*'|[^|}]*?)\\s*(?=\\||$)/;\nconst unquote = (v: string) => v.trim().replace(/^([\"'])([\\s\\S]*)\\1$/, '$2');\n\n/**\n * A fallback as a Liquid string literal. Liquid has no escape inside a\n * literal, so: double quotes; single quotes when the text has a `\"`; with\n * both, single quotes and each `'` as the typographic apostrophe (U+2019),\n * so nothing the marketer typed disappears.\n */\nexport const quoted = (fallback: string): string =>\n !fallback.includes('\"') ? `\"${fallback}\"` : !fallback.includes(\"'\") ? `'${fallback}'` : `'${fallback.replace(/'/g, '\\u2019')}'`;\n\n/** A fallback is plain text: no Liquid in it, one line, at most 200 characters. */\nexport const isPlainFallback = (v: string): boolean => v.length <= 200 && !/\\{[{%]|[}%]\\}|[\\r\\n]/.test(v);\n\n/** The `| default:` value of ONE variable's Liquid (`{{ user.x | default: \"y\" }}`), or null. */\nexport function varFallback(src: string): string | null {\n const m = /^\\{\\{-?([\\s\\S]*?)-?\\}\\}$/.exec((src || '').trim());\n const d = m && DEFAULT_FILTER.exec(m[1].trim());\n return d ? unquote(d[1]) : null;\n}\n\n/** ONE variable's Liquid with `fallback` as its own `| default:` (an empty one removes it); its path is kept. */\nexport function setVarFallback(src: string, fallback: string): string {\n const m = /^\\{\\{-?\\s*([A-Za-z_][A-Za-z0-9_.]*)/.exec((src || '').trim());\n return m ? pathTag(m[1], fallback.trim() || null) : src;\n}\n\n/** The Liquid of one profile field: defaults are `user.<name>`, custom attributes `user.custom.<name>`. */\nexport const variableTag = (name: string, custom: boolean, fallback?: string | null): string => pathTag(custom ? `user.custom.${name}` : `user.${name}`, fallback);\n\n/** The Liquid of one variable by its path (`user.firstName`, the catalog's `key`). */\nexport const pathTag = (path: string, fallback?: string | null): string => (fallback ? `{{ ${path} | default: ${quoted(fallback)} }}` : `{{ ${path} }}`);\n\n/** A Liquid variable path: dotted identifiers (`user.custom.city`). */\nexport const VAR_PATH = /^[A-Za-z_][A-Za-z0-9_]{0,63}(\\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,4}$/;\n\n/** A variable the editor shows as a placeholder pill: its field name, and (in the text field) its exact Liquid. */\nexport interface LiquidVar {\n name: string;\n path: string;\n src: string;\n}\nexport type LiquidPart = string | LiquidVar;\n\nconst pathName = (path: string) => path.replace(/^user\\.(custom\\.)?/, '');\n\n/**\n * What the page shows while editing: each `{{ path ... }}` becomes the\n * sample value the dashboard sent for that path (its known visitor), else\n * the fallback (what an unknown visitor sees), else a placeholder pill with\n * the field name (`{ name }`), so an empty spot is still visible and never\n * mistaken for page text.\n */\nexport function previewParts(value: string, sample: Record<string, string>): LiquidPart[] {\n const out: LiquidPart[] = [];\n const re = new RegExp(OUTPUT_TAG.source, 'g');\n let last = 0;\n let m: RegExpExecArray | null;\n const text = (s: string) => {\n if (!s) return;\n if (typeof out[out.length - 1] === 'string') out[out.length - 1] += s;\n else out.push(s);\n };\n value = value || '';\n while ((m = re.exec(value))) {\n text(value.slice(last, m.index));\n last = re.lastIndex;\n const expr = m[1].trim();\n const path = expr.split('|')[0].trim();\n const d = DEFAULT_FILTER.exec(expr);\n if (Object.prototype.hasOwnProperty.call(sample, path) && sample[path] !== '') text(sample[path]);\n else if (d && unquote(d[1])) text(unquote(d[1]));\n else out.push({ name: pathName(path), path, src: m[0] });\n }\n text(value.slice(last));\n return out;\n}\n\n/** previewParts as plain text (a pill as `[name]`). */\nexport const previewText = (value: string, sample: Record<string, string>): string => previewParts(value, sample).map((p) => (typeof p === 'string' ? p : `[${p.name}]`)).join('');\n\n/** A variable path with at most a quoted `| default:` - what the text field shows as a pill. */\nconst SIMPLE_VAR = /^\\{\\{-?\\s*([A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*)\\s*(?:\\|\\s*default\\s*:\\s*(?:\"[^\"]*\"|'[^']*')\\s*)?-?\\}\\}$/;\n\n/**\n * The text field's view of a text: plain parts and variables (each with its\n * exact Liquid, so the text round-trips byte for byte), or null when it holds\n * Liquid a pill cannot show (a tag like `{% if %}`, a filter other than\n * `default`, a stray brace pair) - the field then stays raw text.\n */\nexport function liquidParts(value: string): LiquidPart[] | null {\n const out: LiquidPart[] = [];\n const re = new RegExp(OUTPUT_TAG.source, 'g');\n let last = 0;\n let m: RegExpExecArray | null;\n value = value || '';\n while ((m = re.exec(value))) {\n const v = SIMPLE_VAR.exec(m[0]);\n if (!v) return null;\n if (m.index > last) out.push(value.slice(last, m.index));\n out.push({ name: pathName(v[1]), path: v[1], src: m[0] });\n last = re.lastIndex;\n }\n if (last < value.length) out.push(value.slice(last));\n return out.some((p) => typeof p === 'string' && /\\{[{%]|[}%]\\}/.test(p)) ? null : out;\n}\n\n/** A slot name as a placement key: lowercase, anything else -> `_`, no leading/trailing `_`, at most 64. */\nexport function slugify(name: string): string {\n return (name || '')\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 64)\n .replace(/_+$/, '');\n}\n\n/** A new edit id, the dashboard's format (`e` + 8 base-36 characters). */\nexport const newEditId = (): string => `e${Math.random().toString(36).slice(2, 10).padEnd(8, '0')}`;\n\n/** The friendly name of an element, by tag (or the selector's last tag when the element is not on the page). */\nexport function kindKey(tagOrSelector: string, isSelector = false): EditorStringKey {\n let t = (tagOrSelector || '').toLowerCase();\n if (isSelector) {\n const parts = t.trim().split(/[\\s>+~]+/).filter(Boolean);\n const m = /^[a-z][a-z0-9]*/.exec(parts[parts.length - 1] || '');\n t = m ? m[0] : '';\n }\n if (/^h[1-6]$/.test(t)) return 'kHeading';\n if (/^(p|span|strong|em|small|label|blockquote|b|i)$/.test(t)) return 'kText';\n if (t === 'a') return 'kLink';\n if (t === 'button') return 'kButton';\n if (t === 'img' || t === 'picture') return 'kImage';\n if (/^(ul|ol|li)$/.test(t)) return 'kList';\n if (t === 'main') return 'kMain';\n if (t === 'header') return 'kHeader';\n if (t === 'footer') return 'kFooter';\n if (t === 'nav') return 'kNav';\n if (t === 'form') return 'kForm';\n if (/^(section|div|article|aside)$/.test(t)) return 'kSection';\n return 'kElement';\n}\n","/**\n * Building blocks of the editor's UI: an element helper that only ever sets\n * attributes and text (never HTML), the icons (fixed SVG paths), and the\n * stylesheet. Everything lives inside the editor's shadow root, so the\n * site's CSS cannot restyle it and this CSS cannot reach the site.\n *\n * Colours are the Joryio product tokens of the design handoff\n * (design_handoff_web_personalization, joryio-tokens.css): navy #071342,\n * teal #31D6C8 / #00A99A, slot lavender #7A6CFF, light panel like the app.\n */\n\ntype Kid = Node | string | null | undefined | false;\n\nexport function h<K extends keyof HTMLElementTagNameMap>(tag: K, attrs?: Record<string, string | boolean | undefined> | null, ...kids: Kid[]): HTMLElementTagNameMap[K] {\n const el = document.createElement(tag);\n for (const [k, v] of Object.entries(attrs || {})) {\n if (v === undefined || v === false) continue;\n el.setAttribute(k, v === true ? '' : v);\n }\n for (const kid of kids) if (kid !== null && kid !== undefined && kid !== false) el.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);\n return el;\n}\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\nconst ICONS = {\n text: ['M4 7V5h16v2M9 19h6M12 5v14'],\n link: ['M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71', 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'],\n image: ['M3 5h18v14H3z', 'm3 16 5-5 4 4 3-3 6 6', 'M15.5 8.5h.01'],\n hide: ['M9.88 9.88a3 3 0 1 0 4.24 4.24', 'M10.73 5.08A10.4 10.4 0 0 1 12 5c7 0 10 7 10 7a13.2 13.2 0 0 1-1.67 2.68', 'M6.61 6.61A13.5 13.5 0 0 0 2 12s3 7 10 7a9.7 9.7 0 0 0 5.39-1.61', 'm2 2 20 20'],\n slot: ['M3 3h18v18H3z', 'M7 9h10v6H7z'],\n undo: ['M3 7v6h6', 'M21 17a9 9 0 0 0-15-6.7L3 13'],\n up: ['m18 15-6-6-6 6'],\n down: ['m6 9 6 6 6-6'],\n cursor: ['m4 4 7.07 17 2.51-7.39L21 11.07z'],\n code: ['m16 18 6-6-6-6M8 6l-6 6 6 6'],\n chevron: ['m9 18 6-6-6-6'],\n check: ['M20 6 9 17l-5-5'],\n close: ['M18 6 6 18M6 6l12 12'],\n};\nexport type IconName = keyof typeof ICONS;\n\nexport function icon(name: IconName, size = 15): SVGSVGElement {\n const s = document.createElementNS(SVG_NS, 'svg');\n for (const [k, v] of Object.entries({ width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.9', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) s.setAttribute(k, v);\n for (const d of ICONS[name]) {\n const p = document.createElementNS(SVG_NS, 'path');\n p.setAttribute('d', d);\n s.appendChild(p);\n }\n return s as SVGSVGElement;\n}\n\n/** The host element's own inline style: nothing of the site's CSS reaches inside, and the host takes no room. */\nexport const HOST_STYLE = 'all:initial !important;position:fixed !important;top:0 !important;left:0 !important;width:0 !important;height:0 !important;z-index:2147483647 !important;display:block !important';\n\n/** A preview element the editor puts IN the page (a slot, a hidden-element note): its own shadow root too. */\nexport const PREVIEW_HOST_STYLE = 'all:initial !important;display:block !important;margin:10px 0 !important';\n\nconst FONT = 'Inter,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif';\nconst MONO = 'ui-monospace,\"SF Mono\",Menlo,monospace';\n\n/**\n * A variable with no sample value and no fallback, in the page preview: an\n * inline host that takes the site's font and line from the element it is in\n * (`all: unset`, so nothing else of the site's CSS applies) and is its own\n * bidi island, so it sits right in a right-to-left text too.\n */\nexport const PREVIEW_VAR_HOST_STYLE = 'all:unset !important;display:inline !important;unicode-bidi:isolate !important';\n\n/** The placeholder pill, the same in the page preview and in the text field: inline, never taller than the line. */\nconst PILL = `font-family:${MONO};font-size:.8em;font-weight:600;line-height:1;padding:.12em .5em;border-radius:999px;background:rgba(0,169,154,.14);color:#0F766E;box-shadow:inset 0 0 0 1px rgba(0,169,154,.5);white-space:nowrap;unicode-bidi:isolate;font-style:normal;text-transform:none;letter-spacing:0`;\n\nexport const PREVIEW_CSS = `.v{${PILL}}.s,.x{font:12.5px/1.4 ${FONT};border-radius:10px;padding:14px 16px;text-align:center}.s{border:2px dashed #7A6CFF;background:#F4F2FF;color:#4C3FD1}.s b{font-weight:700}.s code{font-family:${MONO}}.s div{font-size:11.5px;color:#6B5FD9;margin-top:3px}.x{border:1.5px dashed #F04438;background:#FEF3F2;color:#B42318;text-align:start;padding:10px 12px;font-size:12px}`;\n\nexport const EDITOR_CSS = `\n*{box-sizing:border-box}\n.r{font:13px/1.4 ${FONT};color:#242B3A;-webkit-font-smoothing:antialiased}\nbutton{font:inherit;color:inherit;cursor:pointer}\nbutton:disabled{cursor:not-allowed}\nbutton:focus-visible,input:focus-visible,textarea:focus-visible,.ce:focus{outline:2px solid #31D6C8;outline-offset:1px}\n.box{position:fixed;pointer-events:none;border:2px dashed #00A99A;background:rgba(0,169,154,.07);border-radius:4px;display:none}\n.box.sel{border-style:solid;background:rgba(0,169,154,.04)}\n.chip{position:absolute;bottom:100%;inset-inline-start:-2px;margin-bottom:2px;background:#00A99A;color:#fff;font-size:11px;font-weight:600;padding:3px 8px;border-radius:6px 6px 6px 0;white-space:nowrap;max-width:60vw;overflow:hidden;text-overflow:ellipsis}\n.help{position:fixed;top:16px;inset-inline-end:16px;width:240px;background:#fff;border:1px solid #E5EAF2;border-radius:10px;box-shadow:0 8px 24px rgba(10,18,64,.14);padding:10px 12px}\n.help h3{margin:0 0 6px;font-size:11px;font-weight:700;color:#6B7280;letter-spacing:.5px;text-transform:uppercase}\n.help .row{display:flex;align-items:center;gap:8px;font-size:12px;padding:3px 0}\n.kbd{min-width:38px;text-align:center;font-size:11px;font-weight:600;border:1px solid #E5EAF2;border-radius:5px;padding:1px 5px;background:#F8FAFC}\n.help .x{position:absolute;top:6px;inset-inline-end:6px;border:0;background:none;color:#8990A8;padding:2px;display:grid}\n.dock{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:6px;background:#071342;color:#fff;border-radius:14px;padding:7px 7px 7px 14px;box-shadow:0 12px 32px rgba(10,18,64,.35);white-space:nowrap;max-width:calc(100vw - 24px)}\n.r.open .dock{left:calc(50% - 190px)}\n.r.open[dir=rtl] .dock{left:calc(50% + 190px)}\n.logo{width:22px;height:22px;border-radius:6px;background:#fff;color:#071342;display:grid;place-items:center;font-weight:800;font-size:13px;flex:none}\n.name{font-size:12.5px;font-weight:600;margin-inline-start:4px;overflow:hidden;text-overflow:ellipsis;max-width:200px}\n.sub{font-size:12px;color:#A8AEC1;overflow:hidden;text-overflow:ellipsis;max-width:220px}\n.sep{width:1px;height:22px;background:#2A3366;margin:0 8px;flex:none}\n.hint{font-size:12px;color:#C9CEDD;display:inline-flex;align-items:center;gap:6px}\n.hint svg{color:#31D6C8}\n.db{display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 10px;border-radius:8px;border:0;background:#1B245A;color:#fff;font-size:12.5px;font-weight:600}\n.ib{height:32px;width:32px;border-radius:8px;border:0;background:transparent;color:#fff;display:grid;place-items:center}\n.ib:disabled{color:#4A527A}\n.go{height:32px;padding:0 14px;border-radius:8px;border:0;background:#31D6C8;color:#071342;font-size:12.5px;font-weight:700}\n.pop{position:absolute;bottom:calc(100% + 10px);left:0;right:0;min-width:280px;max-height:50vh;overflow:auto;background:#fff;color:#242B3A;border-radius:12px;border:1px solid #E5EAF2;box-shadow:0 12px 32px rgba(10,18,64,.18);padding:6px;white-space:normal}\n.pop .e{display:flex;align-items:center;gap:10px;width:100%;padding:8px 10px;border:0;background:none;border-radius:8px;font-size:12.5px;text-align:start}\n.pop .e:hover{background:#F8FAFC}\n.pop .empty{padding:12px;font-size:12.5px;color:#6B7280}\n.num{width:20px;height:20px;border-radius:99px;background:#071342;color:#fff;font-size:11px;font-weight:700;display:grid;place-items:center;flex:none}\n.panel{position:fixed;top:0;bottom:0;inset-inline-end:0;width:380px;max-width:100vw;background:#fff;border-inline-start:1px solid #E5EAF2;box-shadow:-8px 0 24px rgba(10,18,64,.06);display:flex;flex-direction:column}\n.hd{padding:16px 18px 14px;border-bottom:1px solid #E5EAF2}\n.crumbs{display:flex;align-items:center;flex-wrap:wrap;gap:4px;font-size:11.5px;color:#6B7280;margin-bottom:6px}\n.crumbs svg{color:#A8AEC1}\n.crumb{border:0;background:transparent;color:#6B7280;font-weight:500;font-size:11.5px;padding:2px 6px;border-radius:5px}\n.crumb.cur{background:#E5F9F6;color:#0F766E;font-weight:600}\n.nav{margin-inline-start:auto;display:flex;gap:2px}\n.nav button{border:1px solid #E5EAF2;background:#fff;border-radius:6px;width:24px;height:22px;display:grid;place-items:center;color:#3A4060;padding:0}\n.nav button:disabled{opacity:.4}\n.tr{display:flex;align-items:center;gap:10px}\n.title{font-size:17px;font-weight:700;color:#0A1240;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}\n.pill{margin-inline-start:auto;display:inline-flex;align-items:center;gap:4px;font-size:11.5px;font-weight:600;padding:3px 8px;border-radius:999px;white-space:nowrap;flex:none}\n.pill.ok{background:#E5F9F6;color:#0F766E}\n.pill.many{background:#FFF7E6;color:#92400E}\n.pill.none{background:#FEF3F2;color:#B42318}\n.bd{padding:16px 18px;overflow:auto;flex:1}\n.lbl{display:block;font-size:12.5px;font-weight:600;color:#242B3A;margin-bottom:8px}\n.tiles{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:18px}\n.tile{display:flex;align-items:center;gap:9px;padding:10px 11px;border-radius:10px;text-align:start;background:#fff;border:1.5px solid #E5EAF2;color:#3A4060}\n.tile[aria-checked=true]{background:#E5F9F6;border-color:#00C8B7;color:#0F766E}\n.tile.slot[aria-checked=true]{background:#F4F2FF;border-color:#7A6CFF;color:#4C3FD1}\n.tile:disabled{opacity:.55}\n.tile[data-e]>span::after{content:'';display:inline-block;width:6px;height:6px;border-radius:9px;background:#00A99A;margin-inline-start:6px;vertical-align:middle}\n.tile b{display:block;font-size:12.5px;font-weight:600;color:#0A1240}\n.tile small{display:block;font-size:10.5px;color:#6B7280}\n.fr{display:flex;align-items:baseline;margin-bottom:8px}\n.fr .lbl{margin:0}\n.was{margin-inline-start:auto;font-size:11.5px;color:#6B7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:55%}\ntextarea,input,.ce{width:100%;font:inherit;font-size:13.5px;color:#0F1424;padding:10px 12px;border-radius:10px;border:1.5px solid #E5EAF2;background:#fff;outline:none}\ntextarea,.ce{line-height:1.5;resize:vertical;border-color:#00C8B7}\n.ce{min-height:72px;white-space:pre-wrap;overflow-wrap:anywhere;cursor:text}\n.vp{${PILL};cursor:pointer}\n.vp .vfb{font-weight:400;opacity:.75}\n.fbp .vc{margin-top:8px}\n.slotc{display:flex;flex-direction:column;align-items:flex-start;gap:6px}\n.slotc .lbl{margin:0}\n.lnk{border:0;background:none;padding:0;color:#4C3FD1;font-size:12.5px;font-weight:600;text-align:start}\ntextarea.mono{height:auto}\ninput{height:40px;padding:0 12px}\ninput.slotin{border-color:#7A6CFF}\n.mono{font-family:${MONO};font-size:12px;height:36px;background:#F8FAFC;border-width:1px}\n.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px;align-items:center}\n.chips span{font-size:11.5px;color:#6B7280;margin-inline-end:2px}\n.vc{font-family:${MONO};font-size:11.5px;padding:3px 8px;border-radius:6px;border:1px solid #E5EAF2;background:#F8FAFC;color:#3A4060}\n.pk{margin-top:8px;border:1px solid #E5EAF2;border-radius:10px;padding:6px;background:#fff;box-shadow:0 8px 24px rgba(10,18,64,.1)}\n.pk input{height:34px}\n.pk [role=listbox]{max-height:220px;overflow:auto;margin-top:4px}\n.pk .g{font-size:10.5px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:.4px;padding:8px 8px 3px}\n.pk .o{display:flex;justify-content:space-between;align-items:baseline;gap:8px;padding:6px 8px;border-radius:7px;font-size:12.5px;cursor:pointer}\n.pk .o[aria-selected=true],.pk .o:hover{background:#E5F9F6}\n.pk code{font-family:${MONO};font-size:11px;color:#6B7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n[hidden]{display:none!important}\n.help2{font-size:11.5px;color:#6B7280;margin-top:5px}\n.err{font-size:11.5px;color:#B42318;margin-top:5px}\n.mt{margin-top:14px}\n.note{background:#FFF7E6;border:1px solid #FCD34D;border-radius:10px;padding:10px 12px;font-size:12.5px;color:#92400E;line-height:1.5}\n.key{font-family:${MONO};color:#4C3FD1;background:#F4F2FF;padding:1px 6px;border-radius:4px}\n.seg{display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;background:#F3F5FA;border-radius:9px;padding:3px}\n.seg button{border:0;background:transparent;border-radius:7px;padding:6px 4px;font-size:12px;color:#3A4060}\n.seg button[aria-checked=true]{background:#fff;color:#0A1240;font-weight:600;box-shadow:0 1px 2px rgba(10,18,64,.08)}\n.css{margin-top:20px;display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;padding:0;color:#6B7280;font-size:12px}\n.ft{padding:12px 18px;border-top:1px solid #E5EAF2;display:flex;gap:10px;background:#F8FAFC}\n.cancel{height:38px;padding:0 14px;border-radius:10px;border:1px solid #E5EAF2;background:#fff;color:#242B3A;font-size:13px;font-weight:600}\n.save{flex:1;height:38px;border-radius:10px;border:0;background:#071342;color:#fff;font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.save:disabled{opacity:.45}\n@media (max-width:760px){.r.open .dock{display:none}.help{display:none}}\n`;\n","/**\n * The \"New text\" field: the text with its variables as placeholder pills\n * (the same pill as the page preview), the stored value unchanged Liquid.\n *\n * - Pill mode (the text has only plain text, `{{ user.x }}` and\n * `| default: \"...\"`): a contenteditable box; each variable is an atomic\n * `contenteditable=false` pill carrying its exact Liquid, so the value\n * round-trips byte for byte. Backspace / Delete next to a pill removes the\n * whole pill, arrow keys step over it (the browser's own handling of a\n * non-editable inline), copy and cut put the Liquid on the clipboard, paste\n * is plain text only (Liquid in it becomes pills). Enter is ignored - a\n * page text edit is one run of text.\n * - Raw mode (anything a pill cannot show: `{% if %}`, other filters): a\n * textarea with the Liquid and a short note, so nothing is lost.\n *\n * - Each pill has its own fallback: a click on it (or Enter / Space on it)\n * opens a small popover, \"If <field> is missing\" + one input, that writes\n * `| default: \"...\"` on THAT variable only. A pill with a fallback shows it\n * after its name (\"firstName · friend\"). The fallback is plain text - Liquid\n * in it is refused. Esc, Enter or Done closes the popover.\n *\n * Inside the editor's closed shadow root the caret comes from the root's\n * own getSelection() where the browser has it (Chromium), else the\n * document's; with no caret in the box an Insert appends, as before.\n */\nimport { isPlainFallback, liquidParts, setVarFallback, varFallback, type LiquidVar } from './editor-model';\nimport { fill } from './editor-strings';\nimport { h } from './editor-ui';\n\nexport interface LiquidField {\n el: HTMLElement;\n /** Show a value (re-renders; the mode follows the value). */\n set(value: string): void;\n /** Insert one variable's Liquid at the caret (or at the end). */\n insert(tag: string): void;\n /** Close a pill's fallback popover; true when one was open. */\n closePop(): boolean;\n}\n\n/** The words of a pill's fallback popover: `title` has `{name}`, the field's label. */\nexport interface FallbackWords {\n title: string;\n help: string;\n bad: string;\n done: string;\n}\n\nconst PILL_ATTR = 'data-liquid';\nconst isPill = (n: Node | null | undefined): n is HTMLElement => !!n && n.nodeType === 1 && (n as Element).hasAttribute(PILL_ATTR);\n\n/** A box's content as Liquid: text as is, a pill as its Liquid, a browser-inserted `<br>` as nothing. */\nexport function serialize(n: Node): string {\n if (n.nodeType === 3) return (n as Text).data;\n if (isPill(n)) return n.getAttribute(PILL_ATTR) || '';\n let s = '';\n for (const k of Array.from(n.childNodes)) s += serialize(k);\n return s;\n}\n\nexport function liquidField(opts: {\n label: string;\n rawNote: string;\n root: ShadowRoot | null;\n onChange: (value: string) => void;\n labelOf?: (path: string) => string | undefined;\n fallback?: FallbackWords;\n}): LiquidField {\n const el = h('div', { 'data-j': 'text-box' });\n let value = '';\n let box: HTMLElement | null = null;\n let saved: Range | null = null;\n let pop: HTMLElement | null = null;\n\n const selection = (): Selection | null => {\n const r = opts.root as unknown as { getSelection?: () => Selection | null } | null;\n return (r && typeof r.getSelection === 'function' ? r.getSelection() : null) || document.getSelection();\n };\n /** The selection as a Range in the box: Chromium's root.getSelection(), else getComposedRanges (Safari, Firefox), else the plain range. */\n const caret = (): Range | null => {\n const s = selection();\n if (!s || !s.rangeCount) return null;\n let r: Range | null = s.getRangeAt(0);\n const composed = (s as unknown as { getComposedRanges?: (o: unknown) => StaticRange[] }).getComposedRanges;\n if (opts.root && composed && !(box && box.contains(r.startContainer))) {\n try {\n const sr = composed.call(s, { shadowRoots: [opts.root] })[0];\n r = document.createRange();\n r.setStart(sr.startContainer, sr.startOffset);\n r.setEnd(sr.endContainer, sr.endOffset);\n } catch {\n r = null;\n }\n }\n return box && r && box.contains(r.startContainer) && box.contains(r.endContainer) ? r : null;\n };\n const remember = () => {\n const r = caret();\n if (r) saved = r.cloneRange();\n };\n const emit = () => {\n if (box && box.tagName === 'DIV') value = serialize(box);\n remember();\n opts.onChange(value);\n };\n const putCaret = (r: Range) => {\n const s = selection();\n try {\n if (s && s.setBaseAndExtent) s.setBaseAndExtent(r.startContainer, r.startOffset, r.endContainer, r.endOffset);\n else if (s) {\n s.removeAllRanges();\n s.addRange(r);\n }\n } catch {\n /* no selection here */\n }\n saved = r.cloneRange();\n };\n const labelOf = (v: LiquidVar) => (opts.labelOf && opts.labelOf(v.path)) || v.name;\n const pill = (v: LiquidVar) => {\n const fb = varFallback(v.src);\n const label = labelOf(v);\n const words = opts.fallback;\n return h(\n 'span',\n {\n class: 'vp',\n contenteditable: 'false',\n dir: 'auto',\n title: v.src,\n [PILL_ATTR]: v.src,\n 'data-path': v.path,\n ...(words ? { role: 'button', tabindex: '0', 'aria-haspopup': 'dialog', 'aria-label': fb ? `${label} · ${fb}` : label } : {}),\n },\n label,\n fb ? h('span', { class: 'vfb', 'data-j': 'pill-fallback' }, ` · ${fb}`) : null,\n );\n };\n\n const closePop = (): boolean => {\n if (!pop) return false;\n pop.remove();\n pop = null;\n return true;\n };\n /** A pill's own fallback: the popover under the field, writing that pill's `| default:` as it is typed. */\n const openPop = (target: HTMLElement) => {\n const words = opts.fallback;\n if (!words || !box || box.tagName !== 'DIV') return;\n closePop();\n let cur = target;\n const v = { path: cur.getAttribute('data-path') || '', name: '', src: cur.getAttribute(PILL_ATTR) || '' };\n v.name = v.path.replace(/^user\\.(custom\\.)?/, '');\n const title = fill(words.title, { name: labelOf(v) });\n const input = h('input', { dir: 'auto', 'data-j': 'fallback', 'aria-label': title, maxlength: '200' });\n input.value = varFallback(v.src) || '';\n const err = h('div', { class: 'err', 'data-j': 'fallback-error', role: 'alert' });\n const done = h('button', { class: 'vc', type: 'button', 'data-j': 'fallback-done' }, words.done);\n const p = h('div', { class: 'pk fbp', role: 'dialog', 'aria-label': title, 'data-j': 'fallback-pop' }, h('label', { class: 'lbl' }, title), input, err, h('div', { class: 'help2' }, words.help), done);\n const finish = () => {\n closePop();\n try {\n cur.focus();\n } catch {\n /* gone */\n }\n };\n input.addEventListener('input', () => {\n const ok = isPlainFallback(input.value);\n err.textContent = ok ? '' : words.bad;\n if (!ok) return;\n const src = setVarFallback(cur.getAttribute(PILL_ATTR) || '', input.value);\n const next = pill({ ...v, src });\n if (cur.parentNode) cur.parentNode.replaceChild(next, cur);\n cur = next;\n if (box && box.tagName === 'DIV') value = serialize(box);\n opts.onChange(value);\n });\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' || e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n finish();\n }\n });\n done.addEventListener('click', finish);\n pop = p;\n el.appendChild(p);\n input.focus();\n };\n\n const set = (v: string) => {\n value = v;\n saved = null;\n pop = null;\n el.textContent = '';\n const parts = liquidParts(v);\n if (!parts) {\n const area = h('textarea', { rows: '3', dir: 'auto', 'data-j': 'text', 'aria-label': opts.label });\n area.value = v;\n area.addEventListener('input', () => {\n value = area.value;\n opts.onChange(value);\n });\n area.addEventListener('blur', () => liquidParts(value) && set(value));\n box = area;\n el.append(area, h('div', { class: 'help2', 'data-j': 'raw-note' }, opts.rawNote));\n return;\n }\n const ce = h('div', { class: 'ce', contenteditable: 'true', role: 'textbox', 'aria-multiline': 'true', dir: 'auto', spellcheck: 'false', 'data-j': 'text', 'aria-label': opts.label });\n for (const p of parts) ce.append(typeof p === 'string' ? document.createTextNode(p) : pill(p));\n ce.addEventListener('input', emit);\n ce.addEventListener('keyup', remember);\n ce.addEventListener('mouseup', remember);\n ce.addEventListener('click', (e) => {\n const t = e.target instanceof Element ? (e.target.closest(`[${PILL_ATTR}]`) as HTMLElement | null) : null;\n if (t && ce.contains(t)) openPop(t);\n });\n ce.addEventListener('keydown', (e) => {\n const onPill = e.target instanceof Element && isPill(e.target) ? (e.target as HTMLElement) : null;\n if (onPill && (e.key === 'Enter' || e.key === ' ')) {\n e.preventDefault();\n return openPop(onPill);\n }\n if (e.key === 'Enter') return e.preventDefault();\n if (e.key !== 'Backspace' && e.key !== 'Delete') return;\n const r = caret();\n if (!r || !r.collapsed) return;\n const back = e.key === 'Backspace';\n const c = r.startContainer;\n const o = r.startOffset;\n let next: Node | null = null;\n if (c.nodeType === 3) {\n if (back && o === 0) next = c.previousSibling;\n else if (!back && o === (c as Text).length) next = c.nextSibling;\n } else next = c.childNodes[back ? o - 1 : o] || null;\n if (!isPill(next)) return;\n e.preventDefault();\n next.remove();\n emit();\n });\n const clip = (cut: boolean) => (e: ClipboardEvent) => {\n const r = caret();\n if (!r || r.collapsed || !e.clipboardData) return;\n e.preventDefault();\n e.clipboardData.setData('text/plain', serialize(r.cloneContents()));\n if (cut) {\n r.deleteContents();\n emit();\n }\n };\n ce.addEventListener('copy', clip(false));\n ce.addEventListener('cut', clip(true));\n ce.addEventListener('paste', (e) => {\n e.preventDefault();\n const text = ((e.clipboardData && e.clipboardData.getData('text/plain')) || '').replace(/\\r/g, '');\n const r = caret();\n if (!text || !r) return;\n r.deleteContents();\n const t = document.createTextNode(text);\n r.insertNode(t);\n r.setStartAfter(t);\n r.collapse(true);\n putCaret(r);\n emit();\n if (/\\{[{%]/.test(text)) set(value);\n });\n // Liquid typed by hand becomes pills (or the raw box) once the field is left.\n ce.addEventListener('blur', () => Array.from(ce.childNodes).some((n) => n.nodeType === 3 && /\\{[{%]/.test((n as Text).data)) && set(value));\n box = ce;\n el.appendChild(ce);\n };\n\n const insert = (tag: string) => {\n const live = caret();\n const r = live || (saved && box && box.isConnected && box.contains(saved.startContainer) ? saved : null);\n if (!r || !box || box.tagName !== 'DIV') {\n set(value ? `${value.replace(/\\s+$/, '')} ${tag}` : tag);\n return opts.onChange(value);\n }\n const parts = liquidParts(tag);\n const v = parts && parts[0];\n if (!v || typeof v === 'string') return;\n box.focus();\n r.deleteContents();\n const before = document.createRange();\n before.selectNodeContents(box);\n before.setEnd(r.startContainer, r.startOffset);\n const prev = serialize(before.cloneContents());\n const frag = document.createDocumentFragment();\n if (prev && !/\\s$/.test(prev)) frag.appendChild(document.createTextNode(' '));\n const p = pill(v);\n frag.appendChild(p);\n r.insertNode(frag);\n r.setStartAfter(p);\n r.collapse(true);\n putCaret(r);\n emit();\n };\n\n return { el, set, insert, closePop };\n}\n","/**\n * The on-site Web personalization editor (BACKLOG D444 Phase 4,\n * docs/PLACEMENTS_WEBSITE_LAYER.md 3) - the body of `joryio-editor.min.js`.\n * Design: design_handoff_web_personalization, screens 1-3 (1.4.0-beta.6).\n *\n * The handshake lives in the core bundle (src/core/editor-gate.ts): this\n * file is loaded, and this class constructed, only once the server vouched\n * for the editor token, with the dashboard origin the token names. From then\n * on it accepts messages only from that origin and that opener window, and\n * posts only to them.\n *\n * What it does on the page:\n * - All of its UI is in ONE shadow root (a closed one, on a host with\n * `all: initial`): the site's CSS cannot restyle it, its CSS cannot reach\n * the site. The previews it puts in the page (a content slot, a \"hidden for\n * this audience\" note) are custom elements with their own shadow roots,\n * never a `div`, so they do not shift the site's `:nth-of-type` selectors.\n * - Hover shows a dashed outline with a label (\"Heading · h1\"); a click\n * selects (the click never reaches the site); arrow up / down or the\n * buttons and the breadcrumb (\"Page › Main › Heading\") move to the element\n * around it or the first one inside it.\n * - A light side panel: the element, how many elements its selector matches,\n * \"What do you want to do?\" (Change text, Change link, Change image, Hide\n * it, Add content slot), ONE field set per action, a collapsible CSS\n * selector, Cancel / Save. The New text field shows variables as the\n * same pills (liquid-field.ts) and stores unchanged Liquid. Selecting an\n * element that already has an edit opens that edit.\n * - Every edit shows live on the page while editing (the draft too); the\n * text with the dashboard's sample values for its variables, else their\n * fallbacks, else a placeholder pill with the field name (a custom element\n * with its own shadow root, never page text). Text is set with textContent, addresses must be http(s), the\n * original nodes come back on undo - nothing is ever parsed as HTML.\n * - A dock: campaign · variant · page, the hint, \"N edits\" (a click jumps to\n * that edit), Undo, \"Save & return to Joryio\".\n *\n * Messages (constants: EDITOR_MESSAGES in the core, EDITOR_SESSION_MESSAGES\n * here; the dashboard's copy is packages/frontend/src/lib/web-experience.ts):\n *\n * editor -> dashboard\n * joryio:editor-active { url } the editor is up\n * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, tag, text }\n * a saved edit; `id` is the edit's id - an id the\n * dashboard already has REPLACES that edit\n * joryio:editor-remove { id } undo of a new edit\n * joryio:editor-done {} \"Save & return to Joryio\"\n * joryio:editor-open-slot { placementKey, campaignId? }\n * \"Create content for this slot\" (no campaignId) or\n * a campaign of the slot (its id): the dashboard\n * opens that campaign, or a new Placement campaign\n * for the slot; sent only to a dashboard that set\n * `openSlot` in its context\n * joryio:editor-closed {} the editor stopped\n *\n * dashboard -> editor\n * joryio:editor-context { campaignName?, variantName?, edits?, focusId?,\n * attributes?: [{ key, label?, group? } | { name, custom? }],\n * placements?: [{ key, name?, campaigns?: [{ id, name, status, statusLabel? }] }],\n * openSlot?: true,\n * sample?: { \"user.firstName\": \"Lior\", ... },\n * strings?: { <EDITOR_STRINGS key>: text }, dir?: 'ltr' | 'rtl' }\n * the variant's edits (shown live and in \"N edits\"),\n * the words in the marketer's language; enables Undo.\n * `campaigns` per placement (1.4.0-beta.7): the\n * campaigns that fill that slot, shown on a saved\n * slot edit (\"In this slot: ...\"); `openSlot`: the\n * dashboard handles joryio:editor-open-slot. An\n * editor before beta.7 ignores both.\n * joryio:editor-focus { id } jump to that edit\n * joryio:editor-close {} stop\n *\n * A dashboard that sends no context still works as before this redesign:\n * every save is a pick, the dock counts this session's edits, and Undo stays\n * off (that dashboard would not hear a remove).\n */\nimport type { Logger } from '../utils/logger';\nimport { isSafeSelector, isSafeEditUrl, trustedEdit, type PageEditOperation, type PageEditPosition, type PageEditWire } from '../core/page-edits';\nimport { EDITOR_MESSAGES } from '../core/editor-gate';\nimport { EDITOR_STRINGS, fill, mergeStrings, type EditorStringKey, type EditorStrings } from './editor-strings';\nimport { VAR_PATH, kindKey, newEditId, pathTag, previewParts, slugify } from './editor-model';\nimport { EDITOR_CSS, HOST_STYLE, PREVIEW_CSS, PREVIEW_HOST_STYLE, PREVIEW_VAR_HOST_STYLE, h, icon, type IconName } from './editor-ui';\nimport { liquidField } from './liquid-field';\n\nexport { EDITOR_MESSAGES };\n\nexport const EDITOR_SESSION_MESSAGES = {\n CONTEXT: 'joryio:editor-context',\n FOCUS: 'joryio:editor-focus',\n REMOVE: 'joryio:editor-remove',\n DONE: 'joryio:editor-done',\n OPEN_SLOT: 'joryio:editor-open-slot',\n} as const;\n\n/** Attributes that name an element on purpose, most stable first. */\nconst NAMING_ATTRIBUTES = ['data-joryio-id', 'data-testid', 'data-test', 'data-qa', 'data-cy', 'data-id', 'name'];\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\nconst ATTRIBUTE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;\nconst MAX_TEXT = 2000;\nconst MAX_EDITS = 100;\nconst PREVIEW_TAG = 'joryio-editor-preview';\nconst OURS = '[data-joryio-editor]';\nconst HELP_DISMISSED_KEY = 'jry_editor_help_dismissed';\n\n/** CSS.escape, for browsers (and test DOMs) without it. */\nexport function cssEscape(value: string): string {\n const css = (globalThis as any).CSS;\n if (css && typeof css.escape === 'function') return css.escape(value);\n let out = '';\n for (let i = 0; i < value.length; i++) {\n const ch = value[i];\n const code = value.charCodeAt(i);\n if (code === 0) out += '\\uFFFD';\n else if (/[0-9]/.test(ch) && (i === 0 || (i === 1 && value[0] === '-'))) out += `\\\\${code.toString(16)} `;\n else if (/[A-Za-z0-9_-]/.test(ch) || code >= 0x80) out += ch;\n else out += `\\\\${ch}`;\n }\n return out;\n}\n\nconst isOurs = (el: Element | null): boolean => !!el && !!el.closest(OURS);\nconst VAR_PILL = 'var';\n\n/** The page element an event on the page is about: a variable pill in the preview stands for the element it is in. */\nfunction pageTarget(t: EventTarget | null): Element | null {\n let el = t instanceof Element ? t : null;\n if (el && el.getAttribute('data-joryio-editor') === VAR_PILL) el = el.parentElement;\n return el && !isOurs(el) && el !== document.body && el !== document.documentElement ? el : null;\n}\n\n/** The page's elements a selector finds - never the editor's own. */\nfunction pageMatches(selector: string): Element[] {\n if (!isSafeSelector(selector)) return [];\n try {\n return Array.from(document.querySelectorAll(selector)).filter((e) => !isOurs(e));\n } catch {\n return [];\n }\n}\n\nconst unique = (doc: Document, selector: string, el: Element): boolean => {\n try {\n const hits = Array.from(doc.querySelectorAll(selector)).filter((e) => !isOurs(e));\n return hits.length === 1 && hits[0] === el;\n } catch {\n return false;\n }\n};\n\n/** An id that looks generated (long digit runs, framework hashes) changes between builds; skip it. */\nconst stableId = (id: string) => !!id && id.length <= 64 && !/\\d{4,}/.test(id) && !/^(ember|react|radix|headlessui|mui)[-_:]/i.test(id) && !/:/.test(id);\n\n/**\n * A selector that finds this element and only it, preferring what the site\n * named on purpose: an id, then a naming data attribute, then a path of\n * tag + nth-of-type from the nearest named ancestor (or the body).\n */\nexport function robustSelector(el: Element): string | null {\n const doc = el.ownerDocument;\n if (!doc) return null;\n const named = (node: Element): string | null => {\n if (stableId(node.id)) {\n const s = `#${cssEscape(node.id)}`;\n if (unique(doc, s, node)) return s;\n }\n for (const attr of NAMING_ATTRIBUTES) {\n const v = node.getAttribute(attr);\n if (!v || v.length > 100) continue;\n const s = `${node.tagName.toLowerCase()}[${attr}=\"${v.replace(/[\"\\\\]/g, '\\\\$&')}\"]`;\n if (unique(doc, s, node)) return s;\n }\n return null;\n };\n const own = named(el);\n if (own) return isSafeSelector(own) ? own : null;\n const parts: string[] = [];\n let node: Element | null = el;\n while (node && node !== doc.body && node !== doc.documentElement) {\n const anchor = parts.length ? named(node) : null;\n if (anchor) {\n parts.unshift(anchor);\n break;\n }\n const tag = node.tagName.toLowerCase();\n const parent: Element | null = node.parentElement;\n const same = parent ? Array.from(parent.children).filter((c) => c.tagName === node!.tagName) : [];\n parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(node) + 1})` : tag);\n node = parent;\n if (node === doc.body) parts.unshift('body');\n }\n const selector = parts.join(' > ');\n return selector && isSafeSelector(selector) && unique(doc, selector, el) ? selector : null;\n}\n\n/** The operations that fit an element: an image can change its picture, a link its address. */\nexport function operationsFor(el: Element): PageEditOperation[] {\n const ops: PageEditOperation[] = [];\n if (el.tagName !== 'IMG' && (el.textContent || '').trim()) ops.push('replace_text');\n if (el.tagName === 'IMG') ops.push('replace_image');\n if (el.tagName === 'A') ops.push('replace_link');\n ops.push('hide', 'insert_placement');\n return ops;\n}\n\nexport interface EditorPick {\n type: typeof EDITOR_MESSAGES.PICK;\n /** The edit's id: new edits get a fresh one, an edit opened from the list keeps its own. */\n id: string;\n selector: string;\n operation: PageEditOperation;\n value?: string;\n placementKey?: string;\n position?: PageEditPosition;\n tag: string;\n text: string;\n}\n\ntype Action = 'text' | 'link' | 'image' | 'hide' | 'slot';\nconst ACTIONS: Action[] = ['text', 'link', 'image', 'hide', 'slot'];\nconst OPERATION_OF: Record<Action, PageEditOperation> = { text: 'replace_text', link: 'replace_link', image: 'replace_image', hide: 'hide', slot: 'insert_placement' };\nconst ACTION_OF: Record<PageEditOperation, Action> = { replace_text: 'text', replace_link: 'link', replace_image: 'image', hide: 'hide', insert_placement: 'slot' };\nconst ACTION_LABEL: Record<Action, EditorStringKey> = { text: 'actText', link: 'actLink', image: 'actImage', hide: 'actHide', slot: 'actSlot' };\nconst ACTION_ICON: Record<Action, IconName> = { text: 'text', link: 'link', image: 'image', hide: 'hide', slot: 'slot' };\nconst POSITIONS: Array<[PageEditPosition, EditorStringKey]> = [\n ['before', 'posBefore'],\n ['after', 'posAfter'],\n ['replace', 'posReplace'],\n ['prepend', 'posPrepend'],\n ['append', 'posAppend'],\n];\n\ninterface Draft {\n action: Action;\n text: string;\n url: string;\n slotName: string;\n position: PageEditPosition;\n selector: string;\n /** The edit being changed (opened from the list or the dashboard), null for a new one. */\n editingId: string | null;\n /** A new draft shows on the page only once something was changed (its untouched text would flatten the element's markup). */\n touched: boolean;\n}\n\ninterface Var {\n path: string;\n label: string;\n group: string;\n}\n\n/** The chips shown before \"More…\": these when the catalog has them, else its first ones. */\nconst COMMON_VARS = ['user.firstName', 'user.lastName', 'user.email', 'user.custom.city'];\nconst CHIPS = 4;\n\ninterface EditorContext {\n campaignName: string;\n variantName: string;\n /** The personalization catalog: Liquid path, label, group ('' for the old `{ name, custom }` shape). */\n attributes: Var[];\n placements: Array<{ key: string; name: string; campaigns: SlotCampaign[] }>;\n sample: Record<string, string>;\n /** The dashboard handles joryio:editor-open-slot: the slot's campaigns and \"Create content for this slot\" show. */\n openSlot: boolean;\n}\n\n/** A campaign that fills a slot, as the dashboard sent it. */\ninterface SlotCampaign {\n id: string;\n name: string;\n /** The wire status (`draft`, `active`, ...), and the dashboard's word for it. */\n status: string;\n statusLabel: string;\n}\nconst CAMPAIGN_ID = /^[A-Za-z0-9_-]{1,64}$/;\n\nconst clip = (v: unknown, n: number): string => (typeof v === 'string' ? v.trim().slice(0, n) : '');\nconst shortText = (el: Element | null): string => ((el && el.textContent) || '').replace(/\\s+/g, ' ').trim();\n\nexport class VisualEditor {\n private listeners: Array<() => void> = [];\n private active = false;\n private host: HTMLElement | null = null;\n /** Kept for tests: the shadow root is closed to the page. */\n root: ShadowRoot | null = null;\n private wrap: HTMLElement | null = null;\n private hoverBox: HTMLElement | null = null;\n private selBox: HTMLElement | null = null;\n private dock: HTMLElement | null = null;\n private panel: HTMLElement | null = null;\n private help: HTMLElement | null = null;\n private hovered: Element | null = null;\n private selected: Element | null = null;\n private draft: Draft | null = null;\n private showCss = false;\n private showLiquid = false;\n /** Closes an open overlay of the panel (the variable picker) on Esc; true when it closed one. */\n private closeOverlay: (() => boolean) | null = null;\n private popOpen = false;\n private edits: PageEditWire[] = [];\n private history: Array<{ id: string; before: PageEditWire | null }> = [];\n /** The dashboard sent a context: it understands remove (Undo) and replace-by-id. */\n private synced = false;\n private t: EditorStrings = { ...EDITOR_STRINGS };\n private dir: 'ltr' | 'rtl' = 'ltr';\n private ctx: EditorContext = { campaignName: '', variantName: '', attributes: [], placements: [], sample: {}, openSlot: false };\n private previewUndo: Array<() => void> = [];\n /** The page's own text / address of an element before any preview, for \"Was:\". */\n private originals = new WeakMap<Element, { text: string; href: string | null; src: string | null }>();\n\n constructor(\n private dashboardOrigin: string,\n private opener: Window,\n private logger: Logger,\n private onStop: () => void = () => undefined,\n ) {}\n\n /** The token was vouched for by the server: show the editor. */\n start(): void {\n if (this.active) return;\n this.active = true;\n const onMessage = (e: MessageEvent) => {\n const data = e.data as { type?: string } | null;\n if (!data || typeof data.type !== 'string') return;\n if (e.origin !== this.dashboardOrigin || e.source !== this.opener) return;\n if (data.type === EDITOR_MESSAGES.CLOSE) this.stop();\n else if (data.type === EDITOR_SESSION_MESSAGES.CONTEXT) this.applyContext(data as Record<string, unknown>);\n else if (data.type === EDITOR_SESSION_MESSAGES.FOCUS) this.focusEdit((data as { id?: unknown }).id);\n };\n window.addEventListener('message', onMessage);\n this.listeners.push(() => window.removeEventListener('message', onMessage));\n this.activate();\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n /** The edits this editor knows of (the dashboard's, then this session's), in order. */\n editList(): PageEditWire[] {\n return this.edits.slice();\n }\n\n stop(): void {\n if (!this.active) return;\n this.send({ type: EDITOR_MESSAGES.CLOSED });\n this.active = false;\n for (const off of this.listeners.splice(0)) off();\n this.clearPreview();\n this.host?.remove();\n this.host = this.root = this.wrap = this.hoverBox = this.selBox = this.dock = this.panel = this.help = null;\n this.selected = this.hovered = null;\n this.draft = null;\n try {\n this.onStop();\n } catch (error) {\n this.logger.debug('Joryio editor stop callback failed', error);\n }\n }\n\n private send(message: Record<string, unknown>): void {\n if (!this.active) return;\n try {\n this.opener.postMessage(message, this.dashboardOrigin);\n } catch {\n /* the dashboard tab closed */\n }\n }\n\n // ── setup ────────────────────────────────────────────────────────────────\n\n private activate(): void {\n const doc = document;\n const host = doc.createElement('joryio-editor');\n host.setAttribute('data-joryio-editor', 'root');\n host.setAttribute('style', HOST_STYLE);\n const root = host.attachShadow({ mode: 'closed' });\n root.appendChild(h('style', null, EDITOR_CSS));\n const wrap = h('div', { class: 'r', dir: this.dir });\n this.hoverBox = h('div', { class: 'box', 'data-j': 'hover' });\n this.selBox = h('div', { class: 'box sel', 'data-j': 'selected' });\n wrap.append(this.hoverBox, this.selBox);\n root.appendChild(wrap);\n doc.documentElement.appendChild(host);\n this.host = host;\n this.root = root;\n this.wrap = wrap;\n\n const onMove = (e: MouseEvent) => {\n const t = e.target instanceof Element ? e.target : null;\n if (isOurs(t) && t!.getAttribute('data-joryio-editor') !== VAR_PILL) return;\n this.hovered = pageTarget(t);\n this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);\n };\n const onClick = (e: MouseEvent) => {\n if (e.target instanceof Element && e.target.closest('[data-joryio-editor=\"root\"]')) return;\n // A click on the page - a preview of ours included - never reaches the site.\n e.preventDefault();\n e.stopPropagation();\n const el = pageTarget(e.target);\n if (el) this.select(el);\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n if (this.closeOverlay && this.closeOverlay()) return;\n if (this.popOpen) this.togglePop(false);\n else if (this.panel) this.cancel();\n else this.stop();\n return;\n }\n if (isOurs(e.target instanceof Element ? e.target : null)) return; // typing in the panel\n if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {\n const from = this.selected || this.hovered;\n if (!from) return;\n e.preventDefault();\n e.stopPropagation();\n this.move(e.key === 'ArrowUp' ? 'up' : 'down', from);\n }\n };\n const onScroll = () => {\n this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);\n this.place(this.selBox, this.selected);\n };\n doc.addEventListener('mousemove', onMove, true);\n doc.addEventListener('click', onClick, true);\n doc.addEventListener('keydown', onKey, true);\n window.addEventListener('scroll', onScroll, true);\n window.addEventListener('resize', onScroll);\n this.listeners.push(\n () => doc.removeEventListener('mousemove', onMove, true),\n () => doc.removeEventListener('click', onClick, true),\n () => doc.removeEventListener('keydown', onKey, true),\n () => window.removeEventListener('scroll', onScroll, true),\n () => window.removeEventListener('resize', onScroll),\n );\n this.renderDock();\n this.renderHelp();\n this.send({ type: EDITOR_MESSAGES.ACTIVE, url: `${location.origin}${location.pathname}` });\n }\n\n /** The dashboard's context: words, campaign, the variant's edits (validated like the runtime does). */\n private applyContext(data: Record<string, unknown>): void {\n this.synced = true;\n this.t = mergeStrings(data.strings);\n this.dir = data.dir === 'rtl' ? 'rtl' : 'ltr';\n this.wrap?.setAttribute('dir', this.dir);\n const list = <T>(v: unknown, map: (x: any) => T | null, max: number): T[] =>\n (Array.isArray(v) ? v : [])\n .map(map)\n .filter((x): x is T => x !== null)\n .slice(0, max);\n this.ctx = {\n campaignName: clip(data.campaignName, 120),\n variantName: clip(data.variantName, 60),\n // Both shapes: the catalog's { key, label, group } and the older { name, custom }.\n attributes: list(\n data.attributes,\n (a): Var | null =>\n !a\n ? null\n : typeof a.key === 'string' && VAR_PATH.test(a.key)\n ? { path: a.key, label: clip(a.label, 60) || a.key.split('.').pop()!, group: clip(a.group, 40) }\n : typeof a.name === 'string' && ATTRIBUTE_NAME.test(a.name)\n ? { path: `user.${a.custom === true ? 'custom.' : ''}${a.name}`, label: a.name, group: '' }\n : null,\n 400,\n ),\n placements: list(\n data.placements,\n (p) =>\n p && typeof p.key === 'string' && PLACEMENT_KEY_PATTERN.test(p.key)\n ? {\n key: p.key,\n name: clip(p.name, 80),\n campaigns: list(\n p.campaigns,\n (c): SlotCampaign | null =>\n c && typeof c.id === 'string' && CAMPAIGN_ID.test(c.id) ? { id: c.id, name: clip(c.name, 120) || c.id, status: clip(c.status, 30), statusLabel: clip(c.statusLabel, 40) } : null,\n 10,\n ),\n }\n : null,\n 200,\n ),\n sample: {},\n openSlot: data.openSlot === true,\n };\n if (data.sample && typeof data.sample === 'object') {\n for (const [k, v] of Object.entries(data.sample as Record<string, unknown>).slice(0, 100)) {\n if (/^user\\.[A-Za-z0-9_.]{1,80}$/.test(k) && typeof v === 'string') this.ctx.sample[k] = v.slice(0, 200);\n }\n }\n if (Array.isArray(data.edits)) {\n this.edits = list(data.edits, (e) => trustedEdit(e), MAX_EDITS).map((e) => {\n const { personalized: _p, ...rest } = e;\n return rest;\n });\n this.history = [];\n }\n this.renderPreview();\n this.renderDock();\n this.renderHelp();\n if (this.draft) this.renderPanel();\n if (typeof data.focusId === 'string') this.focusEdit(data.focusId);\n }\n\n // ── selection ────────────────────────────────────────────────────────────\n\n /** Outline an element (hover: dashed + label; selected: solid). */\n private place(box: HTMLElement | null, el: Element | null, withLabel = false): void {\n if (!box) return;\n if (!el || !el.isConnected) {\n box.style.display = 'none';\n return;\n }\n const r = el.getBoundingClientRect();\n Object.assign(box.style, { display: 'block', top: `${r.top - 2}px`, left: `${r.left - 2}px`, width: `${r.width + 4}px`, height: `${r.height + 4}px` });\n box.textContent = '';\n const label = `${this.t[kindKey(el.tagName)]} · ${el.tagName.toLowerCase()}`;\n box.appendChild(h('span', { class: 'chip', 'data-j': 'label' }, withLabel ? `${label} - ${this.t.clickToEdit}` : label));\n }\n\n private move(dir: 'up' | 'down', from: Element): void {\n const next = dir === 'up' ? from.parentElement : Array.from(from.children).filter((c) => !isOurs(c))[0] || null;\n if (!next || next === document.body || next === document.documentElement) return;\n this.select(next);\n }\n\n /** The edits on an element (its selector finds it, or is the selector the editor would make for it), oldest first. */\n private editsOn(el: Element | null): PageEditWire[] {\n if (!el) return [];\n const own = robustSelector(el);\n return this.edits.filter((e) => e.selector === own || pageMatches(e.selector).indexOf(el) >= 0);\n }\n\n /**\n * The element is chosen: open the panel on it. An element that already\n * has an edit (this session's or the dashboard's) opens that edit - the\n * most recent one - like jumping to it from the list: its value, its\n * fallback, and Save updates the same edit.\n */\n select(el: Element, edit?: PageEditWire): void {\n if (!this.active) return;\n edit = edit || this.editsOn(el).pop();\n this.selected = el;\n this.hovered = null;\n this.place(this.hoverBox, null);\n this.place(this.selBox, el);\n this.popOpen = false;\n const selector = edit ? edit.selector : robustSelector(el) || '';\n this.showCss = !selector;\n this.draft = edit ? this.draftOf(edit) : this.newDraft(el, selector);\n this.renderPanel();\n this.renderDock();\n this.renderHelp();\n this.renderPreview();\n }\n\n private enabled(action: Action, el: Element | null): boolean {\n if (!el) return true;\n if (action === 'text') return el.tagName !== 'IMG' && !!this.orig(el).text;\n if (action === 'link') return el.tagName === 'A';\n if (action === 'image') return el.tagName === 'IMG';\n return true;\n }\n\n private newDraft(el: Element, selector: string): Draft {\n const o = this.orig(el);\n const action: Action = el.tagName === 'IMG' ? 'image' : this.enabled('text', el) ? 'text' : el.tagName === 'A' ? 'link' : 'hide';\n return { action, text: o.text.slice(0, MAX_TEXT), url: (action === 'image' ? o.src : o.href) || '', slotName: '', position: 'after', selector, editingId: null, touched: false };\n }\n\n private draftOf(e: PageEditWire): Draft {\n const action = ACTION_OF[e.operation];\n return {\n action,\n text: e.operation === 'replace_text' ? e.value || '' : '',\n url: action === 'link' || action === 'image' ? e.value || '' : '',\n slotName: e.placementKey || '',\n position: e.position || 'after',\n selector: e.selector,\n editingId: e.id,\n touched: true,\n };\n }\n\n /** The element as the page had it, before any preview of this editor. */\n private orig(el: Element): { text: string; href: string | null; src: string | null } {\n return this.originals.get(el) || { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') };\n }\n\n /** Jump to an edit: from the dock's list, or the dashboard (\"Edit on site\"). */\n focusEdit(id: unknown): boolean {\n const edit = this.edits.filter((e) => e.id === id)[0];\n if (!edit || !this.active) return false;\n const el = pageMatches(edit.selector)[0] || null;\n if (el) {\n try {\n el.scrollIntoView({ block: 'center' });\n } catch {\n /* old browsers */\n }\n this.select(el, edit);\n } else {\n this.selected = null;\n this.place(this.selBox, null);\n this.draft = this.draftOf(edit);\n this.showCss = true;\n this.renderPanel();\n this.renderDock();\n this.renderHelp();\n this.renderPreview();\n }\n return true;\n }\n\n // ── the edit ─────────────────────────────────────────────────────────────\n\n /** The draft as an edit, or null while a field is not valid yet. */\n private draftEdit(d: Draft): PageEditWire | null {\n const base = { id: d.editingId || '', selector: d.selector.trim() };\n if (!isSafeSelector(base.selector)) return null;\n const operation = OPERATION_OF[d.action];\n if (d.action === 'hide') return { ...base, operation };\n if (d.action === 'text') return d.text.trim() && d.text.length <= MAX_TEXT ? { ...base, operation, value: d.text } : null;\n if (d.action === 'link' || d.action === 'image') return isSafeEditUrl(d.url) ? { ...base, operation, value: d.url.trim() } : null;\n const key = slugify(d.slotName);\n return PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: d.position } : null;\n }\n\n private save(): void {\n const d = this.draft;\n const edit = d && this.draftEdit(d);\n if (!d || !edit) return;\n const el = this.selected || pageMatches(edit.selector)[0] || null;\n const id = d.editingId || newEditId();\n if (!this.pick(el, edit.selector, edit.operation, edit.value ?? edit.placementKey ?? '', { id, position: edit.position })) return;\n // A saved slot stays open on its edit, with its campaigns or \"Create content for this slot\".\n if (edit.operation === 'insert_placement' && this.ctx.openSlot) this.focusEdit(id);\n }\n\n /** \"Create content for this slot\" or one of its campaigns: the dashboard opens it, in its own tab. */\n openSlot(placementKey: string, campaignId?: string): boolean {\n if (!this.ctx.openSlot || !PLACEMENT_KEY_PATTERN.test(placementKey)) return false;\n this.send({ type: EDITOR_SESSION_MESSAGES.OPEN_SLOT, placementKey, ...(campaignId ? { campaignId } : {}) });\n try {\n this.opener.focus();\n } catch {\n /* not allowed */\n }\n return true;\n }\n\n /**\n * Validate like the server does, post the edit to the dashboard, keep it\n * in the list (and on the page). `value` is the text, the address or the\n * slot name (made a placement key).\n */\n pick(el: Element | null, selector: string, operation: PageEditOperation, value: string, opts: { id?: string; position?: PageEditPosition } = {}): boolean {\n const id = opts.id || newEditId();\n const tag = el ? el.tagName.toLowerCase() : '';\n const text = el ? this.orig(el).text.slice(0, 200) : '';\n let edit: PageEditWire | null = null;\n if (isSafeSelector(selector)) {\n const base = { id, selector: selector.trim() };\n if (operation === 'hide') edit = { ...base, operation };\n else if (operation === 'replace_text') edit = (value || text) && (value || text).length <= MAX_TEXT ? { ...base, operation, value: value || text } : null;\n else if (operation === 'replace_image' || operation === 'replace_link') edit = isSafeEditUrl(value) ? { ...base, operation, value: value.trim() } : null;\n else if (operation === 'insert_placement') {\n const key = slugify(value);\n edit = PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: opts.position || 'after' } : null;\n }\n }\n if (!edit) return false;\n const msg: EditorPick = { type: EDITOR_MESSAGES.PICK, ...edit, tag, text } as EditorPick;\n this.send(msg as unknown as Record<string, unknown>);\n const at = this.edits.map((e) => e.id).indexOf(id);\n this.history.push({ id, before: at >= 0 ? this.edits[at] : null });\n if (at >= 0) this.edits[at] = edit;\n else this.edits.push(edit);\n this.closePanel();\n return true;\n }\n\n private cancel(): void {\n this.closePanel();\n }\n\n private closePanel(): void {\n this.draft = null;\n this.selected = null;\n this.panel?.remove();\n this.panel = null;\n this.wrap?.classList.remove('open');\n this.place(this.selBox, null);\n this.renderPreview();\n this.renderDock();\n this.renderHelp();\n }\n\n /** Undo the last saved edit: a new one is removed, a changed one goes back to what it was. */\n undo(): boolean {\n if (!this.synced) return false;\n const last = this.history.pop();\n if (!last) return false;\n const at = this.edits.map((e) => e.id).indexOf(last.id);\n if (last.before) {\n if (at >= 0) this.edits[at] = last.before;\n const b = last.before;\n this.send({ type: EDITOR_MESSAGES.PICK, ...b, tag: '', text: '' });\n } else {\n if (at >= 0) this.edits.splice(at, 1);\n this.send({ type: EDITOR_SESSION_MESSAGES.REMOVE, id: last.id });\n }\n if (this.draft) this.closePanel();\n else {\n this.renderPreview();\n this.renderDock();\n }\n return true;\n }\n\n /** \"Save & return to Joryio\": every edit is already with the dashboard; say so, stop, go back. */\n done(): void {\n this.send({ type: EDITOR_SESSION_MESSAGES.DONE });\n this.stop();\n try {\n this.opener.focus();\n } catch {\n /* not allowed */\n }\n try {\n window.close();\n } catch {\n /* not a tab the dashboard opened */\n }\n }\n\n // ── live preview ─────────────────────────────────────────────────────────\n\n private clearPreview(): void {\n for (const off of this.previewUndo.splice(0).reverse()) {\n try {\n off();\n } catch {\n /* the element went away */\n }\n }\n }\n\n /** Every edit, and the draft in place of the edit it changes, applied to the page. */\n private renderPreview(): void {\n this.clearPreview();\n if (!this.active) return;\n const d = this.draft;\n const draft = d ? this.draftEdit(d) : null;\n const shown: PageEditWire[] = [];\n for (const e of this.edits) shown.push(d && d.editingId === e.id ? draft || e : e);\n if (d && !d.editingId && draft && d.touched) shown.push(draft);\n for (const e of shown) for (const el of pageMatches(e.selector).slice(0, 50)) this.applyPreview(e, el);\n if (this.selected) this.place(this.selBox, this.selected);\n }\n\n private previewNode(build: (root: ShadowRoot) => void, style = PREVIEW_HOST_STYLE, kind = 'preview'): HTMLElement {\n const n = document.createElement(PREVIEW_TAG);\n n.setAttribute('data-joryio-editor', kind);\n n.setAttribute('style', style);\n const root = n.attachShadow({ mode: 'open' });\n root.appendChild(h('style', null, PREVIEW_CSS));\n build(root);\n return n;\n }\n\n private applyPreview(e: PageEditWire, el: Element): void {\n if (!this.originals.has(el)) this.originals.set(el, { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') });\n const undo = this.previewUndo;\n const attr = (name: string, value: string | null) => {\n const before = el.getAttribute(name);\n if (value === null) el.removeAttribute(name);\n else el.setAttribute(name, value);\n undo.push(() => (before === null ? el.removeAttribute(name) : el.setAttribute(name, before)));\n };\n const hide = () => {\n const s = (el as HTMLElement).style;\n if (!s) return;\n const display = s.getPropertyValue('display');\n const priority = s.getPropertyPriority('display');\n s.setProperty('display', 'none', 'important');\n undo.push(() => (display ? s.setProperty('display', display, priority) : s.removeProperty('display')));\n };\n const insert = (n: Node, where: PageEditPosition) => {\n const parent = el.parentNode;\n if (where === 'before' && parent) parent.insertBefore(n, el);\n else if ((where === 'after' || where === 'replace') && parent) parent.insertBefore(n, el.nextSibling);\n else if (where === 'prepend') el.insertBefore(n, el.firstChild);\n else el.appendChild(n);\n undo.push(() => n.parentNode && n.parentNode.removeChild(n));\n };\n switch (e.operation) {\n case 'replace_text': {\n const kids = Array.from(el.childNodes);\n el.textContent = '';\n // A variable with neither a sample value nor a fallback is a pill, in its own shadow root.\n for (const p of previewParts(e.value || '', this.ctx.sample)) el.appendChild(typeof p === 'string' ? document.createTextNode(p) : this.previewNode((r) => r.appendChild(h('span', { class: 'v', dir: 'auto' }, this.labelOf(p.path) || p.name)), PREVIEW_VAR_HOST_STYLE, VAR_PILL));\n undo.push(() => {\n el.textContent = '';\n for (const k of kids) el.appendChild(k);\n });\n break;\n }\n case 'replace_link':\n attr('href', e.value || null);\n break;\n case 'replace_image':\n attr('srcset', null);\n attr('src', e.value || null);\n break;\n case 'hide': {\n const what = `${this.t[kindKey(el.tagName)]} \"${this.orig(el).text.slice(0, 40)}\"`;\n insert(this.previewNode((r) => r.appendChild(h('div', { class: 'x' }, `${this.t.hiddenFor}: ${what}`))), 'after');\n hide();\n break;\n }\n case 'insert_placement': {\n const where = e.position || 'after';\n insert(\n this.previewNode((r) => r.appendChild(h('div', { class: 's' }, h('b', null, `${this.t.slotPreview} · `), h('code', null, e.placementKey || ''), h('div', null, this.t.slotHelp)))),\n where,\n );\n if (where === 'replace') hide();\n break;\n }\n }\n }\n\n // ── rendering ────────────────────────────────────────────────────────────\n\n private renderHelp(): void {\n this.help?.remove();\n this.help = null;\n let dismissed = false;\n try {\n dismissed = localStorage.getItem(HELP_DISMISSED_KEY) === '1';\n } catch {\n /* storage blocked: show it */\n }\n if (dismissed || this.draft || !this.wrap) return;\n const t = this.t;\n const row = (k: string, v: string) => h('div', { class: 'row' }, h('span', { class: 'kbd' }, k), v);\n const close = h('button', { class: 'x', type: 'button', 'aria-label': t.dismiss, title: t.dismiss, 'data-j': 'help-dismiss' }, icon('close', 13));\n close.addEventListener('click', () => {\n // persisted: localStorage of this site's origin, in the marketer's browser - the card is a one-time tip.\n try {\n localStorage.setItem(HELP_DISMISSED_KEY, '1');\n } catch {\n /* storage blocked: hidden for this session only */\n }\n this.help?.remove();\n this.help = null;\n });\n this.help = h('div', { class: 'help', 'data-j': 'help', role: 'note' }, close, h('h3', null, t.helpTitle), row('↑', t.helpUp), row('↓', t.helpDown), row(t.helpClickKey, t.helpClick));\n this.wrap.appendChild(this.help);\n }\n\n /** A variable's label from the catalog. */\n private labelOf(path: string): string | undefined {\n const v = this.ctx.attributes.filter((a) => a.path === path)[0];\n return v && v.label;\n }\n\n private editTitle(e: PageEditWire): string {\n const el = pageMatches(e.selector)[0];\n const kind = this.t[el ? kindKey(el.tagName) : kindKey(e.selector, true)];\n return `${this.t[ACTION_LABEL[ACTION_OF[e.operation]]]} · ${kind}`;\n }\n\n private togglePop(open: boolean): void {\n this.popOpen = open;\n this.renderDock();\n }\n\n private renderDock(): void {\n if (!this.wrap) return;\n const t = this.t;\n this.dock?.remove();\n const n = this.edits.length;\n const sub = [this.ctx.variantName ? fill(t.variant, { name: this.ctx.variantName }) : '', location.pathname || '/'].filter(Boolean).join(' · ');\n const countBtn = h('button', { class: 'db', type: 'button', 'aria-expanded': String(this.popOpen), 'data-j': 'edits' }, n === 1 ? t.editsOne : fill(t.editsMany, { n }), icon(this.popOpen ? 'down' : 'up', 11));\n countBtn.addEventListener('click', () => this.togglePop(!this.popOpen));\n const canUndo = this.synced && this.history.length > 0;\n const undoBtn = h('button', { class: 'ib', type: 'button', 'aria-label': t.undo, title: this.synced ? t.undo : t.undoOffline, disabled: !canUndo, 'data-j': 'undo' }, icon('undo', 14));\n undoBtn.addEventListener('click', () => this.undo());\n const doneBtn = h('button', { class: 'go', type: 'button', 'data-j': 'done' }, t.saveReturn);\n doneBtn.addEventListener('click', () => this.done());\n const dock = h(\n 'div',\n { class: 'dock', 'data-j': 'dock', role: 'toolbar', 'aria-label': t.title },\n h('span', { class: 'logo', 'aria-hidden': 'true' }, 'J'),\n h('span', { class: 'name', 'data-j': 'campaign' }, this.ctx.campaignName || t.title),\n h('span', { class: 'sub' }, `· ${sub}`),\n h('span', { class: 'sep' }),\n h('span', { class: 'hint', 'data-j': 'hint' }, icon('cursor', 13), this.draft ? t.hintEditing : t.hintPoint),\n h('span', { class: 'sep' }),\n countBtn,\n undoBtn,\n doneBtn,\n );\n if (this.popOpen) {\n const pop = h('div', { class: 'pop', 'data-j': 'edit-list', role: 'menu' });\n if (!n) pop.appendChild(h('div', { class: 'empty' }, t.noEdits));\n this.edits.forEach((e, i) => {\n const b = h('button', { class: 'e', type: 'button', role: 'menuitem', 'data-j': 'edit-item', 'data-edit-id': e.id }, h('span', { class: 'num' }, String(i + 1)), this.editTitle(e));\n b.addEventListener('click', () => this.focusEdit(e.id));\n pop.appendChild(b);\n });\n dock.appendChild(pop);\n }\n this.dock = dock;\n this.wrap.appendChild(dock);\n }\n\n private renderPanel(): void {\n const d = this.draft;\n if (!d || !this.wrap) return;\n const t = this.t;\n const el = this.selected;\n this.panel?.remove();\n this.wrap.classList.add('open');\n\n // Header: breadcrumb (+ up / down), the element, its matches.\n const crumbs = h('div', { class: 'crumbs', 'data-j': 'crumbs' });\n if (el) {\n const chain: Element[] = [];\n for (let n: Element | null = el; n && n !== document.body && n !== document.documentElement; n = n.parentElement) chain.unshift(n);\n const shown = chain.slice(-3);\n const crumb = (label: string, target: Element | null, cur: boolean) => {\n const b = h('button', { class: cur ? 'crumb cur' : 'crumb', type: 'button', 'data-j': 'crumb', 'aria-current': cur ? 'true' : undefined, disabled: !target }, label);\n if (target && !cur) b.addEventListener('click', () => this.select(target));\n return b;\n };\n crumbs.appendChild(crumb(t.page, null, false));\n for (const n of shown) crumbs.append(icon('chevron', 9), crumb(t[kindKey(n.tagName)], n, n === el));\n const up = h('button', { type: 'button', 'aria-label': t.up, title: t.up, 'data-j': 'up', disabled: !el.parentElement || el.parentElement === document.body }, icon('up', 12));\n up.addEventListener('click', () => this.move('up', el));\n const down = h('button', { type: 'button', 'aria-label': t.down, title: t.down, 'data-j': 'down', disabled: !Array.from(el.children).some((c) => !isOurs(c)) }, icon('down', 12));\n down.addEventListener('click', () => this.move('down', el));\n crumbs.appendChild(h('span', { class: 'nav' }, up, down));\n }\n const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)];\n const snippet = el ? (el.tagName === 'IMG' ? el.getAttribute('alt') || '' : this.orig(el).text) : '';\n const title = h('div', { class: 'title', 'data-j': 'title' }, snippet ? `${kind} \"${snippet.slice(0, 40)}\"` : kind);\n const pill = h('span', { class: 'pill', 'data-j': 'matches' });\n const header = h('div', { class: 'hd' }, crumbs, h('div', { class: 'tr' }, title, pill));\n\n // Body: action tiles, the action's fields, the CSS selector.\n const tiles = h('div', { class: 'tiles', role: 'radiogroup', 'aria-label': t.whatToDo });\n const mine = this.editsOn(el);\n for (const a of ACTIONS) {\n const on = d.action === a;\n const enabled = on || this.enabled(a, el);\n const off = !enabled ? (a === 'link' ? t.notLink : a === 'image' ? t.notImage : t.noText) : '';\n // The element's own edit of this kind, if it has one: the tile opens it (an element can carry several edits).\n const own = mine.filter((e) => ACTION_OF[e.operation] === a).pop();\n const b = h('button', { class: a === 'slot' ? 'tile slot' : 'tile', type: 'button', role: 'radio', 'aria-checked': String(on), disabled: !enabled, 'data-e': !!own, 'data-j': `action-${a}` }, icon(ACTION_ICON[a]), h('span', null, h('b', null, t[ACTION_LABEL[a]]), off ? h('small', null, off) : null));\n b.addEventListener('click', () => {\n if (!this.draft || this.draft.action === a) return;\n if (own) this.draft = this.draftOf(own);\n else {\n // Another kind of change: a new edit next to the one open (that one stays as it is).\n if (el && this.draft.editingId) this.draft = this.newDraft(el, this.draft.selector);\n this.draft.action = a;\n this.draft.touched = true;\n if ((a === 'link' || a === 'image') && el) this.draft.url = (a === 'image' ? this.orig(el).src : this.orig(el).href) || '';\n }\n this.renderPanel();\n this.renderPreview();\n });\n tiles.appendChild(b);\n }\n const fields = h('div', { 'data-j': 'fields' });\n const saveBtn = h('button', { class: 'save', type: 'button', 'data-j': 'save' });\n const refresh = () => {\n const valid = !!this.draftEdit(d);\n saveBtn.disabled = !valid;\n saveBtn.textContent = fill(t.save, { action: t[ACTION_LABEL[d.action]] });\n const n = pageMatches(d.selector).length;\n pill.className = `pill ${n === 1 ? 'ok' : n > 1 ? 'many' : 'none'}`;\n pill.textContent = n === 1 ? t.matchOne : n > 1 ? fill(t.matchMany, { n }) : t.matchNone;\n };\n const changed = () => {\n d.touched = true;\n refresh();\n this.renderPreview();\n };\n this.renderFields(fields, d, el, changed);\n\n const cssToggle = h('button', { class: 'css', type: 'button', 'aria-expanded': String(this.showCss), 'data-j': 'css-toggle' }, icon('code', 13), t.css, icon(this.showCss ? 'up' : 'down', 10));\n cssToggle.addEventListener('click', () => {\n this.showCss = !this.showCss;\n this.renderPanel();\n });\n const body = h('div', { class: 'bd' }, h('span', { class: 'lbl' }, t.whatToDo), tiles, fields, cssToggle);\n if (this.showCss) {\n const input = h('input', { class: 'mono', dir: 'ltr', 'aria-label': t.css, spellcheck: 'false', 'data-j': 'selector' });\n input.value = d.selector;\n const note = h('div', { class: 'help2' });\n const sync = () => {\n const ok = isSafeSelector(d.selector);\n note.className = ok ? 'help2' : 'err';\n note.textContent = !d.selector.trim() ? t.noSelector : ok ? fill(t.cssHelp, { n: pageMatches(d.selector).length }) : t.cssBad;\n };\n input.addEventListener('input', () => {\n d.selector = input.value;\n sync();\n changed();\n });\n sync();\n body.append(h('div', { class: 'mt' }, input, note));\n }\n\n const cancel = h('button', { class: 'cancel', type: 'button', 'data-j': 'cancel' }, t.cancel);\n cancel.addEventListener('click', () => this.cancel());\n saveBtn.addEventListener('click', () => this.save());\n const panel = h('aside', { class: 'panel', 'data-j': 'panel', role: 'dialog', 'aria-label': t.whatToDo }, header, body, h('div', { class: 'ft' }, cancel, saveBtn));\n refresh();\n this.panel = panel;\n this.wrap.appendChild(panel);\n }\n\n /** One field set per action. Typing updates the draft and the page, never re-renders the field typed in. */\n private renderFields(box: HTMLElement, d: Draft, el: Element | null, changed: () => void): void {\n const t = this.t;\n box.textContent = '';\n this.closeOverlay = null;\n const was = (v: string | null) => (v ? h('span', { class: 'was', title: v }, fill(t.was, { value: v.slice(0, 60) })) : null);\n if (d.action === 'text') {\n let code: HTMLTextAreaElement | null = null;\n const textChanged = (v: string) => {\n d.text = v;\n if (code && code !== this.root?.activeElement) code.value = v;\n changed();\n };\n // Each pill has its own \"If <field> is missing\" (a click on it): the `| default:` of that variable only.\n const field = liquidField({\n label: t.newText,\n rawNote: t.rawNote,\n root: this.root,\n onChange: textChanged,\n labelOf: (p) => this.labelOf(p),\n fallback: { title: t.fallbackFor, help: t.fallbackHelp, bad: t.fallbackBad, done: t.fallbackDone },\n });\n field.set(d.text);\n const add = (v: Var) => field.insert(pathTag(v.path));\n const vars: Var[] = this.ctx.attributes.length ? this.ctx.attributes : ['firstName', 'lastName'].map((n) => ({ path: `user.${n}`, label: n, group: '' }));\n const common = COMMON_VARS.map((p) => vars.filter((v) => v.path === p)[0]).filter(Boolean);\n const shown = common.concat(vars.filter((v) => common.indexOf(v) < 0)).slice(0, CHIPS);\n const chips = h('div', { class: 'chips', 'data-j': 'chips' }, h('span', null, t.insert));\n const picker = h('div', { class: 'pk', 'data-j': 'var-picker', hidden: true });\n for (const v of shown) {\n const c = h('button', { class: 'vc', type: 'button', title: v.path, 'data-j': 'chip' }, v.label);\n c.addEventListener('mousedown', (e) => e.preventDefault()); // the caret stays in the text\n c.addEventListener('click', () => add(v));\n chips.appendChild(c);\n }\n if (vars.length > shown.length) {\n // \"More…\": the whole catalog, searchable, by group; ↑ ↓ Enter in the search box, Esc closes.\n const more = h('button', { class: 'vc', type: 'button', 'aria-expanded': 'false', 'data-j': 'more' }, t.more);\n const search = h('input', { dir: 'auto', 'aria-label': t.search, placeholder: t.search, 'data-j': 'var-search', role: 'combobox', 'aria-expanded': 'true' });\n const listEl = h('div', { role: 'listbox', 'aria-label': t.insert, 'data-j': 'var-list' });\n picker.append(search, listEl);\n let hits: Var[] = [];\n let at = 0;\n const close = () => {\n if (picker.hidden) return false;\n picker.hidden = true;\n more.setAttribute('aria-expanded', 'false');\n return true;\n };\n const pick = (v: Var | undefined) => {\n if (!v) return;\n close();\n add(v);\n };\n const draw = () => {\n const q = search.value.trim().toLowerCase();\n hits = vars.filter((v) => !q || `${v.label} ${v.path} ${v.group}`.toLowerCase().indexOf(q) >= 0).slice(0, 200);\n at = Math.min(at, Math.max(hits.length - 1, 0));\n listEl.textContent = '';\n if (!hits.length) listEl.appendChild(h('div', { class: 'g' }, t.noMatch));\n let group: string | null = null;\n hits.forEach((v, i) => {\n if (v.group !== group) {\n group = v.group;\n if (group) listEl.appendChild(h('div', { class: 'g', role: 'presentation' }, group));\n }\n const o = h('div', { class: 'o', role: 'option', id: `jv${i}`, 'aria-selected': String(i === at), 'data-j': 'var-option' }, h('span', { dir: 'auto' }, v.label), h('code', { dir: 'ltr' }, v.path));\n o.addEventListener('mousedown', (e) => e.preventDefault());\n o.addEventListener('click', () => pick(v));\n listEl.appendChild(o);\n });\n search.setAttribute('aria-activedescendant', hits.length ? `jv${at}` : '');\n };\n search.addEventListener('input', () => {\n at = 0;\n draw();\n });\n search.addEventListener('keydown', (e) => {\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n e.preventDefault();\n at = (at + (e.key === 'ArrowDown' ? 1 : hits.length - 1)) % Math.max(hits.length, 1);\n draw();\n const o = listEl.querySelector('[aria-selected=\"true\"]') as HTMLElement | null;\n if (o && o.scrollIntoView) o.scrollIntoView({ block: 'nearest' });\n } else if (e.key === 'Enter') {\n e.preventDefault();\n pick(hits[at]);\n }\n });\n more.addEventListener('mousedown', (e) => e.preventDefault());\n more.addEventListener('click', () => {\n if (close()) return;\n picker.hidden = false;\n more.setAttribute('aria-expanded', 'true');\n search.value = '';\n at = 0;\n draw();\n search.focus();\n });\n this.closeOverlay = () => field.closePop() || close();\n chips.appendChild(more);\n }\n // \"Liquid code\": the stored text itself, for developers; editing it redraws the pills.\n const toggle = h('button', { class: 'css', type: 'button', 'aria-expanded': String(this.showLiquid), 'data-j': 'liquid-toggle' }, icon('code', 13), t.liquid, icon(this.showLiquid ? 'up' : 'down', 10));\n toggle.addEventListener('click', () => {\n this.showLiquid = !this.showLiquid;\n this.renderPanel();\n });\n if (!this.closeOverlay) this.closeOverlay = () => field.closePop();\n box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, t.newText), was(el ? this.orig(el).text : null)), field.el, chips, picker, toggle);\n if (this.showLiquid) {\n const ta = h('textarea', { class: 'mono', rows: '3', dir: 'ltr', spellcheck: 'false', 'aria-label': t.liquid, 'data-j': 'liquid' });\n ta.value = d.text;\n ta.addEventListener('input', () => {\n field.set(ta.value);\n textChanged(ta.value);\n });\n code = ta;\n box.appendChild(h('div', { class: 'mt' }, ta));\n }\n } else if (d.action === 'link' || d.action === 'image') {\n const input = h('input', { type: 'url', dir: 'ltr', inputmode: 'url', placeholder: 'https://', 'data-j': 'url', 'aria-label': d.action === 'link' ? t.newLink : t.newImage });\n input.value = d.url;\n const err = h('div', { class: 'err' });\n const check = () => (err.textContent = d.url.trim() && !isSafeEditUrl(d.url) ? t.urlBad : '');\n input.addEventListener('input', () => {\n d.url = input.value;\n check();\n changed();\n });\n check();\n const before = el ? (d.action === 'image' ? this.orig(el).src : this.orig(el).href) : null;\n box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, d.action === 'link' ? t.newLink : t.newImage), was(before)), input, err);\n } else if (d.action === 'hide') {\n const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)].toLowerCase();\n box.appendChild(h('div', { class: 'note', 'data-j': 'hide-note' }, fill(t.hideNote, { kind })));\n } else {\n const input = h('input', { class: 'slotin', dir: 'auto', 'data-j': 'slot-name', 'aria-label': t.slotName, maxlength: '80' });\n input.value = d.slotName;\n const saved = h('span', { class: 'key', 'data-j': 'slot-key' });\n const help = h('div', { class: 'help2' });\n const sync = () => {\n const key = slugify(d.slotName);\n saved.textContent = key || '-';\n help.textContent = '';\n help.append(`${t.savedAs} `, saved, key ? '' : ` · ${t.slotEmpty}`);\n };\n input.addEventListener('input', () => {\n d.slotName = input.value;\n sync();\n changed();\n });\n sync();\n box.append(h('label', { class: 'lbl' }, t.slotName), input, help);\n if (this.ctx.placements.length) {\n const chips = h('div', { class: 'chips', 'data-j': 'placements' });\n for (const p of this.ctx.placements.slice(0, 12)) {\n const c = h('button', { class: 'vc', type: 'button', title: p.name || p.key, 'data-j': 'placement' }, p.key);\n c.addEventListener('click', () => {\n d.slotName = p.key;\n input.value = p.key;\n sync();\n changed();\n });\n chips.appendChild(c);\n }\n box.appendChild(chips);\n }\n box.appendChild(h('div', { class: 'help2' }, t.slotHelp));\n const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-label': t.where, 'data-j': 'positions' });\n for (const [pos, label] of POSITIONS) {\n const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(d.position === pos), 'data-j': `pos-${pos}` }, t[label]);\n b.addEventListener('click', () => {\n d.position = pos;\n for (const x of Array.from(seg.children)) x.setAttribute('aria-checked', String(x === b));\n changed();\n });\n seg.appendChild(b);\n }\n box.append(h('div', { class: 'mt' }, h('span', { class: 'lbl' }, t.where), seg));\n // A saved slot: what fills it, from the dashboard (the key as saved, not as being typed).\n const savedEdit = this.ctx.openSlot && d.editingId ? this.edits.filter((e) => e.id === d.editingId)[0] : undefined;\n const key = savedEdit && savedEdit.placementKey;\n if (key) {\n const camps = (this.ctx.placements.filter((p) => p.key === key)[0] || { campaigns: [] as SlotCampaign[] }).campaigns;\n const sec = h('div', { class: 'mt slotc', 'data-j': 'slot-content' });\n const link = (label: string, j: string, id?: string) => {\n const b = h('button', { class: 'lnk', type: 'button', 'data-j': j }, label);\n b.addEventListener('click', () => this.openSlot(key, id));\n return b;\n };\n if (!camps.length) sec.appendChild(link(t.slotCreate, 'slot-create'));\n else {\n sec.appendChild(h('span', { class: 'lbl' }, t.slotIn));\n for (const c of camps) sec.appendChild(link(c.statusLabel || c.status ? `${c.name} (${c.statusLabel || c.status})` : c.name, 'slot-campaign', c.id));\n sec.appendChild(link(t.slotAddAnother, 'slot-add'));\n }\n box.appendChild(sec);\n }\n }\n }\n}\n","/**\n * The visual editor bundle - `joryio-editor.min.js` on the SDK host, next to\n * `joryio.min.js` (BACKLOG D444 Phase 4 follow-up).\n *\n * Loaded by the core's EditorGate (src/core/editor-gate.ts) only in a tab the\n * Joryio dashboard opened for the point-and-click editor, and only after the\n * server vouched for the editor token. It registers one global and does\n * nothing else on its own: no request, no listener, until the gate calls\n * `start` with the verified dashboard origin.\n */\nimport { VisualEditor } from './visual-editor';\nimport { EDITOR_API_VERSION, EDITOR_GLOBAL, type EditorBundleApi } from '../core/editor-gate';\n\nconst api: EditorBundleApi = {\n version: EDITOR_API_VERSION,\n start({ dashboardOrigin, opener, logger, onStop }) {\n const editor = new VisualEditor(dashboardOrigin, opener, logger, onStop);\n editor.start();\n return { stop: () => editor.stop() };\n },\n};\n\nif (typeof window !== 'undefined' && !(window as any)[EDITOR_GLOBAL]) {\n (window as any)[EDITOR_GLOBAL] = api;\n}\n\nexport { api as editorApi };\n"],"names":["SuppressedError","PAGE_EDIT_POSITIONS","PLACEMENT_KEY_PATTERN","isSafeSelector","selector","s","trim","length","test","includes","document","createDocumentFragment","querySelector","_a","isSafeEditUrl","url","u","CORE_FILE","coreFolderOf","src","URL","protocol","pathname","origin","replace","current","currentScript","fromCurrent","tags","querySelectorAll","i","folder","readOwnFolder","EDITOR_MESSAGES","EDITOR_GLOBAL","EDITOR_STRINGS","title","variant","hintPoint","hintEditing","editsOne","editsMany","noEdits","undo","undoOffline","saveReturn","clickToEdit","helpTitle","helpUp","helpDown","helpClickKey","helpClick","dismiss","page","up","down","matchOne","matchMany","matchNone","whatToDo","actText","actLink","actImage","actHide","actSlot","noText","notLink","notImage","newText","was","insert","fallbackFor","fallbackHelp","fallbackBad","fallbackDone","liquid","more","search","noMatch","rawNote","newLink","newImage","urlBad","hideNote","hiddenFor","slotName","savedAs","slotHelp","slotEmpty","slotCreate","slotIn","slotAddAnother","where","posBefore","posAfter","posReplace","posPrepend","posAppend","slotPreview","css","cssHelp","cssBad","cancel","save","noSelector","kHeading","kText","kLink","kButton","kImage","kList","kSection","kMain","kHeader","kFooter","kNav","kForm","kElement","fill","text","vars","m","k","String","OUTPUT_TAG","DEFAULT_FILTER","unquote","v","varFallback","exec","d","pathTag","path","fallback","quoted","VAR_PATH","pathName","SIMPLE_VAR","liquidParts","value","out","re","RegExp","source","last","index","push","slice","name","lastIndex","some","p","slugify","toLowerCase","newEditId","Math","random","toString","padEnd","kindKey","tagOrSelector","isSelector","t","parts","split","filter","Boolean","h","tag","attrs","kids","el","createElement","Object","entries","undefined","setAttribute","kid","appendChild","createTextNode","SVG_NS","ICONS","link","image","hide","slot","cursor","code","chevron","check","close","icon","size","createElementNS","width","height","viewBox","stroke","FONT","MONO","PILL","PREVIEW_CSS","EDITOR_CSS","PILL_ATTR","isPill","n","nodeType","hasAttribute","serialize","data","getAttribute","Array","from","childNodes","NAMING_ATTRIBUTES","ATTRIBUTE_NAME","MAX_TEXT","HELP_DISMISSED_KEY","isOurs","closest","VAR_PILL","pageTarget","Element","parentElement","body","documentElement","pageMatches","e","unique","doc","hits","robustSelector","ownerDocument","named","node","id","globalThis","CSS","escape","ch","charCodeAt","cssEscape","attr","tagName","own","anchor","unshift","parent","same","children","c","indexOf","join","ACTIONS","OPERATION_OF","ACTION_OF","replace_text","replace_link","replace_image","insert_placement","ACTION_LABEL","ACTION_ICON","POSITIONS","COMMON_VARS","CAMPAIGN_ID","clip","shortText","textContent","VisualEditor","constructor","dashboardOrigin","opener","logger","onStop","this","listeners","active","host","root","wrap","hoverBox","selBox","dock","panel","help","hovered","selected","draft","showCss","showLiquid","closeOverlay","popOpen","edits","history","synced","assign","dir","ctx","campaignName","variantName","attributes","placements","sample","openSlot","previewUndo","originals","WeakMap","start","onMessage","type","stop","applyContext","focusEdit","window","addEventListener","removeEventListener","activate","isActive","editList","send","off","splice","clearPreview","remove","error","debug","message","postMessage","attachShadow","mode","class","append","onMove","target","place","onClick","preventDefault","stopPropagation","select","onKey","key","move","togglePop","onScroll","renderDock","renderHelp","location","over","keys","mergeStrings","strings","list","map","max","isArray","x","a","label","pop","group","custom","campaigns","status","statusLabel","base","personalized","operation","placementKey","position","trustedEdit","_p","rest","prototype","hasOwnProperty","call","getOwnPropertySymbols","propertyIsEnumerable","__rest","renderPreview","renderPanel","focusId","box","withLabel","isConnected","style","display","r","getBoundingClientRect","top","left","next","editsOn","edit","draftOf","newDraft","enabled","action","orig","o","href","editingId","touched","get","scrollIntoView","block","draftEdit","pick","_b","campaignId","focus","opts","msg","at","before","closePanel","classList","b","done","reverse","shown","applyPreview","previewNode","build","kind","has","set","removeAttribute","getPropertyValue","priority","getPropertyPriority","setProperty","removeProperty","parentNode","insertBefore","firstChild","nextSibling","removeChild","expr","previewParts","labelOf","what","dismissed","localStorage","getItem","row","setItem","role","editTitle","open","sub","countBtn","canUndo","undoBtn","disabled","doneBtn","forEach","add","crumbs","chain","crumb","cur","snippet","pill","header","tiles","mine","on","fields","saveBtn","refresh","valid","className","changed","renderFields","cssToggle","input","spellcheck","note","sync","ok","textChanged","activeElement","field","saved","selection","getSelection","caret","rangeCount","getRangeAt","composed","getComposedRanges","contains","startContainer","sr","shadowRoots","createRange","setStart","startOffset","setEnd","endContainer","endOffset","remember","cloneRange","emit","onChange","putCaret","setBaseAndExtent","removeAllRanges","addRange","fb","words","contenteditable","tabindex","closePop","openPop","maxlength","err","finish","isPlainFallback","bad","setVarFallback","replaceChild","area","rows","ce","onPill","collapsed","back","previousSibling","cut","clipboardData","setData","cloneContents","deleteContents","getData","insertNode","setStartAfter","collapse","selectNodeContents","prev","frag","liquidField","common","concat","chips","picker","hidden","placeholder","listEl","draw","q","min","toggle","ta","inputmode","seg","pos","savedEdit","camps","sec","j","api","version","editor"],"mappings":";;;;;yBAwUkD,mBAApBA,iBAAiCA,gBCpRxD,MAAMC,EAAsB,CAAC,SAAU,QAAS,UAAW,SAAU,WAQtEC,EAAwB,4BAmNxB,SAAUC,EAAeC,GAC7B,GAAwB,iBAAbA,EAAuB,OAAO,EACzC,MAAMC,EAAID,EAASE,OACnB,IAAKD,GAAKA,EAAEE,OAzNc,IAyNgB,OAAO,EACjD,GAAI,UAAUC,KAAKH,IAAMA,EAAEI,SAAS,OAASJ,EAAEI,SAAS,MAAO,OAAO,EAEtE,GAAI,wBAAwBD,KAAKH,GAAI,OAAO,EAC5C,IAC0B,oBAAbK,UAA0BA,SAASC,yBAAyBC,cAAcP,EACvF,CAAE,MAAAQ,GACA,OAAO,CACT,CACA,OAAO,CACT,CAEM,SAAUC,EAAcC,GAC5B,GAAmB,iBAARA,EAAkB,OAAO,EACpC,MAAMC,EAAID,EAAIT,OACd,SAAKU,GAAKA,EAAET,OAtOS,QAwOjB,0BAA0BC,KAAKQ,IAC5B,yBAAyBR,KAAKQ,EACvC,CCzRA,MAAMC,EAAY,oCAQZ,SAAUC,EAAaC,GAC3B,IAAKA,GAAsB,iBAARA,EAAkB,OAAO,KAC5C,IAAIH,EACJ,IACEA,EAAI,IAAII,IAAID,EACd,CAAE,MAAAN,GACA,OAAO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ASxK,EAAExE,SAC9C,IAAK,MAAMgK,KAAKoT,EAAOC,EAAI7X,YAAYI,EAAKoE,EAAEiH,aAAejH,EAAEgH,OAAS,GAAGhH,EAAEtG,SAASsG,EAAEiH,aAAejH,EAAEgH,UAAYhH,EAAEtG,KAAM,gBAAiBsG,EAAEf,KAChJoU,EAAI7X,YAAYI,EAAKpB,EAAEvE,eAAgB,YACzC,MALmBod,EAAI7X,YAAYI,EAAKpB,EAAEzE,WAAY,gBAMtDoS,EAAI3M,YAAY6X,EAClB,CACF,CACF,EC7rCF,MAAME,GAAuB,CAC3BC,QNqBgC,EMpBhC,KAAA/P,EAAMrC,gBAAEA,EAAeC,OAAEA,EAAMC,OAAEA,EAAMC,OAAEA,IACvC,MAAMkS,EAAS,IAAIvS,GAAaE,EAAiBC,EAAQC,EAAQC,GAEjE,OADAkS,EAAOhQ,QACA,CAAEG,KAAM,IAAM6P,EAAO7P,OAC9B,GAGoB,oBAAXG,QAA4BA,OAAevR,KACnDuR,OAAevR,GAAiB+gB","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"joryio-editor.min.js","sources":["../node_modules/tslib/tslib.es6.js","../src/core/page-edits.ts","../src/core/sdk-host-files.ts","../src/core/editor-gate.ts","../src/editor/editor-strings.ts","../src/editor/editor-model.ts","../src/editor/editor-ui.ts","../src/editor/liquid-field.ts","../src/editor/visual-editor.ts","../src/editor/index.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\r\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nvar ownKeys = function(o) {\r\n ownKeys = Object.getOwnPropertyNames || function (o) {\r\n var ar = [];\r\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\r\n return ar;\r\n };\r\n return ownKeys(o);\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose, inner;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n if (async) inner = dispose;\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n var r, s = 0;\r\n function next() {\r\n while (r = env.stack.pop()) {\r\n try {\r\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\r\n if (r.dispose) {\r\n var result = r.dispose.call(r.value);\r\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n else s |= 1;\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\r\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\r\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\r\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\r\n });\r\n }\r\n return path;\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __esDecorate: __esDecorate,\r\n __runInitializers: __runInitializers,\r\n __propKey: __propKey,\r\n __setFunctionName: __setFunctionName,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,\r\n};\r\n","/**\n * Page edits on web (BACKLOG D444 Phase 4, docs/PLACEMENTS_WEBSITE_LAYER.md 2).\n *\n * A page-edit campaign changes elements of the site's own page, found by CSS\n * selector: replace a text, an image, a link, hide an element, or insert a\n * placement next to it. Nothing else - no HTML, no script, no free-form DOM.\n *\n * - Text is set with `textContent` (never parsed as HTML); image and link\n * addresses must be absolute http(s); a selector that could escape the\n * anti-flicker style rule is refused. The server checks the same and this\n * SDK checks again: an edit it does not trust is skipped, never half-applied.\n * - Site settings first (`GET /v1/in-app/site-settings?sdkKey=`, public,\n * the same for every visitor; asked once per SDK session and refreshed at\n * most every SITE_SETTINGS_SESSION_REFRESH_SECONDS, kept in sessionStorage\n * so the session's later page loads do not wait for it): page edits off\n * for this site, or no live page-edit campaign, = nothing is asked or\n * applied on this page view. Otherwise the per-visitor answer.\n * - Anti-flicker: only edited elements are hidden (opacity, so the layout\n * does not move), for at most PAGE_EDIT_ANTI_FLICKER_MS from the start of\n * the page, never the whole body: the ones edited on this page last time,\n * or - on a first view, when there are none - the site's list from the site\n * settings (selectors only).\n * - Static edits from the last answer for this page apply at once, as each\n * element appears (MutationObserver); personalized edits apply when the\n * answer arrives and are never stored.\n * - A route change undoes this page's edits and applies the next page's.\n * - Per device (1.4.0-beta.8): an edit may carry `device: 'mobile' | 'desktop'`\n * (absent or `all` = every device, as before). Mobile = a viewport narrower\n * than PAGE_EDIT_MOBILE_BREAKPOINT (768) CSS pixels, the one number the\n * backend, the dashboard and the editor use too. An edit for the other\n * device is not applied; when the viewport crosses the breakpoint (a\n * resize, a turned phone) every edit is undone and the ones for the new\n * width applied again, so a desktop and a mobile edit of one element never\n * fight. The SDK says it understands this with the capability\n * `page_edit_device`; the server sends an SDK without it no per-device\n * edit at all (an older build would apply both versions everywhere).\n * - Exposure: `in_app.displayed` once an edit of the experience landed on an\n * element; a control visitor reports `in_app.control_viewed` once one of\n * the control's selectors is on the page.\n * - Server-applied edits (D450): a store plugin may already have written the\n * edits that are the same for every visitor into the page's HTML. Its\n * marker - a JSON block `#joryio-server-page-edits` and\n * `data-joryio-applied=\"<campaignId>:<editId>\"` on each changed element -\n * says which. The SDK never applies those again (no double insert, no\n * flicker), counts them as landed for the exposure (once, with its own\n * answer's token), keeps them out of the anti-flicker rule, and undoes one\n * (from `data-joryio-orig` and the element's `<template data-joryio-orig>`)\n * when the definitive answer for this visitor no longer carries it -\n * paused, edited, the visitor suppressed or in a control, page edits\n * switched off - or on a route change to another page.\n */\nimport { bucketHash } from '../utils/bucket-hash';\nimport type { IdentityManager } from './identity';\nimport type { SessionManager } from './session';\nimport type { Logger } from '../utils/logger';\nimport type { InAppAuthProvider } from './inapp';\nimport type { PlacementConsent } from './placements';\nimport { sdkIdentityHeaders } from './config';\nimport { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';\n\nexport const PAGE_EDIT_OPERATIONS = ['replace_text', 'replace_image', 'replace_link', 'hide', 'insert_placement'] as const;\n/** `replace` (\"Instead of it\"): the element is hidden and the spot takes its place, right after it. */\nexport const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append', 'replace'] as const;\nexport const PAGE_EDITS_CAPABILITY = 'page_edits';\n/** Which viewport an edit is for; absent = `all`. */\nexport const PAGE_EDIT_DEVICES = ['all', 'mobile', 'desktop'] as const;\n/** Sent with `page_edits` by a build that applies an edit only on its device. */\nexport const PAGE_EDIT_DEVICE_CAPABILITY = 'page_edit_device';\n/** Mobile = viewport width below this many CSS pixels (backend PAGE_EDIT_MOBILE_BREAKPOINT, the dashboard, the editor). */\nexport const PAGE_EDIT_MOBILE_BREAKPOINT = 768;\nexport const PAGE_EDIT_MOBILE_QUERY = '(max-width: 767.98px)';\nexport type PageEditDevice = (typeof PAGE_EDIT_DEVICES)[number];\n\n/** True when this window is a mobile viewport (below the breakpoint). */\nexport function isMobileViewport(win: Window = window): boolean {\n try {\n return typeof win.matchMedia === 'function' ? win.matchMedia(PAGE_EDIT_MOBILE_QUERY).matches : win.innerWidth < PAGE_EDIT_MOBILE_BREAKPOINT;\n } catch {\n return false;\n }\n}\n\n/** An edit shows on this viewport: no device, `all`, or the viewport's own. */\nexport const editShowsOn = (e: { device?: string }, mobile: boolean): boolean => !e.device || e.device === 'all' || (e.device === 'mobile') === mobile;\n/** The longest edited elements stay hidden while the SDK waits. Never the whole body. */\nexport const PAGE_EDIT_ANTI_FLICKER_MS = 300;\n\nconst MAX_SELECTOR_LENGTH = 500;\nconst MAX_TEXT_LENGTH = 2000;\nconst MAX_URL_LENGTH = 2048;\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\nconst STYLE_ID = 'joryio-page-edits-anti-flicker';\n/**\n * Both stores are per workspace: the names carry a hash of the SDK key (the\n * flags cache's scheme), so two workspaces on one origin never share edits\n * or anti-flicker selectors. The unscoped names of earlier builds are never\n * read; they are removed on the first load.\n */\nconst LEGACY_ANSWER_STORE = 'jry_page_edits';\nconst LEGACY_SELECTOR_STORE = 'jry_page_edit_selectors';\nexport const pageEditsStorageKeys = (sdkKey: string): { answers: string; selectors: string; site: string } => {\n const h = bucketHash(sdkKey).toString(36);\n return { answers: `jry_page_edits_${h}`, selectors: `jry_page_edit_selectors_${h}`, site: `jry_page_edit_site_${h}` };\n};\nconst MAX_REMEMBERED_PAGES = 50;\nconst DEFAULT_TTL_SECONDS = 300;\n/**\n * The site settings are asked once per SDK session and then at most every\n * this many seconds within it (sessionStorage, per workspace, tied to the\n * session id: a new session asks again). The server's `ttlSeconds` (60) is\n * the HTTP cache lifetime for browsers and the CDN and no longer shortens\n * this: on a multi-page store every full page load used to re-ask, and the\n * answer is the same for every visitor and changes only when a page-edit\n * campaign is launched or page edits are switched on or off. The cost, by\n * design: a newly launched page-edit campaign reaches a visitor already on\n * the site within this time. Pausing is not delayed - `/page-edits` checks\n * every campaign's liveness itself on every page.\n */\nexport const SITE_SETTINGS_SESSION_REFRESH_SECONDS = 600;\n/** At most this many selectors of the site list go into the style rule (the server sends at most 200). */\nconst MAX_SITE_SELECTORS = 200;\n\n/**\n * The marker a store plugin writes with the edits it applied in the HTML\n * (backend common/web-experience/server-page-edits.ts, the plugins' shared\n * core; pinned by server-page-edits-parity.spec.ts).\n */\nexport const SERVER_PAGE_EDITS_MARKER_ID = 'joryio-server-page-edits';\nexport const SERVER_APPLIED_ATTR = 'data-joryio-applied';\nexport const SERVER_ORIG_ATTR = 'data-joryio-orig';\nexport const SERVER_SPOT_ATTR = 'data-joryio-server-spot';\nconst SERVER_MARKER_VERSION = 1;\n\ninterface ServerEdit {\n experienceId: string;\n variantId: string | null;\n edit: PageEditWire;\n}\n\nconst sameEdit = (a: PageEditWire, b: PageEditWire): boolean =>\n a.id === b.id &&\n a.selector === b.selector &&\n a.operation === b.operation &&\n (a.value ?? null) === (b.value ?? null) &&\n (a.placementKey ?? null) === (b.placementKey ?? null) &&\n (a.position ?? null) === (b.position ?? null) &&\n (a.device ?? null) === (b.device ?? null) &&\n !b.personalized;\n\nfunction serverMarkerElement(): HTMLScriptElement | null {\n const head = document.head;\n if (!head) return null;\n for (const c of Array.from(head.children)) {\n if (c.id === SERVER_PAGE_EDITS_MARKER_ID) {\n return c.tagName === 'SCRIPT' && (c.getAttribute('type') || '').trim().toLowerCase() === 'application/json' ? (c as HTMLScriptElement) : null;\n }\n }\n return null;\n}\n\n/** An address the undo may write back: absolute http(s) or relative (no scheme). Anything else is dropped. */\nfunction safeRestoredUrl(v: unknown): string | null {\n if (typeof v !== 'string' || v.length > MAX_URL_LENGTH) return null;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(v)) return null;\n const t = v.trim();\n if (/^https?:\\/\\//i.test(t)) return v;\n // A scheme is letters before a ':' that comes before any '/', '?' or '#'.\n return /^[a-z][a-z0-9+.-]*:/i.test(t) ? null : v;\n}\n\nconst safeRestoredSrcset = (v: unknown): string | null =>\n typeof v === 'string' && v.split(',').every((c) => !c.trim() || safeRestoredUrl(c.trim().split(/\\s+/)[0]) !== null) ? v : null;\n\nconst HIDE_DECLARATION = 'display:none !important';\n\n/** Hide one element (display:none !important); returns how to show it again as it was. */\nfunction hideElement(h: HTMLElement): () => void {\n const display = h.style.getPropertyValue('display');\n const priority = h.style.getPropertyPriority('display');\n h.style.setProperty('display', 'none', 'important');\n return () => (display ? h.style.setProperty('display', display, priority) : h.style.removeProperty('display'));\n}\n\n/**\n * Undo a hide the server wrote (`hide`, and `insert_placement` at `replace`).\n * Never a style string from the marker: the original is put back only when\n * the attribute is exactly it plus the server's one declaration; otherwise\n * that one declaration is removed.\n */\nfunction undoServerHide(el: Element, orig: Record<string, any>): void {\n const current = el.getAttribute('style') || '';\n const before = typeof orig.style === 'string' ? orig.style : null;\n const base = before === null ? '' : before.trim().replace(/;+$/, '');\n if (current === (base ? base + ';' : '') + HIDE_DECLARATION) {\n if (before === null) el.removeAttribute('style');\n else el.setAttribute('style', before);\n } else if ((el as HTMLElement).style?.getPropertyValue('display') === 'none') {\n (el as HTMLElement).style.removeProperty('display');\n }\n}\n\n/**\n * Inline text markup a replaced element's original content may come back with.\n * Everything else is unwrapped to its text (its children are kept, checked the same way):\n * no script, frame, object, embed, meta, base, link, style, form, svg or math element is\n * ever created, and no attribute outside RESTORE_ATTRIBUTES (no on*, style, srcdoc, data).\n */\nconst RESTORE_ELEMENTS = new Set(['A', 'ABBR', 'B', 'BDI', 'BDO', 'BR', 'CITE', 'CODE', 'DATA', 'DEL', 'DFN', 'EM', 'I', 'IMG', 'INS', 'KBD', 'MARK', 'Q', 'S', 'SAMP', 'SMALL', 'SPAN', 'STRONG', 'SUB', 'SUP', 'TIME', 'U', 'VAR', 'WBR']);\nconst RESTORE_ATTRIBUTES = new Set(['class', 'id', 'title', 'lang', 'dir', 'alt', 'width', 'height', 'datetime', 'href', 'src', 'srcset', 'rel', 'target']);\nconst MAX_RESTORE_NODES = 500;\n\nfunction restoreInline(from: DocumentFragment): DocumentFragment {\n const out = document.createDocumentFragment();\n let budget = MAX_RESTORE_NODES;\n const copy = (src: Node, into: Node): void => {\n for (const n of Array.from(src.childNodes)) {\n if (budget-- <= 0) return;\n if (n.nodeType === 3) {\n into.appendChild(document.createTextNode(n.nodeValue || ''));\n } else if (n.nodeType === 1) {\n const e = n as Element;\n if (e.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !RESTORE_ELEMENTS.has(e.tagName)) {\n // Not allowed: only its text and allowed descendants, never the element.\n if (!/^(SCRIPT|STYLE|TEMPLATE|IFRAME|OBJECT|EMBED|NOSCRIPT|TEXTAREA|TITLE)$/.test(e.tagName)) copy(e, into);\n continue;\n }\n const made = document.createElement(e.tagName.toLowerCase());\n for (const a of Array.from(e.attributes)) {\n const name = a.name.toLowerCase();\n if (!RESTORE_ATTRIBUTES.has(name)) continue;\n if (name === 'href' || name === 'src') {\n const v = safeRestoredUrl(a.value);\n if (v !== null) made.setAttribute(name, v);\n } else if (name === 'srcset') {\n const v = safeRestoredSrcset(a.value);\n if (v !== null) made.setAttribute(name, v);\n } else {\n made.setAttribute(name, a.value);\n }\n }\n into.appendChild(made);\n copy(e, made);\n }\n }\n };\n copy(from, out);\n return out;\n}\n\nconst tokensOf = (el: Element): string[] => (el.getAttribute(SERVER_APPLIED_ATTR) || '').split(/\\s+/).filter(Boolean);\n\n/** `GET /v1/in-app/site-settings` (backend common/web-experience/page-edit-site.ts). */\nexport interface SiteSettingsResponse {\n success?: boolean;\n ttlSeconds?: number;\n pageEdits?: { enabled?: boolean; active?: boolean; antiFlickerSelectors?: string[] };\n}\nexport interface PageEditSite {\n enabled: boolean;\n active: boolean;\n antiFlickerSelectors: string[];\n}\n\nexport type PageEditOperation = (typeof PAGE_EDIT_OPERATIONS)[number];\nexport type PageEditPosition = (typeof PAGE_EDIT_POSITIONS)[number];\n\nexport interface PageEditWire {\n id: string;\n selector: string;\n operation: PageEditOperation;\n value?: string;\n placementKey?: string;\n position?: PageEditPosition;\n /** Only this viewport (`mobile` / `desktop`); absent = every device. */\n device?: 'mobile' | 'desktop';\n personalized?: true;\n}\n\nexport interface PageEditExperienceWire {\n id: string;\n variantId: string | null;\n deliveryId: string | null;\n deliveryToken: string | null;\n isControl: boolean;\n controlToken: string | null;\n selectors: string[];\n edits: PageEditWire[];\n}\n\nexport interface PageEditsResponse {\n success?: boolean;\n ttlSeconds?: number;\n experiences?: PageEditExperienceWire[];\n}\n\nexport interface PageEditRuntime {\n /** As placements: null = send nothing; `granted` = personal serving and reporting. */\n consent: () => PlacementConsent | null;\n requestTimeoutMs?: number;\n noteStatus?: (status: number, data: any) => void;\n}\n\n/** Same rule as the server: nothing that could close the style rule, no comment, no control character. */\nexport function isSafeSelector(selector: unknown): selector is string {\n if (typeof selector !== 'string') return false;\n const s = selector.trim();\n if (!s || s.length > MAX_SELECTOR_LENGTH) return false;\n if (/[{};<@]/.test(s) || s.includes('/*') || s.includes('*/')) return false;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(s)) return false;\n try {\n if (typeof document !== 'undefined') document.createDocumentFragment().querySelector(s);\n } catch {\n return false; // not a selector this browser parses\n }\n return true;\n}\n\nexport function isSafeEditUrl(url: unknown): url is string {\n if (typeof url !== 'string') return false;\n const u = url.trim();\n if (!u || u.length > MAX_URL_LENGTH) return false;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f\\s]/.test(u)) return false;\n return /^https?:\\/\\/[^/?#\\s]+/i.test(u);\n}\n\n/** The edit as this SDK will apply it, or null - an edit it does not trust is skipped whole. */\nexport function trustedEdit(e: any): PageEditWire | null {\n if (!e || typeof e !== 'object' || typeof e.id !== 'string' || !isSafeSelector(e.selector)) return null;\n // A device this build does not know is skipped whole, never applied everywhere.\n const device = e.device;\n if (device != null && !(PAGE_EDIT_DEVICES as readonly unknown[]).includes(device)) return null;\n const base = {\n id: e.id,\n selector: e.selector.trim(),\n ...(device === 'mobile' || device === 'desktop' ? { device: device as 'mobile' | 'desktop' } : {}),\n ...(e.personalized === true ? { personalized: true as const } : {}),\n };\n switch (e.operation) {\n case 'hide':\n return { ...base, operation: 'hide' };\n case 'replace_text':\n return typeof e.value === 'string' && e.value.length <= MAX_TEXT_LENGTH ? { ...base, operation: 'replace_text', value: e.value } : null;\n case 'replace_image':\n case 'replace_link':\n return isSafeEditUrl(e.value) ? { ...base, operation: e.operation, value: e.value.trim() } : null;\n case 'insert_placement':\n return typeof e.placementKey === 'string' && PLACEMENT_KEY_PATTERN.test(e.placementKey)\n ? { ...base, operation: 'insert_placement', placementKey: e.placementKey, position: (PAGE_EDIT_POSITIONS as readonly string[]).includes(e.position) ? e.position : 'after' }\n : null;\n default:\n return null;\n }\n}\n\ninterface Applied {\n el: Element;\n editId: string;\n undo: () => void;\n}\n\ninterface Experience {\n wire: PageEditExperienceWire;\n edits: PageEditWire[];\n}\n\n/** The site settings as stored for one SDK session (`sid`), answered at `at`. */\ninterface StoredSite {\n sid: string;\n at: number;\n value: PageEditSite;\n}\n\nexport class PageEditManager {\n private page: PageContextTracker | null = null;\n private pageUnsubscribe: (() => void) | null = null;\n private experiences: Experience[] = [];\n private applied: Applied[] = [];\n private reported = new Set<string>();\n private observer: MutationObserver | null = null;\n private scheduled = false;\n private flickerTimer: ReturnType<typeof setTimeout> | null = null;\n /** When the current page started: the anti-flicker never lasts past this + PAGE_EDIT_ANTI_FLICKER_MS. */\n private pageStartedAt = 0;\n /** The last site settings answer, for its session id (mirrors the sessionStorage entry). */\n private site: StoredSite | null = null;\n private siteRequest: Promise<PageEditSite | null> | null = null;\n private readonly stores: { answers: string; selectors: string; site: string };\n /** Edits the page's HTML arrived with (token -> edit); null until the marker was read. */\n private server: Map<string, ServerEdit> | null = null;\n /** The page those were written for: a route change elsewhere undoes them. */\n private serverUrl: string | null = null;\n private generation = 0;\n /** The viewport the applied edits were chosen for (true = mobile). */\n private mobile = false;\n private offMedia: (() => void) | null = null;\n private started = false;\n private destroyed = false;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private identity: IdentityManager,\n private session: SessionManager,\n private logger: Logger,\n private runtime: PageEditRuntime,\n private auth?: InAppAuthProvider,\n ) {\n this.stores = pageEditsStorageKeys(sdkKey);\n try {\n // Not workspace-scoped: another workspace on this origin may have written them.\n localStorage.removeItem(LEGACY_SELECTOR_STORE);\n sessionStorage.removeItem(LEGACY_ANSWER_STORE);\n } catch {\n /* storage blocked */\n }\n }\n\n setPageContext(tracker: PageContextTracker | null): void {\n this.pageUnsubscribe?.();\n this.pageUnsubscribe = null;\n this.page = tracker;\n if (tracker) {\n this.pageUnsubscribe = tracker.onSignal((s) => {\n if (s.type === 'page_change' && this.started) this.loadPage();\n });\n }\n }\n\n /** Hide what was edited here last time, apply what is known, observe the DOM, ask the server. */\n start(): void {\n if (this.started || this.destroyed || typeof document === 'undefined') return;\n this.started = true;\n if (typeof MutationObserver !== 'undefined' && document.documentElement) {\n this.observer = new MutationObserver(() => this.schedule());\n this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n this.mobile = isMobileViewport();\n // The breakpoint crossed (resize, a turned phone): undo, and apply what fits the new width.\n const mq = typeof window.matchMedia === 'function' ? window.matchMedia(PAGE_EDIT_MOBILE_QUERY) : null;\n if (mq) {\n const onChange = () => this.viewportChanged();\n if (mq.addEventListener) mq.addEventListener('change', onChange);\n else mq.addListener?.(onChange);\n this.offMedia = () => (mq.removeEventListener ? mq.removeEventListener('change', onChange) : mq.removeListener?.(onChange));\n }\n this.loadPage();\n }\n\n private viewportChanged(): void {\n const mobile = isMobileViewport();\n if (this.destroyed || mobile === this.mobile) return;\n this.mobile = mobile;\n if (!this.experiences.some((x) => x.edits.some((e) => e.device))) return;\n this.revertAll();\n this.applyAll();\n }\n\n /**\n * The audience changed (identify, reset, consent): forget this visitor's\n * answers and ask again. `siteSettings: true` (reset, wipeData, a consent\n * change) forgets the stored site settings too; identify keeps them - they\n * are the same for every visitor of the site.\n */\n invalidate(opts: { siteSettings?: boolean } = {}): void {\n this.generation++;\n this.reported.clear();\n if (opts.siteSettings) this.forgetSite();\n try {\n sessionStorage.removeItem(this.stores.answers);\n } catch {\n /* ignore */\n }\n if (this.started) this.loadPage();\n }\n\n destroy(): void {\n this.destroyed = true;\n this.pageUnsubscribe?.();\n this.offMedia?.();\n this.offMedia = null;\n this.observer?.disconnect();\n this.observer = null;\n this.revertAll();\n this.showAll();\n }\n\n /** Currently applied edits, for tests and debugging. */\n appliedCount(): number {\n return this.applied.length;\n }\n\n /** Edits the page arrived with from the server and still carries, for tests and debugging. */\n serverAppliedCount(): number {\n return this.serverEdits().size;\n }\n\n // ── one page ─────────────────────────────────────────────────────────────\n\n private url(): string | null {\n return this.page ? this.page.current().url : currentPageUrl();\n }\n\n private loadPage(): void {\n const generation = ++this.generation;\n this.revertAll();\n const url = this.url();\n if (!url) {\n this.experiences = [];\n return;\n }\n this.pageStartedAt = Date.now();\n // The server's edits belong to the page they were written for.\n const server = this.serverEdits();\n if (this.serverUrl === null) this.serverUrl = url;\n else if (url !== this.serverUrl && server.size) this.reconcileServer([]);\n // 1. Anti-flicker: the elements edited on this page last time, at most 300 ms.\n const remembered = this.rememberedSelectors(url);\n this.hide(remembered);\n // 2. Static edits from the last answer for this page, applied as elements appear.\n this.experiences = this.cachedExperiences(url);\n this.applyAll();\n // 3. The site settings (cached), then the answer for this page and visitor.\n void this.siteThenFetch(url, generation, remembered.length > 0);\n }\n\n private async siteThenFetch(url: string, generation: number, rememberedAny: boolean): Promise<void> {\n // A stored answer for this session is used at once - no wait before the\n // per-visitor request - and refreshed in the background when it is older\n // than SITE_SETTINGS_SESSION_REFRESH_SECONDS. Only without one (first\n // page of a session) does the page wait for the site settings.\n const stored = this.storedSite();\n let site: PageEditSite | null;\n if (stored) {\n site = stored.value;\n if (Date.now() - stored.at >= SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) {\n void this.requestSite().then((fresh) => {\n // Was off or idle and is live now: this page asks after all.\n if (fresh && fresh.enabled && fresh.active && !(site!.enabled && site!.active) && generation === this.generation && !this.destroyed) {\n void this.fetch(url, generation);\n }\n });\n }\n } else {\n site = await this.siteSettings();\n }\n if (generation !== this.generation || this.destroyed) return;\n if (site && (!site.enabled || !site.active)) {\n // Off for this site, or nothing live: undo what the cache (or the server) applied, ask nothing.\n this.revertAll();\n this.reconcileServer([]);\n this.experiences = [];\n this.showAll();\n return;\n }\n // First view on this page: hold back the site's edited elements, inside the same 300 ms.\n if (site && !rememberedAny && site.antiFlickerSelectors.length) this.hide(site.antiFlickerSelectors);\n await this.fetch(url, generation);\n }\n\n /**\n * The site settings: one GET per SDK session, then at most one per\n * SITE_SETTINGS_SESSION_REFRESH_SECONDS within it, kept in sessionStorage\n * per workspace across the session's page loads. A CORS-simple request (no\n * custom header, the key in the query string - the server refuses a key in\n * a header there, the URL being the cache key), so no preflight. Null when\n * unknown (network error, an HTTP error, an answer it cannot read): then\n * the SDK asks /page-edits as it always did, and nothing is stored.\n */\n siteSettings(): Promise<PageEditSite | null> {\n const stored = this.storedSite();\n if (stored && Date.now() - stored.at < SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) return Promise.resolve(stored.value);\n return this.requestSite();\n }\n\n /** The stored answer for the current session id (any age), or null. */\n private storedSite(): StoredSite | null {\n const sid = this.session.getSessionId();\n if (!sid) return null; // no session (after wipeData): nothing to tie it to\n if (this.site && this.site.sid === sid) return this.site;\n this.site = null;\n try {\n const raw = JSON.parse(sessionStorage.getItem(this.stores.site) || 'null');\n const v = raw?.value;\n if (raw && raw.sid === sid && typeof raw.at === 'number' && raw.at <= Date.now() && v && typeof v === 'object') {\n this.site = {\n sid,\n at: raw.at,\n value: {\n enabled: v.enabled !== false,\n active: v.active !== false,\n antiFlickerSelectors: (Array.isArray(v.antiFlickerSelectors) ? v.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),\n },\n };\n } else if (raw) {\n sessionStorage.removeItem(this.stores.site); // another session's answer\n }\n } catch {\n /* storage blocked or unreadable: ask */\n }\n return this.site;\n }\n\n private forgetSite(): void {\n this.site = null;\n try {\n sessionStorage.removeItem(this.stores.site);\n } catch {\n /* ignore */\n }\n }\n\n private requestSite(): Promise<PageEditSite | null> {\n if (this.siteRequest) return this.siteRequest;\n const request = (async (): Promise<PageEditSite | null> => {\n const sid = this.session.getSessionId();\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/site-settings?sdkKey=${encodeURIComponent(this.sdkKey)}`, { method: 'GET', credentials: 'omit' });\n if (!res.ok) {\n this.runtime.noteStatus?.(res.status, null);\n this.forgetSite();\n return null;\n }\n const data: SiteSettingsResponse = await res.json();\n const pe = data?.pageEdits;\n if (!pe || typeof pe !== 'object') {\n this.forgetSite();\n return null;\n }\n const value: PageEditSite = {\n enabled: pe.enabled !== false,\n active: pe.active !== false,\n antiFlickerSelectors: (Array.isArray(pe.antiFlickerSelectors) ? pe.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),\n };\n // data.ttlSeconds is the HTTP cache lifetime; the SDK keeps the\n // answer for the session (SITE_SETTINGS_SESSION_REFRESH_SECONDS).\n if (sid) {\n this.site = { sid, at: Date.now(), value };\n try {\n sessionStorage.setItem(this.stores.site, JSON.stringify(this.site));\n } catch {\n /* storage full or blocked: kept in memory for this page */\n }\n }\n return value;\n } catch (error) {\n this.logger.debug('Site settings request failed', error);\n // Unknown: a stale stored answer is not trusted past its refresh time.\n this.forgetSite();\n return null;\n } finally {\n this.siteRequest = null;\n }\n })();\n this.siteRequest = request;\n return request;\n }\n\n private async fetch(url: string, generation: number): Promise<void> {\n const consent = this.runtime.consent();\n if (consent === null || this.destroyed) {\n this.showAll();\n return;\n }\n const personal = consent === 'granted';\n const userId = personal ? this.identity.getUserId() : null;\n const anonymousId = personal ? this.identity.getAnonymousId() : null;\n const body = {\n ...(userId ? { userId } : {}),\n ...(anonymousId ? { anonymousId } : {}),\n ...(personal ? { sessionId: this.session.getSessionId() } : {}),\n deviceType: 'web',\n locale: typeof navigator !== 'undefined' ? navigator.language : undefined,\n capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY, PAGE_EDIT_DEVICE_CAPABILITY],\n trackingConsent: consent,\n context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} },\n };\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/page-edits`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(personal ? this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {} : {}),\n },\n body: JSON.stringify(body),\n ...(controller ? { signal: controller.signal } : {}),\n });\n if (generation !== this.generation) return;\n if (!res.ok) {\n // 429 and every other failure: keep what is applied (the cached static edits).\n this.runtime.noteStatus?.(res.status, null);\n return;\n }\n const data: PageEditsResponse = await res.json();\n if (generation !== this.generation || !data || data.success === false || !Array.isArray(data.experiences)) return;\n const experiences = data.experiences\n .filter((x) => x && typeof x.id === 'string')\n .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e): e is PageEditWire => !!e) }));\n this.revertAll();\n this.experiences = experiences;\n // The definitive answer: a server-applied edit it no longer carries is undone first.\n this.reconcileServer(experiences);\n this.remember(url, experiences, data.ttlSeconds);\n this.applyAll();\n } catch (error) {\n this.logger.debug('Page edits request failed', error);\n } finally {\n clearTimeout(timeout);\n if (generation === this.generation) this.showAll();\n }\n }\n\n // ── applying ─────────────────────────────────────────────────────────────\n\n private schedule(): void {\n if (this.scheduled || this.destroyed) return;\n this.scheduled = true;\n const run = () => {\n this.scheduled = false;\n this.applyAll();\n };\n if (typeof queueMicrotask === 'function') queueMicrotask(run);\n else void Promise.resolve().then(run);\n }\n\n private applyAll(): void {\n if (this.destroyed || typeof document === 'undefined') return;\n // Our own DOM writes would wake the observer; it is paused while we write.\n this.observer?.disconnect();\n try {\n for (const x of this.experiences) {\n if (x.wire.isControl) {\n const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);\n if (seen) this.reportControl(x.wire);\n continue;\n }\n let landed = false;\n for (const edit of x.edits) {\n // Another device's edit: not on this viewport (applied when the width crosses the breakpoint).\n if (!editShowsOn(edit, this.mobile)) continue;\n const token = `${x.wire.id}:${edit.id}`;\n const server = this.serverEdits().get(token);\n const byServer = !!server && server.variantId === (x.wire.variantId ?? null) && sameEdit(server.edit, edit);\n for (const el of this.query(edit.selector)) {\n if (this.applied.some((a) => a.el === el && a.editId === edit.id)) {\n landed = true;\n continue;\n }\n // Already in the HTML the server sent: never applied a second time.\n if (byServer && tokensOf(el).includes(token)) {\n landed = true;\n continue;\n }\n const undo = this.applyOne(el, edit);\n if (undo) {\n this.applied.push({ el, editId: edit.id, undo });\n landed = true;\n }\n }\n }\n if (landed) this.reportDisplayed(x.wire);\n }\n } finally {\n if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n\n private query(selector: string): Element[] {\n try {\n return Array.from(document.querySelectorAll(selector)).filter((el) => !(el as HTMLElement).closest?.('[data-joryio-editor]'));\n } catch {\n return [];\n }\n }\n\n /** One edit on one element; returns how to undo it, or null when it does not fit the element. */\n private applyOne(el: Element, edit: PageEditWire): (() => void) | null {\n const h = el as HTMLElement;\n switch (edit.operation) {\n case 'replace_text': {\n const before = Array.from(el.childNodes);\n el.textContent = edit.value ?? '';\n return () => {\n el.textContent = '';\n before.forEach((n) => el.appendChild(n));\n };\n }\n case 'replace_image': {\n if (el.tagName !== 'IMG') return null;\n const src = el.getAttribute('src');\n const srcset = el.getAttribute('srcset');\n el.setAttribute('src', edit.value!);\n // A srcset would win over the new src in every browser.\n el.removeAttribute('srcset');\n return () => {\n if (src === null) el.removeAttribute('src');\n else el.setAttribute('src', src);\n if (srcset !== null) el.setAttribute('srcset', srcset);\n };\n }\n case 'replace_link': {\n if (el.tagName !== 'A') return null;\n const href = el.getAttribute('href');\n el.setAttribute('href', edit.value!);\n return () => (href === null ? el.removeAttribute('href') : el.setAttribute('href', href));\n }\n case 'hide':\n return hideElement(h);\n case 'insert_placement': {\n const spot = document.createElement('div');\n spot.setAttribute('data-joryio-placement', edit.placementKey!);\n spot.setAttribute('data-joryio-edit', edit.id);\n const where: InsertPosition =\n edit.position === 'before' ? 'beforebegin' : edit.position === 'prepend' ? 'afterbegin' : edit.position === 'append' ? 'beforeend' : 'afterend';\n el.insertAdjacentElement(where, spot);\n if (edit.position !== 'replace') return () => spot.remove();\n // \"Instead of it\": the spot sits where the element was, the element is hidden.\n const show = hideElement(h);\n return () => {\n spot.remove();\n show();\n };\n }\n default:\n return null;\n }\n }\n\n private revertAll(): void {\n const applied = this.applied.splice(0).reverse();\n if (!applied.length) return;\n this.observer?.disconnect();\n try {\n for (const a of applied) {\n try {\n a.undo();\n } catch {\n /* the element may be gone */\n }\n }\n } finally {\n if (this.observer && typeof document !== 'undefined' && document.documentElement) {\n this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n }\n\n // ── anti-flicker ─────────────────────────────────────────────────────────\n\n private hide(selectors: string[]): void {\n const safe = selectors.filter(isSafeSelector);\n if (!safe.length || typeof document === 'undefined') return;\n // Never past PAGE_EDIT_ANTI_FLICKER_MS from the start of this page, however late the list arrived.\n const left = PAGE_EDIT_ANTI_FLICKER_MS - (Date.now() - (this.pageStartedAt || Date.now()));\n if (left <= 0) return;\n let style = document.getElementById(STYLE_ID) as HTMLStyleElement | null;\n if (!style) {\n style = document.createElement('style');\n style.id = STYLE_ID;\n (document.head || document.documentElement).appendChild(style);\n }\n // Only these elements, never the body; opacity, so the layout does not move.\n // Elements the server already edited are never held back.\n style.textContent = this.serverEdits().size\n ? `:is(${safe.join(',')}):not([${SERVER_APPLIED_ATTR}]){opacity:0 !important}`\n : `${safe.join(',')}{opacity:0 !important}`;\n if (this.flickerTimer) clearTimeout(this.flickerTimer);\n this.flickerTimer = setTimeout(() => this.showAll(), left);\n }\n\n private showAll(): void {\n if (this.flickerTimer) clearTimeout(this.flickerTimer);\n this.flickerTimer = null;\n try {\n document.getElementById(STYLE_ID)?.remove();\n } catch {\n /* ignore */\n }\n }\n\n // ── what is remembered (selectors and static edits only, never a personalized value) ──\n\n private subjectKey(): string {\n return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;\n }\n\n private remember(url: string, experiences: Experience[], ttlSeconds?: number): void {\n // Held back next time: only what this viewport shows.\n const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.filter((e) => editShowsOn(e, this.mobile)).map((e) => e.selector))))];\n try {\n const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};\n delete all[url];\n if (selectors.length) all[url] = selectors.slice(0, 50);\n const keys = Object.keys(all);\n for (const k of keys.slice(0, Math.max(0, keys.length - MAX_REMEMBERED_PAGES))) delete all[k];\n localStorage.setItem(this.stores.selectors, JSON.stringify(all));\n } catch {\n /* storage blocked: no anti-flicker next time, nothing else */\n }\n try {\n const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};\n const pages = stored.subject === this.subjectKey() && stored.pages ? stored.pages : {};\n pages[url] = {\n at: Date.now(),\n ttl: (ttlSeconds && ttlSeconds > 0 ? ttlSeconds : DEFAULT_TTL_SECONDS) * 1000,\n experiences: experiences\n .filter((x) => !x.wire.isControl)\n .map((x) => ({ ...x.wire, deliveryToken: null, edits: x.edits.filter((e) => !e.personalized) }))\n .filter((x) => x.edits.length),\n };\n sessionStorage.setItem(this.stores.answers, JSON.stringify({ subject: this.subjectKey(), pages }));\n } catch {\n /* ignore */\n }\n }\n\n private rememberedSelectors(url: string): string[] {\n try {\n const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};\n return Array.isArray(all[url]) ? all[url].filter((s: unknown) => typeof s === 'string') : [];\n } catch {\n return [];\n }\n }\n\n private cachedExperiences(url: string): Experience[] {\n try {\n const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};\n if (stored.subject !== this.subjectKey()) return [];\n const entry = stored.pages?.[url];\n if (!entry || Date.now() - entry.at > entry.ttl) return [];\n // Applied, never reported: the exposure belongs to the answer with a token.\n return (entry.experiences || []).map((wire: PageEditExperienceWire) => ({\n wire: { ...wire, isControl: false, deliveryToken: null },\n edits: (wire.edits || []).map(trustedEdit).filter((e): e is PageEditWire => !!e && !e.personalized),\n }));\n } catch {\n return [];\n }\n }\n\n // ── edits the server applied (D450) ──────────────────────────────────────\n\n /** The marker, read once it is in the DOM (it sits right after <head>). */\n private serverEdits(): Map<string, ServerEdit> {\n if (this.server) return this.server;\n const found = new Map<string, ServerEdit>();\n if (typeof document === 'undefined') return found;\n // Trusted only where the plugin writes it: a JSON <script> directly in <head>\n // (the plugin inserts it right after <head>, before any page script). An\n // element with that id anywhere else - user content in the body, DOM\n // clobbering - is ignored.\n const el = serverMarkerElement();\n if (!el) {\n // Not (yet) in the DOM: asked again on the next call while the page is still loading.\n if (document.readyState !== 'loading') this.server = found;\n return found;\n }\n try {\n const data = JSON.parse(el.textContent || '{}');\n if (data && data.v === SERVER_MARKER_VERSION && Array.isArray(data.experiences)) {\n for (const x of data.experiences) {\n if (!x || typeof x.id !== 'string' || !Array.isArray(x.edits)) continue;\n for (const raw of x.edits) {\n const edit = trustedEdit(raw);\n if (edit && !edit.personalized) found.set(`${x.id}:${edit.id}`, { experienceId: x.id, variantId: typeof x.variantId === 'string' ? x.variantId : null, edit });\n }\n }\n }\n } catch {\n /* a marker this SDK cannot read: treated as none; the edits it lists stay as the page has them */\n }\n this.server = found;\n return found;\n }\n\n /**\n * Keep the server-applied edits the definitive answer still carries for this\n * visitor (same campaign, variant and edit); undo every other one.\n */\n private reconcileServer(experiences: Experience[]): void {\n const server = this.serverEdits();\n if (!server.size || typeof document === 'undefined') return;\n const keep = new Set<string>();\n for (const x of experiences) {\n if (x.wire.isControl) continue;\n for (const e of x.edits) {\n const token = `${x.wire.id}:${e.id}`;\n const s = server.get(token);\n if (s && s.variantId === (x.wire.variantId ?? null) && sameEdit(s.edit, e)) keep.add(token);\n }\n }\n const undo = [...server.keys()].filter((t) => !keep.has(t));\n if (!undo.length) return;\n this.observer?.disconnect();\n try {\n for (const token of undo) {\n this.undoServerEdit(token, server.get(token)!.edit);\n server.delete(token);\n }\n } finally {\n if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n\n /** Put back what the server changed for one edit, from the undo data it left on each element. */\n private undoServerEdit(token: string, edit: PageEditWire): void {\n for (const el of Array.from(document.querySelectorAll(`[${SERVER_APPLIED_ATTR}]`))) {\n const tokens = tokensOf(el);\n if (!tokens.includes(token)) continue;\n let all: Record<string, any> = {};\n try {\n all = JSON.parse(el.getAttribute(SERVER_ORIG_ATTR) || '{}') || {};\n } catch {\n all = {};\n }\n const orig = all[token] || {};\n // Only an element that still shows exactly what the server applied is put back,\n // and only with values that pass the same checks as an edit.\n try {\n switch (edit.operation) {\n case 'replace_text': {\n const tpl = Array.from(el.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute(SERVER_ORIG_ATTR) === token) as HTMLTemplateElement | undefined;\n if (tpl && tpl.content && el.textContent === edit.value) {\n // Rebuilt node by node through an allowlist - never the template's markup made live.\n const restored = restoreInline(tpl.content);\n el.textContent = '';\n el.appendChild(restored);\n }\n break;\n }\n case 'replace_image':\n if (el.tagName === 'IMG' && el.getAttribute('src') === edit.value) {\n const src = safeRestoredUrl(orig.src);\n const srcset = safeRestoredSrcset(orig.srcset);\n if (src === null) el.removeAttribute('src');\n else el.setAttribute('src', src);\n if (srcset !== null) el.setAttribute('srcset', srcset);\n }\n break;\n case 'replace_link':\n if (el.tagName === 'A' && el.getAttribute('href') === edit.value) {\n const href = safeRestoredUrl(orig.href);\n if (href === null) el.removeAttribute('href');\n else el.setAttribute('href', href);\n }\n break;\n case 'hide':\n undoServerHide(el, orig);\n break;\n case 'insert_placement':\n // \"Instead of it\" also hid the element (the spot itself is removed below).\n if (edit.position === 'replace') undoServerHide(el, orig);\n break;\n default:\n break;\n }\n } catch {\n /* the element changed since: leave it */\n }\n const left = tokens.filter((t) => t !== token);\n if (left.length) el.setAttribute(SERVER_APPLIED_ATTR, left.join(' '));\n else el.removeAttribute(SERVER_APPLIED_ATTR);\n delete all[token];\n if (Object.keys(all).length) el.setAttribute(SERVER_ORIG_ATTR, JSON.stringify(all));\n else el.removeAttribute(SERVER_ORIG_ATTR);\n }\n if (edit.operation === 'insert_placement') {\n for (const spot of Array.from(document.querySelectorAll(`div[${SERVER_SPOT_ATTR}][data-joryio-placement]`))) {\n if (spot.getAttribute(SERVER_SPOT_ATTR) === token && spot.getAttribute('data-joryio-placement') === edit.placementKey) spot.remove();\n }\n }\n }\n\n // ── reporting ────────────────────────────────────────────────────────────\n\n private reportDisplayed(x: PageEditExperienceWire): void {\n if (!x.deliveryToken || this.runtime.consent() !== 'granted') return;\n const once = `displayed:${x.deliveryId || x.deliveryToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post({\n campaignId: x.id,\n ...(x.variantId ? { variantId: x.variantId } : {}),\n deliveryToken: x.deliveryToken,\n action: 'displayed',\n displayedAt: new Date().toISOString(),\n });\n }\n\n private reportControl(x: PageEditExperienceWire): void {\n if (!x.controlToken || this.runtime.consent() !== 'granted') return;\n const once = `control:${x.controlToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post({ action: 'control_viewed', controlToken: x.controlToken, viewedAt: new Date().toISOString() });\n }\n\n private post(body: Record<string, any>): void {\n const userId = this.identity.getUserId();\n const full = { ...body, ...(userId ? { userId } : {}), anonymousId: this.identity.getAnonymousId(), sessionId: this.session.getSessionId(), deviceType: 'web' };\n fetch(`${this.apiEndpoint}/v1/in-app/track`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : this.identity.getAnonymousId()) || {}),\n },\n body: JSON.stringify(full),\n keepalive: true,\n })\n .then((r) => {\n if (!r.ok) this.runtime.noteStatus?.(r.status, null);\n })\n .catch((error) => this.logger.debug('Page edit report failed', error));\n }\n}\n","/**\n * The files the core loads on demand from the SDK host, next to\n * `joryio.min.js`: the point-and-click editor (`joryio-editor.min.js`,\n * src/core/editor-gate.ts) and the default card feed (`joryio-cards-ui.min.js`,\n * src/core/cards.ts). Kept out of the core so that a visitor who never needs\n * them never downloads them (BACKLOG D444).\n */\nimport { SDK_VERSION } from './config';\n\nexport const SDK_HOST = 'https://sdk.joryio.com';\n\n/** A core bundle's own file name: what a script tag loads (sdk.joryio.com, the npm package's dist/). */\nconst CORE_FILE = /\\/joryio(?:\\.umd)?(?:\\.min)?\\.js$/;\n\n/**\n * The folder the running core was loaded from (with a trailing slash), when\n * it was loaded by a script tag as `joryio.min.js` over https - for example\n * `https://sdk.joryio.com/web/1.4.0-beta.4/`. Null when bundled into the\n * site's own code (the script is then the site's file), or not over https.\n */\nexport function coreFolderOf(src: string | null | undefined): string | null {\n if (!src || typeof src !== 'string') return null;\n let u: URL;\n try {\n u = new URL(src);\n } catch {\n return null;\n }\n if (u.protocol !== 'https:' || !CORE_FILE.test(u.pathname)) return null;\n return `${u.origin}${u.pathname.replace(/[^/]*$/, '')}`;\n}\n\n/**\n * Read while this module is evaluated, i.e. while the core's script runs:\n * `document.currentScript` is null afterwards (and for a module script),\n * then the last `<script src=\".../joryio.min.js\">` on the page is used.\n */\nfunction readOwnFolder(): string | null {\n if (typeof document === 'undefined') return null;\n try {\n const current = document.currentScript as HTMLScriptElement | null;\n const fromCurrent = coreFolderOf(current && current.src);\n if (fromCurrent || (current && current.src)) return fromCurrent;\n const tags = document.querySelectorAll('script[src]');\n for (let i = tags.length - 1; i >= 0; i--) {\n const folder = coreFolderOf((tags[i] as HTMLScriptElement).src);\n if (folder) return folder;\n }\n } catch {\n /* no DOM access */\n }\n return null;\n}\nconst OWN_FOLDER = readOwnFolder();\n\n/**\n * Where a lazily loaded file comes from, in order:\n * 1. the folder the core itself was loaded from (`coreFolderOf`), so a core\n * from `sdk.joryio.com/web/1.4.0-beta.6/` or from the npm package's\n * `dist/` on a CDN loads the side files of the same build - unless that\n * folder is the major channel `sdk.joryio.com/web/<major>/`, which moves:\n * then 2 goes first;\n * 2. the exact SDK version's folder on the SDK host (immutable, the same\n * build as this core). A beta's SDK_VERSION is the beta's own version\n * (from 1.4.0-beta.6 the release build stamps it), so this is\n * `web/1.4.0-beta.6/`, the only folder a beta is published to;\n * 3. the major channel, as a fallback (a version not on the CDN, such as a\n * local build) - never for a pre-release: the channel carries finals\n * only, so a beta would get the previous final's side files.\n * An init option (`editorScriptUrl`, `cardsUiScriptUrl`) replaces all of\n * them, for a self-hosted SDK.\n */\nexport function sdkHostFileUrls(file: string, override?: string, ownFolder: string | null = OWN_FOLDER, version: string = SDK_VERSION): string[] {\n if (override) return [override];\n const major = version.split('.')[0];\n const exact = `${SDK_HOST}/web/${version}/${file}`;\n const channel = `${SDK_HOST}/web/${major}/${file}`;\n const prerelease = version.includes('-');\n let urls = ownFolder && ownFolder !== `${SDK_HOST}/web/${major}/` ? [`${ownFolder}${file}`, exact, channel] : [exact, channel];\n if (prerelease) urls = urls.filter((u) => u !== channel);\n return urls.filter((u, i) => urls.indexOf(u) === i);\n}\n\n/** Inject one script tag; resolves when it ran (onload), rejects on an error (a 404, a blocking CSP). */\nexport function loadSdkScript(src: string, marker: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const s = document.createElement('script');\n s.src = src;\n s.async = true;\n s.setAttribute(marker, 'bundle');\n s.onload = () => resolve();\n s.onerror = () => {\n s.remove();\n reject(new Error(`could not load ${src}`));\n };\n (document.head || document.documentElement).appendChild(s);\n });\n}\n","/**\n * The point-and-click editor's door in the core bundle (BACKLOG D444 Phase 4,\n * docs/PLACEMENTS_WEBSITE_LAYER.md 3).\n *\n * The visual editor itself (highlight, panel, selector computation) is a\n * separate file, `joryio-editor.min.js`, served from the same SDK host next to\n * `joryio.min.js`, so the ~every-visitor bundle carries only this handshake:\n *\n * 1. only when the tab was opened with `?joryio_editor=1` AND by another\n * window (`window.opener`) AND page edits are not switched off in the\n * site's code (`pageEdits: false`), post `joryio:editor-ready` to the\n * opener (no secret in it);\n * 2. accept `joryio:editor-token` only from that opener window, and check\n * the token with `POST /v1/in-app/editor/verify`, which answers the\n * dashboard origin it was minted for (bound to this site's origin and\n * this SDK key's workspace; refused when page edits are off);\n * 3. only then load the editor bundle and hand it the verified dashboard\n * origin and the opener. Nothing is loaded for any other visitor.\n */\nimport type { Logger } from '../utils/logger';\nimport { sdkIdentityHeaders } from './config';\nimport { loadSdkScript, sdkHostFileUrls } from './sdk-host-files';\n\nexport const EDITOR_QUERY_FLAG = 'joryio_editor';\nexport const EDITOR_MESSAGES = {\n READY: 'joryio:editor-ready',\n TOKEN: 'joryio:editor-token',\n ACTIVE: 'joryio:editor-active',\n PICK: 'joryio:editor-pick',\n CLOSE: 'joryio:editor-close',\n CLOSED: 'joryio:editor-closed',\n} as const;\n\n/** The global the editor bundle registers itself under, and the contract version between the two files. */\nexport const EDITOR_GLOBAL = '__joryioEditor';\nexport const EDITOR_API_VERSION = 1;\n/** The file next to joryio.min.js on the SDK host. */\nexport const EDITOR_BUNDLE_FILE = 'joryio-editor.min.js';\n\nexport interface EditorBundleApi {\n version: number;\n start(ctx: { dashboardOrigin: string; opener: Window; logger: Logger; onStop: () => void }): { stop(): void };\n}\n\n/**\n * Where the editor bundle is loaded from: the exact SDK version's folder on\n * the SDK host, then the major channel (see sdkHostFileUrls).\n * `editorScriptUrl` (init) replaces both, for a self-hosted SDK.\n */\nexport function editorBundleUrls(override?: string): string[] {\n return sdkHostFileUrls(EDITOR_BUNDLE_FILE, override);\n}\n\n/** True when this tab was opened by the dashboard's editor (the flag and an opener). */\nexport function editorRequested(): boolean {\n try {\n return typeof window !== 'undefined' && !!window.opener && new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) === '1';\n } catch {\n return false;\n }\n}\n\n/** The flag's value on the editor's own Mobile view (a frame of the page at phone width, 1.4.0-beta.8). */\nexport const EDITOR_FRAME_FLAG = 'frame';\n\n/**\n * True in the editor's Mobile view: a same-origin frame of the page, opened\n * with `?joryio_editor=frame` by the editor running in its parent tab. The\n * SDK there is inert (no page view, no in-app message, no page edit): the\n * frame is a preview the editor draws on, not a visit. A frame on another\n * origin, or one whose parent is not a running editor, is a normal page.\n */\nexport function editorFrame(): boolean {\n try {\n if (typeof window === 'undefined' || window.parent === window) return false;\n if (new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) !== EDITOR_FRAME_FLAG) return false;\n // Reading the parent's global throws across origins.\n return !!(window.parent as any)[EDITOR_GLOBAL];\n } catch {\n return false;\n }\n}\n\nfunction loadScript(src: string): Promise<void> {\n return loadSdkScript(src, 'data-joryio-editor');\n}\n\nexport class EditorGate {\n private opener: Window | null = null;\n private dashboardOrigin: string | null = null;\n private verifying = false;\n private session: { stop(): void } | null = null;\n private off: (() => void) | null = null;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private logger: Logger,\n private options: { scriptUrl?: string; load?: (src: string) => Promise<void> } = {},\n ) {}\n\n /** Step 1. Does nothing unless the dashboard's editor opened this tab. */\n start(): void {\n if (!editorRequested() || this.opener) return;\n this.opener = window.opener as Window;\n const onMessage = (e: MessageEvent) => void this.onMessage(e);\n window.addEventListener('message', onMessage);\n this.off = () => window.removeEventListener('message', onMessage);\n try {\n // No secret in it, so any target origin: the dashboard checks it came from the tab it opened.\n this.opener.postMessage({ type: EDITOR_MESSAGES.READY }, '*');\n } catch {\n /* the opener went away */\n }\n }\n\n isActive(): boolean {\n return !!this.session;\n }\n\n stop(): void {\n const session = this.session;\n this.session = null;\n session?.stop();\n this.off?.();\n this.off = null;\n this.dashboardOrigin = null;\n this.opener = null;\n }\n\n private async onMessage(e: MessageEvent): Promise<void> {\n const data = e.data as { type?: string; token?: string } | null;\n if (!data || typeof data.type !== 'string' || this.dashboardOrigin) return;\n if (data.type !== EDITOR_MESSAGES.TOKEN || e.source !== this.opener || typeof data.token !== 'string' || this.verifying) return;\n this.verifying = true;\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/editor/verify`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey, ...sdkIdentityHeaders() },\n body: JSON.stringify({ token: data.token }),\n });\n const answer = res.ok ? await res.json() : null;\n // The token says which dashboard may talk to this tab; the message must have come from it.\n if (!answer?.valid || typeof answer.dashboardOrigin !== 'string' || answer.dashboardOrigin !== e.origin) {\n this.logger.warn('Joryio editor: the editor token was not accepted for this site');\n return;\n }\n this.dashboardOrigin = answer.dashboardOrigin;\n // The message listener of the handshake is done; the editor installs its own.\n this.off?.();\n this.off = null;\n await this.loadAndStart(answer.dashboardOrigin);\n } catch (error) {\n this.logger.debug('Joryio editor verification failed', error);\n } finally {\n this.verifying = false;\n }\n }\n\n /** Step 3: the bundle, only now. */\n private async loadAndStart(dashboardOrigin: string): Promise<void> {\n const load = this.options.load ?? loadScript;\n let api: EditorBundleApi | undefined = (window as any)[EDITOR_GLOBAL];\n for (const src of api ? [] : editorBundleUrls(this.options.scriptUrl)) {\n try {\n await load(src);\n api = (window as any)[EDITOR_GLOBAL];\n if (api) break;\n } catch (error) {\n this.logger.debug('Joryio editor bundle failed to load', error);\n }\n }\n if (!api || api.version !== EDITOR_API_VERSION || typeof api.start !== 'function' || !this.opener) {\n this.logger.warn('Joryio editor: the editor could not be loaded (check that your Content-Security-Policy allows sdk.joryio.com)');\n return;\n }\n this.session = api.start({ dashboardOrigin, opener: this.opener, logger: this.logger, onStop: () => this.stop() });\n }\n}\n","/**\n * The editor's words. English is built in; the dashboard sends the same keys\n * in the marketer's language with `joryio:editor-context` (`strings`, plus\n * `dir` for Hebrew and Arabic), so the five dashboard locales reach the\n * editor without shipping every translation to the customer's site. A key\n * the dashboard does not send stays English. `{name}` placeholders are\n * filled with text, never parsed as HTML.\n */\nexport const EDITOR_STRINGS = {\n title: 'Joryio editor',\n variant: 'Variant {name}',\n hintPoint: 'Point at anything on the page',\n hintEditing: 'Editing · changes show live',\n editsOne: '1 edit',\n editsMany: '{n} edits',\n noEdits: 'No edits yet.',\n undo: 'Undo last edit',\n undoOffline: 'Undo is available once the Joryio dashboard is connected',\n saveReturn: 'Save & return to Joryio',\n clickToEdit: 'click to edit',\n helpTitle: 'Not the right box?',\n helpUp: 'Select the section around it',\n helpDown: 'Select something inside it',\n helpClickKey: 'Click',\n helpClick: 'Edit this one',\n dismiss: 'Dismiss',\n page: 'Page',\n up: 'Select the element around it',\n down: 'Select the first element inside it',\n matchOne: '1 match on page',\n matchMany: 'Matches {n} - all will change',\n matchNone: 'Not found',\n whatToDo: 'What do you want to do?',\n actText: 'Change text',\n actLink: 'Change link',\n actImage: 'Change image',\n actHide: 'Hide it',\n actSlot: 'Add content slot',\n noText: 'No text here',\n notLink: 'Not a link',\n notImage: 'Not an image',\n newText: 'New text',\n was: 'Was: \"{value}\"',\n insert: 'Insert',\n fallbackFor: 'If {name} is missing',\n fallbackHelp: \"Shown to visitors we don't know yet.\",\n fallbackBad: 'Plain text only - no Liquid here.',\n fallbackDone: 'Done',\n liquid: 'Liquid code',\n more: 'More…',\n search: 'Search fields',\n noMatch: 'No matching fields',\n groupProfile: 'Profile',\n groupCustom: 'Custom fields',\n rawNote: 'Shown as code: this text uses Liquid beyond profile fields and fallbacks.',\n newLink: 'New link address',\n newImage: 'New image address',\n urlBad: 'Enter an address starting with https:// (or http://).',\n hideNote: \"The {kind} is removed for people in this campaign's audience. Everyone else still sees it.\",\n hiddenFor: 'Hidden for this audience',\n slotName: 'Slot name',\n savedAs: 'Saved as',\n slotHelp: 'Filled by a Placement campaign or a journey step.',\n slotEmpty: 'Enter a name for the slot.',\n slotCreate: 'Create content for this slot →',\n slotIn: 'In this slot:',\n slotAddAnother: '+ Add another campaign',\n where: 'Where',\n posBefore: 'Above it',\n posAfter: 'Below it',\n posReplace: 'Instead of it',\n posPrepend: 'Inside, at the start',\n posAppend: 'Inside, at the end',\n slotPreview: 'Content slot',\n view: 'View',\n viewDesktop: 'Desktop',\n viewMobile: 'Mobile',\n appliesTo: 'Applies to',\n devAll: 'All devices',\n devMobile: 'Mobile only',\n devDesktop: 'Desktop only',\n deviceHidden: 'Not shown in this view - switch to the other view to see it.',\n frameBlocked: 'This site does not allow itself to be shown in a frame, so the mobile view cannot open. Make this window narrower than 768 px to see and edit the mobile layout.',\n css: 'CSS selector',\n cssHelp: 'For developers. Matches {n} on this page.',\n cssBad: 'Not a selector this page can use.',\n cancel: 'Cancel',\n save: 'Save · {action}',\n noSelector: 'This element has no stable selector. Choose the element around it (arrow up) or another one.',\n kHeading: 'Heading',\n kText: 'Text',\n kLink: 'Link',\n kButton: 'Button',\n kImage: 'Image',\n kList: 'List',\n kSection: 'Section',\n kMain: 'Main',\n kHeader: 'Header',\n kFooter: 'Footer',\n kNav: 'Navigation',\n kForm: 'Form',\n kElement: 'Element',\n};\n\nexport type EditorStringKey = keyof typeof EDITOR_STRINGS;\nexport type EditorStrings = Record<EditorStringKey, string>;\n\n/** The built-in English, with the dashboard's translations over it (strings only, at most 500 characters each). */\nexport function mergeStrings(over: unknown): EditorStrings {\n const out: EditorStrings = { ...EDITOR_STRINGS };\n if (over && typeof over === 'object') {\n for (const k of Object.keys(EDITOR_STRINGS) as EditorStringKey[]) {\n const v = (over as Record<string, unknown>)[k];\n if (typeof v === 'string' && v.trim() && v.length <= 500) out[k] = v;\n }\n }\n return out;\n}\n\n/** `{name}` placeholders filled in; the result is only ever set as text. */\nexport function fill(text: string, vars: Record<string, string | number> = {}): string {\n return text.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));\n}\n","/**\n * The editor's pure parts: the Liquid of a personalized text (the same\n * `{{ user.<field> | default: \"...\" }}` the dashboard writes, packages/frontend\n * src/lib/web-experience.ts), the slot-name slug, the friendly element kind,\n * and the live-preview rendering of an edit's text.\n */\nimport type { EditorStringKey } from './editor-strings';\n\nconst OUTPUT_TAG = /\\{\\{-?([\\s\\S]*?)-?\\}\\}/g;\nconst DEFAULT_FILTER = /\\|\\s*default\\s*:\\s*(\"[^\"]*\"|'[^']*'|[^|}]*?)\\s*(?=\\||$)/;\nconst unquote = (v: string) => v.trim().replace(/^([\"'])([\\s\\S]*)\\1$/, '$2');\n\n/**\n * A fallback as a Liquid string literal. Liquid has no escape inside a\n * literal, so: double quotes; single quotes when the text has a `\"`; with\n * both, single quotes and each `'` as the typographic apostrophe (U+2019),\n * so nothing the marketer typed disappears.\n */\nexport const quoted = (fallback: string): string =>\n !fallback.includes('\"') ? `\"${fallback}\"` : !fallback.includes(\"'\") ? `'${fallback}'` : `'${fallback.replace(/'/g, '\\u2019')}'`;\n\n/** A fallback is plain text: no Liquid in it, one line, at most 200 characters. */\nexport const isPlainFallback = (v: string): boolean => v.length <= 200 && !/\\{[{%]|[}%]\\}|[\\r\\n]/.test(v);\n\n/** The `| default:` value of ONE variable's Liquid (`{{ user.x | default: \"y\" }}`), or null. */\nexport function varFallback(src: string): string | null {\n const m = /^\\{\\{-?([\\s\\S]*?)-?\\}\\}$/.exec((src || '').trim());\n const d = m && DEFAULT_FILTER.exec(m[1].trim());\n return d ? unquote(d[1]) : null;\n}\n\n/** ONE variable's Liquid with `fallback` as its own `| default:` (an empty one removes it); its path is kept. */\nexport function setVarFallback(src: string, fallback: string): string {\n const m = /^\\{\\{-?\\s*([A-Za-z_][A-Za-z0-9_.]*)/.exec((src || '').trim());\n return m ? pathTag(m[1], fallback.trim() || null) : src;\n}\n\n/** The Liquid of one profile field: defaults are `user.<name>`, custom attributes `user.custom.<name>`. */\nexport const variableTag = (name: string, custom: boolean, fallback?: string | null): string => pathTag(custom ? `user.custom.${name}` : `user.${name}`, fallback);\n\n/** The Liquid of one variable by its path (`user.firstName`, the catalog's `key`). */\nexport const pathTag = (path: string, fallback?: string | null): string => (fallback ? `{{ ${path} | default: ${quoted(fallback)} }}` : `{{ ${path} }}`);\n\n/** A Liquid variable path: dotted identifiers (`user.custom.city`). */\nexport const VAR_PATH = /^[A-Za-z_][A-Za-z0-9_]{0,63}(\\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,4}$/;\n\n/** A variable the editor shows as a placeholder pill: its field name, and (in the text field) its exact Liquid. */\nexport interface LiquidVar {\n name: string;\n path: string;\n src: string;\n}\nexport type LiquidPart = string | LiquidVar;\n\nconst pathName = (path: string) => path.replace(/^user\\.(custom\\.)?/, '');\n\n/**\n * What the page shows while editing: each `{{ path ... }}` becomes the\n * sample value the dashboard sent for that path (its known visitor), else\n * the fallback (what an unknown visitor sees), else a placeholder pill with\n * the field name (`{ name }`), so an empty spot is still visible and never\n * mistaken for page text.\n */\nexport function previewParts(value: string, sample: Record<string, string>): LiquidPart[] {\n const out: LiquidPart[] = [];\n const re = new RegExp(OUTPUT_TAG.source, 'g');\n let last = 0;\n let m: RegExpExecArray | null;\n const text = (s: string) => {\n if (!s) return;\n if (typeof out[out.length - 1] === 'string') out[out.length - 1] += s;\n else out.push(s);\n };\n value = value || '';\n while ((m = re.exec(value))) {\n text(value.slice(last, m.index));\n last = re.lastIndex;\n const expr = m[1].trim();\n const path = expr.split('|')[0].trim();\n const d = DEFAULT_FILTER.exec(expr);\n if (Object.prototype.hasOwnProperty.call(sample, path) && sample[path] !== '') text(sample[path]);\n else if (d && unquote(d[1])) text(unquote(d[1]));\n else out.push({ name: pathName(path), path, src: m[0] });\n }\n text(value.slice(last));\n return out;\n}\n\n/** previewParts as plain text (a pill as `[name]`). */\nexport const previewText = (value: string, sample: Record<string, string>): string => previewParts(value, sample).map((p) => (typeof p === 'string' ? p : `[${p.name}]`)).join('');\n\n/** A variable path with at most a quoted `| default:` - what the text field shows as a pill. */\nconst SIMPLE_VAR = /^\\{\\{-?\\s*([A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*)\\s*(?:\\|\\s*default\\s*:\\s*(?:\"[^\"]*\"|'[^']*')\\s*)?-?\\}\\}$/;\n\n/**\n * The text field's view of a text: plain parts and variables (each with its\n * exact Liquid, so the text round-trips byte for byte), or null when it holds\n * Liquid a pill cannot show (a tag like `{% if %}`, a filter other than\n * `default`, a stray brace pair) - the field then stays raw text.\n */\nexport function liquidParts(value: string): LiquidPart[] | null {\n const out: LiquidPart[] = [];\n const re = new RegExp(OUTPUT_TAG.source, 'g');\n let last = 0;\n let m: RegExpExecArray | null;\n value = value || '';\n while ((m = re.exec(value))) {\n const v = SIMPLE_VAR.exec(m[0]);\n if (!v) return null;\n if (m.index > last) out.push(value.slice(last, m.index));\n out.push({ name: pathName(v[1]), path: v[1], src: m[0] });\n last = re.lastIndex;\n }\n if (last < value.length) out.push(value.slice(last));\n return out.some((p) => typeof p === 'string' && /\\{[{%]|[}%]\\}/.test(p)) ? null : out;\n}\n\n/** A slot name as a placement key: lowercase, anything else -> `_`, no leading/trailing `_`, at most 64. */\nexport function slugify(name: string): string {\n return (name || '')\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 64)\n .replace(/_+$/, '');\n}\n\n/** A new edit id, the dashboard's format (`e` + 8 base-36 characters). */\nexport const newEditId = (): string => `e${Math.random().toString(36).slice(2, 10).padEnd(8, '0')}`;\n\n/** The friendly name of an element, by tag (or the selector's last tag when the element is not on the page). */\nexport function kindKey(tagOrSelector: string, isSelector = false): EditorStringKey {\n let t = (tagOrSelector || '').toLowerCase();\n if (isSelector) {\n const parts = t.trim().split(/[\\s>+~]+/).filter(Boolean);\n const m = /^[a-z][a-z0-9]*/.exec(parts[parts.length - 1] || '');\n t = m ? m[0] : '';\n }\n if (/^h[1-6]$/.test(t)) return 'kHeading';\n if (/^(p|span|strong|em|small|label|blockquote|b|i)$/.test(t)) return 'kText';\n if (t === 'a') return 'kLink';\n if (t === 'button') return 'kButton';\n if (t === 'img' || t === 'picture') return 'kImage';\n if (/^(ul|ol|li)$/.test(t)) return 'kList';\n if (t === 'main') return 'kMain';\n if (t === 'header') return 'kHeader';\n if (t === 'footer') return 'kFooter';\n if (t === 'nav') return 'kNav';\n if (t === 'form') return 'kForm';\n if (/^(section|div|article|aside)$/.test(t)) return 'kSection';\n return 'kElement';\n}\n","/**\n * Building blocks of the editor's UI: an element helper that only ever sets\n * attributes and text (never HTML), the icons (fixed SVG paths), and the\n * stylesheet. Everything lives inside the editor's shadow root, so the\n * site's CSS cannot restyle it and this CSS cannot reach the site.\n *\n * Colours are the Joryio product tokens of the design handoff\n * (design_handoff_web_personalization, joryio-tokens.css): navy #071342,\n * teal #31D6C8 / #00A99A, slot lavender #7A6CFF, light panel like the app.\n */\n\ntype Kid = Node | string | null | undefined | false;\n\nexport function h<K extends keyof HTMLElementTagNameMap>(tag: K, attrs?: Record<string, string | boolean | undefined> | null, ...kids: Kid[]): HTMLElementTagNameMap[K] {\n const el = document.createElement(tag);\n for (const [k, v] of Object.entries(attrs || {})) {\n if (v === undefined || v === false) continue;\n el.setAttribute(k, v === true ? '' : v);\n }\n for (const kid of kids) if (kid !== null && kid !== undefined && kid !== false) el.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);\n return el;\n}\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\nconst ICONS = {\n text: ['M4 7V5h16v2M9 19h6M12 5v14'],\n link: ['M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71', 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'],\n image: ['M3 5h18v14H3z', 'm3 16 5-5 4 4 3-3 6 6', 'M15.5 8.5h.01'],\n hide: ['M9.88 9.88a3 3 0 1 0 4.24 4.24', 'M10.73 5.08A10.4 10.4 0 0 1 12 5c7 0 10 7 10 7a13.2 13.2 0 0 1-1.67 2.68', 'M6.61 6.61A13.5 13.5 0 0 0 2 12s3 7 10 7a9.7 9.7 0 0 0 5.39-1.61', 'm2 2 20 20'],\n slot: ['M3 3h18v18H3z', 'M7 9h10v6H7z'],\n undo: ['M3 7v6h6', 'M21 17a9 9 0 0 0-15-6.7L3 13'],\n up: ['m18 15-6-6-6 6'],\n down: ['m6 9 6 6 6-6'],\n cursor: ['m4 4 7.07 17 2.51-7.39L21 11.07z'],\n code: ['m16 18 6-6-6-6M8 6l-6 6 6 6'],\n chevron: ['m9 18 6-6-6-6'],\n check: ['M20 6 9 17l-5-5'],\n close: ['M18 6 6 18M6 6l12 12'],\n desktop: ['M3 4h18v12H3z', 'M8 20h8M12 16v4'],\n mobile: ['M7 2h10v20H7z', 'M11 18h2'],\n};\nexport type IconName = keyof typeof ICONS;\n\nexport function icon(name: IconName, size = 15): SVGSVGElement {\n const s = document.createElementNS(SVG_NS, 'svg');\n for (const [k, v] of Object.entries({ width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.9', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) s.setAttribute(k, v);\n for (const d of ICONS[name]) {\n const p = document.createElementNS(SVG_NS, 'path');\n p.setAttribute('d', d);\n s.appendChild(p);\n }\n return s as SVGSVGElement;\n}\n\n/** The host element's own inline style: nothing of the site's CSS reaches inside, and the host takes no room. */\nexport const HOST_STYLE = 'all:initial !important;position:fixed !important;top:0 !important;left:0 !important;width:0 !important;height:0 !important;z-index:2147483647 !important;display:block !important';\n\n/** A preview element the editor puts IN the page (a slot, a hidden-element note): its own shadow root too. */\nexport const PREVIEW_HOST_STYLE = 'all:initial !important;display:block !important;margin:10px 0 !important';\n\n/** The editor's Mobile view width in CSS pixels (a common phone; below the 768 px breakpoint). */\nexport const MOBILE_FRAME_WIDTH = 390;\nconst FONT = 'Inter,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif';\nconst MONO = 'ui-monospace,\"SF Mono\",Menlo,monospace';\n\n/**\n * A variable with no sample value and no fallback, in the page preview: an\n * inline host that takes the site's font and line from the element it is in\n * (`all: unset`, so nothing else of the site's CSS applies) and is its own\n * bidi island, so it sits right in a right-to-left text too.\n */\nexport const PREVIEW_VAR_HOST_STYLE = 'all:unset !important;display:inline !important;unicode-bidi:isolate !important';\n\n/** The placeholder pill, the same in the page preview and in the text field: inline, never taller than the line. */\nconst PILL = `font-family:${MONO};font-size:.8em;font-weight:600;line-height:1;padding:.12em .5em;border-radius:999px;background:rgba(0,169,154,.14);color:#0F766E;box-shadow:inset 0 0 0 1px rgba(0,169,154,.5);white-space:nowrap;unicode-bidi:isolate;font-style:normal;text-transform:none;letter-spacing:0`;\n\nexport const PREVIEW_CSS = `.v{${PILL}}.s,.x{font:12.5px/1.4 ${FONT};border-radius:10px;padding:14px 16px;text-align:center}.s{border:2px dashed #7A6CFF;background:#F4F2FF;color:#4C3FD1}.s b{font-weight:700}.s code{font-family:${MONO}}.s div{font-size:11.5px;color:#6B5FD9;margin-top:3px}.x{border:1.5px dashed #F04438;background:#FEF3F2;color:#B42318;text-align:start;padding:10px 12px;font-size:12px}`;\n\nexport const EDITOR_CSS = `\n*{box-sizing:border-box}\n.r{font:13px/1.4 ${FONT};color:#242B3A;-webkit-font-smoothing:antialiased}\nbutton{font:inherit;color:inherit;cursor:pointer}\nbutton:disabled{cursor:not-allowed}\nbutton:focus-visible,input:focus-visible,textarea:focus-visible,.ce:focus{outline:2px solid #31D6C8;outline-offset:1px}\n.box{position:fixed;pointer-events:none;border:2px dashed #00A99A;background:rgba(0,169,154,.07);border-radius:4px;display:none}\n.box.sel{border-style:solid;background:rgba(0,169,154,.04)}\n.chip{position:absolute;bottom:100%;inset-inline-start:-2px;margin-bottom:2px;background:#00A99A;color:#fff;font-size:11px;font-weight:600;padding:3px 8px;border-radius:6px 6px 6px 0;white-space:nowrap;max-width:60vw;overflow:hidden;text-overflow:ellipsis}\n.help{position:fixed;top:16px;inset-inline-end:16px;width:240px;background:#fff;border:1px solid #E5EAF2;border-radius:10px;box-shadow:0 8px 24px rgba(10,18,64,.14);padding:10px 12px}\n.help h3{margin:0 0 6px;font-size:11px;font-weight:700;color:#6B7280;letter-spacing:.5px;text-transform:uppercase}\n.help .row{display:flex;align-items:center;gap:8px;font-size:12px;padding:3px 0}\n.kbd{min-width:38px;text-align:center;font-size:11px;font-weight:600;border:1px solid #E5EAF2;border-radius:5px;padding:1px 5px;background:#F8FAFC}\n.help .x{position:absolute;top:6px;inset-inline-end:6px;border:0;background:none;color:#8990A8;padding:2px;display:grid}\n.dock{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:6px;background:#071342;color:#fff;border-radius:14px;padding:7px 7px 7px 14px;box-shadow:0 12px 32px rgba(10,18,64,.35);white-space:nowrap;max-width:calc(100vw - 24px)}\n.r.open .dock{left:calc(50% - 190px)}\n.r.open[dir=rtl] .dock{left:calc(50% + 190px)}\n.logo{width:22px;height:22px;border-radius:6px;background:#fff;color:#071342;display:grid;place-items:center;font-weight:800;font-size:13px;flex:none}\n.name{font-size:12.5px;font-weight:600;margin-inline-start:4px;overflow:hidden;text-overflow:ellipsis;max-width:200px}\n.sub{font-size:12px;color:#A8AEC1;overflow:hidden;text-overflow:ellipsis;max-width:220px}\n.sep{width:1px;height:22px;background:#2A3366;margin:0 8px;flex:none}\n.hint{font-size:12px;color:#C9CEDD;display:inline-flex;align-items:center;gap:6px}\n.hint svg{color:#31D6C8}\n.db{display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 10px;border-radius:8px;border:0;background:#1B245A;color:#fff;font-size:12.5px;font-weight:600}\n.ib{height:32px;width:32px;border-radius:8px;border:0;background:transparent;color:#fff;display:grid;place-items:center}\n.ib:disabled{color:#4A527A}\n.go{height:32px;padding:0 14px;border-radius:8px;border:0;background:#31D6C8;color:#071342;font-size:12.5px;font-weight:700}\n.pop{position:absolute;bottom:calc(100% + 10px);left:0;right:0;min-width:280px;max-height:50vh;overflow:auto;background:#fff;color:#242B3A;border-radius:12px;border:1px solid #E5EAF2;box-shadow:0 12px 32px rgba(10,18,64,.18);padding:6px;white-space:normal}\n.pop .e{display:flex;align-items:center;gap:10px;width:100%;padding:8px 10px;border:0;background:none;border-radius:8px;font-size:12.5px;text-align:start}\n.pop .e:hover{background:#F8FAFC}\n.pop .empty{padding:12px;font-size:12.5px;color:#6B7280}\n.num{width:20px;height:20px;border-radius:99px;background:#071342;color:#fff;font-size:11px;font-weight:700;display:grid;place-items:center;flex:none}\n.panel{position:fixed;top:0;bottom:0;inset-inline-end:0;width:380px;max-width:100vw;background:#fff;border-inline-start:1px solid #E5EAF2;box-shadow:-8px 0 24px rgba(10,18,64,.06);display:flex;flex-direction:column}\n.hd{padding:16px 18px 14px;border-bottom:1px solid #E5EAF2}\n.crumbs{display:flex;align-items:center;flex-wrap:wrap;gap:4px;font-size:11.5px;color:#6B7280;margin-bottom:6px}\n.crumbs svg{color:#A8AEC1}\n.crumb{border:0;background:transparent;color:#6B7280;font-weight:500;font-size:11.5px;padding:2px 6px;border-radius:5px}\n.crumb.cur{background:#E5F9F6;color:#0F766E;font-weight:600}\n.nav{margin-inline-start:auto;display:flex;gap:2px}\n.nav button{border:1px solid #E5EAF2;background:#fff;border-radius:6px;width:24px;height:22px;display:grid;place-items:center;color:#3A4060;padding:0}\n.nav button:disabled{opacity:.4}\n.tr{display:flex;align-items:center;gap:10px}\n.title{font-size:17px;font-weight:700;color:#0A1240;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}\n.pill{margin-inline-start:auto;display:inline-flex;align-items:center;gap:4px;font-size:11.5px;font-weight:600;padding:3px 8px;border-radius:999px;white-space:nowrap;flex:none}\n.pill.ok{background:#E5F9F6;color:#0F766E}\n.pill.many{background:#FFF7E6;color:#92400E}\n.pill.none{background:#FEF3F2;color:#B42318}\n.bd{padding:16px 18px;overflow:auto;flex:1}\n.lbl{display:block;font-size:12.5px;font-weight:600;color:#242B3A;margin-bottom:8px}\n.tiles{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:18px}\n.tile{display:flex;align-items:center;gap:9px;padding:10px 11px;border-radius:10px;text-align:start;background:#fff;border:1.5px solid #E5EAF2;color:#3A4060}\n.tile[aria-checked=true]{background:#E5F9F6;border-color:#00C8B7;color:#0F766E}\n.tile.slot[aria-checked=true]{background:#F4F2FF;border-color:#7A6CFF;color:#4C3FD1}\n.tile:disabled{opacity:.55}\n.tile[data-e]>span::after{content:'';display:inline-block;width:6px;height:6px;border-radius:9px;background:#00A99A;margin-inline-start:6px;vertical-align:middle}\n.tile b{display:block;font-size:12.5px;font-weight:600;color:#0A1240}\n.tile small{display:block;font-size:10.5px;color:#6B7280}\n.fr{display:flex;align-items:baseline;margin-bottom:8px}\n.fr .lbl{margin:0}\n.was{margin-inline-start:auto;font-size:11.5px;color:#6B7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:55%}\ntextarea,input,.ce{width:100%;font:inherit;font-size:13.5px;color:#0F1424;padding:10px 12px;border-radius:10px;border:1.5px solid #E5EAF2;background:#fff;outline:none}\ntextarea,.ce{line-height:1.5;resize:vertical;border-color:#00C8B7}\n.ce{min-height:72px;white-space:pre-wrap;overflow-wrap:anywhere;cursor:text}\n.vp{${PILL};cursor:pointer}\n.vp .vfb{font-weight:400;opacity:.75}\n.fbp .vc{margin-top:8px}\n.slotc{display:flex;flex-direction:column;align-items:flex-start;gap:6px}\n.slotc .lbl{margin:0}\n.lnk{border:0;background:none;padding:0;color:#4C3FD1;font-size:12.5px;font-weight:600;text-align:start}\ntextarea.mono{height:auto}\ninput{height:40px;padding:0 12px}\ninput.slotin{border-color:#7A6CFF}\n.mono{font-family:${MONO};font-size:12px;height:36px;background:#F8FAFC;border-width:1px}\n.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px;align-items:center}\n.chips span{font-size:11.5px;color:#6B7280;margin-inline-end:2px}\n.vc{font-family:${MONO};font-size:11.5px;padding:3px 8px;border-radius:6px;border:1px solid #E5EAF2;background:#F8FAFC;color:#3A4060}\n.vc.ui{font-family:${FONT};font-weight:600;letter-spacing:normal}\n.pk{margin-top:8px;border:1px solid #E5EAF2;border-radius:10px;padding:6px;background:#fff;box-shadow:0 8px 24px rgba(10,18,64,.1)}\n.pk input{height:34px}\n.pk [role=listbox]{position:relative;max-height:220px;overflow:auto;overflow-anchor:none;margin-top:6px;padding-top:2px}\n.pk .g{font-size:10.5px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:.4px;padding:8px 8px 3px}\n.pk .o{display:flex;justify-content:space-between;align-items:baseline;gap:8px;padding:6px 8px;border-radius:7px;font-size:12.5px;cursor:pointer}\n.pk .o[aria-selected=true],.pk .o:hover{background:#E5F9F6}\n.pk code{font-family:${MONO};font-size:11px;color:#6B7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n[hidden]{display:none!important}\n.help2{font-size:11.5px;color:#6B7280;margin-top:5px}\n.err{font-size:11.5px;color:#B42318;margin-top:5px}\n.mt{margin-top:14px}\n.note{background:#FFF7E6;border:1px solid #FCD34D;border-radius:10px;padding:10px 12px;font-size:12.5px;color:#92400E;line-height:1.5}\n.key{font-family:${MONO};color:#4C3FD1;background:#F4F2FF;padding:1px 6px;border-radius:4px}\n.seg{display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;background:#F3F5FA;border-radius:9px;padding:3px}\n.seg button{border:0;background:transparent;border-radius:7px;padding:6px 4px;font-size:12px;color:#3A4060}\n.seg button[aria-checked=true]{background:#fff;color:#0A1240;font-weight:600;box-shadow:0 1px 2px rgba(10,18,64,.08)}\n.vw{display:inline-flex;gap:2px;background:#1B245A;border-radius:8px;padding:2px}\n.vw button{height:28px;width:30px;border:0;border-radius:6px;background:transparent;color:#A8AEC1;display:grid;place-items:center}\n.vw button[aria-checked=true]{background:#31D6C8;color:#071342}\n.bdg{margin-inline-start:auto;font-size:10.5px;font-weight:600;padding:2px 7px;border-radius:999px;background:#F4F2FF;color:#4C3FD1;white-space:nowrap}\n.dv.top{margin-bottom:18px;padding:10px;border-radius:10px;background:#F4F2FF}\n.stage{position:fixed;inset:0;background:#E9ECF3;display:flex;justify-content:center;align-items:flex-start;padding:16px 16px 76px}\n.r.open .stage{inset-inline-end:380px}\n.stage iframe{width:${MOBILE_FRAME_WIDTH}px;max-width:100%;height:100%;border:0;border-radius:18px;background:#fff;box-shadow:0 12px 32px rgba(10,18,64,.18)}\n.fnote{max-width:360px;margin-top:40px}\n.css{margin-top:20px;display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;padding:0;color:#6B7280;font-size:12px}\n.ft{padding:12px 18px;border-top:1px solid #E5EAF2;display:flex;gap:10px;background:#F8FAFC}\n.cancel{height:38px;padding:0 14px;border-radius:10px;border:1px solid #E5EAF2;background:#fff;color:#242B3A;font-size:13px;font-weight:600}\n.save{flex:1;height:38px;border-radius:10px;border:0;background:#071342;color:#fff;font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.save:disabled{opacity:.45}\n@media (max-width:760px){.r.open .dock{display:none}.help{display:none}}\n`;\n","/**\n * The \"New text\" field: the text with its variables as placeholder pills\n * (the same pill as the page preview), the stored value unchanged Liquid.\n *\n * - Pill mode (the text has only plain text, `{{ user.x }}` and\n * `| default: \"...\"`): a contenteditable box; each variable is an atomic\n * `contenteditable=false` pill carrying its exact Liquid, so the value\n * round-trips byte for byte. Backspace / Delete next to a pill removes the\n * whole pill, arrow keys step over it (the browser's own handling of a\n * non-editable inline), copy and cut put the Liquid on the clipboard, paste\n * is plain text only (Liquid in it becomes pills). Enter is ignored - a\n * page text edit is one run of text.\n * - Raw mode (anything a pill cannot show: `{% if %}`, other filters): a\n * textarea with the Liquid and a short note, so nothing is lost.\n *\n * - Each pill has its own fallback: a click on it (or Enter / Space on it)\n * opens a small popover, \"If <field> is missing\" + one input, that writes\n * `| default: \"...\"` on THAT variable only. A pill with a fallback shows it\n * after its name (\"firstName · friend\"). The fallback is plain text - Liquid\n * in it is refused. Esc, Enter or Done closes the popover.\n *\n * Inside the editor's closed shadow root the caret comes from the root's\n * own getSelection() where the browser has it (Chromium), else the\n * document's; with no caret in the box an Insert appends, as before.\n */\nimport { isPlainFallback, liquidParts, setVarFallback, varFallback, type LiquidVar } from './editor-model';\nimport { fill } from './editor-strings';\nimport { h } from './editor-ui';\n\nexport interface LiquidField {\n el: HTMLElement;\n /** Show a value (re-renders; the mode follows the value). */\n set(value: string): void;\n /** Insert one variable's Liquid at the caret (or at the end). */\n insert(tag: string): void;\n /** Close a pill's fallback popover; true when one was open. */\n closePop(): boolean;\n /** Open the fallback popover of the (first) pill of this variable path; false when there is none. */\n openPill(path: string): boolean;\n}\n\n/** The words of a pill's fallback popover: `title` has `{name}`, the field's label. */\nexport interface FallbackWords {\n title: string;\n help: string;\n bad: string;\n done: string;\n}\n\nconst PILL_ATTR = 'data-liquid';\nconst isPill = (n: Node | null | undefined): n is HTMLElement => !!n && n.nodeType === 1 && (n as Element).hasAttribute(PILL_ATTR);\n\n/** A box's content as Liquid: text as is, a pill as its Liquid, a browser-inserted `<br>` as nothing. */\nexport function serialize(n: Node): string {\n if (n.nodeType === 3) return (n as Text).data;\n if (isPill(n)) return n.getAttribute(PILL_ATTR) || '';\n let s = '';\n for (const k of Array.from(n.childNodes)) s += serialize(k);\n return s;\n}\n\nexport function liquidField(opts: {\n label: string;\n rawNote: string;\n root: ShadowRoot | null;\n onChange: (value: string) => void;\n labelOf?: (path: string) => string | undefined;\n fallback?: FallbackWords;\n}): LiquidField {\n const el = h('div', { 'data-j': 'text-box' });\n let value = '';\n let box: HTMLElement | null = null;\n let saved: Range | null = null;\n let pop: HTMLElement | null = null;\n\n const selection = (): Selection | null => {\n const r = opts.root as unknown as { getSelection?: () => Selection | null } | null;\n return (r && typeof r.getSelection === 'function' ? r.getSelection() : null) || document.getSelection();\n };\n /** The selection as a Range in the box: Chromium's root.getSelection(), else getComposedRanges (Safari, Firefox), else the plain range. */\n const caret = (): Range | null => {\n const s = selection();\n if (!s || !s.rangeCount) return null;\n let r: Range | null = s.getRangeAt(0);\n const composed = (s as unknown as { getComposedRanges?: (o: unknown) => StaticRange[] }).getComposedRanges;\n if (opts.root && composed && !(box && box.contains(r.startContainer))) {\n try {\n const sr = composed.call(s, { shadowRoots: [opts.root] })[0];\n r = document.createRange();\n r.setStart(sr.startContainer, sr.startOffset);\n r.setEnd(sr.endContainer, sr.endOffset);\n } catch {\n r = null;\n }\n }\n return box && r && box.contains(r.startContainer) && box.contains(r.endContainer) ? r : null;\n };\n const remember = () => {\n const r = caret();\n if (r) saved = r.cloneRange();\n };\n const emit = () => {\n if (box && box.tagName === 'DIV') value = serialize(box);\n remember();\n opts.onChange(value);\n };\n const putCaret = (r: Range) => {\n const s = selection();\n try {\n if (s && s.setBaseAndExtent) s.setBaseAndExtent(r.startContainer, r.startOffset, r.endContainer, r.endOffset);\n else if (s) {\n s.removeAllRanges();\n s.addRange(r);\n }\n } catch {\n /* no selection here */\n }\n saved = r.cloneRange();\n };\n const labelOf = (v: LiquidVar) => (opts.labelOf && opts.labelOf(v.path)) || v.name;\n const pill = (v: LiquidVar) => {\n const fb = varFallback(v.src);\n const label = labelOf(v);\n const words = opts.fallback;\n return h(\n 'span',\n {\n class: 'vp',\n contenteditable: 'false',\n dir: 'auto',\n title: v.src,\n [PILL_ATTR]: v.src,\n 'data-path': v.path,\n ...(words ? { role: 'button', tabindex: '0', 'aria-haspopup': 'dialog', 'aria-label': fb ? `${label} · ${fb}` : label } : {}),\n },\n label,\n fb ? h('span', { class: 'vfb', 'data-j': 'pill-fallback' }, ` · ${fb}`) : null,\n );\n };\n\n const closePop = (): boolean => {\n if (!pop) return false;\n pop.remove();\n pop = null;\n return true;\n };\n /** A pill's own fallback: the popover under the field, writing that pill's `| default:` as it is typed. */\n const openPop = (target: HTMLElement) => {\n const words = opts.fallback;\n if (!words || !box || box.tagName !== 'DIV') return;\n closePop();\n let cur = target;\n const v = { path: cur.getAttribute('data-path') || '', name: '', src: cur.getAttribute(PILL_ATTR) || '' };\n v.name = v.path.replace(/^user\\.(custom\\.)?/, '');\n const title = fill(words.title, { name: labelOf(v) });\n const input = h('input', { dir: 'auto', 'data-j': 'fallback', 'aria-label': title, maxlength: '200' });\n input.value = varFallback(v.src) || '';\n const err = h('div', { class: 'err', 'data-j': 'fallback-error', role: 'alert' });\n const done = h('button', { class: 'vc ui', type: 'button', 'data-j': 'fallback-done' }, words.done);\n const p = h('div', { class: 'pk fbp', role: 'dialog', 'aria-label': title, 'data-j': 'fallback-pop' }, h('label', { class: 'lbl' }, title), input, err, h('div', { class: 'help2' }, words.help), done);\n const finish = () => {\n closePop();\n try {\n cur.focus();\n } catch {\n /* gone */\n }\n };\n input.addEventListener('input', () => {\n const ok = isPlainFallback(input.value);\n err.textContent = ok ? '' : words.bad;\n if (!ok) return;\n const src = setVarFallback(cur.getAttribute(PILL_ATTR) || '', input.value);\n const next = pill({ ...v, src });\n if (cur.parentNode) cur.parentNode.replaceChild(next, cur);\n cur = next;\n if (box && box.tagName === 'DIV') value = serialize(box);\n opts.onChange(value);\n });\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' || e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n finish();\n }\n });\n done.addEventListener('click', finish);\n // Focus leaving the popover (Tab away, a click elsewhere) closes it.\n p.addEventListener('focusout', (e) => {\n const to = e.relatedTarget as Node | null;\n if (pop === p && (!to || !p.contains(to))) closePop();\n });\n pop = p;\n el.appendChild(p);\n input.focus();\n };\n\n const set = (v: string) => {\n value = v;\n saved = null;\n pop = null;\n el.textContent = '';\n const parts = liquidParts(v);\n if (!parts) {\n const area = h('textarea', { rows: '3', dir: 'auto', 'data-j': 'text', 'aria-label': opts.label });\n area.value = v;\n area.addEventListener('input', () => {\n value = area.value;\n opts.onChange(value);\n });\n area.addEventListener('blur', () => liquidParts(value) && set(value));\n box = area;\n el.append(area, h('div', { class: 'help2', 'data-j': 'raw-note' }, opts.rawNote));\n return;\n }\n const ce = h('div', { class: 'ce', contenteditable: 'true', role: 'textbox', 'aria-multiline': 'true', dir: 'auto', spellcheck: 'false', 'data-j': 'text', 'aria-label': opts.label });\n for (const p of parts) ce.append(typeof p === 'string' ? document.createTextNode(p) : pill(p));\n ce.addEventListener('input', emit);\n ce.addEventListener('keyup', remember);\n ce.addEventListener('mouseup', remember);\n ce.addEventListener('click', (e) => {\n const t = e.target instanceof Element ? (e.target.closest(`[${PILL_ATTR}]`) as HTMLElement | null) : null;\n if (t && ce.contains(t)) openPop(t);\n });\n ce.addEventListener('keydown', (e) => {\n const onPill = e.target instanceof Element && isPill(e.target) ? (e.target as HTMLElement) : null;\n if (onPill && (e.key === 'Enter' || e.key === ' ')) {\n e.preventDefault();\n return openPop(onPill);\n }\n if (e.key === 'Enter') return e.preventDefault();\n if (e.key !== 'Backspace' && e.key !== 'Delete') return;\n const r = caret();\n if (!r || !r.collapsed) return;\n const back = e.key === 'Backspace';\n const c = r.startContainer;\n const o = r.startOffset;\n let next: Node | null = null;\n if (c.nodeType === 3) {\n if (back && o === 0) next = c.previousSibling;\n else if (!back && o === (c as Text).length) next = c.nextSibling;\n } else next = c.childNodes[back ? o - 1 : o] || null;\n if (!isPill(next)) return;\n e.preventDefault();\n next.remove();\n emit();\n });\n const clip = (cut: boolean) => (e: ClipboardEvent) => {\n const r = caret();\n if (!r || r.collapsed || !e.clipboardData) return;\n e.preventDefault();\n e.clipboardData.setData('text/plain', serialize(r.cloneContents()));\n if (cut) {\n r.deleteContents();\n emit();\n }\n };\n ce.addEventListener('copy', clip(false));\n ce.addEventListener('cut', clip(true));\n ce.addEventListener('paste', (e) => {\n e.preventDefault();\n const text = ((e.clipboardData && e.clipboardData.getData('text/plain')) || '').replace(/\\r/g, '');\n const r = caret();\n if (!text || !r) return;\n r.deleteContents();\n const t = document.createTextNode(text);\n r.insertNode(t);\n r.setStartAfter(t);\n r.collapse(true);\n putCaret(r);\n emit();\n if (/\\{[{%]/.test(text)) set(value);\n });\n // Liquid typed by hand becomes pills (or the raw box) once the field is left.\n ce.addEventListener('blur', () => Array.from(ce.childNodes).some((n) => n.nodeType === 3 && /\\{[{%]/.test((n as Text).data)) && set(value));\n box = ce;\n el.appendChild(ce);\n };\n\n const insert = (tag: string) => {\n const live = caret();\n const r = live || (saved && box && box.isConnected && box.contains(saved.startContainer) ? saved : null);\n if (!r || !box || box.tagName !== 'DIV') {\n set(value ? `${value.replace(/\\s+$/, '')} ${tag}` : tag);\n return opts.onChange(value);\n }\n const parts = liquidParts(tag);\n const v = parts && parts[0];\n if (!v || typeof v === 'string') return;\n box.focus();\n r.deleteContents();\n const before = document.createRange();\n before.selectNodeContents(box);\n before.setEnd(r.startContainer, r.startOffset);\n const prev = serialize(before.cloneContents());\n const frag = document.createDocumentFragment();\n if (prev && !/\\s$/.test(prev)) frag.appendChild(document.createTextNode(' '));\n const p = pill(v);\n frag.appendChild(p);\n r.insertNode(frag);\n r.setStartAfter(p);\n r.collapse(true);\n putCaret(r);\n emit();\n };\n\n const openPill = (path: string): boolean => {\n if (!box || box.tagName !== 'DIV') return false;\n const target = Array.from(box.querySelectorAll(`[${PILL_ATTR}]`)).filter((n) => n.getAttribute('data-path') === path)[0] as HTMLElement | undefined;\n if (!target) return false;\n openPop(target);\n return true;\n };\n\n return { el, set, insert, closePop, openPill };\n}\n","/**\n * The on-site Web personalization editor (BACKLOG D444 Phase 4,\n * docs/PLACEMENTS_WEBSITE_LAYER.md 3) - the body of `joryio-editor.min.js`.\n * Design: design_handoff_web_personalization, screens 1-3 (1.4.0-beta.6).\n *\n * The handshake lives in the core bundle (src/core/editor-gate.ts): this\n * file is loaded, and this class constructed, only once the server vouched\n * for the editor token, with the dashboard origin the token names. From then\n * on it accepts messages only from that origin and that opener window, and\n * posts only to them.\n *\n * What it does on the page:\n * - All of its UI is in ONE shadow root (a closed one, on a host with\n * `all: initial`): the site's CSS cannot restyle it, its CSS cannot reach\n * the site. The previews it puts in the page (a content slot, a \"hidden for\n * this audience\" note) are custom elements with their own shadow roots,\n * never a `div`, so they do not shift the site's `:nth-of-type` selectors.\n * - Hover shows a dashed outline with a label (\"Heading · h1\"); a click\n * selects (the click never reaches the site); arrow up / down or the\n * buttons and the breadcrumb (\"Page › Main › Heading\") move to the element\n * around it or the first one inside it.\n * - A light side panel: the element, how many elements its selector matches,\n * \"What do you want to do?\" (Change text, Change link, Change image, Hide\n * it, Add content slot), ONE field set per action, a collapsible CSS\n * selector, Cancel / Save. The New text field shows variables as the\n * same pills (liquid-field.ts) and stores unchanged Liquid. Selecting an\n * element that already has an edit opens that edit.\n * - Every edit shows live on the page while editing (the draft too); the\n * text with the dashboard's sample values for its variables, else their\n * fallbacks, else a placeholder pill with the field name (a custom element\n * with its own shadow root, never page text). Text is set with textContent, addresses must be http(s), the\n * original nodes come back on undo - nothing is ever parsed as HTML.\n * - A dock: campaign · variant · page, the hint, \"N edits\" (a click jumps to\n * that edit), Undo, \"Save & return to Joryio\".\n * - Desktop / Mobile (1.4.0-beta.8): the dock's toggle shows the page at\n * phone width (MOBILE_FRAME_WIDTH, 390 px) - a same-origin frame of the\n * current URL with `?joryio_editor=frame` inside the editor's shadow root.\n * The SDK in that frame is inert (core editorFrame(): no page view, no\n * message, no live page edit); the editor works on the frame's document\n * (hover, selection, previews, selectors), its own UI stays in this tab.\n * The site's own scripts run in the frame, so its responsive layout, its\n * SPA routing and its lazy content are the real ones. Limits: a site that\n * forbids being framed (X-Frame-Options DENY, CSP frame-ancestors 'none')\n * shows a note instead - make the window narrower than 768 px; a page that\n * needs state of the tab (a cart, a form step reached by clicks) shows its\n * fresh load; the frame is a phone-width viewport, not a phone (no touch\n * events, the desktop browser's user agent).\n * - Each edit applies to All devices (the default, as before), Mobile only\n * or Desktop only (the panel's \"Applies to\"); mobile = viewport below\n * PAGE_EDIT_MOBILE_BREAKPOINT (768 px), the SDK's rule. The live preview\n * shows only the edits of the current view, and the edit list marks the\n * per-device ones.\n *\n * Messages (constants: EDITOR_MESSAGES in the core, EDITOR_SESSION_MESSAGES\n * here; the dashboard's copy is packages/frontend/src/lib/web-experience.ts):\n *\n * editor -> dashboard\n * joryio:editor-active { url } the editor is up\n * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, device, tag, text }\n * a saved edit; `id` is the edit's id - an id the\n * dashboard already has REPLACES that edit.\n * `device` (1.4.0-beta.8) is always sent: 'all' |\n * 'mobile' | 'desktop'. A pick WITHOUT it comes from\n * an editor before beta.8, which drops the field:\n * the dashboard keeps the stored device of that id\n * joryio:editor-remove { id } undo of a new edit\n * joryio:editor-done {} \"Save & return to Joryio\"\n * joryio:editor-open-slot { placementKey, campaignId? }\n * \"Create content for this slot\" (no campaignId) or\n * a campaign of the slot (its id): the dashboard\n * opens that campaign, or a new Placement campaign\n * for the slot; sent only to a dashboard that set\n * `openSlot` in its context\n * joryio:editor-closed {} the editor stopped\n *\n * dashboard -> editor\n * joryio:editor-context { campaignName?, variantName?, edits? (each may carry device), focusId?,\n * attributes?: [{ key, label?, group? } | { name, custom? }],\n * placements?: [{ key, name?, campaigns?: [{ id, name, status, statusLabel? }] }],\n * openSlot?: true,\n * sample?: { \"user.firstName\": \"Lior\", ... },\n * strings?: { <EDITOR_STRINGS key>: text }, dir?: 'ltr' | 'rtl' }\n * the variant's edits (shown live and in \"N edits\"),\n * the words in the marketer's language; enables Undo.\n * `campaigns` per placement (1.4.0-beta.7): the\n * campaigns that fill that slot, shown on a saved\n * slot edit (\"In this slot: ...\"); `openSlot`: the\n * dashboard handles joryio:editor-open-slot. An\n * editor before beta.7 ignores both.\n * joryio:editor-focus { id } jump to that edit\n * joryio:editor-close {} stop\n *\n * A dashboard that sends no context still works as before this redesign:\n * every save is a pick, the dock counts this session's edits, and Undo stays\n * off (that dashboard would not hear a remove).\n */\nimport type { Logger } from '../utils/logger';\nimport { editShowsOn, isMobileViewport, isSafeSelector, isSafeEditUrl, trustedEdit, type PageEditDevice, type PageEditOperation, type PageEditPosition, type PageEditWire } from '../core/page-edits';\nimport { EDITOR_FRAME_FLAG, EDITOR_MESSAGES, EDITOR_QUERY_FLAG } from '../core/editor-gate';\nimport { EDITOR_STRINGS, fill, mergeStrings, type EditorStringKey, type EditorStrings } from './editor-strings';\nimport { VAR_PATH, kindKey, newEditId, pathTag, previewParts, slugify } from './editor-model';\nimport { EDITOR_CSS, HOST_STYLE, MOBILE_FRAME_WIDTH, PREVIEW_CSS, PREVIEW_HOST_STYLE, PREVIEW_VAR_HOST_STYLE, h, icon, type IconName } from './editor-ui';\nimport { liquidField, type LiquidField } from './liquid-field';\n\nexport { EDITOR_MESSAGES, MOBILE_FRAME_WIDTH };\n\nexport const EDITOR_SESSION_MESSAGES = {\n CONTEXT: 'joryio:editor-context',\n FOCUS: 'joryio:editor-focus',\n REMOVE: 'joryio:editor-remove',\n DONE: 'joryio:editor-done',\n OPEN_SLOT: 'joryio:editor-open-slot',\n} as const;\n\n/** Attributes that name an element on purpose, most stable first. */\nconst NAMING_ATTRIBUTES = ['data-joryio-id', 'data-testid', 'data-test', 'data-qa', 'data-cy', 'data-id', 'name'];\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\nconst ATTRIBUTE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;\nconst MAX_TEXT = 2000;\nconst MAX_EDITS = 100;\nconst PREVIEW_TAG = 'joryio-editor-preview';\n/** The open overlays of the panel and what opens them: a press on anything else closes them. */\nconst OVERLAY_PARTS = '[data-j=\"var-picker\"],[data-j=\"more\"],[data-j=\"fallback-pop\"],[data-liquid]';\n\n/**\n * Scroll the picker's list so the highlighted option shows whole - with its\n * group heading when it is the group's first - inside the list only (never the\n * panel or the page, as scrollIntoView would).\n */\nexport function revealOption(list: HTMLElement, o: HTMLElement | null): void {\n if (!o) return;\n const prev = o.previousElementSibling as HTMLElement | null;\n const top = prev && prev.getAttribute('role') === 'presentation' ? prev : o;\n if (top.offsetTop < list.scrollTop) list.scrollTop = top.offsetTop;\n else if (o.offsetTop + o.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = o.offsetTop + o.offsetHeight - list.clientHeight;\n}\nconst OURS = '[data-joryio-editor]';\nconst HELP_DISMISSED_KEY = 'jry_editor_help_dismissed';\nexport type EditorView = 'desktop' | 'mobile';\nconst DEVICES: Array<[PageEditDevice, EditorStringKey]> = [\n ['all', 'devAll'],\n ['mobile', 'devMobile'],\n ['desktop', 'devDesktop'],\n];\n\n/** CSS.escape, for browsers (and test DOMs) without it. */\nexport function cssEscape(value: string): string {\n const css = (globalThis as any).CSS;\n if (css && typeof css.escape === 'function') return css.escape(value);\n let out = '';\n for (let i = 0; i < value.length; i++) {\n const ch = value[i];\n const code = value.charCodeAt(i);\n if (code === 0) out += '\\uFFFD';\n else if (/[0-9]/.test(ch) && (i === 0 || (i === 1 && value[0] === '-'))) out += `\\\\${code.toString(16)} `;\n else if (/[A-Za-z0-9_-]/.test(ch) || code >= 0x80) out += ch;\n else out += `\\\\${ch}`;\n }\n return out;\n}\n\nconst isOurs = (el: Element | null): boolean => !!el && !!el.closest(OURS);\nconst VAR_PILL = 'var';\n\n/** The page element an event on the page is about: a variable pill in the preview stands for the element it is in. */\nfunction pageTarget(t: EventTarget | null): Element | null {\n let el = t instanceof Element ? t : null;\n if (el && el.getAttribute('data-joryio-editor') === VAR_PILL) el = el.parentElement;\n return el && !isOurs(el) && el !== el.ownerDocument.body && el !== el.ownerDocument.documentElement ? el : null;\n}\n\n/** The page's elements a selector finds - never the editor's own. `doc`: the tab's page, or the Mobile view's frame. */\nfunction pageMatches(selector: string, doc: Document): Element[] {\n if (!isSafeSelector(selector)) return [];\n try {\n return Array.from(doc.querySelectorAll(selector)).filter((e) => !isOurs(e));\n } catch {\n return [];\n }\n}\n\nconst unique = (doc: Document, selector: string, el: Element): boolean => {\n try {\n const hits = Array.from(doc.querySelectorAll(selector)).filter((e) => !isOurs(e));\n return hits.length === 1 && hits[0] === el;\n } catch {\n return false;\n }\n};\n\n/** An id that looks generated (long digit runs, framework hashes) changes between builds; skip it. */\nconst stableId = (id: string) => !!id && id.length <= 64 && !/\\d{4,}/.test(id) && !/^(ember|react|radix|headlessui|mui)[-_:]/i.test(id) && !/:/.test(id);\n\n/**\n * A selector that finds this element and only it, preferring what the site\n * named on purpose: an id, then a naming data attribute, then a path of\n * tag + nth-of-type from the nearest named ancestor (or the body).\n */\nexport function robustSelector(el: Element): string | null {\n const doc = el.ownerDocument;\n if (!doc) return null;\n const named = (node: Element): string | null => {\n if (stableId(node.id)) {\n const s = `#${cssEscape(node.id)}`;\n if (unique(doc, s, node)) return s;\n }\n for (const attr of NAMING_ATTRIBUTES) {\n const v = node.getAttribute(attr);\n if (!v || v.length > 100) continue;\n const s = `${node.tagName.toLowerCase()}[${attr}=\"${v.replace(/[\"\\\\]/g, '\\\\$&')}\"]`;\n if (unique(doc, s, node)) return s;\n }\n return null;\n };\n const own = named(el);\n if (own) return isSafeSelector(own) ? own : null;\n const parts: string[] = [];\n let node: Element | null = el;\n while (node && node !== doc.body && node !== doc.documentElement) {\n const anchor = parts.length ? named(node) : null;\n if (anchor) {\n parts.unshift(anchor);\n break;\n }\n const tag = node.tagName.toLowerCase();\n const parent: Element | null = node.parentElement;\n const same = parent ? Array.from(parent.children).filter((c) => c.tagName === node!.tagName) : [];\n parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(node) + 1})` : tag);\n node = parent;\n if (node === doc.body) parts.unshift('body');\n }\n const selector = parts.join(' > ');\n return selector && isSafeSelector(selector) && unique(doc, selector, el) ? selector : null;\n}\n\n/** The operations that fit an element: an image can change its picture, a link its address. */\nexport function operationsFor(el: Element): PageEditOperation[] {\n const ops: PageEditOperation[] = [];\n if (el.tagName !== 'IMG' && (el.textContent || '').trim()) ops.push('replace_text');\n if (el.tagName === 'IMG') ops.push('replace_image');\n if (el.tagName === 'A') ops.push('replace_link');\n ops.push('hide', 'insert_placement');\n return ops;\n}\n\nexport interface EditorPick {\n type: typeof EDITOR_MESSAGES.PICK;\n /** The edit's id: new edits get a fresh one, an edit opened from the list keeps its own. */\n id: string;\n selector: string;\n operation: PageEditOperation;\n value?: string;\n placementKey?: string;\n position?: PageEditPosition;\n /** Always sent by 1.4.0-beta.8 ('all' included), so the dashboard can tell it from an older editor's pick. */\n device: PageEditDevice;\n tag: string;\n text: string;\n}\n\ntype Action = 'text' | 'link' | 'image' | 'hide' | 'slot';\nconst ACTIONS: Action[] = ['text', 'link', 'image', 'hide', 'slot'];\nconst OPERATION_OF: Record<Action, PageEditOperation> = { text: 'replace_text', link: 'replace_link', image: 'replace_image', hide: 'hide', slot: 'insert_placement' };\nconst ACTION_OF: Record<PageEditOperation, Action> = { replace_text: 'text', replace_link: 'link', replace_image: 'image', hide: 'hide', insert_placement: 'slot' };\nconst ACTION_LABEL: Record<Action, EditorStringKey> = { text: 'actText', link: 'actLink', image: 'actImage', hide: 'actHide', slot: 'actSlot' };\nconst ACTION_ICON: Record<Action, IconName> = { text: 'text', link: 'link', image: 'image', hide: 'hide', slot: 'slot' };\nconst POSITIONS: Array<[PageEditPosition, EditorStringKey]> = [\n ['before', 'posBefore'],\n ['after', 'posAfter'],\n ['replace', 'posReplace'],\n ['prepend', 'posPrepend'],\n ['append', 'posAppend'],\n];\n\ninterface Draft {\n action: Action;\n text: string;\n url: string;\n slotName: string;\n position: PageEditPosition;\n device: PageEditDevice;\n selector: string;\n /** The edit being changed (opened from the list or the dashboard), null for a new one. */\n editingId: string | null;\n /** A new draft shows on the page only once something was changed (its untouched text would flatten the element's markup). */\n touched: boolean;\n}\n\ninterface Var {\n path: string;\n label: string;\n group: string;\n}\n\n/** The chips shown before \"More…\": these when the catalog has them, else its first ones. */\nconst COMMON_VARS = ['user.firstName', 'user.lastName', 'user.email', 'user.custom.city'];\nconst CHIPS = 4;\n\ninterface EditorContext {\n campaignName: string;\n variantName: string;\n /** The personalization catalog: Liquid path, label, group ('' for the old `{ name, custom }` shape). */\n attributes: Var[];\n placements: Array<{ key: string; name: string; campaigns: SlotCampaign[] }>;\n sample: Record<string, string>;\n /** The dashboard handles joryio:editor-open-slot: the slot's campaigns and \"Create content for this slot\" show. */\n openSlot: boolean;\n}\n\n/** A campaign that fills a slot, as the dashboard sent it. */\ninterface SlotCampaign {\n id: string;\n name: string;\n /** The wire status (`draft`, `active`, ...), and the dashboard's word for it. */\n status: string;\n statusLabel: string;\n}\nconst CAMPAIGN_ID = /^[A-Za-z0-9_-]{1,64}$/;\n\nconst clip = (v: unknown, n: number): string => (typeof v === 'string' ? v.trim().slice(0, n) : '');\n/**\n * An element's own text, read from the page: never the editor's previews in it\n * (a placeholder pill, a slot or \"hidden\" note) - a pill's text lives in its\n * shadow root, so reading textContent over it would silently drop the variable.\n */\nexport const shortText = (el: Element | null): string => {\n if (!el) return '';\n let src: Element = el;\n if (el.querySelector(OURS)) {\n src = el.cloneNode(true) as Element;\n for (const n of Array.from(src.querySelectorAll(OURS))) n.remove();\n }\n return (src.textContent || '').replace(/\\s+/g, ' ').trim();\n};\n\nexport class VisualEditor {\n private listeners: Array<() => void> = [];\n private active = false;\n private host: HTMLElement | null = null;\n /** Kept for tests: the shadow root is closed to the page. */\n root: ShadowRoot | null = null;\n private wrap: HTMLElement | null = null;\n private hoverBox: HTMLElement | null = null;\n private selBox: HTMLElement | null = null;\n private dock: HTMLElement | null = null;\n private panel: HTMLElement | null = null;\n private help: HTMLElement | null = null;\n private hovered: Element | null = null;\n private selected: Element | null = null;\n private draft: Draft | null = null;\n private showCss = false;\n private showLiquid = false;\n /** Closes an open overlay of the panel (the variable picker) on Esc; true when it closed one. */\n private closeOverlay: (() => boolean) | null = null;\n /** The New text field on screen (a page pill's click opens its fallback here). */\n private field: LiquidField | null = null;\n private popOpen = false;\n private edits: PageEditWire[] = [];\n private history: Array<{ id: string; before: PageEditWire | null }> = [];\n /** The dashboard sent a context: it understands remove (Undo) and replace-by-id. */\n private synced = false;\n private t: EditorStrings = { ...EDITOR_STRINGS };\n private dir: 'ltr' | 'rtl' = 'ltr';\n private ctx: EditorContext = { campaignName: '', variantName: '', attributes: [], placements: [], sample: {}, openSlot: false };\n private previewUndo: Array<() => void> = [];\n /** The page's own text / address of an element before any preview, for \"Was:\". */\n private originals = new WeakMap<Element, { text: string; href: string | null; src: string | null }>();\n /** The page being edited: this tab's document, or the Mobile view's frame document. */\n private doc: Document = document;\n private view: EditorView = 'desktop';\n private stage: HTMLElement | null = null;\n private frame: HTMLIFrameElement | null = null;\n /** Unbinds the listeners on the page being edited (this tab's, or the frame's). */\n private offPage: (() => void) | null = null;\n /** The viewport the preview was drawn for (a resize across 768 px redraws it). */\n private mobileShown = false;\n\n constructor(\n private dashboardOrigin: string,\n private opener: Window,\n private logger: Logger,\n private onStop: () => void = () => undefined,\n ) {}\n\n /** The token was vouched for by the server: show the editor. */\n start(): void {\n if (this.active) return;\n this.active = true;\n const onMessage = (e: MessageEvent) => {\n const data = e.data as { type?: string } | null;\n if (!data || typeof data.type !== 'string') return;\n if (e.origin !== this.dashboardOrigin || e.source !== this.opener) return;\n if (data.type === EDITOR_MESSAGES.CLOSE) this.stop();\n else if (data.type === EDITOR_SESSION_MESSAGES.CONTEXT) this.applyContext(data as Record<string, unknown>);\n else if (data.type === EDITOR_SESSION_MESSAGES.FOCUS) this.focusEdit((data as { id?: unknown }).id);\n };\n window.addEventListener('message', onMessage);\n this.listeners.push(() => window.removeEventListener('message', onMessage));\n this.activate();\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n /** The edits this editor knows of (the dashboard's, then this session's), in order. */\n editList(): PageEditWire[] {\n return this.edits.slice();\n }\n\n stop(): void {\n if (!this.active) return;\n this.send({ type: EDITOR_MESSAGES.CLOSED });\n this.active = false;\n for (const off of this.listeners.splice(0)) off();\n this.clearPreview();\n this.host?.remove();\n this.host = this.root = this.wrap = this.hoverBox = this.selBox = this.dock = this.panel = this.help = this.stage = this.frame = null;\n this.doc = document;\n this.view = 'desktop';\n this.selected = this.hovered = null;\n this.draft = null;\n try {\n this.onStop();\n } catch (error) {\n this.logger.debug('Joryio editor stop callback failed', error);\n }\n }\n\n private send(message: Record<string, unknown>): void {\n if (!this.active) return;\n try {\n this.opener.postMessage(message, this.dashboardOrigin);\n } catch {\n /* the dashboard tab closed */\n }\n }\n\n // ── setup ────────────────────────────────────────────────────────────────\n\n private activate(): void {\n const doc = document;\n const host = doc.createElement('joryio-editor');\n host.setAttribute('data-joryio-editor', 'root');\n host.setAttribute('style', HOST_STYLE);\n const root = host.attachShadow({ mode: 'closed' });\n root.appendChild(h('style', null, EDITOR_CSS));\n const wrap = h('div', { class: 'r', dir: this.dir });\n this.hoverBox = h('div', { class: 'box', 'data-j': 'hover' });\n this.selBox = h('div', { class: 'box sel', 'data-j': 'selected' });\n wrap.append(this.hoverBox, this.selBox);\n root.appendChild(wrap);\n doc.documentElement.appendChild(host);\n this.host = host;\n this.root = root;\n this.wrap = wrap;\n // A press anywhere in the editor's UI outside the open picker / fallback popover (and the\n // button or pill that opens it) closes it.\n const outside = (e: Event) => {\n const path = typeof e.composedPath === 'function' ? e.composedPath() : [e.target];\n if (path.some((n) => n instanceof Element && n.matches(OVERLAY_PARTS))) return;\n this.closeOverlay?.();\n };\n wrap.addEventListener('pointerdown', outside);\n wrap.addEventListener('mousedown', outside);\n\n // Esc and the arrows also while the focus is in this tab (the panel, or the Mobile view's surroundings).\n const onKey = (e: KeyboardEvent) => this.onKey(e);\n doc.addEventListener('keydown', onKey, true);\n const onResize = () => {\n this.placeBoxes();\n // The tab crossed the 768 px breakpoint: the preview shows the other device's edits.\n if (this.view === 'desktop' && isMobileViewport(window) !== this.mobileShown) {\n this.renderPreview();\n if (this.draft) this.renderPanel();\n }\n };\n window.addEventListener('resize', onResize);\n this.listeners.push(\n () => doc.removeEventListener('keydown', onKey, true),\n () => window.removeEventListener('resize', onResize),\n () => this.unbindPage(),\n );\n this.bindPage(doc, window);\n this.renderDock();\n this.renderHelp();\n this.send({ type: EDITOR_MESSAGES.ACTIVE, url: `${location.origin}${location.pathname}` });\n }\n\n private onKey(e: KeyboardEvent): void {\n if (e.key === 'Escape') {\n if (this.closeOverlay && this.closeOverlay()) return;\n if (this.popOpen) this.togglePop(false);\n else if (this.panel) this.cancel();\n else this.stop();\n return;\n }\n if (isOurs(e.target instanceof Element ? e.target : null)) return; // typing in the panel\n if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {\n const from = this.selected || this.hovered;\n if (!from) return;\n e.preventDefault();\n e.stopPropagation();\n this.move(e.key === 'ArrowUp' ? 'up' : 'down', from);\n }\n }\n\n /** Hover, click (and keys, in a frame) on the page being edited; scroll moves the outlines. */\n private bindPage(doc: Document, win: Window): void {\n this.unbindPage();\n this.doc = doc;\n const onMove = (e: MouseEvent) => {\n const t = e.target instanceof Element ? e.target : null;\n if (isOurs(t) && t!.getAttribute('data-joryio-editor') !== VAR_PILL) return;\n this.hovered = pageTarget(t);\n this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);\n };\n const onClick = (e: MouseEvent) => {\n if (e.target instanceof Element && e.target.closest('[data-joryio-editor=\"root\"]')) return;\n // A click on the page - a preview of ours included - never reaches the site.\n e.preventDefault();\n e.stopPropagation();\n // An open picker or fallback popover: a click outside it only closes it, it selects nothing.\n if (this.closeOverlay && this.closeOverlay()) return;\n const el = pageTarget(e.target);\n if (!el) return;\n // A placeholder pill in the preview: its element's edit, and that variable's fallback - never a new draft.\n const pill = e.target instanceof Element && e.target.getAttribute('data-joryio-editor') === VAR_PILL ? e.target.getAttribute('data-path') : null;\n this.select(el);\n if (pill) this.field?.openPill(pill);\n };\n const onKey = (e: KeyboardEvent) => this.onKey(e);\n const onScroll = () => this.placeBoxes();\n const inFrame = doc !== document;\n doc.addEventListener('mousemove', onMove, true);\n doc.addEventListener('click', onClick, true);\n if (inFrame) doc.addEventListener('keydown', onKey, true);\n win.addEventListener('scroll', onScroll, true);\n if (inFrame) win.addEventListener('resize', onScroll);\n this.offPage = () => {\n doc.removeEventListener('mousemove', onMove, true);\n doc.removeEventListener('click', onClick, true);\n doc.removeEventListener('keydown', onKey, true);\n win.removeEventListener('scroll', onScroll, true);\n win.removeEventListener('resize', onScroll);\n };\n }\n\n private unbindPage(): void {\n const off = this.offPage;\n this.offPage = null;\n try {\n off?.();\n } catch {\n /* the frame went away */\n }\n }\n\n private placeBoxes(): void {\n this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);\n this.place(this.selBox, this.selected);\n }\n\n /** The Desktop / Mobile view (the dock's toggle). */\n currentView(): EditorView {\n return this.view;\n }\n\n /** Switch the view. Mobile = the page at phone width, in a same-origin frame; `focusId` opens that edit there. */\n setView(view: EditorView, focusId?: string): void {\n if (!this.active || !this.wrap) return;\n if (view === this.view) {\n if (focusId) this.focusEdit(focusId);\n return;\n }\n // Leave the page being edited as it was: no preview, no selection, no panel.\n this.clearPreview();\n this.unbindPage();\n this.draft = null;\n this.selected = this.hovered = null;\n this.panel?.remove();\n this.panel = null;\n this.wrap.classList.remove('open');\n this.popOpen = false;\n this.stage?.remove();\n this.stage = this.frame = null;\n this.view = view;\n // Until the frame has loaded, an empty page: nothing to match, nothing previewed in this tab.\n this.doc = document.implementation.createHTMLDocument('');\n if (view === 'desktop') {\n this.bindPage(document, window);\n this.renderAll();\n if (focusId) this.focusEdit(focusId);\n return;\n }\n const frame = h('iframe', { title: this.t.viewMobile, 'data-j': 'frame' }) as HTMLIFrameElement;\n const url = new URL(location.href);\n url.searchParams.set(EDITOR_QUERY_FLAG, EDITOR_FRAME_FLAG);\n const stage = h('div', { class: 'stage', 'data-j': 'stage' }, frame);\n frame.addEventListener('load', () => {\n if (this.frame !== frame) return;\n // Every load of the frame (its first, a redirect, a reload) is a new document to bind.\n let doc: Document | null = null;\n try {\n doc = frame.contentDocument;\n if (doc && (doc.URL === 'about:blank' || !doc.documentElement)) doc = null;\n } catch {\n doc = null; // another origin (a redirect), or the browser's own error page\n }\n if (!doc || !frame.contentWindow) {\n // The site does not allow itself in a frame (X-Frame-Options, CSP frame-ancestors).\n this.unbindPage();\n this.doc = document.implementation.createHTMLDocument('');\n frame.hidden = true;\n stage.appendChild(h('div', { class: 'note fnote', role: 'status', 'data-j': 'frame-blocked' }, this.t.frameBlocked));\n return;\n }\n this.clearPreview();\n this.selected = this.hovered = null;\n this.bindPage(doc, frame.contentWindow);\n this.renderPreview();\n this.placeBoxes();\n if (focusId) {\n this.focusEdit(focusId);\n focusId = undefined;\n }\n });\n frame.setAttribute('src', url.toString());\n this.stage = stage;\n this.frame = frame;\n this.wrap.insertBefore(stage, this.wrap.firstChild);\n this.renderAll();\n }\n\n private renderAll(): void {\n this.renderPreview();\n this.renderDock();\n this.renderHelp();\n this.placeBoxes();\n }\n\n /** True when the page being edited is a mobile viewport: the Mobile view, or a narrow tab. */\n private mobileNow(): boolean {\n return this.view === 'mobile' || isMobileViewport(window);\n }\n\n /** The edit shows in the current view (its device is All, or this view's). */\n private inView(e: { device?: string }): boolean {\n return editShowsOn(e, this.mobileNow());\n }\n\n /** The dashboard's context: words, campaign, the variant's edits (validated like the runtime does). */\n private applyContext(data: Record<string, unknown>): void {\n this.synced = true;\n this.t = mergeStrings(data.strings);\n this.dir = data.dir === 'rtl' ? 'rtl' : 'ltr';\n this.wrap?.setAttribute('dir', this.dir);\n const list = <T>(v: unknown, map: (x: any) => T | null, max: number): T[] =>\n (Array.isArray(v) ? v : [])\n .map(map)\n .filter((x): x is T => x !== null)\n .slice(0, max);\n this.ctx = {\n campaignName: clip(data.campaignName, 120),\n variantName: clip(data.variantName, 60),\n // Both shapes: the catalog's { key, label, group } and the older { name, custom }.\n attributes: list(\n data.attributes,\n (a): Var | null =>\n !a\n ? null\n : typeof a.key === 'string' && VAR_PATH.test(a.key)\n ? { path: a.key, label: clip(a.label, 60) || a.key.split('.').pop()!, group: clip(a.group, 40) }\n : typeof a.name === 'string' && ATTRIBUTE_NAME.test(a.name)\n ? // The older shape has no group: under \"Profile\" / \"Custom fields\", never after another group's heading.\n { path: `user.${a.custom === true ? 'custom.' : ''}${a.name}`, label: a.name, group: a.custom === true ? this.t.groupCustom : this.t.groupProfile }\n : null,\n 400,\n ),\n placements: list(\n data.placements,\n (p) =>\n p && typeof p.key === 'string' && PLACEMENT_KEY_PATTERN.test(p.key)\n ? {\n key: p.key,\n name: clip(p.name, 80),\n campaigns: list(\n p.campaigns,\n (c): SlotCampaign | null =>\n c && typeof c.id === 'string' && CAMPAIGN_ID.test(c.id) ? { id: c.id, name: clip(c.name, 120) || c.id, status: clip(c.status, 30), statusLabel: clip(c.statusLabel, 40) } : null,\n 10,\n ),\n }\n : null,\n 200,\n ),\n sample: {},\n openSlot: data.openSlot === true,\n };\n if (data.sample && typeof data.sample === 'object') {\n for (const [k, v] of Object.entries(data.sample as Record<string, unknown>).slice(0, 100)) {\n if (/^user\\.[A-Za-z0-9_.]{1,80}$/.test(k) && typeof v === 'string') this.ctx.sample[k] = v.slice(0, 200);\n }\n }\n if (Array.isArray(data.edits)) {\n this.edits = list(data.edits, (e) => trustedEdit(e), MAX_EDITS).map((e) => {\n const { personalized: _p, ...rest } = e;\n return rest;\n });\n this.history = [];\n }\n this.renderPreview();\n this.renderDock();\n this.renderHelp();\n if (this.draft) this.renderPanel();\n if (typeof data.focusId === 'string') this.focusEdit(data.focusId);\n }\n\n // ── selection ────────────────────────────────────────────────────────────\n\n /** Outline an element (hover: dashed + label; selected: solid). */\n private place(box: HTMLElement | null, el: Element | null, withLabel = false): void {\n if (!box) return;\n if (!el || !el.isConnected) {\n box.style.display = 'none';\n return;\n }\n const r = el.getBoundingClientRect();\n // An element of the Mobile view's frame: its frame-viewport box, moved to where the frame sits in this tab.\n const f = this.frame && el.ownerDocument !== document ? this.frame.getBoundingClientRect() : { top: 0, left: 0 };\n Object.assign(box.style, { display: 'block', top: `${r.top + f.top - 2}px`, left: `${r.left + f.left - 2}px`, width: `${r.width + 4}px`, height: `${r.height + 4}px` });\n box.textContent = '';\n const label = `${this.t[kindKey(el.tagName)]} · ${el.tagName.toLowerCase()}`;\n box.appendChild(h('span', { class: 'chip', 'data-j': 'label' }, withLabel ? `${label} - ${this.t.clickToEdit}` : label));\n }\n\n private move(dir: 'up' | 'down', from: Element): void {\n const next = dir === 'up' ? from.parentElement : Array.from(from.children).filter((c) => !isOurs(c))[0] || null;\n if (!next || next === from.ownerDocument.body || next === from.ownerDocument.documentElement) return;\n this.select(next);\n }\n\n /**\n * The edits on an element (its selector finds it, or is the selector the\n * editor would make for it), oldest first - only those of the current view:\n * in Mobile view a Desktop-only edit is not what the marketer is looking at.\n */\n private editsOn(el: Element | null): PageEditWire[] {\n if (!el) return [];\n const own = robustSelector(el);\n return this.edits.filter((e) => this.inView(e) && (e.selector === own || pageMatches(e.selector, el.ownerDocument).indexOf(el) >= 0));\n }\n\n /**\n * The element is chosen: open the panel on it. An element that already\n * has an edit (this session's or the dashboard's) opens that edit - the\n * most recent one - like jumping to it from the list: its value, its\n * fallback, and Save updates the same edit.\n */\n select(el: Element, edit?: PageEditWire): void {\n if (!this.active) return;\n // The element already open: keep the draft as typed (re-reading the page would lose it).\n if (!edit && this.draft && el === this.selected) return;\n edit = edit || this.editsOn(el).pop();\n this.selected = el;\n this.hovered = null;\n this.place(this.hoverBox, null);\n this.place(this.selBox, el);\n this.popOpen = false;\n const selector = edit ? edit.selector : robustSelector(el) || '';\n this.showCss = !selector;\n this.draft = edit ? this.draftOf(edit) : this.newDraft(el, selector);\n this.renderPanel();\n this.renderDock();\n this.renderHelp();\n this.renderPreview();\n }\n\n private enabled(action: Action, el: Element | null): boolean {\n if (!el) return true;\n if (action === 'text') return el.tagName !== 'IMG' && !!this.orig(el).text;\n if (action === 'link') return el.tagName === 'A';\n if (action === 'image') return el.tagName === 'IMG';\n return true;\n }\n\n private newDraft(el: Element, selector: string): Draft {\n const o = this.orig(el);\n const action: Action = el.tagName === 'IMG' ? 'image' : this.enabled('text', el) ? 'text' : el.tagName === 'A' ? 'link' : 'hide';\n return { action, text: o.text.slice(0, MAX_TEXT), url: (action === 'image' ? o.src : o.href) || '', slotName: '', position: 'after', device: 'all', selector, editingId: null, touched: false };\n }\n\n private draftOf(e: PageEditWire): Draft {\n const action = ACTION_OF[e.operation];\n return {\n action,\n text: e.operation === 'replace_text' ? e.value || '' : '',\n url: action === 'link' || action === 'image' ? e.value || '' : '',\n slotName: e.placementKey || '',\n position: e.position || 'after',\n device: e.device || 'all',\n selector: e.selector,\n editingId: e.id,\n touched: true,\n };\n }\n\n /** The element as the page had it, before any preview of this editor. */\n private orig(el: Element): { text: string; href: string | null; src: string | null } {\n return this.originals.get(el) || { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') };\n }\n\n /** Jump to an edit: from the dock's list, or the dashboard (\"Edit on site\"). */\n focusEdit(id: unknown): boolean {\n const edit = this.edits.filter((e) => e.id === id)[0];\n if (!edit || !this.active) return false;\n // Another device's edit: switch to its view first (Mobile opens the frame and focuses it once loaded).\n if (!this.inView(edit)) {\n const want: EditorView = edit.device === 'mobile' ? 'mobile' : 'desktop';\n if (want !== this.view) {\n this.setView(want, edit.id);\n if (want === 'mobile') return true;\n }\n }\n const el = (this.inView(edit) && pageMatches(edit.selector, this.doc)[0]) || null;\n if (el) {\n try {\n el.scrollIntoView({ block: 'center' });\n } catch {\n /* old browsers */\n }\n this.select(el, edit);\n } else {\n this.selected = null;\n this.place(this.selBox, null);\n this.draft = this.draftOf(edit);\n this.showCss = true;\n this.renderPanel();\n this.renderDock();\n this.renderHelp();\n this.renderPreview();\n }\n return true;\n }\n\n // ── the edit ─────────────────────────────────────────────────────────────\n\n /** The draft as an edit, or null while a field is not valid yet. */\n private draftEdit(d: Draft): PageEditWire | null {\n const base = { id: d.editingId || '', selector: d.selector.trim(), ...(d.device !== 'all' ? { device: d.device } : {}) };\n if (!isSafeSelector(base.selector)) return null;\n const operation = OPERATION_OF[d.action];\n if (d.action === 'hide') return { ...base, operation };\n if (d.action === 'text') return d.text.trim() && d.text.length <= MAX_TEXT ? { ...base, operation, value: d.text } : null;\n if (d.action === 'link' || d.action === 'image') return isSafeEditUrl(d.url) ? { ...base, operation, value: d.url.trim() } : null;\n const key = slugify(d.slotName);\n return PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: d.position } : null;\n }\n\n private save(): void {\n const d = this.draft;\n const edit = d && this.draftEdit(d);\n if (!d || !edit) return;\n const el = this.selected || pageMatches(edit.selector, this.doc)[0] || null;\n const id = d.editingId || newEditId();\n if (!this.pick(el, edit.selector, edit.operation, edit.value ?? edit.placementKey ?? '', { id, position: edit.position, device: d.device })) return;\n // A saved slot stays open on its edit, with its campaigns or \"Create content for this slot\".\n if (edit.operation === 'insert_placement' && this.ctx.openSlot) this.focusEdit(id);\n }\n\n /** \"Create content for this slot\" or one of its campaigns: the dashboard opens it, in its own tab. */\n openSlot(placementKey: string, campaignId?: string): boolean {\n if (!this.ctx.openSlot || !PLACEMENT_KEY_PATTERN.test(placementKey)) return false;\n this.send({ type: EDITOR_SESSION_MESSAGES.OPEN_SLOT, placementKey, ...(campaignId ? { campaignId } : {}) });\n try {\n this.opener.focus();\n } catch {\n /* not allowed */\n }\n return true;\n }\n\n /**\n * Validate like the server does, post the edit to the dashboard, keep it\n * in the list (and on the page). `value` is the text, the address or the\n * slot name (made a placement key).\n */\n pick(el: Element | null, selector: string, operation: PageEditOperation, value: string, opts: { id?: string; position?: PageEditPosition; device?: PageEditDevice } = {}): boolean {\n const id = opts.id || newEditId();\n const tag = el ? el.tagName.toLowerCase() : '';\n const text = el ? this.orig(el).text.slice(0, 200) : '';\n let edit: PageEditWire | null = null;\n if (isSafeSelector(selector)) {\n const base = { id, selector: selector.trim() };\n if (operation === 'hide') edit = { ...base, operation };\n else if (operation === 'replace_text') edit = (value || text) && (value || text).length <= MAX_TEXT ? { ...base, operation, value: value || text } : null;\n else if (operation === 'replace_image' || operation === 'replace_link') edit = isSafeEditUrl(value) ? { ...base, operation, value: value.trim() } : null;\n else if (operation === 'insert_placement') {\n const key = slugify(value);\n edit = PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: opts.position || 'after' } : null;\n }\n }\n if (!edit) return false;\n if (opts.device === 'mobile' || opts.device === 'desktop') edit.device = opts.device;\n const msg: EditorPick = { type: EDITOR_MESSAGES.PICK, ...edit, device: edit.device || 'all', tag, text } as EditorPick;\n this.send(msg as unknown as Record<string, unknown>);\n const at = this.edits.map((e) => e.id).indexOf(id);\n this.history.push({ id, before: at >= 0 ? this.edits[at] : null });\n if (at >= 0) this.edits[at] = edit;\n else this.edits.push(edit);\n this.closePanel();\n return true;\n }\n\n private cancel(): void {\n this.closePanel();\n }\n\n private closePanel(): void {\n this.draft = null;\n this.selected = null;\n this.panel?.remove();\n this.panel = null;\n this.wrap?.classList.remove('open');\n this.place(this.selBox, null);\n this.renderPreview();\n this.renderDock();\n this.renderHelp();\n }\n\n /** Undo the last saved edit: a new one is removed, a changed one goes back to what it was. */\n undo(): boolean {\n if (!this.synced) return false;\n const last = this.history.pop();\n if (!last) return false;\n const at = this.edits.map((e) => e.id).indexOf(last.id);\n if (last.before) {\n if (at >= 0) this.edits[at] = last.before;\n const b = last.before;\n this.send({ type: EDITOR_MESSAGES.PICK, ...b, device: b.device || 'all', tag: '', text: '' });\n } else {\n if (at >= 0) this.edits.splice(at, 1);\n this.send({ type: EDITOR_SESSION_MESSAGES.REMOVE, id: last.id });\n }\n if (this.draft) this.closePanel();\n else {\n this.renderPreview();\n this.renderDock();\n }\n return true;\n }\n\n /** \"Save & return to Joryio\": every edit is already with the dashboard; say so, stop, go back. */\n done(): void {\n this.send({ type: EDITOR_SESSION_MESSAGES.DONE });\n this.stop();\n try {\n this.opener.focus();\n } catch {\n /* not allowed */\n }\n try {\n window.close();\n } catch {\n /* not a tab the dashboard opened */\n }\n }\n\n // ── live preview ─────────────────────────────────────────────────────────\n\n private clearPreview(): void {\n for (const off of this.previewUndo.splice(0).reverse()) {\n try {\n off();\n } catch {\n /* the element went away */\n }\n }\n }\n\n /** Every edit, and the draft in place of the edit it changes, applied to the page. */\n private renderPreview(): void {\n this.clearPreview();\n if (!this.active) return;\n const d = this.draft;\n const draft = d ? this.draftEdit(d) : null;\n const shown: PageEditWire[] = [];\n for (const e of this.edits) shown.push(d && d.editingId === e.id ? draft || e : e);\n if (d && !d.editingId && draft && d.touched) shown.push(draft);\n // Only the current view's edits: a Mobile-only edit shows in Mobile view, not in Desktop.\n this.mobileShown = this.mobileNow();\n for (const e of shown) if (this.inView(e)) for (const el of pageMatches(e.selector, this.doc).slice(0, 50)) this.applyPreview(e, el);\n if (this.selected) this.place(this.selBox, this.selected);\n }\n\n private previewNode(doc: Document, build: (root: ShadowRoot) => void, style = PREVIEW_HOST_STYLE, kind = 'preview'): HTMLElement {\n const n = doc.createElement(PREVIEW_TAG);\n n.setAttribute('data-joryio-editor', kind);\n n.setAttribute('style', style);\n const root = n.attachShadow({ mode: 'open' });\n root.appendChild(h('style', null, PREVIEW_CSS));\n build(root);\n return n;\n }\n\n /** A variable's placeholder pill in the page preview; `data-path` names the variable (a click opens its fallback). */\n private previewPill(doc: Document, path: string, label: string): HTMLElement {\n const n = this.previewNode(doc, (r) => r.appendChild(h('span', { class: 'v', dir: 'auto' }, label)), PREVIEW_VAR_HOST_STYLE, VAR_PILL);\n n.setAttribute('data-path', path);\n return n;\n }\n\n private applyPreview(e: PageEditWire, el: Element): void {\n const doc = el.ownerDocument;\n if (!this.originals.has(el)) this.originals.set(el, { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') });\n const undo = this.previewUndo;\n const attr = (name: string, value: string | null) => {\n const before = el.getAttribute(name);\n if (value === null) el.removeAttribute(name);\n else el.setAttribute(name, value);\n undo.push(() => (before === null ? el.removeAttribute(name) : el.setAttribute(name, before)));\n };\n const hide = () => {\n const s = (el as HTMLElement).style;\n if (!s) return;\n const display = s.getPropertyValue('display');\n const priority = s.getPropertyPriority('display');\n s.setProperty('display', 'none', 'important');\n undo.push(() => (display ? s.setProperty('display', display, priority) : s.removeProperty('display')));\n };\n const insert = (n: Node, where: PageEditPosition) => {\n const parent = el.parentNode;\n if (where === 'before' && parent) parent.insertBefore(n, el);\n else if ((where === 'after' || where === 'replace') && parent) parent.insertBefore(n, el.nextSibling);\n else if (where === 'prepend') el.insertBefore(n, el.firstChild);\n else el.appendChild(n);\n undo.push(() => n.parentNode && n.parentNode.removeChild(n));\n };\n switch (e.operation) {\n case 'replace_text': {\n const kids = Array.from(el.childNodes);\n el.textContent = '';\n // A variable with neither a sample value nor a fallback is a pill, in its own shadow root.\n for (const p of previewParts(e.value || '', this.ctx.sample)) el.appendChild(typeof p === 'string' ? doc.createTextNode(p) : this.previewPill(doc, p.path, this.labelOf(p.path) || p.name));\n undo.push(() => {\n el.textContent = '';\n for (const k of kids) el.appendChild(k);\n });\n break;\n }\n case 'replace_link':\n attr('href', e.value || null);\n break;\n case 'replace_image':\n attr('srcset', null);\n attr('src', e.value || null);\n break;\n case 'hide': {\n const what = `${this.t[kindKey(el.tagName)]} \"${this.orig(el).text.slice(0, 40)}\"`;\n insert(this.previewNode(doc, (r) => r.appendChild(h('div', { class: 'x' }, `${this.t.hiddenFor}: ${what}`))), 'after');\n hide();\n break;\n }\n case 'insert_placement': {\n const where = e.position || 'after';\n insert(\n this.previewNode(doc, (r) => r.appendChild(h('div', { class: 's' }, h('b', null, `${this.t.slotPreview} · `), h('code', null, e.placementKey || ''), h('div', null, this.t.slotHelp)))),\n where,\n );\n if (where === 'replace') hide();\n break;\n }\n }\n }\n\n // ── rendering ────────────────────────────────────────────────────────────\n\n private renderHelp(): void {\n this.help?.remove();\n this.help = null;\n let dismissed = false;\n try {\n dismissed = localStorage.getItem(HELP_DISMISSED_KEY) === '1';\n } catch {\n /* storage blocked: show it */\n }\n if (dismissed || this.draft || !this.wrap) return;\n const t = this.t;\n const row = (k: string, v: string) => h('div', { class: 'row' }, h('span', { class: 'kbd' }, k), v);\n const close = h('button', { class: 'x', type: 'button', 'aria-label': t.dismiss, title: t.dismiss, 'data-j': 'help-dismiss' }, icon('close', 13));\n close.addEventListener('click', () => {\n // persisted: localStorage of this site's origin, in the marketer's browser - the card is a one-time tip.\n try {\n localStorage.setItem(HELP_DISMISSED_KEY, '1');\n } catch {\n /* storage blocked: hidden for this session only */\n }\n this.help?.remove();\n this.help = null;\n });\n this.help = h('div', { class: 'help', 'data-j': 'help', role: 'note' }, close, h('h3', null, t.helpTitle), row('↑', t.helpUp), row('↓', t.helpDown), row(t.helpClickKey, t.helpClick));\n this.wrap.appendChild(this.help);\n }\n\n /** A variable's label from the catalog. */\n private labelOf(path: string): string | undefined {\n const v = this.ctx.attributes.filter((a) => a.path === path)[0];\n return v && v.label;\n }\n\n private editTitle(e: PageEditWire): string {\n const el = pageMatches(e.selector, this.doc)[0];\n const kind = this.t[el ? kindKey(el.tagName) : kindKey(e.selector, true)];\n return `${this.t[ACTION_LABEL[ACTION_OF[e.operation]]]} · ${kind}`;\n }\n\n private togglePop(open: boolean): void {\n this.popOpen = open;\n this.renderDock();\n }\n\n private renderDock(): void {\n if (!this.wrap) return;\n const t = this.t;\n this.dock?.remove();\n const n = this.edits.length;\n const sub = [this.ctx.variantName ? fill(t.variant, { name: this.ctx.variantName }) : '', location.pathname || '/'].filter(Boolean).join(' · ');\n const countBtn = h('button', { class: 'db', type: 'button', 'aria-expanded': String(this.popOpen), 'data-j': 'edits' }, n === 1 ? t.editsOne : fill(t.editsMany, { n }), icon(this.popOpen ? 'down' : 'up', 11));\n countBtn.addEventListener('click', () => this.togglePop(!this.popOpen));\n const canUndo = this.synced && this.history.length > 0;\n const undoBtn = h('button', { class: 'ib', type: 'button', 'aria-label': t.undo, title: this.synced ? t.undo : t.undoOffline, disabled: !canUndo, 'data-j': 'undo' }, icon('undo', 14));\n undoBtn.addEventListener('click', () => this.undo());\n const doneBtn = h('button', { class: 'go', type: 'button', 'data-j': 'done' }, t.saveReturn);\n doneBtn.addEventListener('click', () => this.done());\n // Desktop / Mobile: the page as it is in this tab, or at phone width.\n const views = h('span', { class: 'vw', role: 'radiogroup', 'aria-label': t.view, 'data-j': 'views' });\n for (const [v, label] of [['desktop', t.viewDesktop], ['mobile', t.viewMobile]] as Array<[EditorView, string]>) {\n const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(this.view === v), 'aria-label': label, title: label, 'data-j': `view-${v}` }, icon(v, 15));\n b.addEventListener('click', () => this.setView(v));\n views.appendChild(b);\n }\n const dock = h(\n 'div',\n { class: 'dock', 'data-j': 'dock', role: 'toolbar', 'aria-label': t.title },\n h('span', { class: 'logo', 'aria-hidden': 'true' }, 'J'),\n h('span', { class: 'name', 'data-j': 'campaign' }, this.ctx.campaignName || t.title),\n h('span', { class: 'sub' }, `· ${sub}`),\n h('span', { class: 'sep' }),\n h('span', { class: 'hint', 'data-j': 'hint' }, icon('cursor', 13), this.draft ? t.hintEditing : t.hintPoint),\n h('span', { class: 'sep' }),\n views,\n countBtn,\n undoBtn,\n doneBtn,\n );\n if (this.popOpen) {\n const pop = h('div', { class: 'pop', 'data-j': 'edit-list', role: 'menu' });\n if (!n) pop.appendChild(h('div', { class: 'empty' }, t.noEdits));\n this.edits.forEach((e, i) => {\n const badge = e.device ? h('span', { class: 'bdg', 'data-j': 'device-badge' }, e.device === 'mobile' ? t.devMobile : t.devDesktop) : null;\n const b = h('button', { class: 'e', type: 'button', role: 'menuitem', 'data-j': 'edit-item', 'data-edit-id': e.id }, h('span', { class: 'num' }, String(i + 1)), this.editTitle(e), badge);\n b.addEventListener('click', () => this.focusEdit(e.id));\n pop.appendChild(b);\n });\n dock.appendChild(pop);\n }\n this.dock = dock;\n this.wrap.appendChild(dock);\n }\n\n private renderPanel(): void {\n const d = this.draft;\n if (!d || !this.wrap) return;\n const t = this.t;\n const el = this.selected;\n this.panel?.remove();\n this.wrap.classList.add('open');\n\n // Header: breadcrumb (+ up / down), the element, its matches.\n const crumbs = h('div', { class: 'crumbs', 'data-j': 'crumbs' });\n if (el) {\n const chain: Element[] = [];\n const doc = el.ownerDocument;\n for (let n: Element | null = el; n && n !== doc.body && n !== doc.documentElement; n = n.parentElement) chain.unshift(n);\n const shown = chain.slice(-3);\n const crumb = (label: string, target: Element | null, cur: boolean) => {\n const b = h('button', { class: cur ? 'crumb cur' : 'crumb', type: 'button', 'data-j': 'crumb', 'aria-current': cur ? 'true' : undefined, disabled: !target }, label);\n if (target && !cur) b.addEventListener('click', () => this.select(target));\n return b;\n };\n crumbs.appendChild(crumb(t.page, null, false));\n for (const n of shown) crumbs.append(icon('chevron', 9), crumb(t[kindKey(n.tagName)], n, n === el));\n const up = h('button', { type: 'button', 'aria-label': t.up, title: t.up, 'data-j': 'up', disabled: !el.parentElement || el.parentElement === doc.body }, icon('up', 12));\n up.addEventListener('click', () => this.move('up', el));\n const down = h('button', { type: 'button', 'aria-label': t.down, title: t.down, 'data-j': 'down', disabled: !Array.from(el.children).some((c) => !isOurs(c)) }, icon('down', 12));\n down.addEventListener('click', () => this.move('down', el));\n crumbs.appendChild(h('span', { class: 'nav' }, up, down));\n }\n const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)];\n const snippet = el ? (el.tagName === 'IMG' ? el.getAttribute('alt') || '' : this.orig(el).text) : '';\n const title = h('div', { class: 'title', 'data-j': 'title' }, snippet ? `${kind} \"${snippet.slice(0, 40)}\"` : kind);\n const pill = h('span', { class: 'pill', 'data-j': 'matches' });\n const header = h('div', { class: 'hd' }, crumbs, h('div', { class: 'tr' }, title, pill));\n\n // Body: action tiles, the action's fields, the CSS selector.\n const tiles = h('div', { class: 'tiles', role: 'radiogroup', 'aria-label': t.whatToDo });\n const mine = this.editsOn(el);\n for (const a of ACTIONS) {\n const on = d.action === a;\n const enabled = on || this.enabled(a, el);\n const off = !enabled ? (a === 'link' ? t.notLink : a === 'image' ? t.notImage : t.noText) : '';\n // The element's own edit of this kind, if it has one: the tile opens it (an element can carry several edits).\n const own = mine.filter((e) => ACTION_OF[e.operation] === a).pop();\n const b = h('button', { class: a === 'slot' ? 'tile slot' : 'tile', type: 'button', role: 'radio', 'aria-checked': String(on), disabled: !enabled, 'data-e': !!own, 'data-j': `action-${a}` }, icon(ACTION_ICON[a]), h('span', null, h('b', null, t[ACTION_LABEL[a]]), off ? h('small', null, off) : null));\n b.addEventListener('click', () => {\n if (!this.draft || this.draft.action === a) return;\n if (own) this.draft = this.draftOf(own);\n else {\n // Another kind of change: a new edit next to the one open (that one stays as it is).\n if (el && this.draft.editingId) this.draft = this.newDraft(el, this.draft.selector);\n this.draft.action = a;\n this.draft.touched = true;\n if ((a === 'link' || a === 'image') && el) this.draft.url = (a === 'image' ? this.orig(el).src : this.orig(el).href) || '';\n }\n this.renderPanel();\n this.renderPreview();\n });\n tiles.appendChild(b);\n }\n const fields = h('div', { 'data-j': 'fields' });\n const saveBtn = h('button', { class: 'save', type: 'button', 'data-j': 'save' });\n const refresh = () => {\n const valid = !!this.draftEdit(d);\n saveBtn.disabled = !valid;\n saveBtn.textContent = fill(t.save, { action: t[ACTION_LABEL[d.action]] });\n const n = pageMatches(d.selector, this.doc).length;\n pill.className = `pill ${n === 1 ? 'ok' : n > 1 ? 'many' : 'none'}`;\n pill.textContent = n === 1 ? t.matchOne : n > 1 ? fill(t.matchMany, { n }) : t.matchNone;\n };\n const changed = () => {\n d.touched = true;\n refresh();\n this.renderPreview();\n };\n this.renderFields(fields, d, el, changed);\n\n const cssToggle = h('button', { class: 'css', type: 'button', 'aria-expanded': String(this.showCss), 'data-j': 'css-toggle' }, icon('code', 13), t.css, icon(this.showCss ? 'up' : 'down', 10));\n cssToggle.addEventListener('click', () => {\n this.showCss = !this.showCss;\n this.renderPanel();\n });\n // \"Applies to\": All devices (default) / Mobile only / Desktop only - first in Mobile view, where it matters most.\n const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-label': t.appliesTo, 'data-j': 'devices' });\n for (const [dev, label] of DEVICES) {\n const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(d.device === dev), 'data-j': `device-${dev}` }, t[label]);\n b.addEventListener('click', () => {\n if (d.device === dev) return;\n d.device = dev;\n d.touched = true;\n this.renderPanel();\n this.renderPreview();\n });\n seg.appendChild(b);\n }\n const devices = h('div', { class: this.view === 'mobile' ? 'dv top' : 'dv mt', 'data-j': 'applies-to' }, h('span', { class: 'lbl' }, t.appliesTo), seg, this.inView({ device: d.device }) ? null : h('div', { class: 'help2', 'data-j': 'device-hidden' }, t.deviceHidden));\n const body = h('div', { class: 'bd' }, this.view === 'mobile' ? devices : null, h('span', { class: 'lbl' }, t.whatToDo), tiles, fields, this.view === 'mobile' ? null : devices, cssToggle);\n if (this.showCss) {\n const input = h('input', { class: 'mono', dir: 'ltr', 'aria-label': t.css, spellcheck: 'false', 'data-j': 'selector' });\n input.value = d.selector;\n const note = h('div', { class: 'help2' });\n const sync = () => {\n const ok = isSafeSelector(d.selector);\n note.className = ok ? 'help2' : 'err';\n note.textContent = !d.selector.trim() ? t.noSelector : ok ? fill(t.cssHelp, { n: pageMatches(d.selector, this.doc).length }) : t.cssBad;\n };\n input.addEventListener('input', () => {\n d.selector = input.value;\n sync();\n changed();\n });\n sync();\n body.append(h('div', { class: 'mt' }, input, note));\n }\n\n const cancel = h('button', { class: 'cancel', type: 'button', 'data-j': 'cancel' }, t.cancel);\n cancel.addEventListener('click', () => this.cancel());\n saveBtn.addEventListener('click', () => this.save());\n const panel = h('aside', { class: 'panel', 'data-j': 'panel', role: 'dialog', 'aria-label': t.whatToDo }, header, body, h('div', { class: 'ft' }, cancel, saveBtn));\n refresh();\n this.panel = panel;\n this.wrap.appendChild(panel);\n }\n\n /** One field set per action. Typing updates the draft and the page, never re-renders the field typed in. */\n private renderFields(box: HTMLElement, d: Draft, el: Element | null, changed: () => void): void {\n const t = this.t;\n box.textContent = '';\n this.closeOverlay = null;\n this.field = null;\n const was = (v: string | null) => (v ? h('span', { class: 'was', title: v }, fill(t.was, { value: v.slice(0, 60) })) : null);\n if (d.action === 'text') {\n let code: HTMLTextAreaElement | null = null;\n const textChanged = (v: string) => {\n d.text = v;\n if (code && code !== this.root?.activeElement) code.value = v;\n changed();\n };\n // Each pill has its own \"If <field> is missing\" (a click on it): the `| default:` of that variable only.\n const field = liquidField({\n label: t.newText,\n rawNote: t.rawNote,\n root: this.root,\n onChange: textChanged,\n labelOf: (p) => this.labelOf(p),\n fallback: { title: t.fallbackFor, help: t.fallbackHelp, bad: t.fallbackBad, done: t.fallbackDone },\n });\n field.set(d.text);\n this.field = field;\n const add = (v: Var) => field.insert(pathTag(v.path));\n const vars: Var[] = this.ctx.attributes.length ? this.ctx.attributes : ['firstName', 'lastName'].map((n) => ({ path: `user.${n}`, label: n, group: '' }));\n const common = COMMON_VARS.map((p) => vars.filter((v) => v.path === p)[0]).filter(Boolean);\n const shown = common.concat(vars.filter((v) => common.indexOf(v) < 0)).slice(0, CHIPS);\n const chips = h('div', { class: 'chips', 'data-j': 'chips' }, h('span', null, t.insert));\n const picker = h('div', { class: 'pk', 'data-j': 'var-picker', hidden: true });\n for (const v of shown) {\n const c = h('button', { class: 'vc', type: 'button', title: v.path, 'data-j': 'chip' }, v.label);\n c.addEventListener('mousedown', (e) => e.preventDefault()); // the caret stays in the text\n c.addEventListener('click', () => add(v));\n chips.appendChild(c);\n }\n if (vars.length > shown.length) {\n // \"More…\": the whole catalog, searchable, by group; ↑ ↓ Enter in the search box, Esc closes.\n const more = h('button', { class: 'vc ui', type: 'button', 'aria-expanded': 'false', 'data-j': 'more' }, t.more);\n const search = h('input', { dir: 'auto', 'aria-label': t.search, placeholder: t.search, 'data-j': 'var-search', role: 'combobox', 'aria-expanded': 'true' });\n const listEl = h('div', { role: 'listbox', 'aria-label': t.insert, 'data-j': 'var-list' });\n picker.append(search, listEl);\n let hits: Var[] = [];\n let at = 0;\n const close = () => {\n if (picker.hidden) return false;\n picker.hidden = true;\n more.setAttribute('aria-expanded', 'false');\n return true;\n };\n const pick = (v: Var | undefined) => {\n if (!v) return;\n close();\n add(v);\n };\n const draw = () => {\n const q = search.value.trim().toLowerCase();\n hits = vars.filter((v) => !q || `${v.label} ${v.path} ${v.group}`.toLowerCase().indexOf(q) >= 0).slice(0, 200);\n at = Math.min(at, Math.max(hits.length - 1, 0));\n listEl.textContent = '';\n if (!hits.length) listEl.appendChild(h('div', { class: 'g' }, t.noMatch));\n let group: string | null = null;\n hits.forEach((v, i) => {\n if (v.group !== group) {\n group = v.group;\n if (group) listEl.appendChild(h('div', { class: 'g', role: 'presentation' }, group));\n }\n const o = h('div', { class: 'o', role: 'option', id: `jv${i}`, 'aria-selected': String(i === at), 'data-j': 'var-option' }, h('span', { dir: 'auto' }, v.label), h('code', { dir: 'ltr' }, v.path));\n o.addEventListener('mousedown', (e) => e.preventDefault());\n o.addEventListener('click', () => pick(v));\n listEl.appendChild(o);\n });\n search.setAttribute('aria-activedescendant', hits.length ? `jv${at}` : '');\n const o = listEl.querySelector('[aria-selected=\"true\"]') as HTMLElement | null;\n revealOption(listEl, o);\n };\n search.addEventListener('input', () => {\n at = 0;\n draw();\n });\n search.addEventListener('keydown', (e) => {\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n e.preventDefault();\n at = (at + (e.key === 'ArrowDown' ? 1 : hits.length - 1)) % Math.max(hits.length, 1);\n draw();\n } else if (e.key === 'Enter') {\n e.preventDefault();\n pick(hits[at]);\n }\n });\n more.addEventListener('mousedown', (e) => e.preventDefault());\n // Focus leaving the picker (Tab, a click elsewhere) closes it; the More button toggles it itself.\n picker.addEventListener('focusout', (e) => {\n const to = e.relatedTarget as Node | null;\n if (!to || (!picker.contains(to) && to !== more)) close();\n });\n more.addEventListener('click', () => {\n if (close()) return;\n picker.hidden = false;\n more.setAttribute('aria-expanded', 'true');\n search.value = '';\n at = 0;\n listEl.scrollTop = 0;\n draw();\n search.focus();\n });\n this.closeOverlay = () => field.closePop() || close();\n chips.appendChild(more);\n }\n // \"Liquid code\": the stored text itself, for developers; editing it redraws the pills.\n const toggle = h('button', { class: 'css', type: 'button', 'aria-expanded': String(this.showLiquid), 'data-j': 'liquid-toggle' }, icon('code', 13), t.liquid, icon(this.showLiquid ? 'up' : 'down', 10));\n toggle.addEventListener('click', () => {\n this.showLiquid = !this.showLiquid;\n this.renderPanel();\n });\n if (!this.closeOverlay) this.closeOverlay = () => field.closePop();\n box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, t.newText), was(el ? this.orig(el).text : null)), field.el, chips, picker, toggle);\n if (this.showLiquid) {\n const ta = h('textarea', { class: 'mono', rows: '3', dir: 'ltr', spellcheck: 'false', 'aria-label': t.liquid, 'data-j': 'liquid' });\n ta.value = d.text;\n ta.addEventListener('input', () => {\n field.set(ta.value);\n textChanged(ta.value);\n });\n code = ta;\n box.appendChild(h('div', { class: 'mt' }, ta));\n }\n } else if (d.action === 'link' || d.action === 'image') {\n const input = h('input', { type: 'url', dir: 'ltr', inputmode: 'url', placeholder: 'https://', 'data-j': 'url', 'aria-label': d.action === 'link' ? t.newLink : t.newImage });\n input.value = d.url;\n const err = h('div', { class: 'err' });\n const check = () => (err.textContent = d.url.trim() && !isSafeEditUrl(d.url) ? t.urlBad : '');\n input.addEventListener('input', () => {\n d.url = input.value;\n check();\n changed();\n });\n check();\n const before = el ? (d.action === 'image' ? this.orig(el).src : this.orig(el).href) : null;\n box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, d.action === 'link' ? t.newLink : t.newImage), was(before)), input, err);\n } else if (d.action === 'hide') {\n const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)].toLowerCase();\n box.appendChild(h('div', { class: 'note', 'data-j': 'hide-note' }, fill(t.hideNote, { kind })));\n } else {\n const input = h('input', { class: 'slotin', dir: 'auto', 'data-j': 'slot-name', 'aria-label': t.slotName, maxlength: '80' });\n input.value = d.slotName;\n const saved = h('span', { class: 'key', 'data-j': 'slot-key' });\n const help = h('div', { class: 'help2' });\n const sync = () => {\n const key = slugify(d.slotName);\n saved.textContent = key || '-';\n help.textContent = '';\n help.append(`${t.savedAs} `, saved, key ? '' : ` · ${t.slotEmpty}`);\n };\n input.addEventListener('input', () => {\n d.slotName = input.value;\n sync();\n changed();\n });\n sync();\n box.append(h('label', { class: 'lbl' }, t.slotName), input, help);\n if (this.ctx.placements.length) {\n const chips = h('div', { class: 'chips', 'data-j': 'placements' });\n for (const p of this.ctx.placements.slice(0, 12)) {\n const c = h('button', { class: 'vc', type: 'button', title: p.name || p.key, 'data-j': 'placement' }, p.key);\n c.addEventListener('click', () => {\n d.slotName = p.key;\n input.value = p.key;\n sync();\n changed();\n });\n chips.appendChild(c);\n }\n box.appendChild(chips);\n }\n box.appendChild(h('div', { class: 'help2' }, t.slotHelp));\n const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-label': t.where, 'data-j': 'positions' });\n for (const [pos, label] of POSITIONS) {\n const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(d.position === pos), 'data-j': `pos-${pos}` }, t[label]);\n b.addEventListener('click', () => {\n d.position = pos;\n for (const x of Array.from(seg.children)) x.setAttribute('aria-checked', String(x === b));\n changed();\n });\n seg.appendChild(b);\n }\n box.append(h('div', { class: 'mt' }, h('span', { class: 'lbl' }, t.where), seg));\n // A saved slot: what fills it, from the dashboard (the key as saved, not as being typed).\n const savedEdit = this.ctx.openSlot && d.editingId ? this.edits.filter((e) => e.id === d.editingId)[0] : undefined;\n const key = savedEdit && savedEdit.placementKey;\n if (key) {\n const camps = (this.ctx.placements.filter((p) => p.key === key)[0] || { campaigns: [] as SlotCampaign[] }).campaigns;\n const sec = h('div', { class: 'mt slotc', 'data-j': 'slot-content' });\n const link = (label: string, j: string, id?: string) => {\n const b = h('button', { class: 'lnk', type: 'button', 'data-j': j }, label);\n b.addEventListener('click', () => this.openSlot(key, id));\n return b;\n };\n if (!camps.length) sec.appendChild(link(t.slotCreate, 'slot-create'));\n else {\n sec.appendChild(h('span', { class: 'lbl' }, t.slotIn));\n for (const c of camps) sec.appendChild(link(c.statusLabel || c.status ? `${c.name} (${c.statusLabel || c.status})` : c.name, 'slot-campaign', c.id));\n sec.appendChild(link(t.slotAddAnother, 'slot-add'));\n }\n box.appendChild(sec);\n }\n }\n }\n}\n","/**\n * The visual editor bundle - `joryio-editor.min.js` on the SDK host, next to\n * `joryio.min.js` (BACKLOG D444 Phase 4 follow-up).\n *\n * Loaded by the core's EditorGate (src/core/editor-gate.ts) only in a tab the\n * Joryio dashboard opened for the point-and-click editor, and only after the\n * server vouched for the editor token. It registers one global and does\n * nothing else on its own: no request, no listener, until the gate calls\n * `start` with the verified dashboard origin.\n */\nimport { VisualEditor } from './visual-editor';\nimport { EDITOR_API_VERSION, EDITOR_GLOBAL, type EditorBundleApi } from '../core/editor-gate';\n\nconst api: EditorBundleApi = {\n version: EDITOR_API_VERSION,\n start({ dashboardOrigin, opener, logger, onStop }) {\n const editor = new VisualEditor(dashboardOrigin, opener, logger, onStop);\n editor.start();\n return { stop: () => editor.stop() };\n },\n};\n\nif (typeof window !== 'undefined' && !(window as any)[EDITOR_GLOBAL]) {\n (window as any)[EDITOR_GLOBAL] = api;\n}\n\nexport { api as editorApi };\n"],"names":["SuppressedError","PAGE_EDIT_POSITIONS","PAGE_EDIT_DEVICES","isMobileViewport","win","window","matchMedia","matches","innerWidth","_a","PLACEMENT_KEY_PATTERN","isSafeSelector","selector","s","trim","length","test","includes","document","createDocumentFragment","querySelector","isSafeEditUrl","url","u","CORE_FILE","coreFolderOf","src","URL","protocol","pathname","origin","replace","current","currentScript","fromCurrent","tags","querySelectorAll","i","folder","readOwnFolder","EDITOR_MESSAGES","EDITOR_GLOBAL","EDITOR_STRINGS","title","variant","hintPoint","hintEditing","editsOne","editsMany","noEdits","undo","undoOffline","saveReturn","clickToEdit","helpTitle","helpUp","helpDown","helpClickKey","helpClick","dismiss","page","up","down","matchOne","matchMany","matchNone","whatToDo","actText","actLink","actImage","actHide","actSlot","noText","notLink","notImage","newText","was","insert","fallbackFor","fallbackHelp","fallbackBad","fallbackDone","liquid","more","search","noMatch","groupProfile","groupCustom","rawNote","newLink","newImage","urlBad","hideNote","hiddenFor","slotName","savedAs","slotHelp","slotEmpty","slotCreate","slotIn","slotAddAnother","where","posBefore","posAfter","posReplace","posPrepend","posAppend","slotPreview","view","viewDesktop","viewMobile","appliesTo","devAll","devMobile","devDesktop","deviceHidden","frameBlocked","css","cssHelp","cssBad","cancel","save","noSelector","kHeading","kText","kLink","kButton","kImage","kList","kSection","kMain","kHeader","kFooter","kNav","kForm","kElement","fill","text","vars","m","k","String","OUTPUT_TAG","DEFAULT_FILTER","unquote","v","varFallback","exec","d","pathTag","path","fallback","quoted","VAR_PATH","pathName","SIMPLE_VAR","liquidParts","value","out","re","RegExp","source","last","index","push","slice","name","lastIndex","some","p","slugify","toLowerCase","newEditId","Math","random","toString","padEnd","kindKey","tagOrSelector","isSelector","t","parts","split","filter","Boolean","h","tag","attrs","kids","el","createElement","Object","entries","undefined","setAttribute","kid","appendChild","createTextNode","SVG_NS","ICONS","link","image","hide","slot","cursor","code","chevron","check","close","desktop","mobile","icon","size","createElementNS","width","height","viewBox","stroke","FONT","MONO","PILL","PREVIEW_CSS","EDITOR_CSS","PILL_ATTR","isPill","n","nodeType","hasAttribute","serialize","data","getAttribute","Array","from","childNodes","NAMING_ATTRIBUTES","ATTRIBUTE_NAME","MAX_TEXT","OURS","HELP_DISMISSED_KEY","DEVICES","isOurs","closest","VAR_PILL","pageTarget","Element","parentElement","ownerDocument","body","documentElement","pageMatches","doc","e","unique","hits","robustSelector","named","node","id","globalThis","CSS","escape","ch","charCodeAt","cssEscape","attr","tagName","own","anchor","unshift","parent","same","children","c","indexOf","join","ACTIONS","OPERATION_OF","ACTION_OF","replace_text","replace_link","replace_image","insert_placement","ACTION_LABEL","ACTION_ICON","POSITIONS","COMMON_VARS","CAMPAIGN_ID","clip","shortText","cloneNode","remove","textContent","VisualEditor","constructor","dashboardOrigin","opener","logger","onStop","this","listeners","active","host","root","wrap","hoverBox","selBox","dock","panel","help","hovered","selected","draft","showCss","showLiquid","closeOverlay","field","popOpen","edits","history","synced","assign","dir","ctx","campaignName","variantName","attributes","placements","sample","openSlot","previewUndo","originals","WeakMap","stage","frame","offPage","mobileShown","start","onMessage","type","stop","applyContext","focusEdit","addEventListener","removeEventListener","activate","isActive","editList","send","off","splice","clearPreview","error","debug","message","postMessage","attachShadow","mode","class","append","outside","composedPath","target","call","onKey","onResize","placeBoxes","renderPreview","renderPanel","unbindPage","bindPage","renderDock","renderHelp","location","key","preventDefault","stopPropagation","move","togglePop","onMove","place","onClick","pill","select","openPill","onScroll","inFrame","currentView","setView","focusId","classList","_b","implementation","createHTMLDocument","renderAll","href","searchParams","set","contentDocument","contentWindow","hidden","role","insertBefore","firstChild","mobileNow","inView","device","editShowsOn","over","keys","mergeStrings","strings","list","map","max","isArray","x","a","label","pop","group","custom","campaigns","status","statusLabel","base","personalized","operation","placementKey","position","trustedEdit","_p","rest","prototype","hasOwnProperty","getOwnPropertySymbols","propertyIsEnumerable","__rest","box","withLabel","isConnected","style","display","r","getBoundingClientRect","f","top","left","next","editsOn","edit","draftOf","newDraft","enabled","action","orig","o","editingId","touched","get","want","scrollIntoView","block","draftEdit","pick","campaignId","focus","opts","msg","at","before","closePanel","b","done","reverse","shown","applyPreview","previewNode","build","kind","previewPill","has","removeAttribute","getPropertyValue","priority","getPropertyPriority","setProperty","removeProperty","parentNode","nextSibling","removeChild","expr","previewParts","labelOf","what","dismissed","localStorage","getItem","row","setItem","editTitle","open","sub","countBtn","canUndo","undoBtn","disabled","doneBtn","views","forEach","badge","add","crumbs","chain","crumb","cur","snippet","header","tiles","mine","on","fields","saveBtn","refresh","valid","className","changed","renderFields","cssToggle","seg","dev","devices","input","spellcheck","note","sync","ok","textChanged","activeElement","saved","selection","getSelection","caret","rangeCount","getRangeAt","composed","getComposedRanges","contains","startContainer","sr","shadowRoots","createRange","setStart","startOffset","setEnd","endContainer","endOffset","remember","cloneRange","emit","onChange","putCaret","setBaseAndExtent","removeAllRanges","addRange","fb","words","contenteditable","tabindex","closePop","openPop","maxlength","err","finish","isPlainFallback","bad","setVarFallback","replaceChild","to","relatedTarget","area","rows","ce","onPill","collapsed","back","previousSibling","cut","clipboardData","setData","cloneContents","deleteContents","getData","insertNode","setStartAfter","collapse","selectNodeContents","prev","frag","liquidField","common","concat","chips","picker","placeholder","listEl","draw","q","min","previousElementSibling","offsetTop","scrollTop","offsetHeight","clientHeight","revealOption","toggle","ta","inputmode","pos","savedEdit","camps","sec","j","api","version","editor"],"mappings":";;;;;yBAwUkD,mBAApBA,iBAAiCA,gBC1QxD,MAAMC,EAAsB,CAAC,SAAU,QAAS,UAAW,SAAU,WAG/DC,EAAoB,CAAC,MAAO,SAAU,WAS7C,SAAUC,EAAiBC,EAAcC,QAC7C,IACE,MAAiC,mBAAnBD,EAAIE,WAA4BF,EAAIE,WANhB,yBAMmDC,QAAUH,EAAII,WAP5D,GAQzC,CAAE,MAAAC,GACA,OAAO,CACT,CACF,CAGO,MAODC,EAAwB,4BAsNxB,SAAUC,EAAeC,GAC7B,GAAwB,iBAAbA,EAAuB,OAAO,EACzC,MAAMC,EAAID,EAASE,OACnB,IAAKD,GAAKA,EAAEE,OA5Nc,IA4NgB,OAAO,EACjD,GAAI,UAAUC,KAAKH,IAAMA,EAAEI,SAAS,OAASJ,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